1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw__Float16: 136 case tok::kw___float128: 137 case tok::kw_wchar_t: 138 case tok::kw_bool: 139 case tok::kw___underlying_type: 140 case tok::kw___auto_type: 141 return true; 142 143 case tok::annot_typename: 144 case tok::kw_char16_t: 145 case tok::kw_char32_t: 146 case tok::kw_typeof: 147 case tok::annot_decltype: 148 case tok::kw_decltype: 149 return getLangOpts().CPlusPlus; 150 151 case tok::kw_char8_t: 152 return getLangOpts().Char8; 153 154 default: 155 break; 156 } 157 158 return false; 159 } 160 161 namespace { 162 enum class UnqualifiedTypeNameLookupResult { 163 NotFound, 164 FoundNonType, 165 FoundType 166 }; 167 } // end anonymous namespace 168 169 /// Tries to perform unqualified lookup of the type decls in bases for 170 /// dependent class. 171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 172 /// type decl, \a FoundType if only type decls are found. 173 static UnqualifiedTypeNameLookupResult 174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 175 SourceLocation NameLoc, 176 const CXXRecordDecl *RD) { 177 if (!RD->hasDefinition()) 178 return UnqualifiedTypeNameLookupResult::NotFound; 179 // Look for type decls in base classes. 180 UnqualifiedTypeNameLookupResult FoundTypeDecl = 181 UnqualifiedTypeNameLookupResult::NotFound; 182 for (const auto &Base : RD->bases()) { 183 const CXXRecordDecl *BaseRD = nullptr; 184 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 185 BaseRD = BaseTT->getAsCXXRecordDecl(); 186 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 187 // Look for type decls in dependent base classes that have known primary 188 // templates. 189 if (!TST || !TST->isDependentType()) 190 continue; 191 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 192 if (!TD) 193 continue; 194 if (auto *BasePrimaryTemplate = 195 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 196 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 197 BaseRD = BasePrimaryTemplate; 198 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 199 if (const ClassTemplatePartialSpecializationDecl *PS = 200 CTD->findPartialSpecialization(Base.getType())) 201 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 202 BaseRD = PS; 203 } 204 } 205 } 206 if (BaseRD) { 207 for (NamedDecl *ND : BaseRD->lookup(&II)) { 208 if (!isa<TypeDecl>(ND)) 209 return UnqualifiedTypeNameLookupResult::FoundNonType; 210 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 211 } 212 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 213 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 214 case UnqualifiedTypeNameLookupResult::FoundNonType: 215 return UnqualifiedTypeNameLookupResult::FoundNonType; 216 case UnqualifiedTypeNameLookupResult::FoundType: 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 break; 219 case UnqualifiedTypeNameLookupResult::NotFound: 220 break; 221 } 222 } 223 } 224 } 225 226 return FoundTypeDecl; 227 } 228 229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 230 const IdentifierInfo &II, 231 SourceLocation NameLoc) { 232 // Lookup in the parent class template context, if any. 233 const CXXRecordDecl *RD = nullptr; 234 UnqualifiedTypeNameLookupResult FoundTypeDecl = 235 UnqualifiedTypeNameLookupResult::NotFound; 236 for (DeclContext *DC = S.CurContext; 237 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 238 DC = DC->getParent()) { 239 // Look for type decls in dependent base classes that have known primary 240 // templates. 241 RD = dyn_cast<CXXRecordDecl>(DC); 242 if (RD && RD->getDescribedClassTemplate()) 243 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 244 } 245 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 246 return nullptr; 247 248 // We found some types in dependent base classes. Recover as if the user 249 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 250 // lookup during template instantiation. 251 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 252 253 ASTContext &Context = S.Context; 254 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 255 cast<Type>(Context.getRecordType(RD))); 256 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 257 258 CXXScopeSpec SS; 259 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 260 261 TypeLocBuilder Builder; 262 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 263 DepTL.setNameLoc(NameLoc); 264 DepTL.setElaboratedKeywordLoc(SourceLocation()); 265 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 266 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 267 } 268 269 /// If the identifier refers to a type name within this scope, 270 /// return the declaration of that type. 271 /// 272 /// This routine performs ordinary name lookup of the identifier II 273 /// within the given scope, with optional C++ scope specifier SS, to 274 /// determine whether the name refers to a type. If so, returns an 275 /// opaque pointer (actually a QualType) corresponding to that 276 /// type. Otherwise, returns NULL. 277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 278 Scope *S, CXXScopeSpec *SS, 279 bool isClassName, bool HasTrailingDot, 280 ParsedType ObjectTypePtr, 281 bool IsCtorOrDtorName, 282 bool WantNontrivialTypeSourceInfo, 283 bool IsClassTemplateDeductionContext, 284 IdentifierInfo **CorrectedII) { 285 // FIXME: Consider allowing this outside C++1z mode as an extension. 286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 287 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 288 !isClassName && !HasTrailingDot; 289 290 // Determine where we will perform name lookup. 291 DeclContext *LookupCtx = nullptr; 292 if (ObjectTypePtr) { 293 QualType ObjectType = ObjectTypePtr.get(); 294 if (ObjectType->isRecordType()) 295 LookupCtx = computeDeclContext(ObjectType); 296 } else if (SS && SS->isNotEmpty()) { 297 LookupCtx = computeDeclContext(*SS, false); 298 299 if (!LookupCtx) { 300 if (isDependentScopeSpecifier(*SS)) { 301 // C++ [temp.res]p3: 302 // A qualified-id that refers to a type and in which the 303 // nested-name-specifier depends on a template-parameter (14.6.2) 304 // shall be prefixed by the keyword typename to indicate that the 305 // qualified-id denotes a type, forming an 306 // elaborated-type-specifier (7.1.5.3). 307 // 308 // We therefore do not perform any name lookup if the result would 309 // refer to a member of an unknown specialization. 310 if (!isClassName && !IsCtorOrDtorName) 311 return nullptr; 312 313 // We know from the grammar that this name refers to a type, 314 // so build a dependent node to describe the type. 315 if (WantNontrivialTypeSourceInfo) 316 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 317 318 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 319 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 320 II, NameLoc); 321 return ParsedType::make(T); 322 } 323 324 return nullptr; 325 } 326 327 if (!LookupCtx->isDependentContext() && 328 RequireCompleteDeclContext(*SS, LookupCtx)) 329 return nullptr; 330 } 331 332 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 333 // lookup for class-names. 334 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 335 LookupOrdinaryName; 336 LookupResult Result(*this, &II, NameLoc, Kind); 337 if (LookupCtx) { 338 // Perform "qualified" name lookup into the declaration context we 339 // computed, which is either the type of the base of a member access 340 // expression or the declaration context associated with a prior 341 // nested-name-specifier. 342 LookupQualifiedName(Result, LookupCtx); 343 344 if (ObjectTypePtr && Result.empty()) { 345 // C++ [basic.lookup.classref]p3: 346 // If the unqualified-id is ~type-name, the type-name is looked up 347 // in the context of the entire postfix-expression. If the type T of 348 // the object expression is of a class type C, the type-name is also 349 // looked up in the scope of class C. At least one of the lookups shall 350 // find a name that refers to (possibly cv-qualified) T. 351 LookupName(Result, S); 352 } 353 } else { 354 // Perform unqualified name lookup. 355 LookupName(Result, S); 356 357 // For unqualified lookup in a class template in MSVC mode, look into 358 // dependent base classes where the primary class template is known. 359 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 360 if (ParsedType TypeInBase = 361 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 362 return TypeInBase; 363 } 364 } 365 366 NamedDecl *IIDecl = nullptr; 367 switch (Result.getResultKind()) { 368 case LookupResult::NotFound: 369 case LookupResult::NotFoundInCurrentInstantiation: 370 if (CorrectedII) { 371 TypoCorrection Correction = 372 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 373 llvm::make_unique<TypeNameValidatorCCC>( 374 true, isClassName, AllowDeducedTemplate), 375 CTK_ErrorRecovery); 376 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 377 TemplateTy Template; 378 bool MemberOfUnknownSpecialization; 379 UnqualifiedId TemplateName; 380 TemplateName.setIdentifier(NewII, NameLoc); 381 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 382 CXXScopeSpec NewSS, *NewSSPtr = SS; 383 if (SS && NNS) { 384 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 385 NewSSPtr = &NewSS; 386 } 387 if (Correction && (NNS || NewII != &II) && 388 // Ignore a correction to a template type as the to-be-corrected 389 // identifier is not a template (typo correction for template names 390 // is handled elsewhere). 391 !(getLangOpts().CPlusPlus && NewSSPtr && 392 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 393 Template, MemberOfUnknownSpecialization))) { 394 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 395 isClassName, HasTrailingDot, ObjectTypePtr, 396 IsCtorOrDtorName, 397 WantNontrivialTypeSourceInfo, 398 IsClassTemplateDeductionContext); 399 if (Ty) { 400 diagnoseTypo(Correction, 401 PDiag(diag::err_unknown_type_or_class_name_suggest) 402 << Result.getLookupName() << isClassName); 403 if (SS && NNS) 404 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 405 *CorrectedII = NewII; 406 return Ty; 407 } 408 } 409 } 410 // If typo correction failed or was not performed, fall through 411 LLVM_FALLTHROUGH; 412 case LookupResult::FoundOverloaded: 413 case LookupResult::FoundUnresolvedValue: 414 Result.suppressDiagnostics(); 415 return nullptr; 416 417 case LookupResult::Ambiguous: 418 // Recover from type-hiding ambiguities by hiding the type. We'll 419 // do the lookup again when looking for an object, and we can 420 // diagnose the error then. If we don't do this, then the error 421 // about hiding the type will be immediately followed by an error 422 // that only makes sense if the identifier was treated like a type. 423 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 424 Result.suppressDiagnostics(); 425 return nullptr; 426 } 427 428 // Look to see if we have a type anywhere in the list of results. 429 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 430 Res != ResEnd; ++Res) { 431 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 432 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 433 if (!IIDecl || 434 (*Res)->getLocation().getRawEncoding() < 435 IIDecl->getLocation().getRawEncoding()) 436 IIDecl = *Res; 437 } 438 } 439 440 if (!IIDecl) { 441 // None of the entities we found is a type, so there is no way 442 // to even assume that the result is a type. In this case, don't 443 // complain about the ambiguity. The parser will either try to 444 // perform this lookup again (e.g., as an object name), which 445 // will produce the ambiguity, or will complain that it expected 446 // a type name. 447 Result.suppressDiagnostics(); 448 return nullptr; 449 } 450 451 // We found a type within the ambiguous lookup; diagnose the 452 // ambiguity and then return that type. This might be the right 453 // answer, or it might not be, but it suppresses any attempt to 454 // perform the name lookup again. 455 break; 456 457 case LookupResult::Found: 458 IIDecl = Result.getFoundDecl(); 459 break; 460 } 461 462 assert(IIDecl && "Didn't find decl"); 463 464 QualType T; 465 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 466 // C++ [class.qual]p2: A lookup that would find the injected-class-name 467 // instead names the constructors of the class, except when naming a class. 468 // This is ill-formed when we're not actually forming a ctor or dtor name. 469 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 470 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 471 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 472 FoundRD->isInjectedClassName() && 473 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 474 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 475 << &II << /*Type*/1; 476 477 DiagnoseUseOfDecl(IIDecl, NameLoc); 478 479 T = Context.getTypeDeclType(TD); 480 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 481 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 482 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 483 if (!HasTrailingDot) 484 T = Context.getObjCInterfaceType(IDecl); 485 } else if (AllowDeducedTemplate) { 486 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 487 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 488 QualType(), false); 489 } 490 491 if (T.isNull()) { 492 // If it's not plausibly a type, suppress diagnostics. 493 Result.suppressDiagnostics(); 494 return nullptr; 495 } 496 497 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 498 // constructor or destructor name (in such a case, the scope specifier 499 // will be attached to the enclosing Expr or Decl node). 500 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 501 !isa<ObjCInterfaceDecl>(IIDecl)) { 502 if (WantNontrivialTypeSourceInfo) { 503 // Construct a type with type-source information. 504 TypeLocBuilder Builder; 505 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 506 507 T = getElaboratedType(ETK_None, *SS, T); 508 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 509 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 510 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 511 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 512 } else { 513 T = getElaboratedType(ETK_None, *SS, T); 514 } 515 } 516 517 return ParsedType::make(T); 518 } 519 520 // Builds a fake NNS for the given decl context. 521 static NestedNameSpecifier * 522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 523 for (;; DC = DC->getLookupParent()) { 524 DC = DC->getPrimaryContext(); 525 auto *ND = dyn_cast<NamespaceDecl>(DC); 526 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 527 return NestedNameSpecifier::Create(Context, nullptr, ND); 528 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 529 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 530 RD->getTypeForDecl()); 531 else if (isa<TranslationUnitDecl>(DC)) 532 return NestedNameSpecifier::GlobalSpecifier(Context); 533 } 534 llvm_unreachable("something isn't in TU scope?"); 535 } 536 537 /// Find the parent class with dependent bases of the innermost enclosing method 538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 539 /// up allowing unqualified dependent type names at class-level, which MSVC 540 /// correctly rejects. 541 static const CXXRecordDecl * 542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 543 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 544 DC = DC->getPrimaryContext(); 545 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 546 if (MD->getParent()->hasAnyDependentBases()) 547 return MD->getParent(); 548 } 549 return nullptr; 550 } 551 552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 553 SourceLocation NameLoc, 554 bool IsTemplateTypeArg) { 555 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 556 557 NestedNameSpecifier *NNS = nullptr; 558 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 559 // If we weren't able to parse a default template argument, delay lookup 560 // until instantiation time by making a non-dependent DependentTypeName. We 561 // pretend we saw a NestedNameSpecifier referring to the current scope, and 562 // lookup is retried. 563 // FIXME: This hurts our diagnostic quality, since we get errors like "no 564 // type named 'Foo' in 'current_namespace'" when the user didn't write any 565 // name specifiers. 566 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 567 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 568 } else if (const CXXRecordDecl *RD = 569 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 570 // Build a DependentNameType that will perform lookup into RD at 571 // instantiation time. 572 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 573 RD->getTypeForDecl()); 574 575 // Diagnose that this identifier was undeclared, and retry the lookup during 576 // template instantiation. 577 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 578 << RD; 579 } else { 580 // This is not a situation that we should recover from. 581 return ParsedType(); 582 } 583 584 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 585 586 // Build type location information. We synthesized the qualifier, so we have 587 // to build a fake NestedNameSpecifierLoc. 588 NestedNameSpecifierLocBuilder NNSLocBuilder; 589 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 590 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 591 592 TypeLocBuilder Builder; 593 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 594 DepTL.setNameLoc(NameLoc); 595 DepTL.setElaboratedKeywordLoc(SourceLocation()); 596 DepTL.setQualifierLoc(QualifierLoc); 597 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 598 } 599 600 /// isTagName() - This method is called *for error recovery purposes only* 601 /// to determine if the specified name is a valid tag name ("struct foo"). If 602 /// so, this returns the TST for the tag corresponding to it (TST_enum, 603 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 604 /// cases in C where the user forgot to specify the tag. 605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 606 // Do a tag name lookup in this scope. 607 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 608 LookupName(R, S, false); 609 R.suppressDiagnostics(); 610 if (R.getResultKind() == LookupResult::Found) 611 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 612 switch (TD->getTagKind()) { 613 case TTK_Struct: return DeclSpec::TST_struct; 614 case TTK_Interface: return DeclSpec::TST_interface; 615 case TTK_Union: return DeclSpec::TST_union; 616 case TTK_Class: return DeclSpec::TST_class; 617 case TTK_Enum: return DeclSpec::TST_enum; 618 } 619 } 620 621 return DeclSpec::TST_unspecified; 622 } 623 624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 626 /// then downgrade the missing typename error to a warning. 627 /// This is needed for MSVC compatibility; Example: 628 /// @code 629 /// template<class T> class A { 630 /// public: 631 /// typedef int TYPE; 632 /// }; 633 /// template<class T> class B : public A<T> { 634 /// public: 635 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 636 /// }; 637 /// @endcode 638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 639 if (CurContext->isRecord()) { 640 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 641 return true; 642 643 const Type *Ty = SS->getScopeRep()->getAsType(); 644 645 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 646 for (const auto &Base : RD->bases()) 647 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 648 return true; 649 return S->isFunctionPrototypeScope(); 650 } 651 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 652 } 653 654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 655 SourceLocation IILoc, 656 Scope *S, 657 CXXScopeSpec *SS, 658 ParsedType &SuggestedType, 659 bool IsTemplateName) { 660 // Don't report typename errors for editor placeholders. 661 if (II->isEditorPlaceholder()) 662 return; 663 // We don't have anything to suggest (yet). 664 SuggestedType = nullptr; 665 666 // There may have been a typo in the name of the type. Look up typo 667 // results, in case we have something that we can suggest. 668 if (TypoCorrection Corrected = 669 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 670 llvm::make_unique<TypeNameValidatorCCC>( 671 false, false, IsTemplateName, !IsTemplateName), 672 CTK_ErrorRecovery)) { 673 // FIXME: Support error recovery for the template-name case. 674 bool CanRecover = !IsTemplateName; 675 if (Corrected.isKeyword()) { 676 // We corrected to a keyword. 677 diagnoseTypo(Corrected, 678 PDiag(IsTemplateName ? diag::err_no_template_suggest 679 : diag::err_unknown_typename_suggest) 680 << II); 681 II = Corrected.getCorrectionAsIdentifierInfo(); 682 } else { 683 // We found a similarly-named type or interface; suggest that. 684 if (!SS || !SS->isSet()) { 685 diagnoseTypo(Corrected, 686 PDiag(IsTemplateName ? diag::err_no_template_suggest 687 : diag::err_unknown_typename_suggest) 688 << II, CanRecover); 689 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 690 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 691 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 692 II->getName().equals(CorrectedStr); 693 diagnoseTypo(Corrected, 694 PDiag(IsTemplateName 695 ? diag::err_no_member_template_suggest 696 : diag::err_unknown_nested_typename_suggest) 697 << II << DC << DroppedSpecifier << SS->getRange(), 698 CanRecover); 699 } else { 700 llvm_unreachable("could not have corrected a typo here"); 701 } 702 703 if (!CanRecover) 704 return; 705 706 CXXScopeSpec tmpSS; 707 if (Corrected.getCorrectionSpecifier()) 708 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 709 SourceRange(IILoc)); 710 // FIXME: Support class template argument deduction here. 711 SuggestedType = 712 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 713 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 714 /*IsCtorOrDtorName=*/false, 715 /*NonTrivialTypeSourceInfo=*/true); 716 } 717 return; 718 } 719 720 if (getLangOpts().CPlusPlus && !IsTemplateName) { 721 // See if II is a class template that the user forgot to pass arguments to. 722 UnqualifiedId Name; 723 Name.setIdentifier(II, IILoc); 724 CXXScopeSpec EmptySS; 725 TemplateTy TemplateResult; 726 bool MemberOfUnknownSpecialization; 727 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 728 Name, nullptr, true, TemplateResult, 729 MemberOfUnknownSpecialization) == TNK_Type_template) { 730 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 731 return; 732 } 733 } 734 735 // FIXME: Should we move the logic that tries to recover from a missing tag 736 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 737 738 if (!SS || (!SS->isSet() && !SS->isInvalid())) 739 Diag(IILoc, IsTemplateName ? diag::err_no_template 740 : diag::err_unknown_typename) 741 << II; 742 else if (DeclContext *DC = computeDeclContext(*SS, false)) 743 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 744 : diag::err_typename_nested_not_found) 745 << II << DC << SS->getRange(); 746 else if (isDependentScopeSpecifier(*SS)) { 747 unsigned DiagID = diag::err_typename_missing; 748 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 749 DiagID = diag::ext_typename_missing; 750 751 Diag(SS->getRange().getBegin(), DiagID) 752 << SS->getScopeRep() << II->getName() 753 << SourceRange(SS->getRange().getBegin(), IILoc) 754 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 755 SuggestedType = ActOnTypenameType(S, SourceLocation(), 756 *SS, *II, IILoc).get(); 757 } else { 758 assert(SS && SS->isInvalid() && 759 "Invalid scope specifier has already been diagnosed"); 760 } 761 } 762 763 /// Determine whether the given result set contains either a type name 764 /// or 765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 766 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 767 NextToken.is(tok::less); 768 769 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 770 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 771 return true; 772 773 if (CheckTemplate && isa<TemplateDecl>(*I)) 774 return true; 775 } 776 777 return false; 778 } 779 780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 781 Scope *S, CXXScopeSpec &SS, 782 IdentifierInfo *&Name, 783 SourceLocation NameLoc) { 784 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 785 SemaRef.LookupParsedName(R, S, &SS); 786 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 787 StringRef FixItTagName; 788 switch (Tag->getTagKind()) { 789 case TTK_Class: 790 FixItTagName = "class "; 791 break; 792 793 case TTK_Enum: 794 FixItTagName = "enum "; 795 break; 796 797 case TTK_Struct: 798 FixItTagName = "struct "; 799 break; 800 801 case TTK_Interface: 802 FixItTagName = "__interface "; 803 break; 804 805 case TTK_Union: 806 FixItTagName = "union "; 807 break; 808 } 809 810 StringRef TagName = FixItTagName.drop_back(); 811 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 812 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 813 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 814 815 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 816 I != IEnd; ++I) 817 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 818 << Name << TagName; 819 820 // Replace lookup results with just the tag decl. 821 Result.clear(Sema::LookupTagName); 822 SemaRef.LookupParsedName(Result, S, &SS); 823 return true; 824 } 825 826 return false; 827 } 828 829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 831 QualType T, SourceLocation NameLoc) { 832 ASTContext &Context = S.Context; 833 834 TypeLocBuilder Builder; 835 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 836 837 T = S.getElaboratedType(ETK_None, SS, T); 838 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 839 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 840 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 841 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 842 } 843 844 Sema::NameClassification 845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 846 SourceLocation NameLoc, const Token &NextToken, 847 bool IsAddressOfOperand, 848 std::unique_ptr<CorrectionCandidateCallback> CCC) { 849 DeclarationNameInfo NameInfo(Name, NameLoc); 850 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 851 852 if (NextToken.is(tok::coloncolon)) { 853 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 854 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 855 } else if (getLangOpts().CPlusPlus && SS.isSet() && 856 isCurrentClassName(*Name, S, &SS)) { 857 // Per [class.qual]p2, this names the constructors of SS, not the 858 // injected-class-name. We don't have a classification for that. 859 // There's not much point caching this result, since the parser 860 // will reject it later. 861 return NameClassification::Unknown(); 862 } 863 864 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 865 LookupParsedName(Result, S, &SS, !CurMethod); 866 867 // For unqualified lookup in a class template in MSVC mode, look into 868 // dependent base classes where the primary class template is known. 869 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 870 if (ParsedType TypeInBase = 871 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 872 return TypeInBase; 873 } 874 875 // Perform lookup for Objective-C instance variables (including automatically 876 // synthesized instance variables), if we're in an Objective-C method. 877 // FIXME: This lookup really, really needs to be folded in to the normal 878 // unqualified lookup mechanism. 879 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 880 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 881 if (E.get() || E.isInvalid()) 882 return E; 883 } 884 885 bool SecondTry = false; 886 bool IsFilteredTemplateName = false; 887 888 Corrected: 889 switch (Result.getResultKind()) { 890 case LookupResult::NotFound: 891 // If an unqualified-id is followed by a '(', then we have a function 892 // call. 893 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 894 // In C++, this is an ADL-only call. 895 // FIXME: Reference? 896 if (getLangOpts().CPlusPlus) 897 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 898 899 // C90 6.3.2.2: 900 // If the expression that precedes the parenthesized argument list in a 901 // function call consists solely of an identifier, and if no 902 // declaration is visible for this identifier, the identifier is 903 // implicitly declared exactly as if, in the innermost block containing 904 // the function call, the declaration 905 // 906 // extern int identifier (); 907 // 908 // appeared. 909 // 910 // We also allow this in C99 as an extension. 911 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 912 Result.addDecl(D); 913 Result.resolveKind(); 914 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 915 } 916 } 917 918 // In C, we first see whether there is a tag type by the same name, in 919 // which case it's likely that the user just forgot to write "enum", 920 // "struct", or "union". 921 if (!getLangOpts().CPlusPlus && !SecondTry && 922 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 923 break; 924 } 925 926 // Perform typo correction to determine if there is another name that is 927 // close to this name. 928 if (!SecondTry && CCC) { 929 SecondTry = true; 930 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 931 Result.getLookupKind(), S, 932 &SS, std::move(CCC), 933 CTK_ErrorRecovery)) { 934 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 935 unsigned QualifiedDiag = diag::err_no_member_suggest; 936 937 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 938 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 939 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 940 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 941 UnqualifiedDiag = diag::err_no_template_suggest; 942 QualifiedDiag = diag::err_no_member_template_suggest; 943 } else if (UnderlyingFirstDecl && 944 (isa<TypeDecl>(UnderlyingFirstDecl) || 945 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 946 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 947 UnqualifiedDiag = diag::err_unknown_typename_suggest; 948 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 949 } 950 951 if (SS.isEmpty()) { 952 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 953 } else {// FIXME: is this even reachable? Test it. 954 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 955 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 956 Name->getName().equals(CorrectedStr); 957 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 958 << Name << computeDeclContext(SS, false) 959 << DroppedSpecifier << SS.getRange()); 960 } 961 962 // Update the name, so that the caller has the new name. 963 Name = Corrected.getCorrectionAsIdentifierInfo(); 964 965 // Typo correction corrected to a keyword. 966 if (Corrected.isKeyword()) 967 return Name; 968 969 // Also update the LookupResult... 970 // FIXME: This should probably go away at some point 971 Result.clear(); 972 Result.setLookupName(Corrected.getCorrection()); 973 if (FirstDecl) 974 Result.addDecl(FirstDecl); 975 976 // If we found an Objective-C instance variable, let 977 // LookupInObjCMethod build the appropriate expression to 978 // reference the ivar. 979 // FIXME: This is a gross hack. 980 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 981 Result.clear(); 982 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 983 return E; 984 } 985 986 goto Corrected; 987 } 988 } 989 990 // We failed to correct; just fall through and let the parser deal with it. 991 Result.suppressDiagnostics(); 992 return NameClassification::Unknown(); 993 994 case LookupResult::NotFoundInCurrentInstantiation: { 995 // We performed name lookup into the current instantiation, and there were 996 // dependent bases, so we treat this result the same way as any other 997 // dependent nested-name-specifier. 998 999 // C++ [temp.res]p2: 1000 // A name used in a template declaration or definition and that is 1001 // dependent on a template-parameter is assumed not to name a type 1002 // unless the applicable name lookup finds a type name or the name is 1003 // qualified by the keyword typename. 1004 // 1005 // FIXME: If the next token is '<', we might want to ask the parser to 1006 // perform some heroics to see if we actually have a 1007 // template-argument-list, which would indicate a missing 'template' 1008 // keyword here. 1009 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1010 NameInfo, IsAddressOfOperand, 1011 /*TemplateArgs=*/nullptr); 1012 } 1013 1014 case LookupResult::Found: 1015 case LookupResult::FoundOverloaded: 1016 case LookupResult::FoundUnresolvedValue: 1017 break; 1018 1019 case LookupResult::Ambiguous: 1020 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1021 hasAnyAcceptableTemplateNames(Result)) { 1022 // C++ [temp.local]p3: 1023 // A lookup that finds an injected-class-name (10.2) can result in an 1024 // ambiguity in certain cases (for example, if it is found in more than 1025 // one base class). If all of the injected-class-names that are found 1026 // refer to specializations of the same class template, and if the name 1027 // is followed by a template-argument-list, the reference refers to the 1028 // class template itself and not a specialization thereof, and is not 1029 // ambiguous. 1030 // 1031 // This filtering can make an ambiguous result into an unambiguous one, 1032 // so try again after filtering out template names. 1033 FilterAcceptableTemplateNames(Result); 1034 if (!Result.isAmbiguous()) { 1035 IsFilteredTemplateName = true; 1036 break; 1037 } 1038 } 1039 1040 // Diagnose the ambiguity and return an error. 1041 return NameClassification::Error(); 1042 } 1043 1044 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1045 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1046 // C++ [temp.names]p3: 1047 // After name lookup (3.4) finds that a name is a template-name or that 1048 // an operator-function-id or a literal- operator-id refers to a set of 1049 // overloaded functions any member of which is a function template if 1050 // this is followed by a <, the < is always taken as the delimiter of a 1051 // template-argument-list and never as the less-than operator. 1052 if (!IsFilteredTemplateName) 1053 FilterAcceptableTemplateNames(Result); 1054 1055 if (!Result.empty()) { 1056 bool IsFunctionTemplate; 1057 bool IsVarTemplate; 1058 TemplateName Template; 1059 if (Result.end() - Result.begin() > 1) { 1060 IsFunctionTemplate = true; 1061 Template = Context.getOverloadedTemplateName(Result.begin(), 1062 Result.end()); 1063 } else { 1064 TemplateDecl *TD 1065 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1066 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1067 IsVarTemplate = isa<VarTemplateDecl>(TD); 1068 1069 if (SS.isSet() && !SS.isInvalid()) 1070 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1071 /*TemplateKeyword=*/false, 1072 TD); 1073 else 1074 Template = TemplateName(TD); 1075 } 1076 1077 if (IsFunctionTemplate) { 1078 // Function templates always go through overload resolution, at which 1079 // point we'll perform the various checks (e.g., accessibility) we need 1080 // to based on which function we selected. 1081 Result.suppressDiagnostics(); 1082 1083 return NameClassification::FunctionTemplate(Template); 1084 } 1085 1086 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1087 : NameClassification::TypeTemplate(Template); 1088 } 1089 } 1090 1091 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1092 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1093 DiagnoseUseOfDecl(Type, NameLoc); 1094 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1095 QualType T = Context.getTypeDeclType(Type); 1096 if (SS.isNotEmpty()) 1097 return buildNestedType(*this, SS, T, NameLoc); 1098 return ParsedType::make(T); 1099 } 1100 1101 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1102 if (!Class) { 1103 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1104 if (ObjCCompatibleAliasDecl *Alias = 1105 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1106 Class = Alias->getClassInterface(); 1107 } 1108 1109 if (Class) { 1110 DiagnoseUseOfDecl(Class, NameLoc); 1111 1112 if (NextToken.is(tok::period)) { 1113 // Interface. <something> is parsed as a property reference expression. 1114 // Just return "unknown" as a fall-through for now. 1115 Result.suppressDiagnostics(); 1116 return NameClassification::Unknown(); 1117 } 1118 1119 QualType T = Context.getObjCInterfaceType(Class); 1120 return ParsedType::make(T); 1121 } 1122 1123 // We can have a type template here if we're classifying a template argument. 1124 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1125 !isa<VarTemplateDecl>(FirstDecl)) 1126 return NameClassification::TypeTemplate( 1127 TemplateName(cast<TemplateDecl>(FirstDecl))); 1128 1129 // Check for a tag type hidden by a non-type decl in a few cases where it 1130 // seems likely a type is wanted instead of the non-type that was found. 1131 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1132 if ((NextToken.is(tok::identifier) || 1133 (NextIsOp && 1134 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1135 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1136 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1137 DiagnoseUseOfDecl(Type, NameLoc); 1138 QualType T = Context.getTypeDeclType(Type); 1139 if (SS.isNotEmpty()) 1140 return buildNestedType(*this, SS, T, NameLoc); 1141 return ParsedType::make(T); 1142 } 1143 1144 if (FirstDecl->isCXXClassMember()) 1145 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1146 nullptr, S); 1147 1148 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1149 return BuildDeclarationNameExpr(SS, Result, ADL); 1150 } 1151 1152 Sema::TemplateNameKindForDiagnostics 1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1154 auto *TD = Name.getAsTemplateDecl(); 1155 if (!TD) 1156 return TemplateNameKindForDiagnostics::DependentTemplate; 1157 if (isa<ClassTemplateDecl>(TD)) 1158 return TemplateNameKindForDiagnostics::ClassTemplate; 1159 if (isa<FunctionTemplateDecl>(TD)) 1160 return TemplateNameKindForDiagnostics::FunctionTemplate; 1161 if (isa<VarTemplateDecl>(TD)) 1162 return TemplateNameKindForDiagnostics::VarTemplate; 1163 if (isa<TypeAliasTemplateDecl>(TD)) 1164 return TemplateNameKindForDiagnostics::AliasTemplate; 1165 if (isa<TemplateTemplateParmDecl>(TD)) 1166 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1167 return TemplateNameKindForDiagnostics::DependentTemplate; 1168 } 1169 1170 // Determines the context to return to after temporarily entering a 1171 // context. This depends in an unnecessarily complicated way on the 1172 // exact ordering of callbacks from the parser. 1173 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1174 1175 // Functions defined inline within classes aren't parsed until we've 1176 // finished parsing the top-level class, so the top-level class is 1177 // the context we'll need to return to. 1178 // A Lambda call operator whose parent is a class must not be treated 1179 // as an inline member function. A Lambda can be used legally 1180 // either as an in-class member initializer or a default argument. These 1181 // are parsed once the class has been marked complete and so the containing 1182 // context would be the nested class (when the lambda is defined in one); 1183 // If the class is not complete, then the lambda is being used in an 1184 // ill-formed fashion (such as to specify the width of a bit-field, or 1185 // in an array-bound) - in which case we still want to return the 1186 // lexically containing DC (which could be a nested class). 1187 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1188 DC = DC->getLexicalParent(); 1189 1190 // A function not defined within a class will always return to its 1191 // lexical context. 1192 if (!isa<CXXRecordDecl>(DC)) 1193 return DC; 1194 1195 // A C++ inline method/friend is parsed *after* the topmost class 1196 // it was declared in is fully parsed ("complete"); the topmost 1197 // class is the context we need to return to. 1198 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1199 DC = RD; 1200 1201 // Return the declaration context of the topmost class the inline method is 1202 // declared in. 1203 return DC; 1204 } 1205 1206 return DC->getLexicalParent(); 1207 } 1208 1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1210 assert(getContainingDC(DC) == CurContext && 1211 "The next DeclContext should be lexically contained in the current one."); 1212 CurContext = DC; 1213 S->setEntity(DC); 1214 } 1215 1216 void Sema::PopDeclContext() { 1217 assert(CurContext && "DeclContext imbalance!"); 1218 1219 CurContext = getContainingDC(CurContext); 1220 assert(CurContext && "Popped translation unit!"); 1221 } 1222 1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1224 Decl *D) { 1225 // Unlike PushDeclContext, the context to which we return is not necessarily 1226 // the containing DC of TD, because the new context will be some pre-existing 1227 // TagDecl definition instead of a fresh one. 1228 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1229 CurContext = cast<TagDecl>(D)->getDefinition(); 1230 assert(CurContext && "skipping definition of undefined tag"); 1231 // Start lookups from the parent of the current context; we don't want to look 1232 // into the pre-existing complete definition. 1233 S->setEntity(CurContext->getLookupParent()); 1234 return Result; 1235 } 1236 1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1238 CurContext = static_cast<decltype(CurContext)>(Context); 1239 } 1240 1241 /// EnterDeclaratorContext - Used when we must lookup names in the context 1242 /// of a declarator's nested name specifier. 1243 /// 1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1245 // C++0x [basic.lookup.unqual]p13: 1246 // A name used in the definition of a static data member of class 1247 // X (after the qualified-id of the static member) is looked up as 1248 // if the name was used in a member function of X. 1249 // C++0x [basic.lookup.unqual]p14: 1250 // If a variable member of a namespace is defined outside of the 1251 // scope of its namespace then any name used in the definition of 1252 // the variable member (after the declarator-id) is looked up as 1253 // if the definition of the variable member occurred in its 1254 // namespace. 1255 // Both of these imply that we should push a scope whose context 1256 // is the semantic context of the declaration. We can't use 1257 // PushDeclContext here because that context is not necessarily 1258 // lexically contained in the current context. Fortunately, 1259 // the containing scope should have the appropriate information. 1260 1261 assert(!S->getEntity() && "scope already has entity"); 1262 1263 #ifndef NDEBUG 1264 Scope *Ancestor = S->getParent(); 1265 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1266 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1267 #endif 1268 1269 CurContext = DC; 1270 S->setEntity(DC); 1271 } 1272 1273 void Sema::ExitDeclaratorContext(Scope *S) { 1274 assert(S->getEntity() == CurContext && "Context imbalance!"); 1275 1276 // Switch back to the lexical context. The safety of this is 1277 // enforced by an assert in EnterDeclaratorContext. 1278 Scope *Ancestor = S->getParent(); 1279 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1280 CurContext = Ancestor->getEntity(); 1281 1282 // We don't need to do anything with the scope, which is going to 1283 // disappear. 1284 } 1285 1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1287 // We assume that the caller has already called 1288 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1289 FunctionDecl *FD = D->getAsFunction(); 1290 if (!FD) 1291 return; 1292 1293 // Same implementation as PushDeclContext, but enters the context 1294 // from the lexical parent, rather than the top-level class. 1295 assert(CurContext == FD->getLexicalParent() && 1296 "The next DeclContext should be lexically contained in the current one."); 1297 CurContext = FD; 1298 S->setEntity(CurContext); 1299 1300 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1301 ParmVarDecl *Param = FD->getParamDecl(P); 1302 // If the parameter has an identifier, then add it to the scope 1303 if (Param->getIdentifier()) { 1304 S->AddDecl(Param); 1305 IdResolver.AddDecl(Param); 1306 } 1307 } 1308 } 1309 1310 void Sema::ActOnExitFunctionContext() { 1311 // Same implementation as PopDeclContext, but returns to the lexical parent, 1312 // rather than the top-level class. 1313 assert(CurContext && "DeclContext imbalance!"); 1314 CurContext = CurContext->getLexicalParent(); 1315 assert(CurContext && "Popped translation unit!"); 1316 } 1317 1318 /// Determine whether we allow overloading of the function 1319 /// PrevDecl with another declaration. 1320 /// 1321 /// This routine determines whether overloading is possible, not 1322 /// whether some new function is actually an overload. It will return 1323 /// true in C++ (where we can always provide overloads) or, as an 1324 /// extension, in C when the previous function is already an 1325 /// overloaded function declaration or has the "overloadable" 1326 /// attribute. 1327 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1328 ASTContext &Context, 1329 const FunctionDecl *New) { 1330 if (Context.getLangOpts().CPlusPlus) 1331 return true; 1332 1333 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1334 return true; 1335 1336 return Previous.getResultKind() == LookupResult::Found && 1337 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1338 New->hasAttr<OverloadableAttr>()); 1339 } 1340 1341 /// Add this decl to the scope shadowed decl chains. 1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1343 // Move up the scope chain until we find the nearest enclosing 1344 // non-transparent context. The declaration will be introduced into this 1345 // scope. 1346 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1347 S = S->getParent(); 1348 1349 // Add scoped declarations into their context, so that they can be 1350 // found later. Declarations without a context won't be inserted 1351 // into any context. 1352 if (AddToContext) 1353 CurContext->addDecl(D); 1354 1355 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1356 // are function-local declarations. 1357 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1358 !D->getDeclContext()->getRedeclContext()->Equals( 1359 D->getLexicalDeclContext()->getRedeclContext()) && 1360 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1361 return; 1362 1363 // Template instantiations should also not be pushed into scope. 1364 if (isa<FunctionDecl>(D) && 1365 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1366 return; 1367 1368 // If this replaces anything in the current scope, 1369 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1370 IEnd = IdResolver.end(); 1371 for (; I != IEnd; ++I) { 1372 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1373 S->RemoveDecl(*I); 1374 IdResolver.RemoveDecl(*I); 1375 1376 // Should only need to replace one decl. 1377 break; 1378 } 1379 } 1380 1381 S->AddDecl(D); 1382 1383 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1384 // Implicitly-generated labels may end up getting generated in an order that 1385 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1386 // the label at the appropriate place in the identifier chain. 1387 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1388 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1389 if (IDC == CurContext) { 1390 if (!S->isDeclScope(*I)) 1391 continue; 1392 } else if (IDC->Encloses(CurContext)) 1393 break; 1394 } 1395 1396 IdResolver.InsertDeclAfter(I, D); 1397 } else { 1398 IdResolver.AddDecl(D); 1399 } 1400 } 1401 1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1403 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1404 TUScope->AddDecl(D); 1405 } 1406 1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1408 bool AllowInlineNamespace) { 1409 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1410 } 1411 1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1413 DeclContext *TargetDC = DC->getPrimaryContext(); 1414 do { 1415 if (DeclContext *ScopeDC = S->getEntity()) 1416 if (ScopeDC->getPrimaryContext() == TargetDC) 1417 return S; 1418 } while ((S = S->getParent())); 1419 1420 return nullptr; 1421 } 1422 1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1424 DeclContext*, 1425 ASTContext&); 1426 1427 /// Filters out lookup results that don't fall within the given scope 1428 /// as determined by isDeclInScope. 1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1430 bool ConsiderLinkage, 1431 bool AllowInlineNamespace) { 1432 LookupResult::Filter F = R.makeFilter(); 1433 while (F.hasNext()) { 1434 NamedDecl *D = F.next(); 1435 1436 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1437 continue; 1438 1439 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1440 continue; 1441 1442 F.erase(); 1443 } 1444 1445 F.done(); 1446 } 1447 1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1449 /// have compatible owning modules. 1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1451 // FIXME: The Modules TS is not clear about how friend declarations are 1452 // to be treated. It's not meaningful to have different owning modules for 1453 // linkage in redeclarations of the same entity, so for now allow the 1454 // redeclaration and change the owning modules to match. 1455 if (New->getFriendObjectKind() && 1456 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1457 New->setLocalOwningModule(Old->getOwningModule()); 1458 makeMergedDefinitionVisible(New); 1459 return false; 1460 } 1461 1462 Module *NewM = New->getOwningModule(); 1463 Module *OldM = Old->getOwningModule(); 1464 if (NewM == OldM) 1465 return false; 1466 1467 // FIXME: Check proclaimed-ownership-declarations here too. 1468 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit; 1469 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit; 1470 if (NewIsModuleInterface || OldIsModuleInterface) { 1471 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1472 // if a declaration of D [...] appears in the purview of a module, all 1473 // other such declarations shall appear in the purview of the same module 1474 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1475 << New 1476 << NewIsModuleInterface 1477 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1478 << OldIsModuleInterface 1479 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1480 Diag(Old->getLocation(), diag::note_previous_declaration); 1481 New->setInvalidDecl(); 1482 return true; 1483 } 1484 1485 return false; 1486 } 1487 1488 static bool isUsingDecl(NamedDecl *D) { 1489 return isa<UsingShadowDecl>(D) || 1490 isa<UnresolvedUsingTypenameDecl>(D) || 1491 isa<UnresolvedUsingValueDecl>(D); 1492 } 1493 1494 /// Removes using shadow declarations from the lookup results. 1495 static void RemoveUsingDecls(LookupResult &R) { 1496 LookupResult::Filter F = R.makeFilter(); 1497 while (F.hasNext()) 1498 if (isUsingDecl(F.next())) 1499 F.erase(); 1500 1501 F.done(); 1502 } 1503 1504 /// Check for this common pattern: 1505 /// @code 1506 /// class S { 1507 /// S(const S&); // DO NOT IMPLEMENT 1508 /// void operator=(const S&); // DO NOT IMPLEMENT 1509 /// }; 1510 /// @endcode 1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1512 // FIXME: Should check for private access too but access is set after we get 1513 // the decl here. 1514 if (D->doesThisDeclarationHaveABody()) 1515 return false; 1516 1517 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1518 return CD->isCopyConstructor(); 1519 return D->isCopyAssignmentOperator(); 1520 } 1521 1522 // We need this to handle 1523 // 1524 // typedef struct { 1525 // void *foo() { return 0; } 1526 // } A; 1527 // 1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1529 // for example. If 'A', foo will have external linkage. If we have '*A', 1530 // foo will have no linkage. Since we can't know until we get to the end 1531 // of the typedef, this function finds out if D might have non-external linkage. 1532 // Callers should verify at the end of the TU if it D has external linkage or 1533 // not. 1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1535 const DeclContext *DC = D->getDeclContext(); 1536 while (!DC->isTranslationUnit()) { 1537 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1538 if (!RD->hasNameForLinkage()) 1539 return true; 1540 } 1541 DC = DC->getParent(); 1542 } 1543 1544 return !D->isExternallyVisible(); 1545 } 1546 1547 // FIXME: This needs to be refactored; some other isInMainFile users want 1548 // these semantics. 1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1550 if (S.TUKind != TU_Complete) 1551 return false; 1552 return S.SourceMgr.isInMainFile(Loc); 1553 } 1554 1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1556 assert(D); 1557 1558 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1559 return false; 1560 1561 // Ignore all entities declared within templates, and out-of-line definitions 1562 // of members of class templates. 1563 if (D->getDeclContext()->isDependentContext() || 1564 D->getLexicalDeclContext()->isDependentContext()) 1565 return false; 1566 1567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1568 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1569 return false; 1570 // A non-out-of-line declaration of a member specialization was implicitly 1571 // instantiated; it's the out-of-line declaration that we're interested in. 1572 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1573 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1574 return false; 1575 1576 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1577 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1578 return false; 1579 } else { 1580 // 'static inline' functions are defined in headers; don't warn. 1581 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1582 return false; 1583 } 1584 1585 if (FD->doesThisDeclarationHaveABody() && 1586 Context.DeclMustBeEmitted(FD)) 1587 return false; 1588 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1589 // Constants and utility variables are defined in headers with internal 1590 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1591 // like "inline".) 1592 if (!isMainFileLoc(*this, VD->getLocation())) 1593 return false; 1594 1595 if (Context.DeclMustBeEmitted(VD)) 1596 return false; 1597 1598 if (VD->isStaticDataMember() && 1599 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1600 return false; 1601 if (VD->isStaticDataMember() && 1602 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1603 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1604 return false; 1605 1606 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1607 return false; 1608 } else { 1609 return false; 1610 } 1611 1612 // Only warn for unused decls internal to the translation unit. 1613 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1614 // for inline functions defined in the main source file, for instance. 1615 return mightHaveNonExternalLinkage(D); 1616 } 1617 1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1619 if (!D) 1620 return; 1621 1622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1623 const FunctionDecl *First = FD->getFirstDecl(); 1624 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1625 return; // First should already be in the vector. 1626 } 1627 1628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1629 const VarDecl *First = VD->getFirstDecl(); 1630 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1631 return; // First should already be in the vector. 1632 } 1633 1634 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1635 UnusedFileScopedDecls.push_back(D); 1636 } 1637 1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1639 if (D->isInvalidDecl()) 1640 return false; 1641 1642 bool Referenced = false; 1643 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1644 // For a decomposition declaration, warn if none of the bindings are 1645 // referenced, instead of if the variable itself is referenced (which 1646 // it is, by the bindings' expressions). 1647 for (auto *BD : DD->bindings()) { 1648 if (BD->isReferenced()) { 1649 Referenced = true; 1650 break; 1651 } 1652 } 1653 } else if (!D->getDeclName()) { 1654 return false; 1655 } else if (D->isReferenced() || D->isUsed()) { 1656 Referenced = true; 1657 } 1658 1659 if (Referenced || D->hasAttr<UnusedAttr>() || 1660 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1661 return false; 1662 1663 if (isa<LabelDecl>(D)) 1664 return true; 1665 1666 // Except for labels, we only care about unused decls that are local to 1667 // functions. 1668 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1669 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1670 // For dependent types, the diagnostic is deferred. 1671 WithinFunction = 1672 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1673 if (!WithinFunction) 1674 return false; 1675 1676 if (isa<TypedefNameDecl>(D)) 1677 return true; 1678 1679 // White-list anything that isn't a local variable. 1680 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1681 return false; 1682 1683 // Types of valid local variables should be complete, so this should succeed. 1684 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1685 1686 // White-list anything with an __attribute__((unused)) type. 1687 const auto *Ty = VD->getType().getTypePtr(); 1688 1689 // Only look at the outermost level of typedef. 1690 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1691 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1692 return false; 1693 } 1694 1695 // If we failed to complete the type for some reason, or if the type is 1696 // dependent, don't diagnose the variable. 1697 if (Ty->isIncompleteType() || Ty->isDependentType()) 1698 return false; 1699 1700 // Look at the element type to ensure that the warning behaviour is 1701 // consistent for both scalars and arrays. 1702 Ty = Ty->getBaseElementTypeUnsafe(); 1703 1704 if (const TagType *TT = Ty->getAs<TagType>()) { 1705 const TagDecl *Tag = TT->getDecl(); 1706 if (Tag->hasAttr<UnusedAttr>()) 1707 return false; 1708 1709 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1710 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1711 return false; 1712 1713 if (const Expr *Init = VD->getInit()) { 1714 if (const ExprWithCleanups *Cleanups = 1715 dyn_cast<ExprWithCleanups>(Init)) 1716 Init = Cleanups->getSubExpr(); 1717 const CXXConstructExpr *Construct = 1718 dyn_cast<CXXConstructExpr>(Init); 1719 if (Construct && !Construct->isElidable()) { 1720 CXXConstructorDecl *CD = Construct->getConstructor(); 1721 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1722 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1723 return false; 1724 } 1725 } 1726 } 1727 } 1728 1729 // TODO: __attribute__((unused)) templates? 1730 } 1731 1732 return true; 1733 } 1734 1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1736 FixItHint &Hint) { 1737 if (isa<LabelDecl>(D)) { 1738 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1739 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1740 true); 1741 if (AfterColon.isInvalid()) 1742 return; 1743 Hint = FixItHint::CreateRemoval( 1744 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1745 } 1746 } 1747 1748 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1749 if (D->getTypeForDecl()->isDependentType()) 1750 return; 1751 1752 for (auto *TmpD : D->decls()) { 1753 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1754 DiagnoseUnusedDecl(T); 1755 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1756 DiagnoseUnusedNestedTypedefs(R); 1757 } 1758 } 1759 1760 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1761 /// unless they are marked attr(unused). 1762 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1763 if (!ShouldDiagnoseUnusedDecl(D)) 1764 return; 1765 1766 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1767 // typedefs can be referenced later on, so the diagnostics are emitted 1768 // at end-of-translation-unit. 1769 UnusedLocalTypedefNameCandidates.insert(TD); 1770 return; 1771 } 1772 1773 FixItHint Hint; 1774 GenerateFixForUnusedDecl(D, Context, Hint); 1775 1776 unsigned DiagID; 1777 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1778 DiagID = diag::warn_unused_exception_param; 1779 else if (isa<LabelDecl>(D)) 1780 DiagID = diag::warn_unused_label; 1781 else 1782 DiagID = diag::warn_unused_variable; 1783 1784 Diag(D->getLocation(), DiagID) << D << Hint; 1785 } 1786 1787 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1788 // Verify that we have no forward references left. If so, there was a goto 1789 // or address of a label taken, but no definition of it. Label fwd 1790 // definitions are indicated with a null substmt which is also not a resolved 1791 // MS inline assembly label name. 1792 bool Diagnose = false; 1793 if (L->isMSAsmLabel()) 1794 Diagnose = !L->isResolvedMSAsmLabel(); 1795 else 1796 Diagnose = L->getStmt() == nullptr; 1797 if (Diagnose) 1798 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1799 } 1800 1801 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1802 S->mergeNRVOIntoParent(); 1803 1804 if (S->decl_empty()) return; 1805 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1806 "Scope shouldn't contain decls!"); 1807 1808 for (auto *TmpD : S->decls()) { 1809 assert(TmpD && "This decl didn't get pushed??"); 1810 1811 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1812 NamedDecl *D = cast<NamedDecl>(TmpD); 1813 1814 // Diagnose unused variables in this scope. 1815 if (!S->hasUnrecoverableErrorOccurred()) { 1816 DiagnoseUnusedDecl(D); 1817 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1818 DiagnoseUnusedNestedTypedefs(RD); 1819 } 1820 1821 if (!D->getDeclName()) continue; 1822 1823 // If this was a forward reference to a label, verify it was defined. 1824 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1825 CheckPoppedLabel(LD, *this); 1826 1827 // Remove this name from our lexical scope, and warn on it if we haven't 1828 // already. 1829 IdResolver.RemoveDecl(D); 1830 auto ShadowI = ShadowingDecls.find(D); 1831 if (ShadowI != ShadowingDecls.end()) { 1832 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1833 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1834 << D << FD << FD->getParent(); 1835 Diag(FD->getLocation(), diag::note_previous_declaration); 1836 } 1837 ShadowingDecls.erase(ShadowI); 1838 } 1839 } 1840 } 1841 1842 /// Look for an Objective-C class in the translation unit. 1843 /// 1844 /// \param Id The name of the Objective-C class we're looking for. If 1845 /// typo-correction fixes this name, the Id will be updated 1846 /// to the fixed name. 1847 /// 1848 /// \param IdLoc The location of the name in the translation unit. 1849 /// 1850 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1851 /// if there is no class with the given name. 1852 /// 1853 /// \returns The declaration of the named Objective-C class, or NULL if the 1854 /// class could not be found. 1855 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1856 SourceLocation IdLoc, 1857 bool DoTypoCorrection) { 1858 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1859 // creation from this context. 1860 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1861 1862 if (!IDecl && DoTypoCorrection) { 1863 // Perform typo correction at the given location, but only if we 1864 // find an Objective-C class name. 1865 if (TypoCorrection C = CorrectTypo( 1866 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1867 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1868 CTK_ErrorRecovery)) { 1869 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1870 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1871 Id = IDecl->getIdentifier(); 1872 } 1873 } 1874 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1875 // This routine must always return a class definition, if any. 1876 if (Def && Def->getDefinition()) 1877 Def = Def->getDefinition(); 1878 return Def; 1879 } 1880 1881 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1882 /// from S, where a non-field would be declared. This routine copes 1883 /// with the difference between C and C++ scoping rules in structs and 1884 /// unions. For example, the following code is well-formed in C but 1885 /// ill-formed in C++: 1886 /// @code 1887 /// struct S6 { 1888 /// enum { BAR } e; 1889 /// }; 1890 /// 1891 /// void test_S6() { 1892 /// struct S6 a; 1893 /// a.e = BAR; 1894 /// } 1895 /// @endcode 1896 /// For the declaration of BAR, this routine will return a different 1897 /// scope. The scope S will be the scope of the unnamed enumeration 1898 /// within S6. In C++, this routine will return the scope associated 1899 /// with S6, because the enumeration's scope is a transparent 1900 /// context but structures can contain non-field names. In C, this 1901 /// routine will return the translation unit scope, since the 1902 /// enumeration's scope is a transparent context and structures cannot 1903 /// contain non-field names. 1904 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1905 while (((S->getFlags() & Scope::DeclScope) == 0) || 1906 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1907 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1908 S = S->getParent(); 1909 return S; 1910 } 1911 1912 /// Looks up the declaration of "struct objc_super" and 1913 /// saves it for later use in building builtin declaration of 1914 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1915 /// pre-existing declaration exists no action takes place. 1916 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1917 IdentifierInfo *II) { 1918 if (!II->isStr("objc_msgSendSuper")) 1919 return; 1920 ASTContext &Context = ThisSema.Context; 1921 1922 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1923 SourceLocation(), Sema::LookupTagName); 1924 ThisSema.LookupName(Result, S); 1925 if (Result.getResultKind() == LookupResult::Found) 1926 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1927 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1928 } 1929 1930 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1931 switch (Error) { 1932 case ASTContext::GE_None: 1933 return ""; 1934 case ASTContext::GE_Missing_stdio: 1935 return "stdio.h"; 1936 case ASTContext::GE_Missing_setjmp: 1937 return "setjmp.h"; 1938 case ASTContext::GE_Missing_ucontext: 1939 return "ucontext.h"; 1940 } 1941 llvm_unreachable("unhandled error kind"); 1942 } 1943 1944 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1945 /// file scope. lazily create a decl for it. ForRedeclaration is true 1946 /// if we're creating this built-in in anticipation of redeclaring the 1947 /// built-in. 1948 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1949 Scope *S, bool ForRedeclaration, 1950 SourceLocation Loc) { 1951 LookupPredefedObjCSuperType(*this, S, II); 1952 1953 ASTContext::GetBuiltinTypeError Error; 1954 QualType R = Context.GetBuiltinType(ID, Error); 1955 if (Error) { 1956 if (ForRedeclaration) 1957 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1958 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1959 return nullptr; 1960 } 1961 1962 if (!ForRedeclaration && 1963 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1964 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1965 Diag(Loc, diag::ext_implicit_lib_function_decl) 1966 << Context.BuiltinInfo.getName(ID) << R; 1967 if (Context.BuiltinInfo.getHeaderName(ID) && 1968 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1969 Diag(Loc, diag::note_include_header_or_declare) 1970 << Context.BuiltinInfo.getHeaderName(ID) 1971 << Context.BuiltinInfo.getName(ID); 1972 } 1973 1974 if (R.isNull()) 1975 return nullptr; 1976 1977 DeclContext *Parent = Context.getTranslationUnitDecl(); 1978 if (getLangOpts().CPlusPlus) { 1979 LinkageSpecDecl *CLinkageDecl = 1980 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1981 LinkageSpecDecl::lang_c, false); 1982 CLinkageDecl->setImplicit(); 1983 Parent->addDecl(CLinkageDecl); 1984 Parent = CLinkageDecl; 1985 } 1986 1987 FunctionDecl *New = FunctionDecl::Create(Context, 1988 Parent, 1989 Loc, Loc, II, R, /*TInfo=*/nullptr, 1990 SC_Extern, 1991 false, 1992 R->isFunctionProtoType()); 1993 New->setImplicit(); 1994 1995 // Create Decl objects for each parameter, adding them to the 1996 // FunctionDecl. 1997 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1998 SmallVector<ParmVarDecl*, 16> Params; 1999 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2000 ParmVarDecl *parm = 2001 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2002 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2003 SC_None, nullptr); 2004 parm->setScopeInfo(0, i); 2005 Params.push_back(parm); 2006 } 2007 New->setParams(Params); 2008 } 2009 2010 AddKnownFunctionAttributes(New); 2011 RegisterLocallyScopedExternCDecl(New, S); 2012 2013 // TUScope is the translation-unit scope to insert this function into. 2014 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2015 // relate Scopes to DeclContexts, and probably eliminate CurContext 2016 // entirely, but we're not there yet. 2017 DeclContext *SavedContext = CurContext; 2018 CurContext = Parent; 2019 PushOnScopeChains(New, TUScope); 2020 CurContext = SavedContext; 2021 return New; 2022 } 2023 2024 /// Typedef declarations don't have linkage, but they still denote the same 2025 /// entity if their types are the same. 2026 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2027 /// isSameEntity. 2028 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2029 TypedefNameDecl *Decl, 2030 LookupResult &Previous) { 2031 // This is only interesting when modules are enabled. 2032 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2033 return; 2034 2035 // Empty sets are uninteresting. 2036 if (Previous.empty()) 2037 return; 2038 2039 LookupResult::Filter Filter = Previous.makeFilter(); 2040 while (Filter.hasNext()) { 2041 NamedDecl *Old = Filter.next(); 2042 2043 // Non-hidden declarations are never ignored. 2044 if (S.isVisible(Old)) 2045 continue; 2046 2047 // Declarations of the same entity are not ignored, even if they have 2048 // different linkages. 2049 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2050 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2051 Decl->getUnderlyingType())) 2052 continue; 2053 2054 // If both declarations give a tag declaration a typedef name for linkage 2055 // purposes, then they declare the same entity. 2056 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2057 Decl->getAnonDeclWithTypedefName()) 2058 continue; 2059 } 2060 2061 Filter.erase(); 2062 } 2063 2064 Filter.done(); 2065 } 2066 2067 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2068 QualType OldType; 2069 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2070 OldType = OldTypedef->getUnderlyingType(); 2071 else 2072 OldType = Context.getTypeDeclType(Old); 2073 QualType NewType = New->getUnderlyingType(); 2074 2075 if (NewType->isVariablyModifiedType()) { 2076 // Must not redefine a typedef with a variably-modified type. 2077 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2078 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2079 << Kind << NewType; 2080 if (Old->getLocation().isValid()) 2081 notePreviousDefinition(Old, New->getLocation()); 2082 New->setInvalidDecl(); 2083 return true; 2084 } 2085 2086 if (OldType != NewType && 2087 !OldType->isDependentType() && 2088 !NewType->isDependentType() && 2089 !Context.hasSameType(OldType, NewType)) { 2090 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2091 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2092 << Kind << NewType << OldType; 2093 if (Old->getLocation().isValid()) 2094 notePreviousDefinition(Old, New->getLocation()); 2095 New->setInvalidDecl(); 2096 return true; 2097 } 2098 return false; 2099 } 2100 2101 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2102 /// same name and scope as a previous declaration 'Old'. Figure out 2103 /// how to resolve this situation, merging decls or emitting 2104 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2105 /// 2106 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2107 LookupResult &OldDecls) { 2108 // If the new decl is known invalid already, don't bother doing any 2109 // merging checks. 2110 if (New->isInvalidDecl()) return; 2111 2112 // Allow multiple definitions for ObjC built-in typedefs. 2113 // FIXME: Verify the underlying types are equivalent! 2114 if (getLangOpts().ObjC) { 2115 const IdentifierInfo *TypeID = New->getIdentifier(); 2116 switch (TypeID->getLength()) { 2117 default: break; 2118 case 2: 2119 { 2120 if (!TypeID->isStr("id")) 2121 break; 2122 QualType T = New->getUnderlyingType(); 2123 if (!T->isPointerType()) 2124 break; 2125 if (!T->isVoidPointerType()) { 2126 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2127 if (!PT->isStructureType()) 2128 break; 2129 } 2130 Context.setObjCIdRedefinitionType(T); 2131 // Install the built-in type for 'id', ignoring the current definition. 2132 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2133 return; 2134 } 2135 case 5: 2136 if (!TypeID->isStr("Class")) 2137 break; 2138 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2139 // Install the built-in type for 'Class', ignoring the current definition. 2140 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2141 return; 2142 case 3: 2143 if (!TypeID->isStr("SEL")) 2144 break; 2145 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2146 // Install the built-in type for 'SEL', ignoring the current definition. 2147 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2148 return; 2149 } 2150 // Fall through - the typedef name was not a builtin type. 2151 } 2152 2153 // Verify the old decl was also a type. 2154 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2155 if (!Old) { 2156 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2157 << New->getDeclName(); 2158 2159 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2160 if (OldD->getLocation().isValid()) 2161 notePreviousDefinition(OldD, New->getLocation()); 2162 2163 return New->setInvalidDecl(); 2164 } 2165 2166 // If the old declaration is invalid, just give up here. 2167 if (Old->isInvalidDecl()) 2168 return New->setInvalidDecl(); 2169 2170 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2171 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2172 auto *NewTag = New->getAnonDeclWithTypedefName(); 2173 NamedDecl *Hidden = nullptr; 2174 if (OldTag && NewTag && 2175 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2176 !hasVisibleDefinition(OldTag, &Hidden)) { 2177 // There is a definition of this tag, but it is not visible. Use it 2178 // instead of our tag. 2179 New->setTypeForDecl(OldTD->getTypeForDecl()); 2180 if (OldTD->isModed()) 2181 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2182 OldTD->getUnderlyingType()); 2183 else 2184 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2185 2186 // Make the old tag definition visible. 2187 makeMergedDefinitionVisible(Hidden); 2188 2189 // If this was an unscoped enumeration, yank all of its enumerators 2190 // out of the scope. 2191 if (isa<EnumDecl>(NewTag)) { 2192 Scope *EnumScope = getNonFieldDeclScope(S); 2193 for (auto *D : NewTag->decls()) { 2194 auto *ED = cast<EnumConstantDecl>(D); 2195 assert(EnumScope->isDeclScope(ED)); 2196 EnumScope->RemoveDecl(ED); 2197 IdResolver.RemoveDecl(ED); 2198 ED->getLexicalDeclContext()->removeDecl(ED); 2199 } 2200 } 2201 } 2202 } 2203 2204 // If the typedef types are not identical, reject them in all languages and 2205 // with any extensions enabled. 2206 if (isIncompatibleTypedef(Old, New)) 2207 return; 2208 2209 // The types match. Link up the redeclaration chain and merge attributes if 2210 // the old declaration was a typedef. 2211 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2212 New->setPreviousDecl(Typedef); 2213 mergeDeclAttributes(New, Old); 2214 } 2215 2216 if (getLangOpts().MicrosoftExt) 2217 return; 2218 2219 if (getLangOpts().CPlusPlus) { 2220 // C++ [dcl.typedef]p2: 2221 // In a given non-class scope, a typedef specifier can be used to 2222 // redefine the name of any type declared in that scope to refer 2223 // to the type to which it already refers. 2224 if (!isa<CXXRecordDecl>(CurContext)) 2225 return; 2226 2227 // C++0x [dcl.typedef]p4: 2228 // In a given class scope, a typedef specifier can be used to redefine 2229 // any class-name declared in that scope that is not also a typedef-name 2230 // to refer to the type to which it already refers. 2231 // 2232 // This wording came in via DR424, which was a correction to the 2233 // wording in DR56, which accidentally banned code like: 2234 // 2235 // struct S { 2236 // typedef struct A { } A; 2237 // }; 2238 // 2239 // in the C++03 standard. We implement the C++0x semantics, which 2240 // allow the above but disallow 2241 // 2242 // struct S { 2243 // typedef int I; 2244 // typedef int I; 2245 // }; 2246 // 2247 // since that was the intent of DR56. 2248 if (!isa<TypedefNameDecl>(Old)) 2249 return; 2250 2251 Diag(New->getLocation(), diag::err_redefinition) 2252 << New->getDeclName(); 2253 notePreviousDefinition(Old, New->getLocation()); 2254 return New->setInvalidDecl(); 2255 } 2256 2257 // Modules always permit redefinition of typedefs, as does C11. 2258 if (getLangOpts().Modules || getLangOpts().C11) 2259 return; 2260 2261 // If we have a redefinition of a typedef in C, emit a warning. This warning 2262 // is normally mapped to an error, but can be controlled with 2263 // -Wtypedef-redefinition. If either the original or the redefinition is 2264 // in a system header, don't emit this for compatibility with GCC. 2265 if (getDiagnostics().getSuppressSystemWarnings() && 2266 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2267 (Old->isImplicit() || 2268 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2269 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2270 return; 2271 2272 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2273 << New->getDeclName(); 2274 notePreviousDefinition(Old, New->getLocation()); 2275 } 2276 2277 /// DeclhasAttr - returns true if decl Declaration already has the target 2278 /// attribute. 2279 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2280 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2281 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2282 for (const auto *i : D->attrs()) 2283 if (i->getKind() == A->getKind()) { 2284 if (Ann) { 2285 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2286 return true; 2287 continue; 2288 } 2289 // FIXME: Don't hardcode this check 2290 if (OA && isa<OwnershipAttr>(i)) 2291 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2292 return true; 2293 } 2294 2295 return false; 2296 } 2297 2298 static bool isAttributeTargetADefinition(Decl *D) { 2299 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2300 return VD->isThisDeclarationADefinition(); 2301 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2302 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2303 return true; 2304 } 2305 2306 /// Merge alignment attributes from \p Old to \p New, taking into account the 2307 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2308 /// 2309 /// \return \c true if any attributes were added to \p New. 2310 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2311 // Look for alignas attributes on Old, and pick out whichever attribute 2312 // specifies the strictest alignment requirement. 2313 AlignedAttr *OldAlignasAttr = nullptr; 2314 AlignedAttr *OldStrictestAlignAttr = nullptr; 2315 unsigned OldAlign = 0; 2316 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2317 // FIXME: We have no way of representing inherited dependent alignments 2318 // in a case like: 2319 // template<int A, int B> struct alignas(A) X; 2320 // template<int A, int B> struct alignas(B) X {}; 2321 // For now, we just ignore any alignas attributes which are not on the 2322 // definition in such a case. 2323 if (I->isAlignmentDependent()) 2324 return false; 2325 2326 if (I->isAlignas()) 2327 OldAlignasAttr = I; 2328 2329 unsigned Align = I->getAlignment(S.Context); 2330 if (Align > OldAlign) { 2331 OldAlign = Align; 2332 OldStrictestAlignAttr = I; 2333 } 2334 } 2335 2336 // Look for alignas attributes on New. 2337 AlignedAttr *NewAlignasAttr = nullptr; 2338 unsigned NewAlign = 0; 2339 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2340 if (I->isAlignmentDependent()) 2341 return false; 2342 2343 if (I->isAlignas()) 2344 NewAlignasAttr = I; 2345 2346 unsigned Align = I->getAlignment(S.Context); 2347 if (Align > NewAlign) 2348 NewAlign = Align; 2349 } 2350 2351 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2352 // Both declarations have 'alignas' attributes. We require them to match. 2353 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2354 // fall short. (If two declarations both have alignas, they must both match 2355 // every definition, and so must match each other if there is a definition.) 2356 2357 // If either declaration only contains 'alignas(0)' specifiers, then it 2358 // specifies the natural alignment for the type. 2359 if (OldAlign == 0 || NewAlign == 0) { 2360 QualType Ty; 2361 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2362 Ty = VD->getType(); 2363 else 2364 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2365 2366 if (OldAlign == 0) 2367 OldAlign = S.Context.getTypeAlign(Ty); 2368 if (NewAlign == 0) 2369 NewAlign = S.Context.getTypeAlign(Ty); 2370 } 2371 2372 if (OldAlign != NewAlign) { 2373 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2374 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2375 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2376 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2377 } 2378 } 2379 2380 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2381 // C++11 [dcl.align]p6: 2382 // if any declaration of an entity has an alignment-specifier, 2383 // every defining declaration of that entity shall specify an 2384 // equivalent alignment. 2385 // C11 6.7.5/7: 2386 // If the definition of an object does not have an alignment 2387 // specifier, any other declaration of that object shall also 2388 // have no alignment specifier. 2389 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2390 << OldAlignasAttr; 2391 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2392 << OldAlignasAttr; 2393 } 2394 2395 bool AnyAdded = false; 2396 2397 // Ensure we have an attribute representing the strictest alignment. 2398 if (OldAlign > NewAlign) { 2399 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2400 Clone->setInherited(true); 2401 New->addAttr(Clone); 2402 AnyAdded = true; 2403 } 2404 2405 // Ensure we have an alignas attribute if the old declaration had one. 2406 if (OldAlignasAttr && !NewAlignasAttr && 2407 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2408 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2409 Clone->setInherited(true); 2410 New->addAttr(Clone); 2411 AnyAdded = true; 2412 } 2413 2414 return AnyAdded; 2415 } 2416 2417 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2418 const InheritableAttr *Attr, 2419 Sema::AvailabilityMergeKind AMK) { 2420 // This function copies an attribute Attr from a previous declaration to the 2421 // new declaration D if the new declaration doesn't itself have that attribute 2422 // yet or if that attribute allows duplicates. 2423 // If you're adding a new attribute that requires logic different from 2424 // "use explicit attribute on decl if present, else use attribute from 2425 // previous decl", for example if the attribute needs to be consistent 2426 // between redeclarations, you need to call a custom merge function here. 2427 InheritableAttr *NewAttr = nullptr; 2428 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2429 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2430 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2431 AA->isImplicit(), AA->getIntroduced(), 2432 AA->getDeprecated(), 2433 AA->getObsoleted(), AA->getUnavailable(), 2434 AA->getMessage(), AA->getStrict(), 2435 AA->getReplacement(), AMK, 2436 AttrSpellingListIndex); 2437 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2438 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2439 AttrSpellingListIndex); 2440 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2441 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2442 AttrSpellingListIndex); 2443 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2444 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2445 AttrSpellingListIndex); 2446 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2447 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2448 AttrSpellingListIndex); 2449 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2450 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2451 FA->getFormatIdx(), FA->getFirstArg(), 2452 AttrSpellingListIndex); 2453 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2454 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2455 AttrSpellingListIndex); 2456 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2457 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(), 2458 AttrSpellingListIndex); 2459 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2460 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2461 AttrSpellingListIndex, 2462 IA->getSemanticSpelling()); 2463 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2464 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2465 &S.Context.Idents.get(AA->getSpelling()), 2466 AttrSpellingListIndex); 2467 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2468 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2469 isa<CUDAGlobalAttr>(Attr))) { 2470 // CUDA target attributes are part of function signature for 2471 // overloading purposes and must not be merged. 2472 return false; 2473 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2474 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2475 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2476 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2477 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2478 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2479 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2480 NewAttr = S.mergeCommonAttr(D, *CommonA); 2481 else if (isa<AlignedAttr>(Attr)) 2482 // AlignedAttrs are handled separately, because we need to handle all 2483 // such attributes on a declaration at the same time. 2484 NewAttr = nullptr; 2485 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2486 (AMK == Sema::AMK_Override || 2487 AMK == Sema::AMK_ProtocolImplementation)) 2488 NewAttr = nullptr; 2489 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2490 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2491 UA->getGuid()); 2492 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2493 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2494 2495 if (NewAttr) { 2496 NewAttr->setInherited(true); 2497 D->addAttr(NewAttr); 2498 if (isa<MSInheritanceAttr>(NewAttr)) 2499 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2500 return true; 2501 } 2502 2503 return false; 2504 } 2505 2506 static const NamedDecl *getDefinition(const Decl *D) { 2507 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2508 return TD->getDefinition(); 2509 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2510 const VarDecl *Def = VD->getDefinition(); 2511 if (Def) 2512 return Def; 2513 return VD->getActingDefinition(); 2514 } 2515 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2516 return FD->getDefinition(); 2517 return nullptr; 2518 } 2519 2520 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2521 for (const auto *Attribute : D->attrs()) 2522 if (Attribute->getKind() == Kind) 2523 return true; 2524 return false; 2525 } 2526 2527 /// checkNewAttributesAfterDef - If we already have a definition, check that 2528 /// there are no new attributes in this declaration. 2529 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2530 if (!New->hasAttrs()) 2531 return; 2532 2533 const NamedDecl *Def = getDefinition(Old); 2534 if (!Def || Def == New) 2535 return; 2536 2537 AttrVec &NewAttributes = New->getAttrs(); 2538 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2539 const Attr *NewAttribute = NewAttributes[I]; 2540 2541 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2542 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2543 Sema::SkipBodyInfo SkipBody; 2544 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2545 2546 // If we're skipping this definition, drop the "alias" attribute. 2547 if (SkipBody.ShouldSkip) { 2548 NewAttributes.erase(NewAttributes.begin() + I); 2549 --E; 2550 continue; 2551 } 2552 } else { 2553 VarDecl *VD = cast<VarDecl>(New); 2554 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2555 VarDecl::TentativeDefinition 2556 ? diag::err_alias_after_tentative 2557 : diag::err_redefinition; 2558 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2559 if (Diag == diag::err_redefinition) 2560 S.notePreviousDefinition(Def, VD->getLocation()); 2561 else 2562 S.Diag(Def->getLocation(), diag::note_previous_definition); 2563 VD->setInvalidDecl(); 2564 } 2565 ++I; 2566 continue; 2567 } 2568 2569 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2570 // Tentative definitions are only interesting for the alias check above. 2571 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2572 ++I; 2573 continue; 2574 } 2575 } 2576 2577 if (hasAttribute(Def, NewAttribute->getKind())) { 2578 ++I; 2579 continue; // regular attr merging will take care of validating this. 2580 } 2581 2582 if (isa<C11NoReturnAttr>(NewAttribute)) { 2583 // C's _Noreturn is allowed to be added to a function after it is defined. 2584 ++I; 2585 continue; 2586 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2587 if (AA->isAlignas()) { 2588 // C++11 [dcl.align]p6: 2589 // if any declaration of an entity has an alignment-specifier, 2590 // every defining declaration of that entity shall specify an 2591 // equivalent alignment. 2592 // C11 6.7.5/7: 2593 // If the definition of an object does not have an alignment 2594 // specifier, any other declaration of that object shall also 2595 // have no alignment specifier. 2596 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2597 << AA; 2598 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2599 << AA; 2600 NewAttributes.erase(NewAttributes.begin() + I); 2601 --E; 2602 continue; 2603 } 2604 } 2605 2606 S.Diag(NewAttribute->getLocation(), 2607 diag::warn_attribute_precede_definition); 2608 S.Diag(Def->getLocation(), diag::note_previous_definition); 2609 NewAttributes.erase(NewAttributes.begin() + I); 2610 --E; 2611 } 2612 } 2613 2614 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2615 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2616 AvailabilityMergeKind AMK) { 2617 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2618 UsedAttr *NewAttr = OldAttr->clone(Context); 2619 NewAttr->setInherited(true); 2620 New->addAttr(NewAttr); 2621 } 2622 2623 if (!Old->hasAttrs() && !New->hasAttrs()) 2624 return; 2625 2626 // Attributes declared post-definition are currently ignored. 2627 checkNewAttributesAfterDef(*this, New, Old); 2628 2629 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2630 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2631 if (OldA->getLabel() != NewA->getLabel()) { 2632 // This redeclaration changes __asm__ label. 2633 Diag(New->getLocation(), diag::err_different_asm_label); 2634 Diag(OldA->getLocation(), diag::note_previous_declaration); 2635 } 2636 } else if (Old->isUsed()) { 2637 // This redeclaration adds an __asm__ label to a declaration that has 2638 // already been ODR-used. 2639 Diag(New->getLocation(), diag::err_late_asm_label_name) 2640 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2641 } 2642 } 2643 2644 // Re-declaration cannot add abi_tag's. 2645 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2646 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2647 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2648 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2649 NewTag) == OldAbiTagAttr->tags_end()) { 2650 Diag(NewAbiTagAttr->getLocation(), 2651 diag::err_new_abi_tag_on_redeclaration) 2652 << NewTag; 2653 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2654 } 2655 } 2656 } else { 2657 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2658 Diag(Old->getLocation(), diag::note_previous_declaration); 2659 } 2660 } 2661 2662 // This redeclaration adds a section attribute. 2663 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2664 if (auto *VD = dyn_cast<VarDecl>(New)) { 2665 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2666 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2667 Diag(Old->getLocation(), diag::note_previous_declaration); 2668 } 2669 } 2670 } 2671 2672 // Redeclaration adds code-seg attribute. 2673 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2674 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2675 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2676 Diag(New->getLocation(), diag::warn_mismatched_section) 2677 << 0 /*codeseg*/; 2678 Diag(Old->getLocation(), diag::note_previous_declaration); 2679 } 2680 2681 if (!Old->hasAttrs()) 2682 return; 2683 2684 bool foundAny = New->hasAttrs(); 2685 2686 // Ensure that any moving of objects within the allocated map is done before 2687 // we process them. 2688 if (!foundAny) New->setAttrs(AttrVec()); 2689 2690 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2691 // Ignore deprecated/unavailable/availability attributes if requested. 2692 AvailabilityMergeKind LocalAMK = AMK_None; 2693 if (isa<DeprecatedAttr>(I) || 2694 isa<UnavailableAttr>(I) || 2695 isa<AvailabilityAttr>(I)) { 2696 switch (AMK) { 2697 case AMK_None: 2698 continue; 2699 2700 case AMK_Redeclaration: 2701 case AMK_Override: 2702 case AMK_ProtocolImplementation: 2703 LocalAMK = AMK; 2704 break; 2705 } 2706 } 2707 2708 // Already handled. 2709 if (isa<UsedAttr>(I)) 2710 continue; 2711 2712 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2713 foundAny = true; 2714 } 2715 2716 if (mergeAlignedAttrs(*this, New, Old)) 2717 foundAny = true; 2718 2719 if (!foundAny) New->dropAttrs(); 2720 } 2721 2722 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2723 /// to the new one. 2724 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2725 const ParmVarDecl *oldDecl, 2726 Sema &S) { 2727 // C++11 [dcl.attr.depend]p2: 2728 // The first declaration of a function shall specify the 2729 // carries_dependency attribute for its declarator-id if any declaration 2730 // of the function specifies the carries_dependency attribute. 2731 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2732 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2733 S.Diag(CDA->getLocation(), 2734 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2735 // Find the first declaration of the parameter. 2736 // FIXME: Should we build redeclaration chains for function parameters? 2737 const FunctionDecl *FirstFD = 2738 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2739 const ParmVarDecl *FirstVD = 2740 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2741 S.Diag(FirstVD->getLocation(), 2742 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2743 } 2744 2745 if (!oldDecl->hasAttrs()) 2746 return; 2747 2748 bool foundAny = newDecl->hasAttrs(); 2749 2750 // Ensure that any moving of objects within the allocated map is 2751 // done before we process them. 2752 if (!foundAny) newDecl->setAttrs(AttrVec()); 2753 2754 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2755 if (!DeclHasAttr(newDecl, I)) { 2756 InheritableAttr *newAttr = 2757 cast<InheritableParamAttr>(I->clone(S.Context)); 2758 newAttr->setInherited(true); 2759 newDecl->addAttr(newAttr); 2760 foundAny = true; 2761 } 2762 } 2763 2764 if (!foundAny) newDecl->dropAttrs(); 2765 } 2766 2767 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2768 const ParmVarDecl *OldParam, 2769 Sema &S) { 2770 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2771 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2772 if (*Oldnullability != *Newnullability) { 2773 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2774 << DiagNullabilityKind( 2775 *Newnullability, 2776 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2777 != 0)) 2778 << DiagNullabilityKind( 2779 *Oldnullability, 2780 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2781 != 0)); 2782 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2783 } 2784 } else { 2785 QualType NewT = NewParam->getType(); 2786 NewT = S.Context.getAttributedType( 2787 AttributedType::getNullabilityAttrKind(*Oldnullability), 2788 NewT, NewT); 2789 NewParam->setType(NewT); 2790 } 2791 } 2792 } 2793 2794 namespace { 2795 2796 /// Used in MergeFunctionDecl to keep track of function parameters in 2797 /// C. 2798 struct GNUCompatibleParamWarning { 2799 ParmVarDecl *OldParm; 2800 ParmVarDecl *NewParm; 2801 QualType PromotedType; 2802 }; 2803 2804 } // end anonymous namespace 2805 2806 /// getSpecialMember - get the special member enum for a method. 2807 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2808 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2809 if (Ctor->isDefaultConstructor()) 2810 return Sema::CXXDefaultConstructor; 2811 2812 if (Ctor->isCopyConstructor()) 2813 return Sema::CXXCopyConstructor; 2814 2815 if (Ctor->isMoveConstructor()) 2816 return Sema::CXXMoveConstructor; 2817 } else if (isa<CXXDestructorDecl>(MD)) { 2818 return Sema::CXXDestructor; 2819 } else if (MD->isCopyAssignmentOperator()) { 2820 return Sema::CXXCopyAssignment; 2821 } else if (MD->isMoveAssignmentOperator()) { 2822 return Sema::CXXMoveAssignment; 2823 } 2824 2825 return Sema::CXXInvalid; 2826 } 2827 2828 // Determine whether the previous declaration was a definition, implicit 2829 // declaration, or a declaration. 2830 template <typename T> 2831 static std::pair<diag::kind, SourceLocation> 2832 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2833 diag::kind PrevDiag; 2834 SourceLocation OldLocation = Old->getLocation(); 2835 if (Old->isThisDeclarationADefinition()) 2836 PrevDiag = diag::note_previous_definition; 2837 else if (Old->isImplicit()) { 2838 PrevDiag = diag::note_previous_implicit_declaration; 2839 if (OldLocation.isInvalid()) 2840 OldLocation = New->getLocation(); 2841 } else 2842 PrevDiag = diag::note_previous_declaration; 2843 return std::make_pair(PrevDiag, OldLocation); 2844 } 2845 2846 /// canRedefineFunction - checks if a function can be redefined. Currently, 2847 /// only extern inline functions can be redefined, and even then only in 2848 /// GNU89 mode. 2849 static bool canRedefineFunction(const FunctionDecl *FD, 2850 const LangOptions& LangOpts) { 2851 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2852 !LangOpts.CPlusPlus && 2853 FD->isInlineSpecified() && 2854 FD->getStorageClass() == SC_Extern); 2855 } 2856 2857 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2858 const AttributedType *AT = T->getAs<AttributedType>(); 2859 while (AT && !AT->isCallingConv()) 2860 AT = AT->getModifiedType()->getAs<AttributedType>(); 2861 return AT; 2862 } 2863 2864 template <typename T> 2865 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2866 const DeclContext *DC = Old->getDeclContext(); 2867 if (DC->isRecord()) 2868 return false; 2869 2870 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2871 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2872 return true; 2873 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2874 return true; 2875 return false; 2876 } 2877 2878 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2879 static bool isExternC(VarTemplateDecl *) { return false; } 2880 2881 /// Check whether a redeclaration of an entity introduced by a 2882 /// using-declaration is valid, given that we know it's not an overload 2883 /// (nor a hidden tag declaration). 2884 template<typename ExpectedDecl> 2885 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2886 ExpectedDecl *New) { 2887 // C++11 [basic.scope.declarative]p4: 2888 // Given a set of declarations in a single declarative region, each of 2889 // which specifies the same unqualified name, 2890 // -- they shall all refer to the same entity, or all refer to functions 2891 // and function templates; or 2892 // -- exactly one declaration shall declare a class name or enumeration 2893 // name that is not a typedef name and the other declarations shall all 2894 // refer to the same variable or enumerator, or all refer to functions 2895 // and function templates; in this case the class name or enumeration 2896 // name is hidden (3.3.10). 2897 2898 // C++11 [namespace.udecl]p14: 2899 // If a function declaration in namespace scope or block scope has the 2900 // same name and the same parameter-type-list as a function introduced 2901 // by a using-declaration, and the declarations do not declare the same 2902 // function, the program is ill-formed. 2903 2904 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2905 if (Old && 2906 !Old->getDeclContext()->getRedeclContext()->Equals( 2907 New->getDeclContext()->getRedeclContext()) && 2908 !(isExternC(Old) && isExternC(New))) 2909 Old = nullptr; 2910 2911 if (!Old) { 2912 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2913 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2914 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2915 return true; 2916 } 2917 return false; 2918 } 2919 2920 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2921 const FunctionDecl *B) { 2922 assert(A->getNumParams() == B->getNumParams()); 2923 2924 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2925 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2926 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2927 if (AttrA == AttrB) 2928 return true; 2929 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2930 }; 2931 2932 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2933 } 2934 2935 /// If necessary, adjust the semantic declaration context for a qualified 2936 /// declaration to name the correct inline namespace within the qualifier. 2937 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2938 DeclaratorDecl *OldD) { 2939 // The only case where we need to update the DeclContext is when 2940 // redeclaration lookup for a qualified name finds a declaration 2941 // in an inline namespace within the context named by the qualifier: 2942 // 2943 // inline namespace N { int f(); } 2944 // int ::f(); // Sema DC needs adjusting from :: to N::. 2945 // 2946 // For unqualified declarations, the semantic context *can* change 2947 // along the redeclaration chain (for local extern declarations, 2948 // extern "C" declarations, and friend declarations in particular). 2949 if (!NewD->getQualifier()) 2950 return; 2951 2952 // NewD is probably already in the right context. 2953 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2954 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2955 if (NamedDC->Equals(SemaDC)) 2956 return; 2957 2958 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2959 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2960 "unexpected context for redeclaration"); 2961 2962 auto *LexDC = NewD->getLexicalDeclContext(); 2963 auto FixSemaDC = [=](NamedDecl *D) { 2964 if (!D) 2965 return; 2966 D->setDeclContext(SemaDC); 2967 D->setLexicalDeclContext(LexDC); 2968 }; 2969 2970 FixSemaDC(NewD); 2971 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 2972 FixSemaDC(FD->getDescribedFunctionTemplate()); 2973 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 2974 FixSemaDC(VD->getDescribedVarTemplate()); 2975 } 2976 2977 /// MergeFunctionDecl - We just parsed a function 'New' from 2978 /// declarator D which has the same name and scope as a previous 2979 /// declaration 'Old'. Figure out how to resolve this situation, 2980 /// merging decls or emitting diagnostics as appropriate. 2981 /// 2982 /// In C++, New and Old must be declarations that are not 2983 /// overloaded. Use IsOverload to determine whether New and Old are 2984 /// overloaded, and to select the Old declaration that New should be 2985 /// merged with. 2986 /// 2987 /// Returns true if there was an error, false otherwise. 2988 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2989 Scope *S, bool MergeTypeWithOld) { 2990 // Verify the old decl was also a function. 2991 FunctionDecl *Old = OldD->getAsFunction(); 2992 if (!Old) { 2993 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2994 if (New->getFriendObjectKind()) { 2995 Diag(New->getLocation(), diag::err_using_decl_friend); 2996 Diag(Shadow->getTargetDecl()->getLocation(), 2997 diag::note_using_decl_target); 2998 Diag(Shadow->getUsingDecl()->getLocation(), 2999 diag::note_using_decl) << 0; 3000 return true; 3001 } 3002 3003 // Check whether the two declarations might declare the same function. 3004 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3005 return true; 3006 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3007 } else { 3008 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3009 << New->getDeclName(); 3010 notePreviousDefinition(OldD, New->getLocation()); 3011 return true; 3012 } 3013 } 3014 3015 // If the old declaration is invalid, just give up here. 3016 if (Old->isInvalidDecl()) 3017 return true; 3018 3019 // Disallow redeclaration of some builtins. 3020 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3021 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3022 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3023 << Old << Old->getType(); 3024 return true; 3025 } 3026 3027 diag::kind PrevDiag; 3028 SourceLocation OldLocation; 3029 std::tie(PrevDiag, OldLocation) = 3030 getNoteDiagForInvalidRedeclaration(Old, New); 3031 3032 // Don't complain about this if we're in GNU89 mode and the old function 3033 // is an extern inline function. 3034 // Don't complain about specializations. They are not supposed to have 3035 // storage classes. 3036 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3037 New->getStorageClass() == SC_Static && 3038 Old->hasExternalFormalLinkage() && 3039 !New->getTemplateSpecializationInfo() && 3040 !canRedefineFunction(Old, getLangOpts())) { 3041 if (getLangOpts().MicrosoftExt) { 3042 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3043 Diag(OldLocation, PrevDiag); 3044 } else { 3045 Diag(New->getLocation(), diag::err_static_non_static) << New; 3046 Diag(OldLocation, PrevDiag); 3047 return true; 3048 } 3049 } 3050 3051 if (New->hasAttr<InternalLinkageAttr>() && 3052 !Old->hasAttr<InternalLinkageAttr>()) { 3053 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3054 << New->getDeclName(); 3055 notePreviousDefinition(Old, New->getLocation()); 3056 New->dropAttr<InternalLinkageAttr>(); 3057 } 3058 3059 if (CheckRedeclarationModuleOwnership(New, Old)) 3060 return true; 3061 3062 if (!getLangOpts().CPlusPlus) { 3063 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3064 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3065 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3066 << New << OldOvl; 3067 3068 // Try our best to find a decl that actually has the overloadable 3069 // attribute for the note. In most cases (e.g. programs with only one 3070 // broken declaration/definition), this won't matter. 3071 // 3072 // FIXME: We could do this if we juggled some extra state in 3073 // OverloadableAttr, rather than just removing it. 3074 const Decl *DiagOld = Old; 3075 if (OldOvl) { 3076 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3077 const auto *A = D->getAttr<OverloadableAttr>(); 3078 return A && !A->isImplicit(); 3079 }); 3080 // If we've implicitly added *all* of the overloadable attrs to this 3081 // chain, emitting a "previous redecl" note is pointless. 3082 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3083 } 3084 3085 if (DiagOld) 3086 Diag(DiagOld->getLocation(), 3087 diag::note_attribute_overloadable_prev_overload) 3088 << OldOvl; 3089 3090 if (OldOvl) 3091 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3092 else 3093 New->dropAttr<OverloadableAttr>(); 3094 } 3095 } 3096 3097 // If a function is first declared with a calling convention, but is later 3098 // declared or defined without one, all following decls assume the calling 3099 // convention of the first. 3100 // 3101 // It's OK if a function is first declared without a calling convention, 3102 // but is later declared or defined with the default calling convention. 3103 // 3104 // To test if either decl has an explicit calling convention, we look for 3105 // AttributedType sugar nodes on the type as written. If they are missing or 3106 // were canonicalized away, we assume the calling convention was implicit. 3107 // 3108 // Note also that we DO NOT return at this point, because we still have 3109 // other tests to run. 3110 QualType OldQType = Context.getCanonicalType(Old->getType()); 3111 QualType NewQType = Context.getCanonicalType(New->getType()); 3112 const FunctionType *OldType = cast<FunctionType>(OldQType); 3113 const FunctionType *NewType = cast<FunctionType>(NewQType); 3114 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3115 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3116 bool RequiresAdjustment = false; 3117 3118 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3119 FunctionDecl *First = Old->getFirstDecl(); 3120 const FunctionType *FT = 3121 First->getType().getCanonicalType()->castAs<FunctionType>(); 3122 FunctionType::ExtInfo FI = FT->getExtInfo(); 3123 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3124 if (!NewCCExplicit) { 3125 // Inherit the CC from the previous declaration if it was specified 3126 // there but not here. 3127 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3128 RequiresAdjustment = true; 3129 } else { 3130 // Calling conventions aren't compatible, so complain. 3131 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3132 Diag(New->getLocation(), diag::err_cconv_change) 3133 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3134 << !FirstCCExplicit 3135 << (!FirstCCExplicit ? "" : 3136 FunctionType::getNameForCallConv(FI.getCC())); 3137 3138 // Put the note on the first decl, since it is the one that matters. 3139 Diag(First->getLocation(), diag::note_previous_declaration); 3140 return true; 3141 } 3142 } 3143 3144 // FIXME: diagnose the other way around? 3145 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3146 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3147 RequiresAdjustment = true; 3148 } 3149 3150 // Merge regparm attribute. 3151 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3152 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3153 if (NewTypeInfo.getHasRegParm()) { 3154 Diag(New->getLocation(), diag::err_regparm_mismatch) 3155 << NewType->getRegParmType() 3156 << OldType->getRegParmType(); 3157 Diag(OldLocation, diag::note_previous_declaration); 3158 return true; 3159 } 3160 3161 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3162 RequiresAdjustment = true; 3163 } 3164 3165 // Merge ns_returns_retained attribute. 3166 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3167 if (NewTypeInfo.getProducesResult()) { 3168 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3169 << "'ns_returns_retained'"; 3170 Diag(OldLocation, diag::note_previous_declaration); 3171 return true; 3172 } 3173 3174 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3175 RequiresAdjustment = true; 3176 } 3177 3178 if (OldTypeInfo.getNoCallerSavedRegs() != 3179 NewTypeInfo.getNoCallerSavedRegs()) { 3180 if (NewTypeInfo.getNoCallerSavedRegs()) { 3181 AnyX86NoCallerSavedRegistersAttr *Attr = 3182 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3183 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3184 Diag(OldLocation, diag::note_previous_declaration); 3185 return true; 3186 } 3187 3188 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3189 RequiresAdjustment = true; 3190 } 3191 3192 if (RequiresAdjustment) { 3193 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3194 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3195 New->setType(QualType(AdjustedType, 0)); 3196 NewQType = Context.getCanonicalType(New->getType()); 3197 NewType = cast<FunctionType>(NewQType); 3198 } 3199 3200 // If this redeclaration makes the function inline, we may need to add it to 3201 // UndefinedButUsed. 3202 if (!Old->isInlined() && New->isInlined() && 3203 !New->hasAttr<GNUInlineAttr>() && 3204 !getLangOpts().GNUInline && 3205 Old->isUsed(false) && 3206 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3207 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3208 SourceLocation())); 3209 3210 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3211 // about it. 3212 if (New->hasAttr<GNUInlineAttr>() && 3213 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3214 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3215 } 3216 3217 // If pass_object_size params don't match up perfectly, this isn't a valid 3218 // redeclaration. 3219 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3220 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3221 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3222 << New->getDeclName(); 3223 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3224 return true; 3225 } 3226 3227 if (getLangOpts().CPlusPlus) { 3228 // C++1z [over.load]p2 3229 // Certain function declarations cannot be overloaded: 3230 // -- Function declarations that differ only in the return type, 3231 // the exception specification, or both cannot be overloaded. 3232 3233 // Check the exception specifications match. This may recompute the type of 3234 // both Old and New if it resolved exception specifications, so grab the 3235 // types again after this. Because this updates the type, we do this before 3236 // any of the other checks below, which may update the "de facto" NewQType 3237 // but do not necessarily update the type of New. 3238 if (CheckEquivalentExceptionSpec(Old, New)) 3239 return true; 3240 OldQType = Context.getCanonicalType(Old->getType()); 3241 NewQType = Context.getCanonicalType(New->getType()); 3242 3243 // Go back to the type source info to compare the declared return types, 3244 // per C++1y [dcl.type.auto]p13: 3245 // Redeclarations or specializations of a function or function template 3246 // with a declared return type that uses a placeholder type shall also 3247 // use that placeholder, not a deduced type. 3248 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3249 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3250 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3251 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3252 OldDeclaredReturnType)) { 3253 QualType ResQT; 3254 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3255 OldDeclaredReturnType->isObjCObjectPointerType()) 3256 // FIXME: This does the wrong thing for a deduced return type. 3257 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3258 if (ResQT.isNull()) { 3259 if (New->isCXXClassMember() && New->isOutOfLine()) 3260 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3261 << New << New->getReturnTypeSourceRange(); 3262 else 3263 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3264 << New->getReturnTypeSourceRange(); 3265 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3266 << Old->getReturnTypeSourceRange(); 3267 return true; 3268 } 3269 else 3270 NewQType = ResQT; 3271 } 3272 3273 QualType OldReturnType = OldType->getReturnType(); 3274 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3275 if (OldReturnType != NewReturnType) { 3276 // If this function has a deduced return type and has already been 3277 // defined, copy the deduced value from the old declaration. 3278 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3279 if (OldAT && OldAT->isDeduced()) { 3280 New->setType( 3281 SubstAutoType(New->getType(), 3282 OldAT->isDependentType() ? Context.DependentTy 3283 : OldAT->getDeducedType())); 3284 NewQType = Context.getCanonicalType( 3285 SubstAutoType(NewQType, 3286 OldAT->isDependentType() ? Context.DependentTy 3287 : OldAT->getDeducedType())); 3288 } 3289 } 3290 3291 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3292 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3293 if (OldMethod && NewMethod) { 3294 // Preserve triviality. 3295 NewMethod->setTrivial(OldMethod->isTrivial()); 3296 3297 // MSVC allows explicit template specialization at class scope: 3298 // 2 CXXMethodDecls referring to the same function will be injected. 3299 // We don't want a redeclaration error. 3300 bool IsClassScopeExplicitSpecialization = 3301 OldMethod->isFunctionTemplateSpecialization() && 3302 NewMethod->isFunctionTemplateSpecialization(); 3303 bool isFriend = NewMethod->getFriendObjectKind(); 3304 3305 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3306 !IsClassScopeExplicitSpecialization) { 3307 // -- Member function declarations with the same name and the 3308 // same parameter types cannot be overloaded if any of them 3309 // is a static member function declaration. 3310 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3311 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3312 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3313 return true; 3314 } 3315 3316 // C++ [class.mem]p1: 3317 // [...] A member shall not be declared twice in the 3318 // member-specification, except that a nested class or member 3319 // class template can be declared and then later defined. 3320 if (!inTemplateInstantiation()) { 3321 unsigned NewDiag; 3322 if (isa<CXXConstructorDecl>(OldMethod)) 3323 NewDiag = diag::err_constructor_redeclared; 3324 else if (isa<CXXDestructorDecl>(NewMethod)) 3325 NewDiag = diag::err_destructor_redeclared; 3326 else if (isa<CXXConversionDecl>(NewMethod)) 3327 NewDiag = diag::err_conv_function_redeclared; 3328 else 3329 NewDiag = diag::err_member_redeclared; 3330 3331 Diag(New->getLocation(), NewDiag); 3332 } else { 3333 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3334 << New << New->getType(); 3335 } 3336 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3337 return true; 3338 3339 // Complain if this is an explicit declaration of a special 3340 // member that was initially declared implicitly. 3341 // 3342 // As an exception, it's okay to befriend such methods in order 3343 // to permit the implicit constructor/destructor/operator calls. 3344 } else if (OldMethod->isImplicit()) { 3345 if (isFriend) { 3346 NewMethod->setImplicit(); 3347 } else { 3348 Diag(NewMethod->getLocation(), 3349 diag::err_definition_of_implicitly_declared_member) 3350 << New << getSpecialMember(OldMethod); 3351 return true; 3352 } 3353 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3354 Diag(NewMethod->getLocation(), 3355 diag::err_definition_of_explicitly_defaulted_member) 3356 << getSpecialMember(OldMethod); 3357 return true; 3358 } 3359 } 3360 3361 // C++11 [dcl.attr.noreturn]p1: 3362 // The first declaration of a function shall specify the noreturn 3363 // attribute if any declaration of that function specifies the noreturn 3364 // attribute. 3365 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3366 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3367 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3368 Diag(Old->getFirstDecl()->getLocation(), 3369 diag::note_noreturn_missing_first_decl); 3370 } 3371 3372 // C++11 [dcl.attr.depend]p2: 3373 // The first declaration of a function shall specify the 3374 // carries_dependency attribute for its declarator-id if any declaration 3375 // of the function specifies the carries_dependency attribute. 3376 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3377 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3378 Diag(CDA->getLocation(), 3379 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3380 Diag(Old->getFirstDecl()->getLocation(), 3381 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3382 } 3383 3384 // (C++98 8.3.5p3): 3385 // All declarations for a function shall agree exactly in both the 3386 // return type and the parameter-type-list. 3387 // We also want to respect all the extended bits except noreturn. 3388 3389 // noreturn should now match unless the old type info didn't have it. 3390 QualType OldQTypeForComparison = OldQType; 3391 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3392 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3393 const FunctionType *OldTypeForComparison 3394 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3395 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3396 assert(OldQTypeForComparison.isCanonical()); 3397 } 3398 3399 if (haveIncompatibleLanguageLinkages(Old, New)) { 3400 // As a special case, retain the language linkage from previous 3401 // declarations of a friend function as an extension. 3402 // 3403 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3404 // and is useful because there's otherwise no way to specify language 3405 // linkage within class scope. 3406 // 3407 // Check cautiously as the friend object kind isn't yet complete. 3408 if (New->getFriendObjectKind() != Decl::FOK_None) { 3409 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3410 Diag(OldLocation, PrevDiag); 3411 } else { 3412 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3413 Diag(OldLocation, PrevDiag); 3414 return true; 3415 } 3416 } 3417 3418 if (OldQTypeForComparison == NewQType) 3419 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3420 3421 // If the types are imprecise (due to dependent constructs in friends or 3422 // local extern declarations), it's OK if they differ. We'll check again 3423 // during instantiation. 3424 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3425 return false; 3426 3427 // Fall through for conflicting redeclarations and redefinitions. 3428 } 3429 3430 // C: Function types need to be compatible, not identical. This handles 3431 // duplicate function decls like "void f(int); void f(enum X);" properly. 3432 if (!getLangOpts().CPlusPlus && 3433 Context.typesAreCompatible(OldQType, NewQType)) { 3434 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3435 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3436 const FunctionProtoType *OldProto = nullptr; 3437 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3438 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3439 // The old declaration provided a function prototype, but the 3440 // new declaration does not. Merge in the prototype. 3441 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3442 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3443 NewQType = 3444 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3445 OldProto->getExtProtoInfo()); 3446 New->setType(NewQType); 3447 New->setHasInheritedPrototype(); 3448 3449 // Synthesize parameters with the same types. 3450 SmallVector<ParmVarDecl*, 16> Params; 3451 for (const auto &ParamType : OldProto->param_types()) { 3452 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3453 SourceLocation(), nullptr, 3454 ParamType, /*TInfo=*/nullptr, 3455 SC_None, nullptr); 3456 Param->setScopeInfo(0, Params.size()); 3457 Param->setImplicit(); 3458 Params.push_back(Param); 3459 } 3460 3461 New->setParams(Params); 3462 } 3463 3464 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3465 } 3466 3467 // GNU C permits a K&R definition to follow a prototype declaration 3468 // if the declared types of the parameters in the K&R definition 3469 // match the types in the prototype declaration, even when the 3470 // promoted types of the parameters from the K&R definition differ 3471 // from the types in the prototype. GCC then keeps the types from 3472 // the prototype. 3473 // 3474 // If a variadic prototype is followed by a non-variadic K&R definition, 3475 // the K&R definition becomes variadic. This is sort of an edge case, but 3476 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3477 // C99 6.9.1p8. 3478 if (!getLangOpts().CPlusPlus && 3479 Old->hasPrototype() && !New->hasPrototype() && 3480 New->getType()->getAs<FunctionProtoType>() && 3481 Old->getNumParams() == New->getNumParams()) { 3482 SmallVector<QualType, 16> ArgTypes; 3483 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3484 const FunctionProtoType *OldProto 3485 = Old->getType()->getAs<FunctionProtoType>(); 3486 const FunctionProtoType *NewProto 3487 = New->getType()->getAs<FunctionProtoType>(); 3488 3489 // Determine whether this is the GNU C extension. 3490 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3491 NewProto->getReturnType()); 3492 bool LooseCompatible = !MergedReturn.isNull(); 3493 for (unsigned Idx = 0, End = Old->getNumParams(); 3494 LooseCompatible && Idx != End; ++Idx) { 3495 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3496 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3497 if (Context.typesAreCompatible(OldParm->getType(), 3498 NewProto->getParamType(Idx))) { 3499 ArgTypes.push_back(NewParm->getType()); 3500 } else if (Context.typesAreCompatible(OldParm->getType(), 3501 NewParm->getType(), 3502 /*CompareUnqualified=*/true)) { 3503 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3504 NewProto->getParamType(Idx) }; 3505 Warnings.push_back(Warn); 3506 ArgTypes.push_back(NewParm->getType()); 3507 } else 3508 LooseCompatible = false; 3509 } 3510 3511 if (LooseCompatible) { 3512 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3513 Diag(Warnings[Warn].NewParm->getLocation(), 3514 diag::ext_param_promoted_not_compatible_with_prototype) 3515 << Warnings[Warn].PromotedType 3516 << Warnings[Warn].OldParm->getType(); 3517 if (Warnings[Warn].OldParm->getLocation().isValid()) 3518 Diag(Warnings[Warn].OldParm->getLocation(), 3519 diag::note_previous_declaration); 3520 } 3521 3522 if (MergeTypeWithOld) 3523 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3524 OldProto->getExtProtoInfo())); 3525 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3526 } 3527 3528 // Fall through to diagnose conflicting types. 3529 } 3530 3531 // A function that has already been declared has been redeclared or 3532 // defined with a different type; show an appropriate diagnostic. 3533 3534 // If the previous declaration was an implicitly-generated builtin 3535 // declaration, then at the very least we should use a specialized note. 3536 unsigned BuiltinID; 3537 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3538 // If it's actually a library-defined builtin function like 'malloc' 3539 // or 'printf', just warn about the incompatible redeclaration. 3540 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3541 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3542 Diag(OldLocation, diag::note_previous_builtin_declaration) 3543 << Old << Old->getType(); 3544 3545 // If this is a global redeclaration, just forget hereafter 3546 // about the "builtin-ness" of the function. 3547 // 3548 // Doing this for local extern declarations is problematic. If 3549 // the builtin declaration remains visible, a second invalid 3550 // local declaration will produce a hard error; if it doesn't 3551 // remain visible, a single bogus local redeclaration (which is 3552 // actually only a warning) could break all the downstream code. 3553 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3554 New->getIdentifier()->revertBuiltin(); 3555 3556 return false; 3557 } 3558 3559 PrevDiag = diag::note_previous_builtin_declaration; 3560 } 3561 3562 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3563 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3564 return true; 3565 } 3566 3567 /// Completes the merge of two function declarations that are 3568 /// known to be compatible. 3569 /// 3570 /// This routine handles the merging of attributes and other 3571 /// properties of function declarations from the old declaration to 3572 /// the new declaration, once we know that New is in fact a 3573 /// redeclaration of Old. 3574 /// 3575 /// \returns false 3576 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3577 Scope *S, bool MergeTypeWithOld) { 3578 // Merge the attributes 3579 mergeDeclAttributes(New, Old); 3580 3581 // Merge "pure" flag. 3582 if (Old->isPure()) 3583 New->setPure(); 3584 3585 // Merge "used" flag. 3586 if (Old->getMostRecentDecl()->isUsed(false)) 3587 New->setIsUsed(); 3588 3589 // Merge attributes from the parameters. These can mismatch with K&R 3590 // declarations. 3591 if (New->getNumParams() == Old->getNumParams()) 3592 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3593 ParmVarDecl *NewParam = New->getParamDecl(i); 3594 ParmVarDecl *OldParam = Old->getParamDecl(i); 3595 mergeParamDeclAttributes(NewParam, OldParam, *this); 3596 mergeParamDeclTypes(NewParam, OldParam, *this); 3597 } 3598 3599 if (getLangOpts().CPlusPlus) 3600 return MergeCXXFunctionDecl(New, Old, S); 3601 3602 // Merge the function types so the we get the composite types for the return 3603 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3604 // was visible. 3605 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3606 if (!Merged.isNull() && MergeTypeWithOld) 3607 New->setType(Merged); 3608 3609 return false; 3610 } 3611 3612 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3613 ObjCMethodDecl *oldMethod) { 3614 // Merge the attributes, including deprecated/unavailable 3615 AvailabilityMergeKind MergeKind = 3616 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3617 ? AMK_ProtocolImplementation 3618 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3619 : AMK_Override; 3620 3621 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3622 3623 // Merge attributes from the parameters. 3624 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3625 oe = oldMethod->param_end(); 3626 for (ObjCMethodDecl::param_iterator 3627 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3628 ni != ne && oi != oe; ++ni, ++oi) 3629 mergeParamDeclAttributes(*ni, *oi, *this); 3630 3631 CheckObjCMethodOverride(newMethod, oldMethod); 3632 } 3633 3634 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3635 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3636 3637 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3638 ? diag::err_redefinition_different_type 3639 : diag::err_redeclaration_different_type) 3640 << New->getDeclName() << New->getType() << Old->getType(); 3641 3642 diag::kind PrevDiag; 3643 SourceLocation OldLocation; 3644 std::tie(PrevDiag, OldLocation) 3645 = getNoteDiagForInvalidRedeclaration(Old, New); 3646 S.Diag(OldLocation, PrevDiag); 3647 New->setInvalidDecl(); 3648 } 3649 3650 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3651 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3652 /// emitting diagnostics as appropriate. 3653 /// 3654 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3655 /// to here in AddInitializerToDecl. We can't check them before the initializer 3656 /// is attached. 3657 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3658 bool MergeTypeWithOld) { 3659 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3660 return; 3661 3662 QualType MergedT; 3663 if (getLangOpts().CPlusPlus) { 3664 if (New->getType()->isUndeducedType()) { 3665 // We don't know what the new type is until the initializer is attached. 3666 return; 3667 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3668 // These could still be something that needs exception specs checked. 3669 return MergeVarDeclExceptionSpecs(New, Old); 3670 } 3671 // C++ [basic.link]p10: 3672 // [...] the types specified by all declarations referring to a given 3673 // object or function shall be identical, except that declarations for an 3674 // array object can specify array types that differ by the presence or 3675 // absence of a major array bound (8.3.4). 3676 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3677 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3678 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3679 3680 // We are merging a variable declaration New into Old. If it has an array 3681 // bound, and that bound differs from Old's bound, we should diagnose the 3682 // mismatch. 3683 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3684 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3685 PrevVD = PrevVD->getPreviousDecl()) { 3686 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3687 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3688 continue; 3689 3690 if (!Context.hasSameType(NewArray, PrevVDTy)) 3691 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3692 } 3693 } 3694 3695 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3696 if (Context.hasSameType(OldArray->getElementType(), 3697 NewArray->getElementType())) 3698 MergedT = New->getType(); 3699 } 3700 // FIXME: Check visibility. New is hidden but has a complete type. If New 3701 // has no array bound, it should not inherit one from Old, if Old is not 3702 // visible. 3703 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3704 if (Context.hasSameType(OldArray->getElementType(), 3705 NewArray->getElementType())) 3706 MergedT = Old->getType(); 3707 } 3708 } 3709 else if (New->getType()->isObjCObjectPointerType() && 3710 Old->getType()->isObjCObjectPointerType()) { 3711 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3712 Old->getType()); 3713 } 3714 } else { 3715 // C 6.2.7p2: 3716 // All declarations that refer to the same object or function shall have 3717 // compatible type. 3718 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3719 } 3720 if (MergedT.isNull()) { 3721 // It's OK if we couldn't merge types if either type is dependent, for a 3722 // block-scope variable. In other cases (static data members of class 3723 // templates, variable templates, ...), we require the types to be 3724 // equivalent. 3725 // FIXME: The C++ standard doesn't say anything about this. 3726 if ((New->getType()->isDependentType() || 3727 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3728 // If the old type was dependent, we can't merge with it, so the new type 3729 // becomes dependent for now. We'll reproduce the original type when we 3730 // instantiate the TypeSourceInfo for the variable. 3731 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3732 New->setType(Context.DependentTy); 3733 return; 3734 } 3735 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3736 } 3737 3738 // Don't actually update the type on the new declaration if the old 3739 // declaration was an extern declaration in a different scope. 3740 if (MergeTypeWithOld) 3741 New->setType(MergedT); 3742 } 3743 3744 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3745 LookupResult &Previous) { 3746 // C11 6.2.7p4: 3747 // For an identifier with internal or external linkage declared 3748 // in a scope in which a prior declaration of that identifier is 3749 // visible, if the prior declaration specifies internal or 3750 // external linkage, the type of the identifier at the later 3751 // declaration becomes the composite type. 3752 // 3753 // If the variable isn't visible, we do not merge with its type. 3754 if (Previous.isShadowed()) 3755 return false; 3756 3757 if (S.getLangOpts().CPlusPlus) { 3758 // C++11 [dcl.array]p3: 3759 // If there is a preceding declaration of the entity in the same 3760 // scope in which the bound was specified, an omitted array bound 3761 // is taken to be the same as in that earlier declaration. 3762 return NewVD->isPreviousDeclInSameBlockScope() || 3763 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3764 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3765 } else { 3766 // If the old declaration was function-local, don't merge with its 3767 // type unless we're in the same function. 3768 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3769 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3770 } 3771 } 3772 3773 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3774 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3775 /// situation, merging decls or emitting diagnostics as appropriate. 3776 /// 3777 /// Tentative definition rules (C99 6.9.2p2) are checked by 3778 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3779 /// definitions here, since the initializer hasn't been attached. 3780 /// 3781 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3782 // If the new decl is already invalid, don't do any other checking. 3783 if (New->isInvalidDecl()) 3784 return; 3785 3786 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3787 return; 3788 3789 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3790 3791 // Verify the old decl was also a variable or variable template. 3792 VarDecl *Old = nullptr; 3793 VarTemplateDecl *OldTemplate = nullptr; 3794 if (Previous.isSingleResult()) { 3795 if (NewTemplate) { 3796 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3797 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3798 3799 if (auto *Shadow = 3800 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3801 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3802 return New->setInvalidDecl(); 3803 } else { 3804 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3805 3806 if (auto *Shadow = 3807 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3808 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3809 return New->setInvalidDecl(); 3810 } 3811 } 3812 if (!Old) { 3813 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3814 << New->getDeclName(); 3815 notePreviousDefinition(Previous.getRepresentativeDecl(), 3816 New->getLocation()); 3817 return New->setInvalidDecl(); 3818 } 3819 3820 // Ensure the template parameters are compatible. 3821 if (NewTemplate && 3822 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3823 OldTemplate->getTemplateParameters(), 3824 /*Complain=*/true, TPL_TemplateMatch)) 3825 return New->setInvalidDecl(); 3826 3827 // C++ [class.mem]p1: 3828 // A member shall not be declared twice in the member-specification [...] 3829 // 3830 // Here, we need only consider static data members. 3831 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3832 Diag(New->getLocation(), diag::err_duplicate_member) 3833 << New->getIdentifier(); 3834 Diag(Old->getLocation(), diag::note_previous_declaration); 3835 New->setInvalidDecl(); 3836 } 3837 3838 mergeDeclAttributes(New, Old); 3839 // Warn if an already-declared variable is made a weak_import in a subsequent 3840 // declaration 3841 if (New->hasAttr<WeakImportAttr>() && 3842 Old->getStorageClass() == SC_None && 3843 !Old->hasAttr<WeakImportAttr>()) { 3844 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3845 notePreviousDefinition(Old, New->getLocation()); 3846 // Remove weak_import attribute on new declaration. 3847 New->dropAttr<WeakImportAttr>(); 3848 } 3849 3850 if (New->hasAttr<InternalLinkageAttr>() && 3851 !Old->hasAttr<InternalLinkageAttr>()) { 3852 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3853 << New->getDeclName(); 3854 notePreviousDefinition(Old, New->getLocation()); 3855 New->dropAttr<InternalLinkageAttr>(); 3856 } 3857 3858 // Merge the types. 3859 VarDecl *MostRecent = Old->getMostRecentDecl(); 3860 if (MostRecent != Old) { 3861 MergeVarDeclTypes(New, MostRecent, 3862 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3863 if (New->isInvalidDecl()) 3864 return; 3865 } 3866 3867 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3868 if (New->isInvalidDecl()) 3869 return; 3870 3871 diag::kind PrevDiag; 3872 SourceLocation OldLocation; 3873 std::tie(PrevDiag, OldLocation) = 3874 getNoteDiagForInvalidRedeclaration(Old, New); 3875 3876 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3877 if (New->getStorageClass() == SC_Static && 3878 !New->isStaticDataMember() && 3879 Old->hasExternalFormalLinkage()) { 3880 if (getLangOpts().MicrosoftExt) { 3881 Diag(New->getLocation(), diag::ext_static_non_static) 3882 << New->getDeclName(); 3883 Diag(OldLocation, PrevDiag); 3884 } else { 3885 Diag(New->getLocation(), diag::err_static_non_static) 3886 << New->getDeclName(); 3887 Diag(OldLocation, PrevDiag); 3888 return New->setInvalidDecl(); 3889 } 3890 } 3891 // C99 6.2.2p4: 3892 // For an identifier declared with the storage-class specifier 3893 // extern in a scope in which a prior declaration of that 3894 // identifier is visible,23) if the prior declaration specifies 3895 // internal or external linkage, the linkage of the identifier at 3896 // the later declaration is the same as the linkage specified at 3897 // the prior declaration. If no prior declaration is visible, or 3898 // if the prior declaration specifies no linkage, then the 3899 // identifier has external linkage. 3900 if (New->hasExternalStorage() && Old->hasLinkage()) 3901 /* Okay */; 3902 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3903 !New->isStaticDataMember() && 3904 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3905 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3906 Diag(OldLocation, PrevDiag); 3907 return New->setInvalidDecl(); 3908 } 3909 3910 // Check if extern is followed by non-extern and vice-versa. 3911 if (New->hasExternalStorage() && 3912 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3913 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3914 Diag(OldLocation, PrevDiag); 3915 return New->setInvalidDecl(); 3916 } 3917 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3918 !New->hasExternalStorage()) { 3919 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3920 Diag(OldLocation, PrevDiag); 3921 return New->setInvalidDecl(); 3922 } 3923 3924 if (CheckRedeclarationModuleOwnership(New, Old)) 3925 return; 3926 3927 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3928 3929 // FIXME: The test for external storage here seems wrong? We still 3930 // need to check for mismatches. 3931 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3932 // Don't complain about out-of-line definitions of static members. 3933 !(Old->getLexicalDeclContext()->isRecord() && 3934 !New->getLexicalDeclContext()->isRecord())) { 3935 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3936 Diag(OldLocation, PrevDiag); 3937 return New->setInvalidDecl(); 3938 } 3939 3940 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3941 if (VarDecl *Def = Old->getDefinition()) { 3942 // C++1z [dcl.fcn.spec]p4: 3943 // If the definition of a variable appears in a translation unit before 3944 // its first declaration as inline, the program is ill-formed. 3945 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3946 Diag(Def->getLocation(), diag::note_previous_definition); 3947 } 3948 } 3949 3950 // If this redeclaration makes the variable inline, we may need to add it to 3951 // UndefinedButUsed. 3952 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3953 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3954 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3955 SourceLocation())); 3956 3957 if (New->getTLSKind() != Old->getTLSKind()) { 3958 if (!Old->getTLSKind()) { 3959 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3960 Diag(OldLocation, PrevDiag); 3961 } else if (!New->getTLSKind()) { 3962 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3963 Diag(OldLocation, PrevDiag); 3964 } else { 3965 // Do not allow redeclaration to change the variable between requiring 3966 // static and dynamic initialization. 3967 // FIXME: GCC allows this, but uses the TLS keyword on the first 3968 // declaration to determine the kind. Do we need to be compatible here? 3969 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3970 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3971 Diag(OldLocation, PrevDiag); 3972 } 3973 } 3974 3975 // C++ doesn't have tentative definitions, so go right ahead and check here. 3976 if (getLangOpts().CPlusPlus && 3977 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3978 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3979 Old->getCanonicalDecl()->isConstexpr()) { 3980 // This definition won't be a definition any more once it's been merged. 3981 Diag(New->getLocation(), 3982 diag::warn_deprecated_redundant_constexpr_static_def); 3983 } else if (VarDecl *Def = Old->getDefinition()) { 3984 if (checkVarDeclRedefinition(Def, New)) 3985 return; 3986 } 3987 } 3988 3989 if (haveIncompatibleLanguageLinkages(Old, New)) { 3990 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3991 Diag(OldLocation, PrevDiag); 3992 New->setInvalidDecl(); 3993 return; 3994 } 3995 3996 // Merge "used" flag. 3997 if (Old->getMostRecentDecl()->isUsed(false)) 3998 New->setIsUsed(); 3999 4000 // Keep a chain of previous declarations. 4001 New->setPreviousDecl(Old); 4002 if (NewTemplate) 4003 NewTemplate->setPreviousDecl(OldTemplate); 4004 adjustDeclContextForDeclaratorDecl(New, Old); 4005 4006 // Inherit access appropriately. 4007 New->setAccess(Old->getAccess()); 4008 if (NewTemplate) 4009 NewTemplate->setAccess(New->getAccess()); 4010 4011 if (Old->isInline()) 4012 New->setImplicitlyInline(); 4013 } 4014 4015 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4016 SourceManager &SrcMgr = getSourceManager(); 4017 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4018 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4019 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4020 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4021 auto &HSI = PP.getHeaderSearchInfo(); 4022 StringRef HdrFilename = 4023 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4024 4025 auto noteFromModuleOrInclude = [&](Module *Mod, 4026 SourceLocation IncLoc) -> bool { 4027 // Redefinition errors with modules are common with non modular mapped 4028 // headers, example: a non-modular header H in module A that also gets 4029 // included directly in a TU. Pointing twice to the same header/definition 4030 // is confusing, try to get better diagnostics when modules is on. 4031 if (IncLoc.isValid()) { 4032 if (Mod) { 4033 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4034 << HdrFilename.str() << Mod->getFullModuleName(); 4035 if (!Mod->DefinitionLoc.isInvalid()) 4036 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4037 << Mod->getFullModuleName(); 4038 } else { 4039 Diag(IncLoc, diag::note_redefinition_include_same_file) 4040 << HdrFilename.str(); 4041 } 4042 return true; 4043 } 4044 4045 return false; 4046 }; 4047 4048 // Is it the same file and same offset? Provide more information on why 4049 // this leads to a redefinition error. 4050 bool EmittedDiag = false; 4051 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4052 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4053 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4054 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4055 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4056 4057 // If the header has no guards, emit a note suggesting one. 4058 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4059 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4060 4061 if (EmittedDiag) 4062 return; 4063 } 4064 4065 // Redefinition coming from different files or couldn't do better above. 4066 if (Old->getLocation().isValid()) 4067 Diag(Old->getLocation(), diag::note_previous_definition); 4068 } 4069 4070 /// We've just determined that \p Old and \p New both appear to be definitions 4071 /// of the same variable. Either diagnose or fix the problem. 4072 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4073 if (!hasVisibleDefinition(Old) && 4074 (New->getFormalLinkage() == InternalLinkage || 4075 New->isInline() || 4076 New->getDescribedVarTemplate() || 4077 New->getNumTemplateParameterLists() || 4078 New->getDeclContext()->isDependentContext())) { 4079 // The previous definition is hidden, and multiple definitions are 4080 // permitted (in separate TUs). Demote this to a declaration. 4081 New->demoteThisDefinitionToDeclaration(); 4082 4083 // Make the canonical definition visible. 4084 if (auto *OldTD = Old->getDescribedVarTemplate()) 4085 makeMergedDefinitionVisible(OldTD); 4086 makeMergedDefinitionVisible(Old); 4087 return false; 4088 } else { 4089 Diag(New->getLocation(), diag::err_redefinition) << New; 4090 notePreviousDefinition(Old, New->getLocation()); 4091 New->setInvalidDecl(); 4092 return true; 4093 } 4094 } 4095 4096 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4097 /// no declarator (e.g. "struct foo;") is parsed. 4098 Decl * 4099 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4100 RecordDecl *&AnonRecord) { 4101 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4102 AnonRecord); 4103 } 4104 4105 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4106 // disambiguate entities defined in different scopes. 4107 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4108 // compatibility. 4109 // We will pick our mangling number depending on which version of MSVC is being 4110 // targeted. 4111 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4112 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4113 ? S->getMSCurManglingNumber() 4114 : S->getMSLastManglingNumber(); 4115 } 4116 4117 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4118 if (!Context.getLangOpts().CPlusPlus) 4119 return; 4120 4121 if (isa<CXXRecordDecl>(Tag->getParent())) { 4122 // If this tag is the direct child of a class, number it if 4123 // it is anonymous. 4124 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4125 return; 4126 MangleNumberingContext &MCtx = 4127 Context.getManglingNumberContext(Tag->getParent()); 4128 Context.setManglingNumber( 4129 Tag, MCtx.getManglingNumber( 4130 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4131 return; 4132 } 4133 4134 // If this tag isn't a direct child of a class, number it if it is local. 4135 Decl *ManglingContextDecl; 4136 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4137 Tag->getDeclContext(), ManglingContextDecl)) { 4138 Context.setManglingNumber( 4139 Tag, MCtx->getManglingNumber( 4140 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4141 } 4142 } 4143 4144 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4145 TypedefNameDecl *NewTD) { 4146 if (TagFromDeclSpec->isInvalidDecl()) 4147 return; 4148 4149 // Do nothing if the tag already has a name for linkage purposes. 4150 if (TagFromDeclSpec->hasNameForLinkage()) 4151 return; 4152 4153 // A well-formed anonymous tag must always be a TUK_Definition. 4154 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4155 4156 // The type must match the tag exactly; no qualifiers allowed. 4157 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4158 Context.getTagDeclType(TagFromDeclSpec))) { 4159 if (getLangOpts().CPlusPlus) 4160 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4161 return; 4162 } 4163 4164 // If we've already computed linkage for the anonymous tag, then 4165 // adding a typedef name for the anonymous decl can change that 4166 // linkage, which might be a serious problem. Diagnose this as 4167 // unsupported and ignore the typedef name. TODO: we should 4168 // pursue this as a language defect and establish a formal rule 4169 // for how to handle it. 4170 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4171 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4172 4173 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4174 tagLoc = getLocForEndOfToken(tagLoc); 4175 4176 llvm::SmallString<40> textToInsert; 4177 textToInsert += ' '; 4178 textToInsert += NewTD->getIdentifier()->getName(); 4179 Diag(tagLoc, diag::note_typedef_changes_linkage) 4180 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4181 return; 4182 } 4183 4184 // Otherwise, set this is the anon-decl typedef for the tag. 4185 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4186 } 4187 4188 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4189 switch (T) { 4190 case DeclSpec::TST_class: 4191 return 0; 4192 case DeclSpec::TST_struct: 4193 return 1; 4194 case DeclSpec::TST_interface: 4195 return 2; 4196 case DeclSpec::TST_union: 4197 return 3; 4198 case DeclSpec::TST_enum: 4199 return 4; 4200 default: 4201 llvm_unreachable("unexpected type specifier"); 4202 } 4203 } 4204 4205 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4206 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4207 /// parameters to cope with template friend declarations. 4208 Decl * 4209 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4210 MultiTemplateParamsArg TemplateParams, 4211 bool IsExplicitInstantiation, 4212 RecordDecl *&AnonRecord) { 4213 Decl *TagD = nullptr; 4214 TagDecl *Tag = nullptr; 4215 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4216 DS.getTypeSpecType() == DeclSpec::TST_struct || 4217 DS.getTypeSpecType() == DeclSpec::TST_interface || 4218 DS.getTypeSpecType() == DeclSpec::TST_union || 4219 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4220 TagD = DS.getRepAsDecl(); 4221 4222 if (!TagD) // We probably had an error 4223 return nullptr; 4224 4225 // Note that the above type specs guarantee that the 4226 // type rep is a Decl, whereas in many of the others 4227 // it's a Type. 4228 if (isa<TagDecl>(TagD)) 4229 Tag = cast<TagDecl>(TagD); 4230 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4231 Tag = CTD->getTemplatedDecl(); 4232 } 4233 4234 if (Tag) { 4235 handleTagNumbering(Tag, S); 4236 Tag->setFreeStanding(); 4237 if (Tag->isInvalidDecl()) 4238 return Tag; 4239 } 4240 4241 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4242 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4243 // or incomplete types shall not be restrict-qualified." 4244 if (TypeQuals & DeclSpec::TQ_restrict) 4245 Diag(DS.getRestrictSpecLoc(), 4246 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4247 << DS.getSourceRange(); 4248 } 4249 4250 if (DS.isInlineSpecified()) 4251 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4252 << getLangOpts().CPlusPlus17; 4253 4254 if (DS.isConstexprSpecified()) { 4255 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4256 // and definitions of functions and variables. 4257 if (Tag) 4258 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4259 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4260 else 4261 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4262 // Don't emit warnings after this error. 4263 return TagD; 4264 } 4265 4266 DiagnoseFunctionSpecifiers(DS); 4267 4268 if (DS.isFriendSpecified()) { 4269 // If we're dealing with a decl but not a TagDecl, assume that 4270 // whatever routines created it handled the friendship aspect. 4271 if (TagD && !Tag) 4272 return nullptr; 4273 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4274 } 4275 4276 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4277 bool IsExplicitSpecialization = 4278 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4279 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4280 !IsExplicitInstantiation && !IsExplicitSpecialization && 4281 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4282 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4283 // nested-name-specifier unless it is an explicit instantiation 4284 // or an explicit specialization. 4285 // 4286 // FIXME: We allow class template partial specializations here too, per the 4287 // obvious intent of DR1819. 4288 // 4289 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4290 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4291 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4292 return nullptr; 4293 } 4294 4295 // Track whether this decl-specifier declares anything. 4296 bool DeclaresAnything = true; 4297 4298 // Handle anonymous struct definitions. 4299 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4300 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4301 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4302 if (getLangOpts().CPlusPlus || 4303 Record->getDeclContext()->isRecord()) { 4304 // If CurContext is a DeclContext that can contain statements, 4305 // RecursiveASTVisitor won't visit the decls that 4306 // BuildAnonymousStructOrUnion() will put into CurContext. 4307 // Also store them here so that they can be part of the 4308 // DeclStmt that gets created in this case. 4309 // FIXME: Also return the IndirectFieldDecls created by 4310 // BuildAnonymousStructOr union, for the same reason? 4311 if (CurContext->isFunctionOrMethod()) 4312 AnonRecord = Record; 4313 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4314 Context.getPrintingPolicy()); 4315 } 4316 4317 DeclaresAnything = false; 4318 } 4319 } 4320 4321 // C11 6.7.2.1p2: 4322 // A struct-declaration that does not declare an anonymous structure or 4323 // anonymous union shall contain a struct-declarator-list. 4324 // 4325 // This rule also existed in C89 and C99; the grammar for struct-declaration 4326 // did not permit a struct-declaration without a struct-declarator-list. 4327 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4328 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4329 // Check for Microsoft C extension: anonymous struct/union member. 4330 // Handle 2 kinds of anonymous struct/union: 4331 // struct STRUCT; 4332 // union UNION; 4333 // and 4334 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4335 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4336 if ((Tag && Tag->getDeclName()) || 4337 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4338 RecordDecl *Record = nullptr; 4339 if (Tag) 4340 Record = dyn_cast<RecordDecl>(Tag); 4341 else if (const RecordType *RT = 4342 DS.getRepAsType().get()->getAsStructureType()) 4343 Record = RT->getDecl(); 4344 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4345 Record = UT->getDecl(); 4346 4347 if (Record && getLangOpts().MicrosoftExt) { 4348 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4349 << Record->isUnion() << DS.getSourceRange(); 4350 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4351 } 4352 4353 DeclaresAnything = false; 4354 } 4355 } 4356 4357 // Skip all the checks below if we have a type error. 4358 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4359 (TagD && TagD->isInvalidDecl())) 4360 return TagD; 4361 4362 if (getLangOpts().CPlusPlus && 4363 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4364 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4365 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4366 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4367 DeclaresAnything = false; 4368 4369 if (!DS.isMissingDeclaratorOk()) { 4370 // Customize diagnostic for a typedef missing a name. 4371 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4372 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4373 << DS.getSourceRange(); 4374 else 4375 DeclaresAnything = false; 4376 } 4377 4378 if (DS.isModulePrivateSpecified() && 4379 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4380 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4381 << Tag->getTagKind() 4382 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4383 4384 ActOnDocumentableDecl(TagD); 4385 4386 // C 6.7/2: 4387 // A declaration [...] shall declare at least a declarator [...], a tag, 4388 // or the members of an enumeration. 4389 // C++ [dcl.dcl]p3: 4390 // [If there are no declarators], and except for the declaration of an 4391 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4392 // names into the program, or shall redeclare a name introduced by a 4393 // previous declaration. 4394 if (!DeclaresAnything) { 4395 // In C, we allow this as a (popular) extension / bug. Don't bother 4396 // producing further diagnostics for redundant qualifiers after this. 4397 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4398 return TagD; 4399 } 4400 4401 // C++ [dcl.stc]p1: 4402 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4403 // init-declarator-list of the declaration shall not be empty. 4404 // C++ [dcl.fct.spec]p1: 4405 // If a cv-qualifier appears in a decl-specifier-seq, the 4406 // init-declarator-list of the declaration shall not be empty. 4407 // 4408 // Spurious qualifiers here appear to be valid in C. 4409 unsigned DiagID = diag::warn_standalone_specifier; 4410 if (getLangOpts().CPlusPlus) 4411 DiagID = diag::ext_standalone_specifier; 4412 4413 // Note that a linkage-specification sets a storage class, but 4414 // 'extern "C" struct foo;' is actually valid and not theoretically 4415 // useless. 4416 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4417 if (SCS == DeclSpec::SCS_mutable) 4418 // Since mutable is not a viable storage class specifier in C, there is 4419 // no reason to treat it as an extension. Instead, diagnose as an error. 4420 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4421 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4422 Diag(DS.getStorageClassSpecLoc(), DiagID) 4423 << DeclSpec::getSpecifierName(SCS); 4424 } 4425 4426 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4427 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4428 << DeclSpec::getSpecifierName(TSCS); 4429 if (DS.getTypeQualifiers()) { 4430 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4431 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4432 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4433 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4434 // Restrict is covered above. 4435 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4436 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4437 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4438 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4439 } 4440 4441 // Warn about ignored type attributes, for example: 4442 // __attribute__((aligned)) struct A; 4443 // Attributes should be placed after tag to apply to type declaration. 4444 if (!DS.getAttributes().empty()) { 4445 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4446 if (TypeSpecType == DeclSpec::TST_class || 4447 TypeSpecType == DeclSpec::TST_struct || 4448 TypeSpecType == DeclSpec::TST_interface || 4449 TypeSpecType == DeclSpec::TST_union || 4450 TypeSpecType == DeclSpec::TST_enum) { 4451 for (const ParsedAttr &AL : DS.getAttributes()) 4452 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4453 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4454 } 4455 } 4456 4457 return TagD; 4458 } 4459 4460 /// We are trying to inject an anonymous member into the given scope; 4461 /// check if there's an existing declaration that can't be overloaded. 4462 /// 4463 /// \return true if this is a forbidden redeclaration 4464 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4465 Scope *S, 4466 DeclContext *Owner, 4467 DeclarationName Name, 4468 SourceLocation NameLoc, 4469 bool IsUnion) { 4470 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4471 Sema::ForVisibleRedeclaration); 4472 if (!SemaRef.LookupName(R, S)) return false; 4473 4474 // Pick a representative declaration. 4475 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4476 assert(PrevDecl && "Expected a non-null Decl"); 4477 4478 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4479 return false; 4480 4481 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4482 << IsUnion << Name; 4483 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4484 4485 return true; 4486 } 4487 4488 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4489 /// anonymous struct or union AnonRecord into the owning context Owner 4490 /// and scope S. This routine will be invoked just after we realize 4491 /// that an unnamed union or struct is actually an anonymous union or 4492 /// struct, e.g., 4493 /// 4494 /// @code 4495 /// union { 4496 /// int i; 4497 /// float f; 4498 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4499 /// // f into the surrounding scope.x 4500 /// @endcode 4501 /// 4502 /// This routine is recursive, injecting the names of nested anonymous 4503 /// structs/unions into the owning context and scope as well. 4504 static bool 4505 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4506 RecordDecl *AnonRecord, AccessSpecifier AS, 4507 SmallVectorImpl<NamedDecl *> &Chaining) { 4508 bool Invalid = false; 4509 4510 // Look every FieldDecl and IndirectFieldDecl with a name. 4511 for (auto *D : AnonRecord->decls()) { 4512 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4513 cast<NamedDecl>(D)->getDeclName()) { 4514 ValueDecl *VD = cast<ValueDecl>(D); 4515 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4516 VD->getLocation(), 4517 AnonRecord->isUnion())) { 4518 // C++ [class.union]p2: 4519 // The names of the members of an anonymous union shall be 4520 // distinct from the names of any other entity in the 4521 // scope in which the anonymous union is declared. 4522 Invalid = true; 4523 } else { 4524 // C++ [class.union]p2: 4525 // For the purpose of name lookup, after the anonymous union 4526 // definition, the members of the anonymous union are 4527 // considered to have been defined in the scope in which the 4528 // anonymous union is declared. 4529 unsigned OldChainingSize = Chaining.size(); 4530 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4531 Chaining.append(IF->chain_begin(), IF->chain_end()); 4532 else 4533 Chaining.push_back(VD); 4534 4535 assert(Chaining.size() >= 2); 4536 NamedDecl **NamedChain = 4537 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4538 for (unsigned i = 0; i < Chaining.size(); i++) 4539 NamedChain[i] = Chaining[i]; 4540 4541 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4542 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4543 VD->getType(), {NamedChain, Chaining.size()}); 4544 4545 for (const auto *Attr : VD->attrs()) 4546 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4547 4548 IndirectField->setAccess(AS); 4549 IndirectField->setImplicit(); 4550 SemaRef.PushOnScopeChains(IndirectField, S); 4551 4552 // That includes picking up the appropriate access specifier. 4553 if (AS != AS_none) IndirectField->setAccess(AS); 4554 4555 Chaining.resize(OldChainingSize); 4556 } 4557 } 4558 } 4559 4560 return Invalid; 4561 } 4562 4563 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4564 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4565 /// illegal input values are mapped to SC_None. 4566 static StorageClass 4567 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4568 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4569 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4570 "Parser allowed 'typedef' as storage class VarDecl."); 4571 switch (StorageClassSpec) { 4572 case DeclSpec::SCS_unspecified: return SC_None; 4573 case DeclSpec::SCS_extern: 4574 if (DS.isExternInLinkageSpec()) 4575 return SC_None; 4576 return SC_Extern; 4577 case DeclSpec::SCS_static: return SC_Static; 4578 case DeclSpec::SCS_auto: return SC_Auto; 4579 case DeclSpec::SCS_register: return SC_Register; 4580 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4581 // Illegal SCSs map to None: error reporting is up to the caller. 4582 case DeclSpec::SCS_mutable: // Fall through. 4583 case DeclSpec::SCS_typedef: return SC_None; 4584 } 4585 llvm_unreachable("unknown storage class specifier"); 4586 } 4587 4588 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4589 assert(Record->hasInClassInitializer()); 4590 4591 for (const auto *I : Record->decls()) { 4592 const auto *FD = dyn_cast<FieldDecl>(I); 4593 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4594 FD = IFD->getAnonField(); 4595 if (FD && FD->hasInClassInitializer()) 4596 return FD->getLocation(); 4597 } 4598 4599 llvm_unreachable("couldn't find in-class initializer"); 4600 } 4601 4602 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4603 SourceLocation DefaultInitLoc) { 4604 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4605 return; 4606 4607 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4608 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4609 } 4610 4611 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4612 CXXRecordDecl *AnonUnion) { 4613 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4614 return; 4615 4616 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4617 } 4618 4619 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4620 /// anonymous structure or union. Anonymous unions are a C++ feature 4621 /// (C++ [class.union]) and a C11 feature; anonymous structures 4622 /// are a C11 feature and GNU C++ extension. 4623 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4624 AccessSpecifier AS, 4625 RecordDecl *Record, 4626 const PrintingPolicy &Policy) { 4627 DeclContext *Owner = Record->getDeclContext(); 4628 4629 // Diagnose whether this anonymous struct/union is an extension. 4630 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4631 Diag(Record->getLocation(), diag::ext_anonymous_union); 4632 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4633 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4634 else if (!Record->isUnion() && !getLangOpts().C11) 4635 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4636 4637 // C and C++ require different kinds of checks for anonymous 4638 // structs/unions. 4639 bool Invalid = false; 4640 if (getLangOpts().CPlusPlus) { 4641 const char *PrevSpec = nullptr; 4642 unsigned DiagID; 4643 if (Record->isUnion()) { 4644 // C++ [class.union]p6: 4645 // C++17 [class.union.anon]p2: 4646 // Anonymous unions declared in a named namespace or in the 4647 // global namespace shall be declared static. 4648 DeclContext *OwnerScope = Owner->getRedeclContext(); 4649 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4650 (OwnerScope->isTranslationUnit() || 4651 (OwnerScope->isNamespace() && 4652 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4653 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4654 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4655 4656 // Recover by adding 'static'. 4657 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4658 PrevSpec, DiagID, Policy); 4659 } 4660 // C++ [class.union]p6: 4661 // A storage class is not allowed in a declaration of an 4662 // anonymous union in a class scope. 4663 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4664 isa<RecordDecl>(Owner)) { 4665 Diag(DS.getStorageClassSpecLoc(), 4666 diag::err_anonymous_union_with_storage_spec) 4667 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4668 4669 // Recover by removing the storage specifier. 4670 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4671 SourceLocation(), 4672 PrevSpec, DiagID, Context.getPrintingPolicy()); 4673 } 4674 } 4675 4676 // Ignore const/volatile/restrict qualifiers. 4677 if (DS.getTypeQualifiers()) { 4678 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4679 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4680 << Record->isUnion() << "const" 4681 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4682 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4683 Diag(DS.getVolatileSpecLoc(), 4684 diag::ext_anonymous_struct_union_qualified) 4685 << Record->isUnion() << "volatile" 4686 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4687 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4688 Diag(DS.getRestrictSpecLoc(), 4689 diag::ext_anonymous_struct_union_qualified) 4690 << Record->isUnion() << "restrict" 4691 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4692 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4693 Diag(DS.getAtomicSpecLoc(), 4694 diag::ext_anonymous_struct_union_qualified) 4695 << Record->isUnion() << "_Atomic" 4696 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4697 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4698 Diag(DS.getUnalignedSpecLoc(), 4699 diag::ext_anonymous_struct_union_qualified) 4700 << Record->isUnion() << "__unaligned" 4701 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4702 4703 DS.ClearTypeQualifiers(); 4704 } 4705 4706 // C++ [class.union]p2: 4707 // The member-specification of an anonymous union shall only 4708 // define non-static data members. [Note: nested types and 4709 // functions cannot be declared within an anonymous union. ] 4710 for (auto *Mem : Record->decls()) { 4711 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4712 // C++ [class.union]p3: 4713 // An anonymous union shall not have private or protected 4714 // members (clause 11). 4715 assert(FD->getAccess() != AS_none); 4716 if (FD->getAccess() != AS_public) { 4717 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4718 << Record->isUnion() << (FD->getAccess() == AS_protected); 4719 Invalid = true; 4720 } 4721 4722 // C++ [class.union]p1 4723 // An object of a class with a non-trivial constructor, a non-trivial 4724 // copy constructor, a non-trivial destructor, or a non-trivial copy 4725 // assignment operator cannot be a member of a union, nor can an 4726 // array of such objects. 4727 if (CheckNontrivialField(FD)) 4728 Invalid = true; 4729 } else if (Mem->isImplicit()) { 4730 // Any implicit members are fine. 4731 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4732 // This is a type that showed up in an 4733 // elaborated-type-specifier inside the anonymous struct or 4734 // union, but which actually declares a type outside of the 4735 // anonymous struct or union. It's okay. 4736 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4737 if (!MemRecord->isAnonymousStructOrUnion() && 4738 MemRecord->getDeclName()) { 4739 // Visual C++ allows type definition in anonymous struct or union. 4740 if (getLangOpts().MicrosoftExt) 4741 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4742 << Record->isUnion(); 4743 else { 4744 // This is a nested type declaration. 4745 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4746 << Record->isUnion(); 4747 Invalid = true; 4748 } 4749 } else { 4750 // This is an anonymous type definition within another anonymous type. 4751 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4752 // not part of standard C++. 4753 Diag(MemRecord->getLocation(), 4754 diag::ext_anonymous_record_with_anonymous_type) 4755 << Record->isUnion(); 4756 } 4757 } else if (isa<AccessSpecDecl>(Mem)) { 4758 // Any access specifier is fine. 4759 } else if (isa<StaticAssertDecl>(Mem)) { 4760 // In C++1z, static_assert declarations are also fine. 4761 } else { 4762 // We have something that isn't a non-static data 4763 // member. Complain about it. 4764 unsigned DK = diag::err_anonymous_record_bad_member; 4765 if (isa<TypeDecl>(Mem)) 4766 DK = diag::err_anonymous_record_with_type; 4767 else if (isa<FunctionDecl>(Mem)) 4768 DK = diag::err_anonymous_record_with_function; 4769 else if (isa<VarDecl>(Mem)) 4770 DK = diag::err_anonymous_record_with_static; 4771 4772 // Visual C++ allows type definition in anonymous struct or union. 4773 if (getLangOpts().MicrosoftExt && 4774 DK == diag::err_anonymous_record_with_type) 4775 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4776 << Record->isUnion(); 4777 else { 4778 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4779 Invalid = true; 4780 } 4781 } 4782 } 4783 4784 // C++11 [class.union]p8 (DR1460): 4785 // At most one variant member of a union may have a 4786 // brace-or-equal-initializer. 4787 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4788 Owner->isRecord()) 4789 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4790 cast<CXXRecordDecl>(Record)); 4791 } 4792 4793 if (!Record->isUnion() && !Owner->isRecord()) { 4794 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4795 << getLangOpts().CPlusPlus; 4796 Invalid = true; 4797 } 4798 4799 // Mock up a declarator. 4800 Declarator Dc(DS, DeclaratorContext::MemberContext); 4801 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4802 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4803 4804 // Create a declaration for this anonymous struct/union. 4805 NamedDecl *Anon = nullptr; 4806 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4807 Anon = FieldDecl::Create( 4808 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 4809 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 4810 /*BitWidth=*/nullptr, /*Mutable=*/false, 4811 /*InitStyle=*/ICIS_NoInit); 4812 Anon->setAccess(AS); 4813 if (getLangOpts().CPlusPlus) 4814 FieldCollector->Add(cast<FieldDecl>(Anon)); 4815 } else { 4816 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4817 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4818 if (SCSpec == DeclSpec::SCS_mutable) { 4819 // mutable can only appear on non-static class members, so it's always 4820 // an error here 4821 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4822 Invalid = true; 4823 SC = SC_None; 4824 } 4825 4826 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 4827 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4828 Context.getTypeDeclType(Record), TInfo, SC); 4829 4830 // Default-initialize the implicit variable. This initialization will be 4831 // trivial in almost all cases, except if a union member has an in-class 4832 // initializer: 4833 // union { int n = 0; }; 4834 ActOnUninitializedDecl(Anon); 4835 } 4836 Anon->setImplicit(); 4837 4838 // Mark this as an anonymous struct/union type. 4839 Record->setAnonymousStructOrUnion(true); 4840 4841 // Add the anonymous struct/union object to the current 4842 // context. We'll be referencing this object when we refer to one of 4843 // its members. 4844 Owner->addDecl(Anon); 4845 4846 // Inject the members of the anonymous struct/union into the owning 4847 // context and into the identifier resolver chain for name lookup 4848 // purposes. 4849 SmallVector<NamedDecl*, 2> Chain; 4850 Chain.push_back(Anon); 4851 4852 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4853 Invalid = true; 4854 4855 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4856 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4857 Decl *ManglingContextDecl; 4858 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4859 NewVD->getDeclContext(), ManglingContextDecl)) { 4860 Context.setManglingNumber( 4861 NewVD, MCtx->getManglingNumber( 4862 NewVD, getMSManglingNumber(getLangOpts(), S))); 4863 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4864 } 4865 } 4866 } 4867 4868 if (Invalid) 4869 Anon->setInvalidDecl(); 4870 4871 return Anon; 4872 } 4873 4874 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4875 /// Microsoft C anonymous structure. 4876 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4877 /// Example: 4878 /// 4879 /// struct A { int a; }; 4880 /// struct B { struct A; int b; }; 4881 /// 4882 /// void foo() { 4883 /// B var; 4884 /// var.a = 3; 4885 /// } 4886 /// 4887 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4888 RecordDecl *Record) { 4889 assert(Record && "expected a record!"); 4890 4891 // Mock up a declarator. 4892 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4893 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4894 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4895 4896 auto *ParentDecl = cast<RecordDecl>(CurContext); 4897 QualType RecTy = Context.getTypeDeclType(Record); 4898 4899 // Create a declaration for this anonymous struct. 4900 NamedDecl *Anon = 4901 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 4902 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 4903 /*BitWidth=*/nullptr, /*Mutable=*/false, 4904 /*InitStyle=*/ICIS_NoInit); 4905 Anon->setImplicit(); 4906 4907 // Add the anonymous struct object to the current context. 4908 CurContext->addDecl(Anon); 4909 4910 // Inject the members of the anonymous struct into the current 4911 // context and into the identifier resolver chain for name lookup 4912 // purposes. 4913 SmallVector<NamedDecl*, 2> Chain; 4914 Chain.push_back(Anon); 4915 4916 RecordDecl *RecordDef = Record->getDefinition(); 4917 if (RequireCompleteType(Anon->getLocation(), RecTy, 4918 diag::err_field_incomplete) || 4919 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4920 AS_none, Chain)) { 4921 Anon->setInvalidDecl(); 4922 ParentDecl->setInvalidDecl(); 4923 } 4924 4925 return Anon; 4926 } 4927 4928 /// GetNameForDeclarator - Determine the full declaration name for the 4929 /// given Declarator. 4930 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4931 return GetNameFromUnqualifiedId(D.getName()); 4932 } 4933 4934 /// Retrieves the declaration name from a parsed unqualified-id. 4935 DeclarationNameInfo 4936 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4937 DeclarationNameInfo NameInfo; 4938 NameInfo.setLoc(Name.StartLocation); 4939 4940 switch (Name.getKind()) { 4941 4942 case UnqualifiedIdKind::IK_ImplicitSelfParam: 4943 case UnqualifiedIdKind::IK_Identifier: 4944 NameInfo.setName(Name.Identifier); 4945 return NameInfo; 4946 4947 case UnqualifiedIdKind::IK_DeductionGuideName: { 4948 // C++ [temp.deduct.guide]p3: 4949 // The simple-template-id shall name a class template specialization. 4950 // The template-name shall be the same identifier as the template-name 4951 // of the simple-template-id. 4952 // These together intend to imply that the template-name shall name a 4953 // class template. 4954 // FIXME: template<typename T> struct X {}; 4955 // template<typename T> using Y = X<T>; 4956 // Y(int) -> Y<int>; 4957 // satisfies these rules but does not name a class template. 4958 TemplateName TN = Name.TemplateName.get().get(); 4959 auto *Template = TN.getAsTemplateDecl(); 4960 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4961 Diag(Name.StartLocation, 4962 diag::err_deduction_guide_name_not_class_template) 4963 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4964 if (Template) 4965 Diag(Template->getLocation(), diag::note_template_decl_here); 4966 return DeclarationNameInfo(); 4967 } 4968 4969 NameInfo.setName( 4970 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4971 return NameInfo; 4972 } 4973 4974 case UnqualifiedIdKind::IK_OperatorFunctionId: 4975 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4976 Name.OperatorFunctionId.Operator)); 4977 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4978 = Name.OperatorFunctionId.SymbolLocations[0]; 4979 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4980 = Name.EndLocation.getRawEncoding(); 4981 return NameInfo; 4982 4983 case UnqualifiedIdKind::IK_LiteralOperatorId: 4984 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4985 Name.Identifier)); 4986 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4987 return NameInfo; 4988 4989 case UnqualifiedIdKind::IK_ConversionFunctionId: { 4990 TypeSourceInfo *TInfo; 4991 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4992 if (Ty.isNull()) 4993 return DeclarationNameInfo(); 4994 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4995 Context.getCanonicalType(Ty))); 4996 NameInfo.setNamedTypeInfo(TInfo); 4997 return NameInfo; 4998 } 4999 5000 case UnqualifiedIdKind::IK_ConstructorName: { 5001 TypeSourceInfo *TInfo; 5002 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5003 if (Ty.isNull()) 5004 return DeclarationNameInfo(); 5005 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5006 Context.getCanonicalType(Ty))); 5007 NameInfo.setNamedTypeInfo(TInfo); 5008 return NameInfo; 5009 } 5010 5011 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5012 // In well-formed code, we can only have a constructor 5013 // template-id that refers to the current context, so go there 5014 // to find the actual type being constructed. 5015 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5016 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5017 return DeclarationNameInfo(); 5018 5019 // Determine the type of the class being constructed. 5020 QualType CurClassType = Context.getTypeDeclType(CurClass); 5021 5022 // FIXME: Check two things: that the template-id names the same type as 5023 // CurClassType, and that the template-id does not occur when the name 5024 // was qualified. 5025 5026 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5027 Context.getCanonicalType(CurClassType))); 5028 // FIXME: should we retrieve TypeSourceInfo? 5029 NameInfo.setNamedTypeInfo(nullptr); 5030 return NameInfo; 5031 } 5032 5033 case UnqualifiedIdKind::IK_DestructorName: { 5034 TypeSourceInfo *TInfo; 5035 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5036 if (Ty.isNull()) 5037 return DeclarationNameInfo(); 5038 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5039 Context.getCanonicalType(Ty))); 5040 NameInfo.setNamedTypeInfo(TInfo); 5041 return NameInfo; 5042 } 5043 5044 case UnqualifiedIdKind::IK_TemplateId: { 5045 TemplateName TName = Name.TemplateId->Template.get(); 5046 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5047 return Context.getNameForTemplate(TName, TNameLoc); 5048 } 5049 5050 } // switch (Name.getKind()) 5051 5052 llvm_unreachable("Unknown name kind"); 5053 } 5054 5055 static QualType getCoreType(QualType Ty) { 5056 do { 5057 if (Ty->isPointerType() || Ty->isReferenceType()) 5058 Ty = Ty->getPointeeType(); 5059 else if (Ty->isArrayType()) 5060 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5061 else 5062 return Ty.withoutLocalFastQualifiers(); 5063 } while (true); 5064 } 5065 5066 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5067 /// and Definition have "nearly" matching parameters. This heuristic is 5068 /// used to improve diagnostics in the case where an out-of-line function 5069 /// definition doesn't match any declaration within the class or namespace. 5070 /// Also sets Params to the list of indices to the parameters that differ 5071 /// between the declaration and the definition. If hasSimilarParameters 5072 /// returns true and Params is empty, then all of the parameters match. 5073 static bool hasSimilarParameters(ASTContext &Context, 5074 FunctionDecl *Declaration, 5075 FunctionDecl *Definition, 5076 SmallVectorImpl<unsigned> &Params) { 5077 Params.clear(); 5078 if (Declaration->param_size() != Definition->param_size()) 5079 return false; 5080 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5081 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5082 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5083 5084 // The parameter types are identical 5085 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5086 continue; 5087 5088 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5089 QualType DefParamBaseTy = getCoreType(DefParamTy); 5090 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5091 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5092 5093 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5094 (DeclTyName && DeclTyName == DefTyName)) 5095 Params.push_back(Idx); 5096 else // The two parameters aren't even close 5097 return false; 5098 } 5099 5100 return true; 5101 } 5102 5103 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5104 /// declarator needs to be rebuilt in the current instantiation. 5105 /// Any bits of declarator which appear before the name are valid for 5106 /// consideration here. That's specifically the type in the decl spec 5107 /// and the base type in any member-pointer chunks. 5108 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5109 DeclarationName Name) { 5110 // The types we specifically need to rebuild are: 5111 // - typenames, typeofs, and decltypes 5112 // - types which will become injected class names 5113 // Of course, we also need to rebuild any type referencing such a 5114 // type. It's safest to just say "dependent", but we call out a 5115 // few cases here. 5116 5117 DeclSpec &DS = D.getMutableDeclSpec(); 5118 switch (DS.getTypeSpecType()) { 5119 case DeclSpec::TST_typename: 5120 case DeclSpec::TST_typeofType: 5121 case DeclSpec::TST_underlyingType: 5122 case DeclSpec::TST_atomic: { 5123 // Grab the type from the parser. 5124 TypeSourceInfo *TSI = nullptr; 5125 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5126 if (T.isNull() || !T->isDependentType()) break; 5127 5128 // Make sure there's a type source info. This isn't really much 5129 // of a waste; most dependent types should have type source info 5130 // attached already. 5131 if (!TSI) 5132 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5133 5134 // Rebuild the type in the current instantiation. 5135 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5136 if (!TSI) return true; 5137 5138 // Store the new type back in the decl spec. 5139 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5140 DS.UpdateTypeRep(LocType); 5141 break; 5142 } 5143 5144 case DeclSpec::TST_decltype: 5145 case DeclSpec::TST_typeofExpr: { 5146 Expr *E = DS.getRepAsExpr(); 5147 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5148 if (Result.isInvalid()) return true; 5149 DS.UpdateExprRep(Result.get()); 5150 break; 5151 } 5152 5153 default: 5154 // Nothing to do for these decl specs. 5155 break; 5156 } 5157 5158 // It doesn't matter what order we do this in. 5159 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5160 DeclaratorChunk &Chunk = D.getTypeObject(I); 5161 5162 // The only type information in the declarator which can come 5163 // before the declaration name is the base type of a member 5164 // pointer. 5165 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5166 continue; 5167 5168 // Rebuild the scope specifier in-place. 5169 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5170 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5171 return true; 5172 } 5173 5174 return false; 5175 } 5176 5177 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5178 D.setFunctionDefinitionKind(FDK_Declaration); 5179 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5180 5181 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5182 Dcl && Dcl->getDeclContext()->isFileContext()) 5183 Dcl->setTopLevelDeclInObjCContainer(); 5184 5185 if (getLangOpts().OpenCL) 5186 setCurrentOpenCLExtensionForDecl(Dcl); 5187 5188 return Dcl; 5189 } 5190 5191 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5192 /// If T is the name of a class, then each of the following shall have a 5193 /// name different from T: 5194 /// - every static data member of class T; 5195 /// - every member function of class T 5196 /// - every member of class T that is itself a type; 5197 /// \returns true if the declaration name violates these rules. 5198 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5199 DeclarationNameInfo NameInfo) { 5200 DeclarationName Name = NameInfo.getName(); 5201 5202 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5203 while (Record && Record->isAnonymousStructOrUnion()) 5204 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5205 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5206 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5207 return true; 5208 } 5209 5210 return false; 5211 } 5212 5213 /// Diagnose a declaration whose declarator-id has the given 5214 /// nested-name-specifier. 5215 /// 5216 /// \param SS The nested-name-specifier of the declarator-id. 5217 /// 5218 /// \param DC The declaration context to which the nested-name-specifier 5219 /// resolves. 5220 /// 5221 /// \param Name The name of the entity being declared. 5222 /// 5223 /// \param Loc The location of the name of the entity being declared. 5224 /// 5225 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5226 /// we're declaring an explicit / partial specialization / instantiation. 5227 /// 5228 /// \returns true if we cannot safely recover from this error, false otherwise. 5229 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5230 DeclarationName Name, 5231 SourceLocation Loc, bool IsTemplateId) { 5232 DeclContext *Cur = CurContext; 5233 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5234 Cur = Cur->getParent(); 5235 5236 // If the user provided a superfluous scope specifier that refers back to the 5237 // class in which the entity is already declared, diagnose and ignore it. 5238 // 5239 // class X { 5240 // void X::f(); 5241 // }; 5242 // 5243 // Note, it was once ill-formed to give redundant qualification in all 5244 // contexts, but that rule was removed by DR482. 5245 if (Cur->Equals(DC)) { 5246 if (Cur->isRecord()) { 5247 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5248 : diag::err_member_extra_qualification) 5249 << Name << FixItHint::CreateRemoval(SS.getRange()); 5250 SS.clear(); 5251 } else { 5252 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5253 } 5254 return false; 5255 } 5256 5257 // Check whether the qualifying scope encloses the scope of the original 5258 // declaration. For a template-id, we perform the checks in 5259 // CheckTemplateSpecializationScope. 5260 if (!Cur->Encloses(DC) && !IsTemplateId) { 5261 if (Cur->isRecord()) 5262 Diag(Loc, diag::err_member_qualification) 5263 << Name << SS.getRange(); 5264 else if (isa<TranslationUnitDecl>(DC)) 5265 Diag(Loc, diag::err_invalid_declarator_global_scope) 5266 << Name << SS.getRange(); 5267 else if (isa<FunctionDecl>(Cur)) 5268 Diag(Loc, diag::err_invalid_declarator_in_function) 5269 << Name << SS.getRange(); 5270 else if (isa<BlockDecl>(Cur)) 5271 Diag(Loc, diag::err_invalid_declarator_in_block) 5272 << Name << SS.getRange(); 5273 else 5274 Diag(Loc, diag::err_invalid_declarator_scope) 5275 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5276 5277 return true; 5278 } 5279 5280 if (Cur->isRecord()) { 5281 // Cannot qualify members within a class. 5282 Diag(Loc, diag::err_member_qualification) 5283 << Name << SS.getRange(); 5284 SS.clear(); 5285 5286 // C++ constructors and destructors with incorrect scopes can break 5287 // our AST invariants by having the wrong underlying types. If 5288 // that's the case, then drop this declaration entirely. 5289 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5290 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5291 !Context.hasSameType(Name.getCXXNameType(), 5292 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5293 return true; 5294 5295 return false; 5296 } 5297 5298 // C++11 [dcl.meaning]p1: 5299 // [...] "The nested-name-specifier of the qualified declarator-id shall 5300 // not begin with a decltype-specifer" 5301 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5302 while (SpecLoc.getPrefix()) 5303 SpecLoc = SpecLoc.getPrefix(); 5304 if (dyn_cast_or_null<DecltypeType>( 5305 SpecLoc.getNestedNameSpecifier()->getAsType())) 5306 Diag(Loc, diag::err_decltype_in_declarator) 5307 << SpecLoc.getTypeLoc().getSourceRange(); 5308 5309 return false; 5310 } 5311 5312 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5313 MultiTemplateParamsArg TemplateParamLists) { 5314 // TODO: consider using NameInfo for diagnostic. 5315 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5316 DeclarationName Name = NameInfo.getName(); 5317 5318 // All of these full declarators require an identifier. If it doesn't have 5319 // one, the ParsedFreeStandingDeclSpec action should be used. 5320 if (D.isDecompositionDeclarator()) { 5321 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5322 } else if (!Name) { 5323 if (!D.isInvalidType()) // Reject this if we think it is valid. 5324 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5325 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5326 return nullptr; 5327 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5328 return nullptr; 5329 5330 // The scope passed in may not be a decl scope. Zip up the scope tree until 5331 // we find one that is. 5332 while ((S->getFlags() & Scope::DeclScope) == 0 || 5333 (S->getFlags() & Scope::TemplateParamScope) != 0) 5334 S = S->getParent(); 5335 5336 DeclContext *DC = CurContext; 5337 if (D.getCXXScopeSpec().isInvalid()) 5338 D.setInvalidType(); 5339 else if (D.getCXXScopeSpec().isSet()) { 5340 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5341 UPPC_DeclarationQualifier)) 5342 return nullptr; 5343 5344 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5345 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5346 if (!DC || isa<EnumDecl>(DC)) { 5347 // If we could not compute the declaration context, it's because the 5348 // declaration context is dependent but does not refer to a class, 5349 // class template, or class template partial specialization. Complain 5350 // and return early, to avoid the coming semantic disaster. 5351 Diag(D.getIdentifierLoc(), 5352 diag::err_template_qualified_declarator_no_match) 5353 << D.getCXXScopeSpec().getScopeRep() 5354 << D.getCXXScopeSpec().getRange(); 5355 return nullptr; 5356 } 5357 bool IsDependentContext = DC->isDependentContext(); 5358 5359 if (!IsDependentContext && 5360 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5361 return nullptr; 5362 5363 // If a class is incomplete, do not parse entities inside it. 5364 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5365 Diag(D.getIdentifierLoc(), 5366 diag::err_member_def_undefined_record) 5367 << Name << DC << D.getCXXScopeSpec().getRange(); 5368 return nullptr; 5369 } 5370 if (!D.getDeclSpec().isFriendSpecified()) { 5371 if (diagnoseQualifiedDeclaration( 5372 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5373 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5374 if (DC->isRecord()) 5375 return nullptr; 5376 5377 D.setInvalidType(); 5378 } 5379 } 5380 5381 // Check whether we need to rebuild the type of the given 5382 // declaration in the current instantiation. 5383 if (EnteringContext && IsDependentContext && 5384 TemplateParamLists.size() != 0) { 5385 ContextRAII SavedContext(*this, DC); 5386 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5387 D.setInvalidType(); 5388 } 5389 } 5390 5391 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5392 QualType R = TInfo->getType(); 5393 5394 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5395 UPPC_DeclarationType)) 5396 D.setInvalidType(); 5397 5398 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5399 forRedeclarationInCurContext()); 5400 5401 // See if this is a redefinition of a variable in the same scope. 5402 if (!D.getCXXScopeSpec().isSet()) { 5403 bool IsLinkageLookup = false; 5404 bool CreateBuiltins = false; 5405 5406 // If the declaration we're planning to build will be a function 5407 // or object with linkage, then look for another declaration with 5408 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5409 // 5410 // If the declaration we're planning to build will be declared with 5411 // external linkage in the translation unit, create any builtin with 5412 // the same name. 5413 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5414 /* Do nothing*/; 5415 else if (CurContext->isFunctionOrMethod() && 5416 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5417 R->isFunctionType())) { 5418 IsLinkageLookup = true; 5419 CreateBuiltins = 5420 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5421 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5422 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5423 CreateBuiltins = true; 5424 5425 if (IsLinkageLookup) { 5426 Previous.clear(LookupRedeclarationWithLinkage); 5427 Previous.setRedeclarationKind(ForExternalRedeclaration); 5428 } 5429 5430 LookupName(Previous, S, CreateBuiltins); 5431 } else { // Something like "int foo::x;" 5432 LookupQualifiedName(Previous, DC); 5433 5434 // C++ [dcl.meaning]p1: 5435 // When the declarator-id is qualified, the declaration shall refer to a 5436 // previously declared member of the class or namespace to which the 5437 // qualifier refers (or, in the case of a namespace, of an element of the 5438 // inline namespace set of that namespace (7.3.1)) or to a specialization 5439 // thereof; [...] 5440 // 5441 // Note that we already checked the context above, and that we do not have 5442 // enough information to make sure that Previous contains the declaration 5443 // we want to match. For example, given: 5444 // 5445 // class X { 5446 // void f(); 5447 // void f(float); 5448 // }; 5449 // 5450 // void X::f(int) { } // ill-formed 5451 // 5452 // In this case, Previous will point to the overload set 5453 // containing the two f's declared in X, but neither of them 5454 // matches. 5455 5456 // C++ [dcl.meaning]p1: 5457 // [...] the member shall not merely have been introduced by a 5458 // using-declaration in the scope of the class or namespace nominated by 5459 // the nested-name-specifier of the declarator-id. 5460 RemoveUsingDecls(Previous); 5461 } 5462 5463 if (Previous.isSingleResult() && 5464 Previous.getFoundDecl()->isTemplateParameter()) { 5465 // Maybe we will complain about the shadowed template parameter. 5466 if (!D.isInvalidType()) 5467 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5468 Previous.getFoundDecl()); 5469 5470 // Just pretend that we didn't see the previous declaration. 5471 Previous.clear(); 5472 } 5473 5474 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5475 // Forget that the previous declaration is the injected-class-name. 5476 Previous.clear(); 5477 5478 // In C++, the previous declaration we find might be a tag type 5479 // (class or enum). In this case, the new declaration will hide the 5480 // tag type. Note that this applies to functions, function templates, and 5481 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5482 if (Previous.isSingleTagDecl() && 5483 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5484 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5485 Previous.clear(); 5486 5487 // Check that there are no default arguments other than in the parameters 5488 // of a function declaration (C++ only). 5489 if (getLangOpts().CPlusPlus) 5490 CheckExtraCXXDefaultArguments(D); 5491 5492 NamedDecl *New; 5493 5494 bool AddToScope = true; 5495 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5496 if (TemplateParamLists.size()) { 5497 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5498 return nullptr; 5499 } 5500 5501 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5502 } else if (R->isFunctionType()) { 5503 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5504 TemplateParamLists, 5505 AddToScope); 5506 } else { 5507 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5508 AddToScope); 5509 } 5510 5511 if (!New) 5512 return nullptr; 5513 5514 // If this has an identifier and is not a function template specialization, 5515 // add it to the scope stack. 5516 if (New->getDeclName() && AddToScope) 5517 PushOnScopeChains(New, S); 5518 5519 if (isInOpenMPDeclareTargetContext()) 5520 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5521 5522 return New; 5523 } 5524 5525 /// Helper method to turn variable array types into constant array 5526 /// types in certain situations which would otherwise be errors (for 5527 /// GCC compatibility). 5528 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5529 ASTContext &Context, 5530 bool &SizeIsNegative, 5531 llvm::APSInt &Oversized) { 5532 // This method tries to turn a variable array into a constant 5533 // array even when the size isn't an ICE. This is necessary 5534 // for compatibility with code that depends on gcc's buggy 5535 // constant expression folding, like struct {char x[(int)(char*)2];} 5536 SizeIsNegative = false; 5537 Oversized = 0; 5538 5539 if (T->isDependentType()) 5540 return QualType(); 5541 5542 QualifierCollector Qs; 5543 const Type *Ty = Qs.strip(T); 5544 5545 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5546 QualType Pointee = PTy->getPointeeType(); 5547 QualType FixedType = 5548 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5549 Oversized); 5550 if (FixedType.isNull()) return FixedType; 5551 FixedType = Context.getPointerType(FixedType); 5552 return Qs.apply(Context, FixedType); 5553 } 5554 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5555 QualType Inner = PTy->getInnerType(); 5556 QualType FixedType = 5557 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5558 Oversized); 5559 if (FixedType.isNull()) return FixedType; 5560 FixedType = Context.getParenType(FixedType); 5561 return Qs.apply(Context, FixedType); 5562 } 5563 5564 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5565 if (!VLATy) 5566 return QualType(); 5567 // FIXME: We should probably handle this case 5568 if (VLATy->getElementType()->isVariablyModifiedType()) 5569 return QualType(); 5570 5571 Expr::EvalResult Result; 5572 if (!VLATy->getSizeExpr() || 5573 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5574 return QualType(); 5575 5576 llvm::APSInt Res = Result.Val.getInt(); 5577 5578 // Check whether the array size is negative. 5579 if (Res.isSigned() && Res.isNegative()) { 5580 SizeIsNegative = true; 5581 return QualType(); 5582 } 5583 5584 // Check whether the array is too large to be addressed. 5585 unsigned ActiveSizeBits 5586 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5587 Res); 5588 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5589 Oversized = Res; 5590 return QualType(); 5591 } 5592 5593 return Context.getConstantArrayType(VLATy->getElementType(), 5594 Res, ArrayType::Normal, 0); 5595 } 5596 5597 static void 5598 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5599 SrcTL = SrcTL.getUnqualifiedLoc(); 5600 DstTL = DstTL.getUnqualifiedLoc(); 5601 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5602 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5603 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5604 DstPTL.getPointeeLoc()); 5605 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5606 return; 5607 } 5608 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5609 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5610 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5611 DstPTL.getInnerLoc()); 5612 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5613 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5614 return; 5615 } 5616 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5617 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5618 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5619 TypeLoc DstElemTL = DstATL.getElementLoc(); 5620 DstElemTL.initializeFullCopy(SrcElemTL); 5621 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5622 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5623 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5624 } 5625 5626 /// Helper method to turn variable array types into constant array 5627 /// types in certain situations which would otherwise be errors (for 5628 /// GCC compatibility). 5629 static TypeSourceInfo* 5630 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5631 ASTContext &Context, 5632 bool &SizeIsNegative, 5633 llvm::APSInt &Oversized) { 5634 QualType FixedTy 5635 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5636 SizeIsNegative, Oversized); 5637 if (FixedTy.isNull()) 5638 return nullptr; 5639 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5640 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5641 FixedTInfo->getTypeLoc()); 5642 return FixedTInfo; 5643 } 5644 5645 /// Register the given locally-scoped extern "C" declaration so 5646 /// that it can be found later for redeclarations. We include any extern "C" 5647 /// declaration that is not visible in the translation unit here, not just 5648 /// function-scope declarations. 5649 void 5650 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5651 if (!getLangOpts().CPlusPlus && 5652 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5653 // Don't need to track declarations in the TU in C. 5654 return; 5655 5656 // Note that we have a locally-scoped external with this name. 5657 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5658 } 5659 5660 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5661 // FIXME: We can have multiple results via __attribute__((overloadable)). 5662 auto Result = Context.getExternCContextDecl()->lookup(Name); 5663 return Result.empty() ? nullptr : *Result.begin(); 5664 } 5665 5666 /// Diagnose function specifiers on a declaration of an identifier that 5667 /// does not identify a function. 5668 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5669 // FIXME: We should probably indicate the identifier in question to avoid 5670 // confusion for constructs like "virtual int a(), b;" 5671 if (DS.isVirtualSpecified()) 5672 Diag(DS.getVirtualSpecLoc(), 5673 diag::err_virtual_non_function); 5674 5675 if (DS.isExplicitSpecified()) 5676 Diag(DS.getExplicitSpecLoc(), 5677 diag::err_explicit_non_function); 5678 5679 if (DS.isNoreturnSpecified()) 5680 Diag(DS.getNoreturnSpecLoc(), 5681 diag::err_noreturn_non_function); 5682 } 5683 5684 NamedDecl* 5685 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5686 TypeSourceInfo *TInfo, LookupResult &Previous) { 5687 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5688 if (D.getCXXScopeSpec().isSet()) { 5689 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5690 << D.getCXXScopeSpec().getRange(); 5691 D.setInvalidType(); 5692 // Pretend we didn't see the scope specifier. 5693 DC = CurContext; 5694 Previous.clear(); 5695 } 5696 5697 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5698 5699 if (D.getDeclSpec().isInlineSpecified()) 5700 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5701 << getLangOpts().CPlusPlus17; 5702 if (D.getDeclSpec().isConstexprSpecified()) 5703 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5704 << 1; 5705 5706 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5707 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5708 Diag(D.getName().StartLocation, 5709 diag::err_deduction_guide_invalid_specifier) 5710 << "typedef"; 5711 else 5712 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5713 << D.getName().getSourceRange(); 5714 return nullptr; 5715 } 5716 5717 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5718 if (!NewTD) return nullptr; 5719 5720 // Handle attributes prior to checking for duplicates in MergeVarDecl 5721 ProcessDeclAttributes(S, NewTD, D); 5722 5723 CheckTypedefForVariablyModifiedType(S, NewTD); 5724 5725 bool Redeclaration = D.isRedeclaration(); 5726 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5727 D.setRedeclaration(Redeclaration); 5728 return ND; 5729 } 5730 5731 void 5732 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5733 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5734 // then it shall have block scope. 5735 // Note that variably modified types must be fixed before merging the decl so 5736 // that redeclarations will match. 5737 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5738 QualType T = TInfo->getType(); 5739 if (T->isVariablyModifiedType()) { 5740 setFunctionHasBranchProtectedScope(); 5741 5742 if (S->getFnParent() == nullptr) { 5743 bool SizeIsNegative; 5744 llvm::APSInt Oversized; 5745 TypeSourceInfo *FixedTInfo = 5746 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5747 SizeIsNegative, 5748 Oversized); 5749 if (FixedTInfo) { 5750 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5751 NewTD->setTypeSourceInfo(FixedTInfo); 5752 } else { 5753 if (SizeIsNegative) 5754 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5755 else if (T->isVariableArrayType()) 5756 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5757 else if (Oversized.getBoolValue()) 5758 Diag(NewTD->getLocation(), diag::err_array_too_large) 5759 << Oversized.toString(10); 5760 else 5761 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5762 NewTD->setInvalidDecl(); 5763 } 5764 } 5765 } 5766 } 5767 5768 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5769 /// declares a typedef-name, either using the 'typedef' type specifier or via 5770 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5771 NamedDecl* 5772 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5773 LookupResult &Previous, bool &Redeclaration) { 5774 5775 // Find the shadowed declaration before filtering for scope. 5776 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5777 5778 // Merge the decl with the existing one if appropriate. If the decl is 5779 // in an outer scope, it isn't the same thing. 5780 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5781 /*AllowInlineNamespace*/false); 5782 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5783 if (!Previous.empty()) { 5784 Redeclaration = true; 5785 MergeTypedefNameDecl(S, NewTD, Previous); 5786 } 5787 5788 if (ShadowedDecl && !Redeclaration) 5789 CheckShadow(NewTD, ShadowedDecl, Previous); 5790 5791 // If this is the C FILE type, notify the AST context. 5792 if (IdentifierInfo *II = NewTD->getIdentifier()) 5793 if (!NewTD->isInvalidDecl() && 5794 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5795 if (II->isStr("FILE")) 5796 Context.setFILEDecl(NewTD); 5797 else if (II->isStr("jmp_buf")) 5798 Context.setjmp_bufDecl(NewTD); 5799 else if (II->isStr("sigjmp_buf")) 5800 Context.setsigjmp_bufDecl(NewTD); 5801 else if (II->isStr("ucontext_t")) 5802 Context.setucontext_tDecl(NewTD); 5803 } 5804 5805 return NewTD; 5806 } 5807 5808 /// Determines whether the given declaration is an out-of-scope 5809 /// previous declaration. 5810 /// 5811 /// This routine should be invoked when name lookup has found a 5812 /// previous declaration (PrevDecl) that is not in the scope where a 5813 /// new declaration by the same name is being introduced. If the new 5814 /// declaration occurs in a local scope, previous declarations with 5815 /// linkage may still be considered previous declarations (C99 5816 /// 6.2.2p4-5, C++ [basic.link]p6). 5817 /// 5818 /// \param PrevDecl the previous declaration found by name 5819 /// lookup 5820 /// 5821 /// \param DC the context in which the new declaration is being 5822 /// declared. 5823 /// 5824 /// \returns true if PrevDecl is an out-of-scope previous declaration 5825 /// for a new delcaration with the same name. 5826 static bool 5827 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5828 ASTContext &Context) { 5829 if (!PrevDecl) 5830 return false; 5831 5832 if (!PrevDecl->hasLinkage()) 5833 return false; 5834 5835 if (Context.getLangOpts().CPlusPlus) { 5836 // C++ [basic.link]p6: 5837 // If there is a visible declaration of an entity with linkage 5838 // having the same name and type, ignoring entities declared 5839 // outside the innermost enclosing namespace scope, the block 5840 // scope declaration declares that same entity and receives the 5841 // linkage of the previous declaration. 5842 DeclContext *OuterContext = DC->getRedeclContext(); 5843 if (!OuterContext->isFunctionOrMethod()) 5844 // This rule only applies to block-scope declarations. 5845 return false; 5846 5847 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5848 if (PrevOuterContext->isRecord()) 5849 // We found a member function: ignore it. 5850 return false; 5851 5852 // Find the innermost enclosing namespace for the new and 5853 // previous declarations. 5854 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5855 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5856 5857 // The previous declaration is in a different namespace, so it 5858 // isn't the same function. 5859 if (!OuterContext->Equals(PrevOuterContext)) 5860 return false; 5861 } 5862 5863 return true; 5864 } 5865 5866 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 5867 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5868 if (!SS.isSet()) return; 5869 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 5870 } 5871 5872 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5873 QualType type = decl->getType(); 5874 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5875 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5876 // Various kinds of declaration aren't allowed to be __autoreleasing. 5877 unsigned kind = -1U; 5878 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5879 if (var->hasAttr<BlocksAttr>()) 5880 kind = 0; // __block 5881 else if (!var->hasLocalStorage()) 5882 kind = 1; // global 5883 } else if (isa<ObjCIvarDecl>(decl)) { 5884 kind = 3; // ivar 5885 } else if (isa<FieldDecl>(decl)) { 5886 kind = 2; // field 5887 } 5888 5889 if (kind != -1U) { 5890 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5891 << kind; 5892 } 5893 } else if (lifetime == Qualifiers::OCL_None) { 5894 // Try to infer lifetime. 5895 if (!type->isObjCLifetimeType()) 5896 return false; 5897 5898 lifetime = type->getObjCARCImplicitLifetime(); 5899 type = Context.getLifetimeQualifiedType(type, lifetime); 5900 decl->setType(type); 5901 } 5902 5903 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5904 // Thread-local variables cannot have lifetime. 5905 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5906 var->getTLSKind()) { 5907 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5908 << var->getType(); 5909 return true; 5910 } 5911 } 5912 5913 return false; 5914 } 5915 5916 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5917 // Ensure that an auto decl is deduced otherwise the checks below might cache 5918 // the wrong linkage. 5919 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5920 5921 // 'weak' only applies to declarations with external linkage. 5922 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5923 if (!ND.isExternallyVisible()) { 5924 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5925 ND.dropAttr<WeakAttr>(); 5926 } 5927 } 5928 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5929 if (ND.isExternallyVisible()) { 5930 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5931 ND.dropAttr<WeakRefAttr>(); 5932 ND.dropAttr<AliasAttr>(); 5933 } 5934 } 5935 5936 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5937 if (VD->hasInit()) { 5938 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5939 assert(VD->isThisDeclarationADefinition() && 5940 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5941 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5942 VD->dropAttr<AliasAttr>(); 5943 } 5944 } 5945 } 5946 5947 // 'selectany' only applies to externally visible variable declarations. 5948 // It does not apply to functions. 5949 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5950 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5951 S.Diag(Attr->getLocation(), 5952 diag::err_attribute_selectany_non_extern_data); 5953 ND.dropAttr<SelectAnyAttr>(); 5954 } 5955 } 5956 5957 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5958 // dll attributes require external linkage. Static locals may have external 5959 // linkage but still cannot be explicitly imported or exported. 5960 auto *VD = dyn_cast<VarDecl>(&ND); 5961 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5962 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5963 << &ND << Attr; 5964 ND.setInvalidDecl(); 5965 } 5966 } 5967 5968 // Virtual functions cannot be marked as 'notail'. 5969 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5970 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5971 if (MD->isVirtual()) { 5972 S.Diag(ND.getLocation(), 5973 diag::err_invalid_attribute_on_virtual_function) 5974 << Attr; 5975 ND.dropAttr<NotTailCalledAttr>(); 5976 } 5977 5978 // Check the attributes on the function type, if any. 5979 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 5980 // Don't declare this variable in the second operand of the for-statement; 5981 // GCC miscompiles that by ending its lifetime before evaluating the 5982 // third operand. See gcc.gnu.org/PR86769. 5983 AttributedTypeLoc ATL; 5984 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 5985 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 5986 TL = ATL.getModifiedLoc()) { 5987 // The [[lifetimebound]] attribute can be applied to the implicit object 5988 // parameter of a non-static member function (other than a ctor or dtor) 5989 // by applying it to the function type. 5990 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 5991 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 5992 if (!MD || MD->isStatic()) { 5993 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 5994 << !MD << A->getRange(); 5995 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 5996 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 5997 << isa<CXXDestructorDecl>(MD) << A->getRange(); 5998 } 5999 } 6000 } 6001 } 6002 } 6003 6004 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6005 NamedDecl *NewDecl, 6006 bool IsSpecialization, 6007 bool IsDefinition) { 6008 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6009 return; 6010 6011 bool IsTemplate = false; 6012 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6013 OldDecl = OldTD->getTemplatedDecl(); 6014 IsTemplate = true; 6015 if (!IsSpecialization) 6016 IsDefinition = false; 6017 } 6018 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6019 NewDecl = NewTD->getTemplatedDecl(); 6020 IsTemplate = true; 6021 } 6022 6023 if (!OldDecl || !NewDecl) 6024 return; 6025 6026 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6027 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6028 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6029 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6030 6031 // dllimport and dllexport are inheritable attributes so we have to exclude 6032 // inherited attribute instances. 6033 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6034 (NewExportAttr && !NewExportAttr->isInherited()); 6035 6036 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6037 // the only exception being explicit specializations. 6038 // Implicitly generated declarations are also excluded for now because there 6039 // is no other way to switch these to use dllimport or dllexport. 6040 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6041 6042 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6043 // Allow with a warning for free functions and global variables. 6044 bool JustWarn = false; 6045 if (!OldDecl->isCXXClassMember()) { 6046 auto *VD = dyn_cast<VarDecl>(OldDecl); 6047 if (VD && !VD->getDescribedVarTemplate()) 6048 JustWarn = true; 6049 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6050 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6051 JustWarn = true; 6052 } 6053 6054 // We cannot change a declaration that's been used because IR has already 6055 // been emitted. Dllimported functions will still work though (modulo 6056 // address equality) as they can use the thunk. 6057 if (OldDecl->isUsed()) 6058 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6059 JustWarn = false; 6060 6061 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6062 : diag::err_attribute_dll_redeclaration; 6063 S.Diag(NewDecl->getLocation(), DiagID) 6064 << NewDecl 6065 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6066 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6067 if (!JustWarn) { 6068 NewDecl->setInvalidDecl(); 6069 return; 6070 } 6071 } 6072 6073 // A redeclaration is not allowed to drop a dllimport attribute, the only 6074 // exceptions being inline function definitions (except for function 6075 // templates), local extern declarations, qualified friend declarations or 6076 // special MSVC extension: in the last case, the declaration is treated as if 6077 // it were marked dllexport. 6078 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6079 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6080 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6081 // Ignore static data because out-of-line definitions are diagnosed 6082 // separately. 6083 IsStaticDataMember = VD->isStaticDataMember(); 6084 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6085 VarDecl::DeclarationOnly; 6086 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6087 IsInline = FD->isInlined(); 6088 IsQualifiedFriend = FD->getQualifier() && 6089 FD->getFriendObjectKind() == Decl::FOK_Declared; 6090 } 6091 6092 if (OldImportAttr && !HasNewAttr && 6093 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6094 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6095 if (IsMicrosoft && IsDefinition) { 6096 S.Diag(NewDecl->getLocation(), 6097 diag::warn_redeclaration_without_import_attribute) 6098 << NewDecl; 6099 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6100 NewDecl->dropAttr<DLLImportAttr>(); 6101 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6102 NewImportAttr->getRange(), S.Context, 6103 NewImportAttr->getSpellingListIndex())); 6104 } else { 6105 S.Diag(NewDecl->getLocation(), 6106 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6107 << NewDecl << OldImportAttr; 6108 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6109 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6110 OldDecl->dropAttr<DLLImportAttr>(); 6111 NewDecl->dropAttr<DLLImportAttr>(); 6112 } 6113 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6114 // In MinGW, seeing a function declared inline drops the dllimport 6115 // attribute. 6116 OldDecl->dropAttr<DLLImportAttr>(); 6117 NewDecl->dropAttr<DLLImportAttr>(); 6118 S.Diag(NewDecl->getLocation(), 6119 diag::warn_dllimport_dropped_from_inline_function) 6120 << NewDecl << OldImportAttr; 6121 } 6122 6123 // A specialization of a class template member function is processed here 6124 // since it's a redeclaration. If the parent class is dllexport, the 6125 // specialization inherits that attribute. This doesn't happen automatically 6126 // since the parent class isn't instantiated until later. 6127 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6128 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6129 !NewImportAttr && !NewExportAttr) { 6130 if (const DLLExportAttr *ParentExportAttr = 6131 MD->getParent()->getAttr<DLLExportAttr>()) { 6132 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6133 NewAttr->setInherited(true); 6134 NewDecl->addAttr(NewAttr); 6135 } 6136 } 6137 } 6138 } 6139 6140 /// Given that we are within the definition of the given function, 6141 /// will that definition behave like C99's 'inline', where the 6142 /// definition is discarded except for optimization purposes? 6143 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6144 // Try to avoid calling GetGVALinkageForFunction. 6145 6146 // All cases of this require the 'inline' keyword. 6147 if (!FD->isInlined()) return false; 6148 6149 // This is only possible in C++ with the gnu_inline attribute. 6150 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6151 return false; 6152 6153 // Okay, go ahead and call the relatively-more-expensive function. 6154 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6155 } 6156 6157 /// Determine whether a variable is extern "C" prior to attaching 6158 /// an initializer. We can't just call isExternC() here, because that 6159 /// will also compute and cache whether the declaration is externally 6160 /// visible, which might change when we attach the initializer. 6161 /// 6162 /// This can only be used if the declaration is known to not be a 6163 /// redeclaration of an internal linkage declaration. 6164 /// 6165 /// For instance: 6166 /// 6167 /// auto x = []{}; 6168 /// 6169 /// Attaching the initializer here makes this declaration not externally 6170 /// visible, because its type has internal linkage. 6171 /// 6172 /// FIXME: This is a hack. 6173 template<typename T> 6174 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6175 if (S.getLangOpts().CPlusPlus) { 6176 // In C++, the overloadable attribute negates the effects of extern "C". 6177 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6178 return false; 6179 6180 // So do CUDA's host/device attributes. 6181 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6182 D->template hasAttr<CUDAHostAttr>())) 6183 return false; 6184 } 6185 return D->isExternC(); 6186 } 6187 6188 static bool shouldConsiderLinkage(const VarDecl *VD) { 6189 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6190 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6191 return VD->hasExternalStorage(); 6192 if (DC->isFileContext()) 6193 return true; 6194 if (DC->isRecord()) 6195 return false; 6196 llvm_unreachable("Unexpected context"); 6197 } 6198 6199 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6200 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6201 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6202 isa<OMPDeclareReductionDecl>(DC)) 6203 return true; 6204 if (DC->isRecord()) 6205 return false; 6206 llvm_unreachable("Unexpected context"); 6207 } 6208 6209 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6210 ParsedAttr::Kind Kind) { 6211 // Check decl attributes on the DeclSpec. 6212 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6213 return true; 6214 6215 // Walk the declarator structure, checking decl attributes that were in a type 6216 // position to the decl itself. 6217 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6218 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6219 return true; 6220 } 6221 6222 // Finally, check attributes on the decl itself. 6223 return PD.getAttributes().hasAttribute(Kind); 6224 } 6225 6226 /// Adjust the \c DeclContext for a function or variable that might be a 6227 /// function-local external declaration. 6228 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6229 if (!DC->isFunctionOrMethod()) 6230 return false; 6231 6232 // If this is a local extern function or variable declared within a function 6233 // template, don't add it into the enclosing namespace scope until it is 6234 // instantiated; it might have a dependent type right now. 6235 if (DC->isDependentContext()) 6236 return true; 6237 6238 // C++11 [basic.link]p7: 6239 // When a block scope declaration of an entity with linkage is not found to 6240 // refer to some other declaration, then that entity is a member of the 6241 // innermost enclosing namespace. 6242 // 6243 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6244 // semantically-enclosing namespace, not a lexically-enclosing one. 6245 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6246 DC = DC->getParent(); 6247 return true; 6248 } 6249 6250 /// Returns true if given declaration has external C language linkage. 6251 static bool isDeclExternC(const Decl *D) { 6252 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6253 return FD->isExternC(); 6254 if (const auto *VD = dyn_cast<VarDecl>(D)) 6255 return VD->isExternC(); 6256 6257 llvm_unreachable("Unknown type of decl!"); 6258 } 6259 6260 NamedDecl *Sema::ActOnVariableDeclarator( 6261 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6262 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6263 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6264 QualType R = TInfo->getType(); 6265 DeclarationName Name = GetNameForDeclarator(D).getName(); 6266 6267 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6268 6269 if (D.isDecompositionDeclarator()) { 6270 // Take the name of the first declarator as our name for diagnostic 6271 // purposes. 6272 auto &Decomp = D.getDecompositionDeclarator(); 6273 if (!Decomp.bindings().empty()) { 6274 II = Decomp.bindings()[0].Name; 6275 Name = II; 6276 } 6277 } else if (!II) { 6278 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6279 return nullptr; 6280 } 6281 6282 if (getLangOpts().OpenCL) { 6283 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6284 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6285 // argument. 6286 if (R->isImageType() || R->isPipeType()) { 6287 Diag(D.getIdentifierLoc(), 6288 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6289 << R; 6290 D.setInvalidType(); 6291 return nullptr; 6292 } 6293 6294 // OpenCL v1.2 s6.9.r: 6295 // The event type cannot be used to declare a program scope variable. 6296 // OpenCL v2.0 s6.9.q: 6297 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6298 if (NULL == S->getParent()) { 6299 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6300 Diag(D.getIdentifierLoc(), 6301 diag::err_invalid_type_for_program_scope_var) << R; 6302 D.setInvalidType(); 6303 return nullptr; 6304 } 6305 } 6306 6307 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6308 QualType NR = R; 6309 while (NR->isPointerType()) { 6310 if (NR->isFunctionPointerType()) { 6311 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6312 D.setInvalidType(); 6313 break; 6314 } 6315 NR = NR->getPointeeType(); 6316 } 6317 6318 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6319 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6320 // half array type (unless the cl_khr_fp16 extension is enabled). 6321 if (Context.getBaseElementType(R)->isHalfType()) { 6322 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6323 D.setInvalidType(); 6324 } 6325 } 6326 6327 if (R->isSamplerT()) { 6328 // OpenCL v1.2 s6.9.b p4: 6329 // The sampler type cannot be used with the __local and __global address 6330 // space qualifiers. 6331 if (R.getAddressSpace() == LangAS::opencl_local || 6332 R.getAddressSpace() == LangAS::opencl_global) { 6333 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6334 } 6335 6336 // OpenCL v1.2 s6.12.14.1: 6337 // A global sampler must be declared with either the constant address 6338 // space qualifier or with the const qualifier. 6339 if (DC->isTranslationUnit() && 6340 !(R.getAddressSpace() == LangAS::opencl_constant || 6341 R.isConstQualified())) { 6342 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6343 D.setInvalidType(); 6344 } 6345 } 6346 6347 // OpenCL v1.2 s6.9.r: 6348 // The event type cannot be used with the __local, __constant and __global 6349 // address space qualifiers. 6350 if (R->isEventT()) { 6351 if (R.getAddressSpace() != LangAS::opencl_private) { 6352 Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6353 D.setInvalidType(); 6354 } 6355 } 6356 6357 // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not 6358 // supported. OpenCL C does not support thread_local either, and 6359 // also reject all other thread storage class specifiers. 6360 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6361 if (TSC != TSCS_unspecified) { 6362 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6363 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6364 diag::err_opencl_unknown_type_specifier) 6365 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6366 << DeclSpec::getSpecifierName(TSC) << 1; 6367 D.setInvalidType(); 6368 return nullptr; 6369 } 6370 } 6371 6372 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6373 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6374 6375 // dllimport globals without explicit storage class are treated as extern. We 6376 // have to change the storage class this early to get the right DeclContext. 6377 if (SC == SC_None && !DC->isRecord() && 6378 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6379 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6380 SC = SC_Extern; 6381 6382 DeclContext *OriginalDC = DC; 6383 bool IsLocalExternDecl = SC == SC_Extern && 6384 adjustContextForLocalExternDecl(DC); 6385 6386 if (SCSpec == DeclSpec::SCS_mutable) { 6387 // mutable can only appear on non-static class members, so it's always 6388 // an error here 6389 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6390 D.setInvalidType(); 6391 SC = SC_None; 6392 } 6393 6394 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6395 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6396 D.getDeclSpec().getStorageClassSpecLoc())) { 6397 // In C++11, the 'register' storage class specifier is deprecated. 6398 // Suppress the warning in system macros, it's used in macros in some 6399 // popular C system headers, such as in glibc's htonl() macro. 6400 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6401 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6402 : diag::warn_deprecated_register) 6403 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6404 } 6405 6406 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6407 6408 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6409 // C99 6.9p2: The storage-class specifiers auto and register shall not 6410 // appear in the declaration specifiers in an external declaration. 6411 // Global Register+Asm is a GNU extension we support. 6412 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6413 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6414 D.setInvalidType(); 6415 } 6416 } 6417 6418 bool IsMemberSpecialization = false; 6419 bool IsVariableTemplateSpecialization = false; 6420 bool IsPartialSpecialization = false; 6421 bool IsVariableTemplate = false; 6422 VarDecl *NewVD = nullptr; 6423 VarTemplateDecl *NewTemplate = nullptr; 6424 TemplateParameterList *TemplateParams = nullptr; 6425 if (!getLangOpts().CPlusPlus) { 6426 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6427 II, R, TInfo, SC); 6428 6429 if (R->getContainedDeducedType()) 6430 ParsingInitForAutoVars.insert(NewVD); 6431 6432 if (D.isInvalidType()) 6433 NewVD->setInvalidDecl(); 6434 } else { 6435 bool Invalid = false; 6436 6437 if (DC->isRecord() && !CurContext->isRecord()) { 6438 // This is an out-of-line definition of a static data member. 6439 switch (SC) { 6440 case SC_None: 6441 break; 6442 case SC_Static: 6443 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6444 diag::err_static_out_of_line) 6445 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6446 break; 6447 case SC_Auto: 6448 case SC_Register: 6449 case SC_Extern: 6450 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6451 // to names of variables declared in a block or to function parameters. 6452 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6453 // of class members 6454 6455 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6456 diag::err_storage_class_for_static_member) 6457 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6458 break; 6459 case SC_PrivateExtern: 6460 llvm_unreachable("C storage class in c++!"); 6461 } 6462 } 6463 6464 if (SC == SC_Static && CurContext->isRecord()) { 6465 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6466 if (RD->isLocalClass()) 6467 Diag(D.getIdentifierLoc(), 6468 diag::err_static_data_member_not_allowed_in_local_class) 6469 << Name << RD->getDeclName(); 6470 6471 // C++98 [class.union]p1: If a union contains a static data member, 6472 // the program is ill-formed. C++11 drops this restriction. 6473 if (RD->isUnion()) 6474 Diag(D.getIdentifierLoc(), 6475 getLangOpts().CPlusPlus11 6476 ? diag::warn_cxx98_compat_static_data_member_in_union 6477 : diag::ext_static_data_member_in_union) << Name; 6478 // We conservatively disallow static data members in anonymous structs. 6479 else if (!RD->getDeclName()) 6480 Diag(D.getIdentifierLoc(), 6481 diag::err_static_data_member_not_allowed_in_anon_struct) 6482 << Name << RD->isUnion(); 6483 } 6484 } 6485 6486 // Match up the template parameter lists with the scope specifier, then 6487 // determine whether we have a template or a template specialization. 6488 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6489 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6490 D.getCXXScopeSpec(), 6491 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6492 ? D.getName().TemplateId 6493 : nullptr, 6494 TemplateParamLists, 6495 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6496 6497 if (TemplateParams) { 6498 if (!TemplateParams->size() && 6499 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6500 // There is an extraneous 'template<>' for this variable. Complain 6501 // about it, but allow the declaration of the variable. 6502 Diag(TemplateParams->getTemplateLoc(), 6503 diag::err_template_variable_noparams) 6504 << II 6505 << SourceRange(TemplateParams->getTemplateLoc(), 6506 TemplateParams->getRAngleLoc()); 6507 TemplateParams = nullptr; 6508 } else { 6509 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6510 // This is an explicit specialization or a partial specialization. 6511 // FIXME: Check that we can declare a specialization here. 6512 IsVariableTemplateSpecialization = true; 6513 IsPartialSpecialization = TemplateParams->size() > 0; 6514 } else { // if (TemplateParams->size() > 0) 6515 // This is a template declaration. 6516 IsVariableTemplate = true; 6517 6518 // Check that we can declare a template here. 6519 if (CheckTemplateDeclScope(S, TemplateParams)) 6520 return nullptr; 6521 6522 // Only C++1y supports variable templates (N3651). 6523 Diag(D.getIdentifierLoc(), 6524 getLangOpts().CPlusPlus14 6525 ? diag::warn_cxx11_compat_variable_template 6526 : diag::ext_variable_template); 6527 } 6528 } 6529 } else { 6530 assert((Invalid || 6531 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6532 "should have a 'template<>' for this decl"); 6533 } 6534 6535 if (IsVariableTemplateSpecialization) { 6536 SourceLocation TemplateKWLoc = 6537 TemplateParamLists.size() > 0 6538 ? TemplateParamLists[0]->getTemplateLoc() 6539 : SourceLocation(); 6540 DeclResult Res = ActOnVarTemplateSpecialization( 6541 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6542 IsPartialSpecialization); 6543 if (Res.isInvalid()) 6544 return nullptr; 6545 NewVD = cast<VarDecl>(Res.get()); 6546 AddToScope = false; 6547 } else if (D.isDecompositionDeclarator()) { 6548 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6549 D.getIdentifierLoc(), R, TInfo, SC, 6550 Bindings); 6551 } else 6552 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6553 D.getIdentifierLoc(), II, R, TInfo, SC); 6554 6555 // If this is supposed to be a variable template, create it as such. 6556 if (IsVariableTemplate) { 6557 NewTemplate = 6558 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6559 TemplateParams, NewVD); 6560 NewVD->setDescribedVarTemplate(NewTemplate); 6561 } 6562 6563 // If this decl has an auto type in need of deduction, make a note of the 6564 // Decl so we can diagnose uses of it in its own initializer. 6565 if (R->getContainedDeducedType()) 6566 ParsingInitForAutoVars.insert(NewVD); 6567 6568 if (D.isInvalidType() || Invalid) { 6569 NewVD->setInvalidDecl(); 6570 if (NewTemplate) 6571 NewTemplate->setInvalidDecl(); 6572 } 6573 6574 SetNestedNameSpecifier(*this, NewVD, D); 6575 6576 // If we have any template parameter lists that don't directly belong to 6577 // the variable (matching the scope specifier), store them. 6578 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6579 if (TemplateParamLists.size() > VDTemplateParamLists) 6580 NewVD->setTemplateParameterListsInfo( 6581 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6582 6583 if (D.getDeclSpec().isConstexprSpecified()) { 6584 NewVD->setConstexpr(true); 6585 // C++1z [dcl.spec.constexpr]p1: 6586 // A static data member declared with the constexpr specifier is 6587 // implicitly an inline variable. 6588 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6589 NewVD->setImplicitlyInline(); 6590 } 6591 } 6592 6593 if (D.getDeclSpec().isInlineSpecified()) { 6594 if (!getLangOpts().CPlusPlus) { 6595 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6596 << 0; 6597 } else if (CurContext->isFunctionOrMethod()) { 6598 // 'inline' is not allowed on block scope variable declaration. 6599 Diag(D.getDeclSpec().getInlineSpecLoc(), 6600 diag::err_inline_declaration_block_scope) << Name 6601 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6602 } else { 6603 Diag(D.getDeclSpec().getInlineSpecLoc(), 6604 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6605 : diag::ext_inline_variable); 6606 NewVD->setInlineSpecified(); 6607 } 6608 } 6609 6610 // Set the lexical context. If the declarator has a C++ scope specifier, the 6611 // lexical context will be different from the semantic context. 6612 NewVD->setLexicalDeclContext(CurContext); 6613 if (NewTemplate) 6614 NewTemplate->setLexicalDeclContext(CurContext); 6615 6616 if (IsLocalExternDecl) { 6617 if (D.isDecompositionDeclarator()) 6618 for (auto *B : Bindings) 6619 B->setLocalExternDecl(); 6620 else 6621 NewVD->setLocalExternDecl(); 6622 } 6623 6624 bool EmitTLSUnsupportedError = false; 6625 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6626 // C++11 [dcl.stc]p4: 6627 // When thread_local is applied to a variable of block scope the 6628 // storage-class-specifier static is implied if it does not appear 6629 // explicitly. 6630 // Core issue: 'static' is not implied if the variable is declared 6631 // 'extern'. 6632 if (NewVD->hasLocalStorage() && 6633 (SCSpec != DeclSpec::SCS_unspecified || 6634 TSCS != DeclSpec::TSCS_thread_local || 6635 !DC->isFunctionOrMethod())) 6636 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6637 diag::err_thread_non_global) 6638 << DeclSpec::getSpecifierName(TSCS); 6639 else if (!Context.getTargetInfo().isTLSSupported()) { 6640 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6641 // Postpone error emission until we've collected attributes required to 6642 // figure out whether it's a host or device variable and whether the 6643 // error should be ignored. 6644 EmitTLSUnsupportedError = true; 6645 // We still need to mark the variable as TLS so it shows up in AST with 6646 // proper storage class for other tools to use even if we're not going 6647 // to emit any code for it. 6648 NewVD->setTSCSpec(TSCS); 6649 } else 6650 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6651 diag::err_thread_unsupported); 6652 } else 6653 NewVD->setTSCSpec(TSCS); 6654 } 6655 6656 // C99 6.7.4p3 6657 // An inline definition of a function with external linkage shall 6658 // not contain a definition of a modifiable object with static or 6659 // thread storage duration... 6660 // We only apply this when the function is required to be defined 6661 // elsewhere, i.e. when the function is not 'extern inline'. Note 6662 // that a local variable with thread storage duration still has to 6663 // be marked 'static'. Also note that it's possible to get these 6664 // semantics in C++ using __attribute__((gnu_inline)). 6665 if (SC == SC_Static && S->getFnParent() != nullptr && 6666 !NewVD->getType().isConstQualified()) { 6667 FunctionDecl *CurFD = getCurFunctionDecl(); 6668 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6669 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6670 diag::warn_static_local_in_extern_inline); 6671 MaybeSuggestAddingStaticToDecl(CurFD); 6672 } 6673 } 6674 6675 if (D.getDeclSpec().isModulePrivateSpecified()) { 6676 if (IsVariableTemplateSpecialization) 6677 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6678 << (IsPartialSpecialization ? 1 : 0) 6679 << FixItHint::CreateRemoval( 6680 D.getDeclSpec().getModulePrivateSpecLoc()); 6681 else if (IsMemberSpecialization) 6682 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6683 << 2 6684 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6685 else if (NewVD->hasLocalStorage()) 6686 Diag(NewVD->getLocation(), diag::err_module_private_local) 6687 << 0 << NewVD->getDeclName() 6688 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6689 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6690 else { 6691 NewVD->setModulePrivate(); 6692 if (NewTemplate) 6693 NewTemplate->setModulePrivate(); 6694 for (auto *B : Bindings) 6695 B->setModulePrivate(); 6696 } 6697 } 6698 6699 // Handle attributes prior to checking for duplicates in MergeVarDecl 6700 ProcessDeclAttributes(S, NewVD, D); 6701 6702 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6703 if (EmitTLSUnsupportedError && 6704 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6705 (getLangOpts().OpenMPIsDevice && 6706 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6707 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6708 diag::err_thread_unsupported); 6709 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6710 // storage [duration]." 6711 if (SC == SC_None && S->getFnParent() != nullptr && 6712 (NewVD->hasAttr<CUDASharedAttr>() || 6713 NewVD->hasAttr<CUDAConstantAttr>())) { 6714 NewVD->setStorageClass(SC_Static); 6715 } 6716 } 6717 6718 // Ensure that dllimport globals without explicit storage class are treated as 6719 // extern. The storage class is set above using parsed attributes. Now we can 6720 // check the VarDecl itself. 6721 assert(!NewVD->hasAttr<DLLImportAttr>() || 6722 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6723 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6724 6725 // In auto-retain/release, infer strong retension for variables of 6726 // retainable type. 6727 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6728 NewVD->setInvalidDecl(); 6729 6730 // Handle GNU asm-label extension (encoded as an attribute). 6731 if (Expr *E = (Expr*)D.getAsmLabel()) { 6732 // The parser guarantees this is a string. 6733 StringLiteral *SE = cast<StringLiteral>(E); 6734 StringRef Label = SE->getString(); 6735 if (S->getFnParent() != nullptr) { 6736 switch (SC) { 6737 case SC_None: 6738 case SC_Auto: 6739 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6740 break; 6741 case SC_Register: 6742 // Local Named register 6743 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6744 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6745 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6746 break; 6747 case SC_Static: 6748 case SC_Extern: 6749 case SC_PrivateExtern: 6750 break; 6751 } 6752 } else if (SC == SC_Register) { 6753 // Global Named register 6754 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6755 const auto &TI = Context.getTargetInfo(); 6756 bool HasSizeMismatch; 6757 6758 if (!TI.isValidGCCRegisterName(Label)) 6759 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6760 else if (!TI.validateGlobalRegisterVariable(Label, 6761 Context.getTypeSize(R), 6762 HasSizeMismatch)) 6763 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6764 else if (HasSizeMismatch) 6765 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6766 } 6767 6768 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6769 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 6770 NewVD->setInvalidDecl(true); 6771 } 6772 } 6773 6774 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6775 Context, Label, 0)); 6776 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6777 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6778 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6779 if (I != ExtnameUndeclaredIdentifiers.end()) { 6780 if (isDeclExternC(NewVD)) { 6781 NewVD->addAttr(I->second); 6782 ExtnameUndeclaredIdentifiers.erase(I); 6783 } else 6784 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6785 << /*Variable*/1 << NewVD; 6786 } 6787 } 6788 6789 // Find the shadowed declaration before filtering for scope. 6790 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6791 ? getShadowedDeclaration(NewVD, Previous) 6792 : nullptr; 6793 6794 // Don't consider existing declarations that are in a different 6795 // scope and are out-of-semantic-context declarations (if the new 6796 // declaration has linkage). 6797 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6798 D.getCXXScopeSpec().isNotEmpty() || 6799 IsMemberSpecialization || 6800 IsVariableTemplateSpecialization); 6801 6802 // Check whether the previous declaration is in the same block scope. This 6803 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6804 if (getLangOpts().CPlusPlus && 6805 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6806 NewVD->setPreviousDeclInSameBlockScope( 6807 Previous.isSingleResult() && !Previous.isShadowed() && 6808 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6809 6810 if (!getLangOpts().CPlusPlus) { 6811 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6812 } else { 6813 // If this is an explicit specialization of a static data member, check it. 6814 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6815 CheckMemberSpecialization(NewVD, Previous)) 6816 NewVD->setInvalidDecl(); 6817 6818 // Merge the decl with the existing one if appropriate. 6819 if (!Previous.empty()) { 6820 if (Previous.isSingleResult() && 6821 isa<FieldDecl>(Previous.getFoundDecl()) && 6822 D.getCXXScopeSpec().isSet()) { 6823 // The user tried to define a non-static data member 6824 // out-of-line (C++ [dcl.meaning]p1). 6825 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6826 << D.getCXXScopeSpec().getRange(); 6827 Previous.clear(); 6828 NewVD->setInvalidDecl(); 6829 } 6830 } else if (D.getCXXScopeSpec().isSet()) { 6831 // No previous declaration in the qualifying scope. 6832 Diag(D.getIdentifierLoc(), diag::err_no_member) 6833 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6834 << D.getCXXScopeSpec().getRange(); 6835 NewVD->setInvalidDecl(); 6836 } 6837 6838 if (!IsVariableTemplateSpecialization) 6839 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6840 6841 if (NewTemplate) { 6842 VarTemplateDecl *PrevVarTemplate = 6843 NewVD->getPreviousDecl() 6844 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6845 : nullptr; 6846 6847 // Check the template parameter list of this declaration, possibly 6848 // merging in the template parameter list from the previous variable 6849 // template declaration. 6850 if (CheckTemplateParameterList( 6851 TemplateParams, 6852 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6853 : nullptr, 6854 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6855 DC->isDependentContext()) 6856 ? TPC_ClassTemplateMember 6857 : TPC_VarTemplate)) 6858 NewVD->setInvalidDecl(); 6859 6860 // If we are providing an explicit specialization of a static variable 6861 // template, make a note of that. 6862 if (PrevVarTemplate && 6863 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6864 PrevVarTemplate->setMemberSpecialization(); 6865 } 6866 } 6867 6868 // Diagnose shadowed variables iff this isn't a redeclaration. 6869 if (ShadowedDecl && !D.isRedeclaration()) 6870 CheckShadow(NewVD, ShadowedDecl, Previous); 6871 6872 ProcessPragmaWeak(S, NewVD); 6873 6874 // If this is the first declaration of an extern C variable, update 6875 // the map of such variables. 6876 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6877 isIncompleteDeclExternC(*this, NewVD)) 6878 RegisterLocallyScopedExternCDecl(NewVD, S); 6879 6880 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6881 Decl *ManglingContextDecl; 6882 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6883 NewVD->getDeclContext(), ManglingContextDecl)) { 6884 Context.setManglingNumber( 6885 NewVD, MCtx->getManglingNumber( 6886 NewVD, getMSManglingNumber(getLangOpts(), S))); 6887 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6888 } 6889 } 6890 6891 // Special handling of variable named 'main'. 6892 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6893 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6894 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6895 6896 // C++ [basic.start.main]p3 6897 // A program that declares a variable main at global scope is ill-formed. 6898 if (getLangOpts().CPlusPlus) 6899 Diag(D.getBeginLoc(), diag::err_main_global_variable); 6900 6901 // In C, and external-linkage variable named main results in undefined 6902 // behavior. 6903 else if (NewVD->hasExternalFormalLinkage()) 6904 Diag(D.getBeginLoc(), diag::warn_main_redefined); 6905 } 6906 6907 if (D.isRedeclaration() && !Previous.empty()) { 6908 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6909 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6910 D.isFunctionDefinition()); 6911 } 6912 6913 if (NewTemplate) { 6914 if (NewVD->isInvalidDecl()) 6915 NewTemplate->setInvalidDecl(); 6916 ActOnDocumentableDecl(NewTemplate); 6917 return NewTemplate; 6918 } 6919 6920 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6921 CompleteMemberSpecialization(NewVD, Previous); 6922 6923 return NewVD; 6924 } 6925 6926 /// Enum describing the %select options in diag::warn_decl_shadow. 6927 enum ShadowedDeclKind { 6928 SDK_Local, 6929 SDK_Global, 6930 SDK_StaticMember, 6931 SDK_Field, 6932 SDK_Typedef, 6933 SDK_Using 6934 }; 6935 6936 /// Determine what kind of declaration we're shadowing. 6937 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6938 const DeclContext *OldDC) { 6939 if (isa<TypeAliasDecl>(ShadowedDecl)) 6940 return SDK_Using; 6941 else if (isa<TypedefDecl>(ShadowedDecl)) 6942 return SDK_Typedef; 6943 else if (isa<RecordDecl>(OldDC)) 6944 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6945 6946 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6947 } 6948 6949 /// Return the location of the capture if the given lambda captures the given 6950 /// variable \p VD, or an invalid source location otherwise. 6951 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6952 const VarDecl *VD) { 6953 for (const Capture &Capture : LSI->Captures) { 6954 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6955 return Capture.getLocation(); 6956 } 6957 return SourceLocation(); 6958 } 6959 6960 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6961 const LookupResult &R) { 6962 // Only diagnose if we're shadowing an unambiguous field or variable. 6963 if (R.getResultKind() != LookupResult::Found) 6964 return false; 6965 6966 // Return false if warning is ignored. 6967 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6968 } 6969 6970 /// Return the declaration shadowed by the given variable \p D, or null 6971 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6972 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6973 const LookupResult &R) { 6974 if (!shouldWarnIfShadowedDecl(Diags, R)) 6975 return nullptr; 6976 6977 // Don't diagnose declarations at file scope. 6978 if (D->hasGlobalStorage()) 6979 return nullptr; 6980 6981 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6982 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6983 ? ShadowedDecl 6984 : nullptr; 6985 } 6986 6987 /// Return the declaration shadowed by the given typedef \p D, or null 6988 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6989 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6990 const LookupResult &R) { 6991 // Don't warn if typedef declaration is part of a class 6992 if (D->getDeclContext()->isRecord()) 6993 return nullptr; 6994 6995 if (!shouldWarnIfShadowedDecl(Diags, R)) 6996 return nullptr; 6997 6998 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6999 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7000 } 7001 7002 /// Diagnose variable or built-in function shadowing. Implements 7003 /// -Wshadow. 7004 /// 7005 /// This method is called whenever a VarDecl is added to a "useful" 7006 /// scope. 7007 /// 7008 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7009 /// \param R the lookup of the name 7010 /// 7011 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7012 const LookupResult &R) { 7013 DeclContext *NewDC = D->getDeclContext(); 7014 7015 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7016 // Fields are not shadowed by variables in C++ static methods. 7017 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7018 if (MD->isStatic()) 7019 return; 7020 7021 // Fields shadowed by constructor parameters are a special case. Usually 7022 // the constructor initializes the field with the parameter. 7023 if (isa<CXXConstructorDecl>(NewDC)) 7024 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7025 // Remember that this was shadowed so we can either warn about its 7026 // modification or its existence depending on warning settings. 7027 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7028 return; 7029 } 7030 } 7031 7032 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7033 if (shadowedVar->isExternC()) { 7034 // For shadowing external vars, make sure that we point to the global 7035 // declaration, not a locally scoped extern declaration. 7036 for (auto I : shadowedVar->redecls()) 7037 if (I->isFileVarDecl()) { 7038 ShadowedDecl = I; 7039 break; 7040 } 7041 } 7042 7043 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7044 7045 unsigned WarningDiag = diag::warn_decl_shadow; 7046 SourceLocation CaptureLoc; 7047 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7048 isa<CXXMethodDecl>(NewDC)) { 7049 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7050 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7051 if (RD->getLambdaCaptureDefault() == LCD_None) { 7052 // Try to avoid warnings for lambdas with an explicit capture list. 7053 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7054 // Warn only when the lambda captures the shadowed decl explicitly. 7055 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7056 if (CaptureLoc.isInvalid()) 7057 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7058 } else { 7059 // Remember that this was shadowed so we can avoid the warning if the 7060 // shadowed decl isn't captured and the warning settings allow it. 7061 cast<LambdaScopeInfo>(getCurFunction()) 7062 ->ShadowingDecls.push_back( 7063 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7064 return; 7065 } 7066 } 7067 7068 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7069 // A variable can't shadow a local variable in an enclosing scope, if 7070 // they are separated by a non-capturing declaration context. 7071 for (DeclContext *ParentDC = NewDC; 7072 ParentDC && !ParentDC->Equals(OldDC); 7073 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7074 // Only block literals, captured statements, and lambda expressions 7075 // can capture; other scopes don't. 7076 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7077 !isLambdaCallOperator(ParentDC)) { 7078 return; 7079 } 7080 } 7081 } 7082 } 7083 } 7084 7085 // Only warn about certain kinds of shadowing for class members. 7086 if (NewDC && NewDC->isRecord()) { 7087 // In particular, don't warn about shadowing non-class members. 7088 if (!OldDC->isRecord()) 7089 return; 7090 7091 // TODO: should we warn about static data members shadowing 7092 // static data members from base classes? 7093 7094 // TODO: don't diagnose for inaccessible shadowed members. 7095 // This is hard to do perfectly because we might friend the 7096 // shadowing context, but that's just a false negative. 7097 } 7098 7099 7100 DeclarationName Name = R.getLookupName(); 7101 7102 // Emit warning and note. 7103 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7104 return; 7105 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7106 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7107 if (!CaptureLoc.isInvalid()) 7108 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7109 << Name << /*explicitly*/ 1; 7110 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7111 } 7112 7113 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7114 /// when these variables are captured by the lambda. 7115 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7116 for (const auto &Shadow : LSI->ShadowingDecls) { 7117 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7118 // Try to avoid the warning when the shadowed decl isn't captured. 7119 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7120 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7121 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7122 ? diag::warn_decl_shadow_uncaptured_local 7123 : diag::warn_decl_shadow) 7124 << Shadow.VD->getDeclName() 7125 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7126 if (!CaptureLoc.isInvalid()) 7127 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7128 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7129 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7130 } 7131 } 7132 7133 /// Check -Wshadow without the advantage of a previous lookup. 7134 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7135 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7136 return; 7137 7138 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7139 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7140 LookupName(R, S); 7141 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7142 CheckShadow(D, ShadowedDecl, R); 7143 } 7144 7145 /// Check if 'E', which is an expression that is about to be modified, refers 7146 /// to a constructor parameter that shadows a field. 7147 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7148 // Quickly ignore expressions that can't be shadowing ctor parameters. 7149 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7150 return; 7151 E = E->IgnoreParenImpCasts(); 7152 auto *DRE = dyn_cast<DeclRefExpr>(E); 7153 if (!DRE) 7154 return; 7155 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7156 auto I = ShadowingDecls.find(D); 7157 if (I == ShadowingDecls.end()) 7158 return; 7159 const NamedDecl *ShadowedDecl = I->second; 7160 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7161 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7162 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7163 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7164 7165 // Avoid issuing multiple warnings about the same decl. 7166 ShadowingDecls.erase(I); 7167 } 7168 7169 /// Check for conflict between this global or extern "C" declaration and 7170 /// previous global or extern "C" declarations. This is only used in C++. 7171 template<typename T> 7172 static bool checkGlobalOrExternCConflict( 7173 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7174 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7175 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7176 7177 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7178 // The common case: this global doesn't conflict with any extern "C" 7179 // declaration. 7180 return false; 7181 } 7182 7183 if (Prev) { 7184 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7185 // Both the old and new declarations have C language linkage. This is a 7186 // redeclaration. 7187 Previous.clear(); 7188 Previous.addDecl(Prev); 7189 return true; 7190 } 7191 7192 // This is a global, non-extern "C" declaration, and there is a previous 7193 // non-global extern "C" declaration. Diagnose if this is a variable 7194 // declaration. 7195 if (!isa<VarDecl>(ND)) 7196 return false; 7197 } else { 7198 // The declaration is extern "C". Check for any declaration in the 7199 // translation unit which might conflict. 7200 if (IsGlobal) { 7201 // We have already performed the lookup into the translation unit. 7202 IsGlobal = false; 7203 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7204 I != E; ++I) { 7205 if (isa<VarDecl>(*I)) { 7206 Prev = *I; 7207 break; 7208 } 7209 } 7210 } else { 7211 DeclContext::lookup_result R = 7212 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7213 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7214 I != E; ++I) { 7215 if (isa<VarDecl>(*I)) { 7216 Prev = *I; 7217 break; 7218 } 7219 // FIXME: If we have any other entity with this name in global scope, 7220 // the declaration is ill-formed, but that is a defect: it breaks the 7221 // 'stat' hack, for instance. Only variables can have mangled name 7222 // clashes with extern "C" declarations, so only they deserve a 7223 // diagnostic. 7224 } 7225 } 7226 7227 if (!Prev) 7228 return false; 7229 } 7230 7231 // Use the first declaration's location to ensure we point at something which 7232 // is lexically inside an extern "C" linkage-spec. 7233 assert(Prev && "should have found a previous declaration to diagnose"); 7234 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7235 Prev = FD->getFirstDecl(); 7236 else 7237 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7238 7239 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7240 << IsGlobal << ND; 7241 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7242 << IsGlobal; 7243 return false; 7244 } 7245 7246 /// Apply special rules for handling extern "C" declarations. Returns \c true 7247 /// if we have found that this is a redeclaration of some prior entity. 7248 /// 7249 /// Per C++ [dcl.link]p6: 7250 /// Two declarations [for a function or variable] with C language linkage 7251 /// with the same name that appear in different scopes refer to the same 7252 /// [entity]. An entity with C language linkage shall not be declared with 7253 /// the same name as an entity in global scope. 7254 template<typename T> 7255 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7256 LookupResult &Previous) { 7257 if (!S.getLangOpts().CPlusPlus) { 7258 // In C, when declaring a global variable, look for a corresponding 'extern' 7259 // variable declared in function scope. We don't need this in C++, because 7260 // we find local extern decls in the surrounding file-scope DeclContext. 7261 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7262 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7263 Previous.clear(); 7264 Previous.addDecl(Prev); 7265 return true; 7266 } 7267 } 7268 return false; 7269 } 7270 7271 // A declaration in the translation unit can conflict with an extern "C" 7272 // declaration. 7273 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7274 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7275 7276 // An extern "C" declaration can conflict with a declaration in the 7277 // translation unit or can be a redeclaration of an extern "C" declaration 7278 // in another scope. 7279 if (isIncompleteDeclExternC(S,ND)) 7280 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7281 7282 // Neither global nor extern "C": nothing to do. 7283 return false; 7284 } 7285 7286 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7287 // If the decl is already known invalid, don't check it. 7288 if (NewVD->isInvalidDecl()) 7289 return; 7290 7291 QualType T = NewVD->getType(); 7292 7293 // Defer checking an 'auto' type until its initializer is attached. 7294 if (T->isUndeducedType()) 7295 return; 7296 7297 if (NewVD->hasAttrs()) 7298 CheckAlignasUnderalignment(NewVD); 7299 7300 if (T->isObjCObjectType()) { 7301 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7302 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7303 T = Context.getObjCObjectPointerType(T); 7304 NewVD->setType(T); 7305 } 7306 7307 // Emit an error if an address space was applied to decl with local storage. 7308 // This includes arrays of objects with address space qualifiers, but not 7309 // automatic variables that point to other address spaces. 7310 // ISO/IEC TR 18037 S5.1.2 7311 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7312 T.getAddressSpace() != LangAS::Default) { 7313 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7314 NewVD->setInvalidDecl(); 7315 return; 7316 } 7317 7318 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7319 // scope. 7320 if (getLangOpts().OpenCLVersion == 120 && 7321 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7322 NewVD->isStaticLocal()) { 7323 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7324 NewVD->setInvalidDecl(); 7325 return; 7326 } 7327 7328 if (getLangOpts().OpenCL) { 7329 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7330 if (NewVD->hasAttr<BlocksAttr>()) { 7331 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7332 return; 7333 } 7334 7335 if (T->isBlockPointerType()) { 7336 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7337 // can't use 'extern' storage class. 7338 if (!T.isConstQualified()) { 7339 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7340 << 0 /*const*/; 7341 NewVD->setInvalidDecl(); 7342 return; 7343 } 7344 if (NewVD->hasExternalStorage()) { 7345 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7346 NewVD->setInvalidDecl(); 7347 return; 7348 } 7349 } 7350 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7351 // __constant address space. 7352 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7353 // variables inside a function can also be declared in the global 7354 // address space. 7355 // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local 7356 // address space additionally. 7357 // FIXME: Add local AS for OpenCL C++. 7358 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7359 NewVD->hasExternalStorage()) { 7360 if (!T->isSamplerT() && 7361 !(T.getAddressSpace() == LangAS::opencl_constant || 7362 (T.getAddressSpace() == LangAS::opencl_global && 7363 (getLangOpts().OpenCLVersion == 200 || 7364 getLangOpts().OpenCLCPlusPlus)))) { 7365 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7366 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7367 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7368 << Scope << "global or constant"; 7369 else 7370 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7371 << Scope << "constant"; 7372 NewVD->setInvalidDecl(); 7373 return; 7374 } 7375 } else { 7376 if (T.getAddressSpace() == LangAS::opencl_global) { 7377 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7378 << 1 /*is any function*/ << "global"; 7379 NewVD->setInvalidDecl(); 7380 return; 7381 } 7382 if (T.getAddressSpace() == LangAS::opencl_constant || 7383 T.getAddressSpace() == LangAS::opencl_local) { 7384 FunctionDecl *FD = getCurFunctionDecl(); 7385 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7386 // in functions. 7387 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7388 if (T.getAddressSpace() == LangAS::opencl_constant) 7389 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7390 << 0 /*non-kernel only*/ << "constant"; 7391 else 7392 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7393 << 0 /*non-kernel only*/ << "local"; 7394 NewVD->setInvalidDecl(); 7395 return; 7396 } 7397 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7398 // in the outermost scope of a kernel function. 7399 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7400 if (!getCurScope()->isFunctionScope()) { 7401 if (T.getAddressSpace() == LangAS::opencl_constant) 7402 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7403 << "constant"; 7404 else 7405 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7406 << "local"; 7407 NewVD->setInvalidDecl(); 7408 return; 7409 } 7410 } 7411 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7412 // Do not allow other address spaces on automatic variable. 7413 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7414 NewVD->setInvalidDecl(); 7415 return; 7416 } 7417 } 7418 } 7419 7420 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7421 && !NewVD->hasAttr<BlocksAttr>()) { 7422 if (getLangOpts().getGC() != LangOptions::NonGC) 7423 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7424 else { 7425 assert(!getLangOpts().ObjCAutoRefCount); 7426 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7427 } 7428 } 7429 7430 bool isVM = T->isVariablyModifiedType(); 7431 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7432 NewVD->hasAttr<BlocksAttr>()) 7433 setFunctionHasBranchProtectedScope(); 7434 7435 if ((isVM && NewVD->hasLinkage()) || 7436 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7437 bool SizeIsNegative; 7438 llvm::APSInt Oversized; 7439 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7440 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7441 QualType FixedT; 7442 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7443 FixedT = FixedTInfo->getType(); 7444 else if (FixedTInfo) { 7445 // Type and type-as-written are canonically different. We need to fix up 7446 // both types separately. 7447 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7448 Oversized); 7449 } 7450 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7451 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7452 // FIXME: This won't give the correct result for 7453 // int a[10][n]; 7454 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7455 7456 if (NewVD->isFileVarDecl()) 7457 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7458 << SizeRange; 7459 else if (NewVD->isStaticLocal()) 7460 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7461 << SizeRange; 7462 else 7463 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7464 << SizeRange; 7465 NewVD->setInvalidDecl(); 7466 return; 7467 } 7468 7469 if (!FixedTInfo) { 7470 if (NewVD->isFileVarDecl()) 7471 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7472 else 7473 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7474 NewVD->setInvalidDecl(); 7475 return; 7476 } 7477 7478 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7479 NewVD->setType(FixedT); 7480 NewVD->setTypeSourceInfo(FixedTInfo); 7481 } 7482 7483 if (T->isVoidType()) { 7484 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7485 // of objects and functions. 7486 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7487 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7488 << T; 7489 NewVD->setInvalidDecl(); 7490 return; 7491 } 7492 } 7493 7494 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7495 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7496 NewVD->setInvalidDecl(); 7497 return; 7498 } 7499 7500 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7501 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7502 NewVD->setInvalidDecl(); 7503 return; 7504 } 7505 7506 if (NewVD->isConstexpr() && !T->isDependentType() && 7507 RequireLiteralType(NewVD->getLocation(), T, 7508 diag::err_constexpr_var_non_literal)) { 7509 NewVD->setInvalidDecl(); 7510 return; 7511 } 7512 } 7513 7514 /// Perform semantic checking on a newly-created variable 7515 /// declaration. 7516 /// 7517 /// This routine performs all of the type-checking required for a 7518 /// variable declaration once it has been built. It is used both to 7519 /// check variables after they have been parsed and their declarators 7520 /// have been translated into a declaration, and to check variables 7521 /// that have been instantiated from a template. 7522 /// 7523 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7524 /// 7525 /// Returns true if the variable declaration is a redeclaration. 7526 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7527 CheckVariableDeclarationType(NewVD); 7528 7529 // If the decl is already known invalid, don't check it. 7530 if (NewVD->isInvalidDecl()) 7531 return false; 7532 7533 // If we did not find anything by this name, look for a non-visible 7534 // extern "C" declaration with the same name. 7535 if (Previous.empty() && 7536 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7537 Previous.setShadowed(); 7538 7539 if (!Previous.empty()) { 7540 MergeVarDecl(NewVD, Previous); 7541 return true; 7542 } 7543 return false; 7544 } 7545 7546 namespace { 7547 struct FindOverriddenMethod { 7548 Sema *S; 7549 CXXMethodDecl *Method; 7550 7551 /// Member lookup function that determines whether a given C++ 7552 /// method overrides a method in a base class, to be used with 7553 /// CXXRecordDecl::lookupInBases(). 7554 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7555 RecordDecl *BaseRecord = 7556 Specifier->getType()->getAs<RecordType>()->getDecl(); 7557 7558 DeclarationName Name = Method->getDeclName(); 7559 7560 // FIXME: Do we care about other names here too? 7561 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7562 // We really want to find the base class destructor here. 7563 QualType T = S->Context.getTypeDeclType(BaseRecord); 7564 CanQualType CT = S->Context.getCanonicalType(T); 7565 7566 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7567 } 7568 7569 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7570 Path.Decls = Path.Decls.slice(1)) { 7571 NamedDecl *D = Path.Decls.front(); 7572 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7573 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7574 return true; 7575 } 7576 } 7577 7578 return false; 7579 } 7580 }; 7581 7582 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7583 } // end anonymous namespace 7584 7585 /// Report an error regarding overriding, along with any relevant 7586 /// overridden methods. 7587 /// 7588 /// \param DiagID the primary error to report. 7589 /// \param MD the overriding method. 7590 /// \param OEK which overrides to include as notes. 7591 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7592 OverrideErrorKind OEK = OEK_All) { 7593 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7594 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7595 // This check (& the OEK parameter) could be replaced by a predicate, but 7596 // without lambdas that would be overkill. This is still nicer than writing 7597 // out the diag loop 3 times. 7598 if ((OEK == OEK_All) || 7599 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7600 (OEK == OEK_Deleted && O->isDeleted())) 7601 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7602 } 7603 } 7604 7605 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7606 /// and if so, check that it's a valid override and remember it. 7607 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7608 // Look for methods in base classes that this method might override. 7609 CXXBasePaths Paths; 7610 FindOverriddenMethod FOM; 7611 FOM.Method = MD; 7612 FOM.S = this; 7613 bool hasDeletedOverridenMethods = false; 7614 bool hasNonDeletedOverridenMethods = false; 7615 bool AddedAny = false; 7616 if (DC->lookupInBases(FOM, Paths)) { 7617 for (auto *I : Paths.found_decls()) { 7618 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7619 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7620 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7621 !CheckOverridingFunctionAttributes(MD, OldMD) && 7622 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7623 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7624 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7625 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7626 AddedAny = true; 7627 } 7628 } 7629 } 7630 } 7631 7632 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7633 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7634 } 7635 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7636 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7637 } 7638 7639 return AddedAny; 7640 } 7641 7642 namespace { 7643 // Struct for holding all of the extra arguments needed by 7644 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7645 struct ActOnFDArgs { 7646 Scope *S; 7647 Declarator &D; 7648 MultiTemplateParamsArg TemplateParamLists; 7649 bool AddToScope; 7650 }; 7651 } // end anonymous namespace 7652 7653 namespace { 7654 7655 // Callback to only accept typo corrections that have a non-zero edit distance. 7656 // Also only accept corrections that have the same parent decl. 7657 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7658 public: 7659 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7660 CXXRecordDecl *Parent) 7661 : Context(Context), OriginalFD(TypoFD), 7662 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7663 7664 bool ValidateCandidate(const TypoCorrection &candidate) override { 7665 if (candidate.getEditDistance() == 0) 7666 return false; 7667 7668 SmallVector<unsigned, 1> MismatchedParams; 7669 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7670 CDeclEnd = candidate.end(); 7671 CDecl != CDeclEnd; ++CDecl) { 7672 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7673 7674 if (FD && !FD->hasBody() && 7675 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7676 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7677 CXXRecordDecl *Parent = MD->getParent(); 7678 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7679 return true; 7680 } else if (!ExpectedParent) { 7681 return true; 7682 } 7683 } 7684 } 7685 7686 return false; 7687 } 7688 7689 private: 7690 ASTContext &Context; 7691 FunctionDecl *OriginalFD; 7692 CXXRecordDecl *ExpectedParent; 7693 }; 7694 7695 } // end anonymous namespace 7696 7697 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7698 TypoCorrectedFunctionDefinitions.insert(F); 7699 } 7700 7701 /// Generate diagnostics for an invalid function redeclaration. 7702 /// 7703 /// This routine handles generating the diagnostic messages for an invalid 7704 /// function redeclaration, including finding possible similar declarations 7705 /// or performing typo correction if there are no previous declarations with 7706 /// the same name. 7707 /// 7708 /// Returns a NamedDecl iff typo correction was performed and substituting in 7709 /// the new declaration name does not cause new errors. 7710 static NamedDecl *DiagnoseInvalidRedeclaration( 7711 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7712 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7713 DeclarationName Name = NewFD->getDeclName(); 7714 DeclContext *NewDC = NewFD->getDeclContext(); 7715 SmallVector<unsigned, 1> MismatchedParams; 7716 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7717 TypoCorrection Correction; 7718 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7719 unsigned DiagMsg = 7720 IsLocalFriend ? diag::err_no_matching_local_friend : 7721 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 7722 diag::err_member_decl_does_not_match; 7723 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7724 IsLocalFriend ? Sema::LookupLocalFriendName 7725 : Sema::LookupOrdinaryName, 7726 Sema::ForVisibleRedeclaration); 7727 7728 NewFD->setInvalidDecl(); 7729 if (IsLocalFriend) 7730 SemaRef.LookupName(Prev, S); 7731 else 7732 SemaRef.LookupQualifiedName(Prev, NewDC); 7733 assert(!Prev.isAmbiguous() && 7734 "Cannot have an ambiguity in previous-declaration lookup"); 7735 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7736 if (!Prev.empty()) { 7737 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7738 Func != FuncEnd; ++Func) { 7739 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7740 if (FD && 7741 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7742 // Add 1 to the index so that 0 can mean the mismatch didn't 7743 // involve a parameter 7744 unsigned ParamNum = 7745 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7746 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7747 } 7748 } 7749 // If the qualified name lookup yielded nothing, try typo correction 7750 } else if ((Correction = SemaRef.CorrectTypo( 7751 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7752 &ExtraArgs.D.getCXXScopeSpec(), 7753 llvm::make_unique<DifferentNameValidatorCCC>( 7754 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7755 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7756 // Set up everything for the call to ActOnFunctionDeclarator 7757 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7758 ExtraArgs.D.getIdentifierLoc()); 7759 Previous.clear(); 7760 Previous.setLookupName(Correction.getCorrection()); 7761 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7762 CDeclEnd = Correction.end(); 7763 CDecl != CDeclEnd; ++CDecl) { 7764 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7765 if (FD && !FD->hasBody() && 7766 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7767 Previous.addDecl(FD); 7768 } 7769 } 7770 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7771 7772 NamedDecl *Result; 7773 // Retry building the function declaration with the new previous 7774 // declarations, and with errors suppressed. 7775 { 7776 // Trap errors. 7777 Sema::SFINAETrap Trap(SemaRef); 7778 7779 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7780 // pieces need to verify the typo-corrected C++ declaration and hopefully 7781 // eliminate the need for the parameter pack ExtraArgs. 7782 Result = SemaRef.ActOnFunctionDeclarator( 7783 ExtraArgs.S, ExtraArgs.D, 7784 Correction.getCorrectionDecl()->getDeclContext(), 7785 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7786 ExtraArgs.AddToScope); 7787 7788 if (Trap.hasErrorOccurred()) 7789 Result = nullptr; 7790 } 7791 7792 if (Result) { 7793 // Determine which correction we picked. 7794 Decl *Canonical = Result->getCanonicalDecl(); 7795 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7796 I != E; ++I) 7797 if ((*I)->getCanonicalDecl() == Canonical) 7798 Correction.setCorrectionDecl(*I); 7799 7800 // Let Sema know about the correction. 7801 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7802 SemaRef.diagnoseTypo( 7803 Correction, 7804 SemaRef.PDiag(IsLocalFriend 7805 ? diag::err_no_matching_local_friend_suggest 7806 : diag::err_member_decl_does_not_match_suggest) 7807 << Name << NewDC << IsDefinition); 7808 return Result; 7809 } 7810 7811 // Pretend the typo correction never occurred 7812 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7813 ExtraArgs.D.getIdentifierLoc()); 7814 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7815 Previous.clear(); 7816 Previous.setLookupName(Name); 7817 } 7818 7819 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7820 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7821 7822 bool NewFDisConst = false; 7823 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7824 NewFDisConst = NewMD->isConst(); 7825 7826 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7827 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7828 NearMatch != NearMatchEnd; ++NearMatch) { 7829 FunctionDecl *FD = NearMatch->first; 7830 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7831 bool FDisConst = MD && MD->isConst(); 7832 bool IsMember = MD || !IsLocalFriend; 7833 7834 // FIXME: These notes are poorly worded for the local friend case. 7835 if (unsigned Idx = NearMatch->second) { 7836 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7837 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7838 if (Loc.isInvalid()) Loc = FD->getLocation(); 7839 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7840 : diag::note_local_decl_close_param_match) 7841 << Idx << FDParam->getType() 7842 << NewFD->getParamDecl(Idx - 1)->getType(); 7843 } else if (FDisConst != NewFDisConst) { 7844 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7845 << NewFDisConst << FD->getSourceRange().getEnd(); 7846 } else 7847 SemaRef.Diag(FD->getLocation(), 7848 IsMember ? diag::note_member_def_close_match 7849 : diag::note_local_decl_close_match); 7850 } 7851 return nullptr; 7852 } 7853 7854 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7855 switch (D.getDeclSpec().getStorageClassSpec()) { 7856 default: llvm_unreachable("Unknown storage class!"); 7857 case DeclSpec::SCS_auto: 7858 case DeclSpec::SCS_register: 7859 case DeclSpec::SCS_mutable: 7860 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7861 diag::err_typecheck_sclass_func); 7862 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7863 D.setInvalidType(); 7864 break; 7865 case DeclSpec::SCS_unspecified: break; 7866 case DeclSpec::SCS_extern: 7867 if (D.getDeclSpec().isExternInLinkageSpec()) 7868 return SC_None; 7869 return SC_Extern; 7870 case DeclSpec::SCS_static: { 7871 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7872 // C99 6.7.1p5: 7873 // The declaration of an identifier for a function that has 7874 // block scope shall have no explicit storage-class specifier 7875 // other than extern 7876 // See also (C++ [dcl.stc]p4). 7877 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7878 diag::err_static_block_func); 7879 break; 7880 } else 7881 return SC_Static; 7882 } 7883 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7884 } 7885 7886 // No explicit storage class has already been returned 7887 return SC_None; 7888 } 7889 7890 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7891 DeclContext *DC, QualType &R, 7892 TypeSourceInfo *TInfo, 7893 StorageClass SC, 7894 bool &IsVirtualOkay) { 7895 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7896 DeclarationName Name = NameInfo.getName(); 7897 7898 FunctionDecl *NewFD = nullptr; 7899 bool isInline = D.getDeclSpec().isInlineSpecified(); 7900 7901 if (!SemaRef.getLangOpts().CPlusPlus) { 7902 // Determine whether the function was written with a 7903 // prototype. This true when: 7904 // - there is a prototype in the declarator, or 7905 // - the type R of the function is some kind of typedef or other non- 7906 // attributed reference to a type name (which eventually refers to a 7907 // function type). 7908 bool HasPrototype = 7909 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7910 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7911 7912 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 7913 R, TInfo, SC, isInline, HasPrototype, false); 7914 if (D.isInvalidType()) 7915 NewFD->setInvalidDecl(); 7916 7917 return NewFD; 7918 } 7919 7920 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7921 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7922 7923 // Check that the return type is not an abstract class type. 7924 // For record types, this is done by the AbstractClassUsageDiagnoser once 7925 // the class has been completely parsed. 7926 if (!DC->isRecord() && 7927 SemaRef.RequireNonAbstractType( 7928 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7929 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7930 D.setInvalidType(); 7931 7932 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7933 // This is a C++ constructor declaration. 7934 assert(DC->isRecord() && 7935 "Constructors can only be declared in a member context"); 7936 7937 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7938 return CXXConstructorDecl::Create( 7939 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 7940 TInfo, isExplicit, isInline, 7941 /*isImplicitlyDeclared=*/false, isConstexpr); 7942 7943 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7944 // This is a C++ destructor declaration. 7945 if (DC->isRecord()) { 7946 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7947 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7948 CXXDestructorDecl *NewDD = 7949 CXXDestructorDecl::Create(SemaRef.Context, Record, D.getBeginLoc(), 7950 NameInfo, R, TInfo, isInline, 7951 /*isImplicitlyDeclared=*/false); 7952 7953 // If the destructor needs an implicit exception specification, set it 7954 // now. FIXME: It'd be nice to be able to create the right type to start 7955 // with, but the type needs to reference the destructor declaration. 7956 if (SemaRef.getLangOpts().CPlusPlus11) 7957 SemaRef.AdjustDestructorExceptionSpec(NewDD); 7958 7959 IsVirtualOkay = true; 7960 return NewDD; 7961 7962 } else { 7963 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7964 D.setInvalidType(); 7965 7966 // Create a FunctionDecl to satisfy the function definition parsing 7967 // code path. 7968 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 7969 D.getIdentifierLoc(), Name, R, TInfo, SC, 7970 isInline, 7971 /*hasPrototype=*/true, isConstexpr); 7972 } 7973 7974 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7975 if (!DC->isRecord()) { 7976 SemaRef.Diag(D.getIdentifierLoc(), 7977 diag::err_conv_function_not_member); 7978 return nullptr; 7979 } 7980 7981 SemaRef.CheckConversionDeclarator(D, R, SC); 7982 IsVirtualOkay = true; 7983 return CXXConversionDecl::Create( 7984 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 7985 TInfo, isInline, isExplicit, isConstexpr, SourceLocation()); 7986 7987 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7988 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7989 7990 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 7991 isExplicit, NameInfo, R, TInfo, 7992 D.getEndLoc()); 7993 } else if (DC->isRecord()) { 7994 // If the name of the function is the same as the name of the record, 7995 // then this must be an invalid constructor that has a return type. 7996 // (The parser checks for a return type and makes the declarator a 7997 // constructor if it has no return type). 7998 if (Name.getAsIdentifierInfo() && 7999 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8000 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8001 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8002 << SourceRange(D.getIdentifierLoc()); 8003 return nullptr; 8004 } 8005 8006 // This is a C++ method declaration. 8007 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8008 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8009 TInfo, SC, isInline, isConstexpr, SourceLocation()); 8010 IsVirtualOkay = !Ret->isStatic(); 8011 return Ret; 8012 } else { 8013 bool isFriend = 8014 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8015 if (!isFriend && SemaRef.CurContext->isRecord()) 8016 return nullptr; 8017 8018 // Determine whether the function was written with a 8019 // prototype. This true when: 8020 // - we're in C++ (where every function has a prototype), 8021 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8022 R, TInfo, SC, isInline, true /*HasPrototype*/, 8023 isConstexpr); 8024 } 8025 } 8026 8027 enum OpenCLParamType { 8028 ValidKernelParam, 8029 PtrPtrKernelParam, 8030 PtrKernelParam, 8031 InvalidAddrSpacePtrKernelParam, 8032 InvalidKernelParam, 8033 RecordKernelParam 8034 }; 8035 8036 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8037 // Size dependent types are just typedefs to normal integer types 8038 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8039 // integers other than by their names. 8040 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8041 8042 // Remove typedefs one by one until we reach a typedef 8043 // for a size dependent type. 8044 QualType DesugaredTy = Ty; 8045 do { 8046 ArrayRef<StringRef> Names(SizeTypeNames); 8047 auto Match = 8048 std::find(Names.begin(), Names.end(), DesugaredTy.getAsString()); 8049 if (Names.end() != Match) 8050 return true; 8051 8052 Ty = DesugaredTy; 8053 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8054 } while (DesugaredTy != Ty); 8055 8056 return false; 8057 } 8058 8059 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8060 if (PT->isPointerType()) { 8061 QualType PointeeType = PT->getPointeeType(); 8062 if (PointeeType->isPointerType()) 8063 return PtrPtrKernelParam; 8064 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8065 PointeeType.getAddressSpace() == LangAS::opencl_private || 8066 PointeeType.getAddressSpace() == LangAS::Default) 8067 return InvalidAddrSpacePtrKernelParam; 8068 return PtrKernelParam; 8069 } 8070 8071 // OpenCL v1.2 s6.9.k: 8072 // Arguments to kernel functions in a program cannot be declared with the 8073 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8074 // uintptr_t or a struct and/or union that contain fields declared to be one 8075 // of these built-in scalar types. 8076 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8077 return InvalidKernelParam; 8078 8079 if (PT->isImageType()) 8080 return PtrKernelParam; 8081 8082 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8083 return InvalidKernelParam; 8084 8085 // OpenCL extension spec v1.2 s9.5: 8086 // This extension adds support for half scalar and vector types as built-in 8087 // types that can be used for arithmetic operations, conversions etc. 8088 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8089 return InvalidKernelParam; 8090 8091 if (PT->isRecordType()) 8092 return RecordKernelParam; 8093 8094 // Look into an array argument to check if it has a forbidden type. 8095 if (PT->isArrayType()) { 8096 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8097 // Call ourself to check an underlying type of an array. Since the 8098 // getPointeeOrArrayElementType returns an innermost type which is not an 8099 // array, this recursive call only happens once. 8100 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8101 } 8102 8103 return ValidKernelParam; 8104 } 8105 8106 static void checkIsValidOpenCLKernelParameter( 8107 Sema &S, 8108 Declarator &D, 8109 ParmVarDecl *Param, 8110 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8111 QualType PT = Param->getType(); 8112 8113 // Cache the valid types we encounter to avoid rechecking structs that are 8114 // used again 8115 if (ValidTypes.count(PT.getTypePtr())) 8116 return; 8117 8118 switch (getOpenCLKernelParameterType(S, PT)) { 8119 case PtrPtrKernelParam: 8120 // OpenCL v1.2 s6.9.a: 8121 // A kernel function argument cannot be declared as a 8122 // pointer to a pointer type. 8123 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8124 D.setInvalidType(); 8125 return; 8126 8127 case InvalidAddrSpacePtrKernelParam: 8128 // OpenCL v1.0 s6.5: 8129 // __kernel function arguments declared to be a pointer of a type can point 8130 // to one of the following address spaces only : __global, __local or 8131 // __constant. 8132 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8133 D.setInvalidType(); 8134 return; 8135 8136 // OpenCL v1.2 s6.9.k: 8137 // Arguments to kernel functions in a program cannot be declared with the 8138 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8139 // uintptr_t or a struct and/or union that contain fields declared to be 8140 // one of these built-in scalar types. 8141 8142 case InvalidKernelParam: 8143 // OpenCL v1.2 s6.8 n: 8144 // A kernel function argument cannot be declared 8145 // of event_t type. 8146 // Do not diagnose half type since it is diagnosed as invalid argument 8147 // type for any function elsewhere. 8148 if (!PT->isHalfType()) { 8149 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8150 8151 // Explain what typedefs are involved. 8152 const TypedefType *Typedef = nullptr; 8153 while ((Typedef = PT->getAs<TypedefType>())) { 8154 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8155 // SourceLocation may be invalid for a built-in type. 8156 if (Loc.isValid()) 8157 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8158 PT = Typedef->desugar(); 8159 } 8160 } 8161 8162 D.setInvalidType(); 8163 return; 8164 8165 case PtrKernelParam: 8166 case ValidKernelParam: 8167 ValidTypes.insert(PT.getTypePtr()); 8168 return; 8169 8170 case RecordKernelParam: 8171 break; 8172 } 8173 8174 // Track nested structs we will inspect 8175 SmallVector<const Decl *, 4> VisitStack; 8176 8177 // Track where we are in the nested structs. Items will migrate from 8178 // VisitStack to HistoryStack as we do the DFS for bad field. 8179 SmallVector<const FieldDecl *, 4> HistoryStack; 8180 HistoryStack.push_back(nullptr); 8181 8182 // At this point we already handled everything except of a RecordType or 8183 // an ArrayType of a RecordType. 8184 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8185 const RecordType *RecTy = 8186 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8187 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8188 8189 VisitStack.push_back(RecTy->getDecl()); 8190 assert(VisitStack.back() && "First decl null?"); 8191 8192 do { 8193 const Decl *Next = VisitStack.pop_back_val(); 8194 if (!Next) { 8195 assert(!HistoryStack.empty()); 8196 // Found a marker, we have gone up a level 8197 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8198 ValidTypes.insert(Hist->getType().getTypePtr()); 8199 8200 continue; 8201 } 8202 8203 // Adds everything except the original parameter declaration (which is not a 8204 // field itself) to the history stack. 8205 const RecordDecl *RD; 8206 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8207 HistoryStack.push_back(Field); 8208 8209 QualType FieldTy = Field->getType(); 8210 // Other field types (known to be valid or invalid) are handled while we 8211 // walk around RecordDecl::fields(). 8212 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8213 "Unexpected type."); 8214 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8215 8216 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8217 } else { 8218 RD = cast<RecordDecl>(Next); 8219 } 8220 8221 // Add a null marker so we know when we've gone back up a level 8222 VisitStack.push_back(nullptr); 8223 8224 for (const auto *FD : RD->fields()) { 8225 QualType QT = FD->getType(); 8226 8227 if (ValidTypes.count(QT.getTypePtr())) 8228 continue; 8229 8230 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8231 if (ParamType == ValidKernelParam) 8232 continue; 8233 8234 if (ParamType == RecordKernelParam) { 8235 VisitStack.push_back(FD); 8236 continue; 8237 } 8238 8239 // OpenCL v1.2 s6.9.p: 8240 // Arguments to kernel functions that are declared to be a struct or union 8241 // do not allow OpenCL objects to be passed as elements of the struct or 8242 // union. 8243 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8244 ParamType == InvalidAddrSpacePtrKernelParam) { 8245 S.Diag(Param->getLocation(), 8246 diag::err_record_with_pointers_kernel_param) 8247 << PT->isUnionType() 8248 << PT; 8249 } else { 8250 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8251 } 8252 8253 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8254 << OrigRecDecl->getDeclName(); 8255 8256 // We have an error, now let's go back up through history and show where 8257 // the offending field came from 8258 for (ArrayRef<const FieldDecl *>::const_iterator 8259 I = HistoryStack.begin() + 1, 8260 E = HistoryStack.end(); 8261 I != E; ++I) { 8262 const FieldDecl *OuterField = *I; 8263 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8264 << OuterField->getType(); 8265 } 8266 8267 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8268 << QT->isPointerType() 8269 << QT; 8270 D.setInvalidType(); 8271 return; 8272 } 8273 } while (!VisitStack.empty()); 8274 } 8275 8276 /// Find the DeclContext in which a tag is implicitly declared if we see an 8277 /// elaborated type specifier in the specified context, and lookup finds 8278 /// nothing. 8279 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8280 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8281 DC = DC->getParent(); 8282 return DC; 8283 } 8284 8285 /// Find the Scope in which a tag is implicitly declared if we see an 8286 /// elaborated type specifier in the specified context, and lookup finds 8287 /// nothing. 8288 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8289 while (S->isClassScope() || 8290 (LangOpts.CPlusPlus && 8291 S->isFunctionPrototypeScope()) || 8292 ((S->getFlags() & Scope::DeclScope) == 0) || 8293 (S->getEntity() && S->getEntity()->isTransparentContext())) 8294 S = S->getParent(); 8295 return S; 8296 } 8297 8298 NamedDecl* 8299 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8300 TypeSourceInfo *TInfo, LookupResult &Previous, 8301 MultiTemplateParamsArg TemplateParamLists, 8302 bool &AddToScope) { 8303 QualType R = TInfo->getType(); 8304 8305 assert(R->isFunctionType()); 8306 8307 // TODO: consider using NameInfo for diagnostic. 8308 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8309 DeclarationName Name = NameInfo.getName(); 8310 StorageClass SC = getFunctionStorageClass(*this, D); 8311 8312 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8313 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8314 diag::err_invalid_thread) 8315 << DeclSpec::getSpecifierName(TSCS); 8316 8317 if (D.isFirstDeclarationOfMember()) 8318 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8319 D.getIdentifierLoc()); 8320 8321 bool isFriend = false; 8322 FunctionTemplateDecl *FunctionTemplate = nullptr; 8323 bool isMemberSpecialization = false; 8324 bool isFunctionTemplateSpecialization = false; 8325 8326 bool isDependentClassScopeExplicitSpecialization = false; 8327 bool HasExplicitTemplateArgs = false; 8328 TemplateArgumentListInfo TemplateArgs; 8329 8330 bool isVirtualOkay = false; 8331 8332 DeclContext *OriginalDC = DC; 8333 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8334 8335 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8336 isVirtualOkay); 8337 if (!NewFD) return nullptr; 8338 8339 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8340 NewFD->setTopLevelDeclInObjCContainer(); 8341 8342 // Set the lexical context. If this is a function-scope declaration, or has a 8343 // C++ scope specifier, or is the object of a friend declaration, the lexical 8344 // context will be different from the semantic context. 8345 NewFD->setLexicalDeclContext(CurContext); 8346 8347 if (IsLocalExternDecl) 8348 NewFD->setLocalExternDecl(); 8349 8350 if (getLangOpts().CPlusPlus) { 8351 bool isInline = D.getDeclSpec().isInlineSpecified(); 8352 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8353 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8354 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8355 isFriend = D.getDeclSpec().isFriendSpecified(); 8356 if (isFriend && !isInline && D.isFunctionDefinition()) { 8357 // C++ [class.friend]p5 8358 // A function can be defined in a friend declaration of a 8359 // class . . . . Such a function is implicitly inline. 8360 NewFD->setImplicitlyInline(); 8361 } 8362 8363 // If this is a method defined in an __interface, and is not a constructor 8364 // or an overloaded operator, then set the pure flag (isVirtual will already 8365 // return true). 8366 if (const CXXRecordDecl *Parent = 8367 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8368 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8369 NewFD->setPure(true); 8370 8371 // C++ [class.union]p2 8372 // A union can have member functions, but not virtual functions. 8373 if (isVirtual && Parent->isUnion()) 8374 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8375 } 8376 8377 SetNestedNameSpecifier(*this, NewFD, D); 8378 isMemberSpecialization = false; 8379 isFunctionTemplateSpecialization = false; 8380 if (D.isInvalidType()) 8381 NewFD->setInvalidDecl(); 8382 8383 // Match up the template parameter lists with the scope specifier, then 8384 // determine whether we have a template or a template specialization. 8385 bool Invalid = false; 8386 if (TemplateParameterList *TemplateParams = 8387 MatchTemplateParametersToScopeSpecifier( 8388 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8389 D.getCXXScopeSpec(), 8390 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8391 ? D.getName().TemplateId 8392 : nullptr, 8393 TemplateParamLists, isFriend, isMemberSpecialization, 8394 Invalid)) { 8395 if (TemplateParams->size() > 0) { 8396 // This is a function template 8397 8398 // Check that we can declare a template here. 8399 if (CheckTemplateDeclScope(S, TemplateParams)) 8400 NewFD->setInvalidDecl(); 8401 8402 // A destructor cannot be a template. 8403 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8404 Diag(NewFD->getLocation(), diag::err_destructor_template); 8405 NewFD->setInvalidDecl(); 8406 } 8407 8408 // If we're adding a template to a dependent context, we may need to 8409 // rebuilding some of the types used within the template parameter list, 8410 // now that we know what the current instantiation is. 8411 if (DC->isDependentContext()) { 8412 ContextRAII SavedContext(*this, DC); 8413 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8414 Invalid = true; 8415 } 8416 8417 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8418 NewFD->getLocation(), 8419 Name, TemplateParams, 8420 NewFD); 8421 FunctionTemplate->setLexicalDeclContext(CurContext); 8422 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8423 8424 // For source fidelity, store the other template param lists. 8425 if (TemplateParamLists.size() > 1) { 8426 NewFD->setTemplateParameterListsInfo(Context, 8427 TemplateParamLists.drop_back(1)); 8428 } 8429 } else { 8430 // This is a function template specialization. 8431 isFunctionTemplateSpecialization = true; 8432 // For source fidelity, store all the template param lists. 8433 if (TemplateParamLists.size() > 0) 8434 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8435 8436 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8437 if (isFriend) { 8438 // We want to remove the "template<>", found here. 8439 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8440 8441 // If we remove the template<> and the name is not a 8442 // template-id, we're actually silently creating a problem: 8443 // the friend declaration will refer to an untemplated decl, 8444 // and clearly the user wants a template specialization. So 8445 // we need to insert '<>' after the name. 8446 SourceLocation InsertLoc; 8447 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8448 InsertLoc = D.getName().getSourceRange().getEnd(); 8449 InsertLoc = getLocForEndOfToken(InsertLoc); 8450 } 8451 8452 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8453 << Name << RemoveRange 8454 << FixItHint::CreateRemoval(RemoveRange) 8455 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8456 } 8457 } 8458 } else { 8459 // All template param lists were matched against the scope specifier: 8460 // this is NOT (an explicit specialization of) a template. 8461 if (TemplateParamLists.size() > 0) 8462 // For source fidelity, store all the template param lists. 8463 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8464 } 8465 8466 if (Invalid) { 8467 NewFD->setInvalidDecl(); 8468 if (FunctionTemplate) 8469 FunctionTemplate->setInvalidDecl(); 8470 } 8471 8472 // C++ [dcl.fct.spec]p5: 8473 // The virtual specifier shall only be used in declarations of 8474 // nonstatic class member functions that appear within a 8475 // member-specification of a class declaration; see 10.3. 8476 // 8477 if (isVirtual && !NewFD->isInvalidDecl()) { 8478 if (!isVirtualOkay) { 8479 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8480 diag::err_virtual_non_function); 8481 } else if (!CurContext->isRecord()) { 8482 // 'virtual' was specified outside of the class. 8483 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8484 diag::err_virtual_out_of_class) 8485 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8486 } else if (NewFD->getDescribedFunctionTemplate()) { 8487 // C++ [temp.mem]p3: 8488 // A member function template shall not be virtual. 8489 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8490 diag::err_virtual_member_function_template) 8491 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8492 } else { 8493 // Okay: Add virtual to the method. 8494 NewFD->setVirtualAsWritten(true); 8495 } 8496 8497 if (getLangOpts().CPlusPlus14 && 8498 NewFD->getReturnType()->isUndeducedType()) 8499 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8500 } 8501 8502 if (getLangOpts().CPlusPlus14 && 8503 (NewFD->isDependentContext() || 8504 (isFriend && CurContext->isDependentContext())) && 8505 NewFD->getReturnType()->isUndeducedType()) { 8506 // If the function template is referenced directly (for instance, as a 8507 // member of the current instantiation), pretend it has a dependent type. 8508 // This is not really justified by the standard, but is the only sane 8509 // thing to do. 8510 // FIXME: For a friend function, we have not marked the function as being 8511 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8512 const FunctionProtoType *FPT = 8513 NewFD->getType()->castAs<FunctionProtoType>(); 8514 QualType Result = 8515 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8516 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8517 FPT->getExtProtoInfo())); 8518 } 8519 8520 // C++ [dcl.fct.spec]p3: 8521 // The inline specifier shall not appear on a block scope function 8522 // declaration. 8523 if (isInline && !NewFD->isInvalidDecl()) { 8524 if (CurContext->isFunctionOrMethod()) { 8525 // 'inline' is not allowed on block scope function declaration. 8526 Diag(D.getDeclSpec().getInlineSpecLoc(), 8527 diag::err_inline_declaration_block_scope) << Name 8528 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8529 } 8530 } 8531 8532 // C++ [dcl.fct.spec]p6: 8533 // The explicit specifier shall be used only in the declaration of a 8534 // constructor or conversion function within its class definition; 8535 // see 12.3.1 and 12.3.2. 8536 if (isExplicit && !NewFD->isInvalidDecl() && 8537 !isa<CXXDeductionGuideDecl>(NewFD)) { 8538 if (!CurContext->isRecord()) { 8539 // 'explicit' was specified outside of the class. 8540 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8541 diag::err_explicit_out_of_class) 8542 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8543 } else if (!isa<CXXConstructorDecl>(NewFD) && 8544 !isa<CXXConversionDecl>(NewFD)) { 8545 // 'explicit' was specified on a function that wasn't a constructor 8546 // or conversion function. 8547 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8548 diag::err_explicit_non_ctor_or_conv_function) 8549 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8550 } 8551 } 8552 8553 if (isConstexpr) { 8554 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8555 // are implicitly inline. 8556 NewFD->setImplicitlyInline(); 8557 8558 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8559 // be either constructors or to return a literal type. Therefore, 8560 // destructors cannot be declared constexpr. 8561 if (isa<CXXDestructorDecl>(NewFD)) 8562 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8563 } 8564 8565 // If __module_private__ was specified, mark the function accordingly. 8566 if (D.getDeclSpec().isModulePrivateSpecified()) { 8567 if (isFunctionTemplateSpecialization) { 8568 SourceLocation ModulePrivateLoc 8569 = D.getDeclSpec().getModulePrivateSpecLoc(); 8570 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8571 << 0 8572 << FixItHint::CreateRemoval(ModulePrivateLoc); 8573 } else { 8574 NewFD->setModulePrivate(); 8575 if (FunctionTemplate) 8576 FunctionTemplate->setModulePrivate(); 8577 } 8578 } 8579 8580 if (isFriend) { 8581 if (FunctionTemplate) { 8582 FunctionTemplate->setObjectOfFriendDecl(); 8583 FunctionTemplate->setAccess(AS_public); 8584 } 8585 NewFD->setObjectOfFriendDecl(); 8586 NewFD->setAccess(AS_public); 8587 } 8588 8589 // If a function is defined as defaulted or deleted, mark it as such now. 8590 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8591 // definition kind to FDK_Definition. 8592 switch (D.getFunctionDefinitionKind()) { 8593 case FDK_Declaration: 8594 case FDK_Definition: 8595 break; 8596 8597 case FDK_Defaulted: 8598 NewFD->setDefaulted(); 8599 break; 8600 8601 case FDK_Deleted: 8602 NewFD->setDeletedAsWritten(); 8603 break; 8604 } 8605 8606 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8607 D.isFunctionDefinition()) { 8608 // C++ [class.mfct]p2: 8609 // A member function may be defined (8.4) in its class definition, in 8610 // which case it is an inline member function (7.1.2) 8611 NewFD->setImplicitlyInline(); 8612 } 8613 8614 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8615 !CurContext->isRecord()) { 8616 // C++ [class.static]p1: 8617 // A data or function member of a class may be declared static 8618 // in a class definition, in which case it is a static member of 8619 // the class. 8620 8621 // Complain about the 'static' specifier if it's on an out-of-line 8622 // member function definition. 8623 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8624 diag::err_static_out_of_line) 8625 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8626 } 8627 8628 // C++11 [except.spec]p15: 8629 // A deallocation function with no exception-specification is treated 8630 // as if it were specified with noexcept(true). 8631 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8632 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8633 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8634 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8635 NewFD->setType(Context.getFunctionType( 8636 FPT->getReturnType(), FPT->getParamTypes(), 8637 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8638 } 8639 8640 // Filter out previous declarations that don't match the scope. 8641 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8642 D.getCXXScopeSpec().isNotEmpty() || 8643 isMemberSpecialization || 8644 isFunctionTemplateSpecialization); 8645 8646 // Handle GNU asm-label extension (encoded as an attribute). 8647 if (Expr *E = (Expr*) D.getAsmLabel()) { 8648 // The parser guarantees this is a string. 8649 StringLiteral *SE = cast<StringLiteral>(E); 8650 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8651 SE->getString(), 0)); 8652 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8653 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8654 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8655 if (I != ExtnameUndeclaredIdentifiers.end()) { 8656 if (isDeclExternC(NewFD)) { 8657 NewFD->addAttr(I->second); 8658 ExtnameUndeclaredIdentifiers.erase(I); 8659 } else 8660 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8661 << /*Variable*/0 << NewFD; 8662 } 8663 } 8664 8665 // Copy the parameter declarations from the declarator D to the function 8666 // declaration NewFD, if they are available. First scavenge them into Params. 8667 SmallVector<ParmVarDecl*, 16> Params; 8668 unsigned FTIIdx; 8669 if (D.isFunctionDeclarator(FTIIdx)) { 8670 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8671 8672 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8673 // function that takes no arguments, not a function that takes a 8674 // single void argument. 8675 // We let through "const void" here because Sema::GetTypeForDeclarator 8676 // already checks for that case. 8677 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8678 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8679 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8680 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8681 Param->setDeclContext(NewFD); 8682 Params.push_back(Param); 8683 8684 if (Param->isInvalidDecl()) 8685 NewFD->setInvalidDecl(); 8686 } 8687 } 8688 8689 if (!getLangOpts().CPlusPlus) { 8690 // In C, find all the tag declarations from the prototype and move them 8691 // into the function DeclContext. Remove them from the surrounding tag 8692 // injection context of the function, which is typically but not always 8693 // the TU. 8694 DeclContext *PrototypeTagContext = 8695 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8696 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8697 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8698 8699 // We don't want to reparent enumerators. Look at their parent enum 8700 // instead. 8701 if (!TD) { 8702 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8703 TD = cast<EnumDecl>(ECD->getDeclContext()); 8704 } 8705 if (!TD) 8706 continue; 8707 DeclContext *TagDC = TD->getLexicalDeclContext(); 8708 if (!TagDC->containsDecl(TD)) 8709 continue; 8710 TagDC->removeDecl(TD); 8711 TD->setDeclContext(NewFD); 8712 NewFD->addDecl(TD); 8713 8714 // Preserve the lexical DeclContext if it is not the surrounding tag 8715 // injection context of the FD. In this example, the semantic context of 8716 // E will be f and the lexical context will be S, while both the 8717 // semantic and lexical contexts of S will be f: 8718 // void f(struct S { enum E { a } f; } s); 8719 if (TagDC != PrototypeTagContext) 8720 TD->setLexicalDeclContext(TagDC); 8721 } 8722 } 8723 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8724 // When we're declaring a function with a typedef, typeof, etc as in the 8725 // following example, we'll need to synthesize (unnamed) 8726 // parameters for use in the declaration. 8727 // 8728 // @code 8729 // typedef void fn(int); 8730 // fn f; 8731 // @endcode 8732 8733 // Synthesize a parameter for each argument type. 8734 for (const auto &AI : FT->param_types()) { 8735 ParmVarDecl *Param = 8736 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8737 Param->setScopeInfo(0, Params.size()); 8738 Params.push_back(Param); 8739 } 8740 } else { 8741 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8742 "Should not need args for typedef of non-prototype fn"); 8743 } 8744 8745 // Finally, we know we have the right number of parameters, install them. 8746 NewFD->setParams(Params); 8747 8748 if (D.getDeclSpec().isNoreturnSpecified()) 8749 NewFD->addAttr( 8750 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8751 Context, 0)); 8752 8753 // Functions returning a variably modified type violate C99 6.7.5.2p2 8754 // because all functions have linkage. 8755 if (!NewFD->isInvalidDecl() && 8756 NewFD->getReturnType()->isVariablyModifiedType()) { 8757 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8758 NewFD->setInvalidDecl(); 8759 } 8760 8761 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8762 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8763 !NewFD->hasAttr<SectionAttr>()) { 8764 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8765 PragmaClangTextSection.SectionName, 8766 PragmaClangTextSection.PragmaLocation)); 8767 } 8768 8769 // Apply an implicit SectionAttr if #pragma code_seg is active. 8770 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8771 !NewFD->hasAttr<SectionAttr>()) { 8772 NewFD->addAttr( 8773 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8774 CodeSegStack.CurrentValue->getString(), 8775 CodeSegStack.CurrentPragmaLocation)); 8776 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8777 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8778 ASTContext::PSF_Read, 8779 NewFD)) 8780 NewFD->dropAttr<SectionAttr>(); 8781 } 8782 8783 // Apply an implicit CodeSegAttr from class declspec or 8784 // apply an implicit SectionAttr from #pragma code_seg if active. 8785 if (!NewFD->hasAttr<CodeSegAttr>()) { 8786 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 8787 D.isFunctionDefinition())) { 8788 NewFD->addAttr(SAttr); 8789 } 8790 } 8791 8792 // Handle attributes. 8793 ProcessDeclAttributes(S, NewFD, D); 8794 8795 if (getLangOpts().OpenCL) { 8796 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8797 // type declaration will generate a compilation error. 8798 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8799 if (AddressSpace != LangAS::Default) { 8800 Diag(NewFD->getLocation(), 8801 diag::err_opencl_return_value_with_address_space); 8802 NewFD->setInvalidDecl(); 8803 } 8804 } 8805 8806 if (!getLangOpts().CPlusPlus) { 8807 // Perform semantic checking on the function declaration. 8808 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8809 CheckMain(NewFD, D.getDeclSpec()); 8810 8811 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8812 CheckMSVCRTEntryPoint(NewFD); 8813 8814 if (!NewFD->isInvalidDecl()) 8815 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8816 isMemberSpecialization)); 8817 else if (!Previous.empty()) 8818 // Recover gracefully from an invalid redeclaration. 8819 D.setRedeclaration(true); 8820 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8821 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8822 "previous declaration set still overloaded"); 8823 8824 // Diagnose no-prototype function declarations with calling conventions that 8825 // don't support variadic calls. Only do this in C and do it after merging 8826 // possibly prototyped redeclarations. 8827 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8828 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8829 CallingConv CC = FT->getExtInfo().getCC(); 8830 if (!supportsVariadicCall(CC)) { 8831 // Windows system headers sometimes accidentally use stdcall without 8832 // (void) parameters, so we relax this to a warning. 8833 int DiagID = 8834 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8835 Diag(NewFD->getLocation(), DiagID) 8836 << FunctionType::getNameForCallConv(CC); 8837 } 8838 } 8839 } else { 8840 // C++11 [replacement.functions]p3: 8841 // The program's definitions shall not be specified as inline. 8842 // 8843 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8844 // 8845 // Suppress the diagnostic if the function is __attribute__((used)), since 8846 // that forces an external definition to be emitted. 8847 if (D.getDeclSpec().isInlineSpecified() && 8848 NewFD->isReplaceableGlobalAllocationFunction() && 8849 !NewFD->hasAttr<UsedAttr>()) 8850 Diag(D.getDeclSpec().getInlineSpecLoc(), 8851 diag::ext_operator_new_delete_declared_inline) 8852 << NewFD->getDeclName(); 8853 8854 // If the declarator is a template-id, translate the parser's template 8855 // argument list into our AST format. 8856 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8857 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8858 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8859 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8860 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8861 TemplateId->NumArgs); 8862 translateTemplateArguments(TemplateArgsPtr, 8863 TemplateArgs); 8864 8865 HasExplicitTemplateArgs = true; 8866 8867 if (NewFD->isInvalidDecl()) { 8868 HasExplicitTemplateArgs = false; 8869 } else if (FunctionTemplate) { 8870 // Function template with explicit template arguments. 8871 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8872 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8873 8874 HasExplicitTemplateArgs = false; 8875 } else { 8876 assert((isFunctionTemplateSpecialization || 8877 D.getDeclSpec().isFriendSpecified()) && 8878 "should have a 'template<>' for this decl"); 8879 // "friend void foo<>(int);" is an implicit specialization decl. 8880 isFunctionTemplateSpecialization = true; 8881 } 8882 } else if (isFriend && isFunctionTemplateSpecialization) { 8883 // This combination is only possible in a recovery case; the user 8884 // wrote something like: 8885 // template <> friend void foo(int); 8886 // which we're recovering from as if the user had written: 8887 // friend void foo<>(int); 8888 // Go ahead and fake up a template id. 8889 HasExplicitTemplateArgs = true; 8890 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8891 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8892 } 8893 8894 // We do not add HD attributes to specializations here because 8895 // they may have different constexpr-ness compared to their 8896 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8897 // may end up with different effective targets. Instead, a 8898 // specialization inherits its target attributes from its template 8899 // in the CheckFunctionTemplateSpecialization() call below. 8900 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8901 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8902 8903 // If it's a friend (and only if it's a friend), it's possible 8904 // that either the specialized function type or the specialized 8905 // template is dependent, and therefore matching will fail. In 8906 // this case, don't check the specialization yet. 8907 bool InstantiationDependent = false; 8908 if (isFunctionTemplateSpecialization && isFriend && 8909 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8910 TemplateSpecializationType::anyDependentTemplateArguments( 8911 TemplateArgs, 8912 InstantiationDependent))) { 8913 assert(HasExplicitTemplateArgs && 8914 "friend function specialization without template args"); 8915 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8916 Previous)) 8917 NewFD->setInvalidDecl(); 8918 } else if (isFunctionTemplateSpecialization) { 8919 if (CurContext->isDependentContext() && CurContext->isRecord() 8920 && !isFriend) { 8921 isDependentClassScopeExplicitSpecialization = true; 8922 } else if (!NewFD->isInvalidDecl() && 8923 CheckFunctionTemplateSpecialization( 8924 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8925 Previous)) 8926 NewFD->setInvalidDecl(); 8927 8928 // C++ [dcl.stc]p1: 8929 // A storage-class-specifier shall not be specified in an explicit 8930 // specialization (14.7.3) 8931 FunctionTemplateSpecializationInfo *Info = 8932 NewFD->getTemplateSpecializationInfo(); 8933 if (Info && SC != SC_None) { 8934 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8935 Diag(NewFD->getLocation(), 8936 diag::err_explicit_specialization_inconsistent_storage_class) 8937 << SC 8938 << FixItHint::CreateRemoval( 8939 D.getDeclSpec().getStorageClassSpecLoc()); 8940 8941 else 8942 Diag(NewFD->getLocation(), 8943 diag::ext_explicit_specialization_storage_class) 8944 << FixItHint::CreateRemoval( 8945 D.getDeclSpec().getStorageClassSpecLoc()); 8946 } 8947 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8948 if (CheckMemberSpecialization(NewFD, Previous)) 8949 NewFD->setInvalidDecl(); 8950 } 8951 8952 // Perform semantic checking on the function declaration. 8953 if (!isDependentClassScopeExplicitSpecialization) { 8954 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8955 CheckMain(NewFD, D.getDeclSpec()); 8956 8957 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8958 CheckMSVCRTEntryPoint(NewFD); 8959 8960 if (!NewFD->isInvalidDecl()) 8961 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8962 isMemberSpecialization)); 8963 else if (!Previous.empty()) 8964 // Recover gracefully from an invalid redeclaration. 8965 D.setRedeclaration(true); 8966 } 8967 8968 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8969 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8970 "previous declaration set still overloaded"); 8971 8972 NamedDecl *PrincipalDecl = (FunctionTemplate 8973 ? cast<NamedDecl>(FunctionTemplate) 8974 : NewFD); 8975 8976 if (isFriend && NewFD->getPreviousDecl()) { 8977 AccessSpecifier Access = AS_public; 8978 if (!NewFD->isInvalidDecl()) 8979 Access = NewFD->getPreviousDecl()->getAccess(); 8980 8981 NewFD->setAccess(Access); 8982 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8983 } 8984 8985 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8986 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8987 PrincipalDecl->setNonMemberOperator(); 8988 8989 // If we have a function template, check the template parameter 8990 // list. This will check and merge default template arguments. 8991 if (FunctionTemplate) { 8992 FunctionTemplateDecl *PrevTemplate = 8993 FunctionTemplate->getPreviousDecl(); 8994 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8995 PrevTemplate ? PrevTemplate->getTemplateParameters() 8996 : nullptr, 8997 D.getDeclSpec().isFriendSpecified() 8998 ? (D.isFunctionDefinition() 8999 ? TPC_FriendFunctionTemplateDefinition 9000 : TPC_FriendFunctionTemplate) 9001 : (D.getCXXScopeSpec().isSet() && 9002 DC && DC->isRecord() && 9003 DC->isDependentContext()) 9004 ? TPC_ClassTemplateMember 9005 : TPC_FunctionTemplate); 9006 } 9007 9008 if (NewFD->isInvalidDecl()) { 9009 // Ignore all the rest of this. 9010 } else if (!D.isRedeclaration()) { 9011 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9012 AddToScope }; 9013 // Fake up an access specifier if it's supposed to be a class member. 9014 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9015 NewFD->setAccess(AS_public); 9016 9017 // Qualified decls generally require a previous declaration. 9018 if (D.getCXXScopeSpec().isSet()) { 9019 // ...with the major exception of templated-scope or 9020 // dependent-scope friend declarations. 9021 9022 // TODO: we currently also suppress this check in dependent 9023 // contexts because (1) the parameter depth will be off when 9024 // matching friend templates and (2) we might actually be 9025 // selecting a friend based on a dependent factor. But there 9026 // are situations where these conditions don't apply and we 9027 // can actually do this check immediately. 9028 // 9029 // Unless the scope is dependent, it's always an error if qualified 9030 // redeclaration lookup found nothing at all. Diagnose that now; 9031 // nothing will diagnose that error later. 9032 if (isFriend && 9033 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9034 (!Previous.empty() && (TemplateParamLists.size() || 9035 CurContext->isDependentContext())))) { 9036 // ignore these 9037 } else { 9038 // The user tried to provide an out-of-line definition for a 9039 // function that is a member of a class or namespace, but there 9040 // was no such member function declared (C++ [class.mfct]p2, 9041 // C++ [namespace.memdef]p2). For example: 9042 // 9043 // class X { 9044 // void f() const; 9045 // }; 9046 // 9047 // void X::f() { } // ill-formed 9048 // 9049 // Complain about this problem, and attempt to suggest close 9050 // matches (e.g., those that differ only in cv-qualifiers and 9051 // whether the parameter types are references). 9052 9053 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9054 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9055 AddToScope = ExtraArgs.AddToScope; 9056 return Result; 9057 } 9058 } 9059 9060 // Unqualified local friend declarations are required to resolve 9061 // to something. 9062 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9063 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9064 *this, Previous, NewFD, ExtraArgs, true, S)) { 9065 AddToScope = ExtraArgs.AddToScope; 9066 return Result; 9067 } 9068 } 9069 } else if (!D.isFunctionDefinition() && 9070 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9071 !isFriend && !isFunctionTemplateSpecialization && 9072 !isMemberSpecialization) { 9073 // An out-of-line member function declaration must also be a 9074 // definition (C++ [class.mfct]p2). 9075 // Note that this is not the case for explicit specializations of 9076 // function templates or member functions of class templates, per 9077 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9078 // extension for compatibility with old SWIG code which likes to 9079 // generate them. 9080 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9081 << D.getCXXScopeSpec().getRange(); 9082 } 9083 } 9084 9085 ProcessPragmaWeak(S, NewFD); 9086 checkAttributesAfterMerging(*this, *NewFD); 9087 9088 AddKnownFunctionAttributes(NewFD); 9089 9090 if (NewFD->hasAttr<OverloadableAttr>() && 9091 !NewFD->getType()->getAs<FunctionProtoType>()) { 9092 Diag(NewFD->getLocation(), 9093 diag::err_attribute_overloadable_no_prototype) 9094 << NewFD; 9095 9096 // Turn this into a variadic function with no parameters. 9097 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9098 FunctionProtoType::ExtProtoInfo EPI( 9099 Context.getDefaultCallingConvention(true, false)); 9100 EPI.Variadic = true; 9101 EPI.ExtInfo = FT->getExtInfo(); 9102 9103 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9104 NewFD->setType(R); 9105 } 9106 9107 // If there's a #pragma GCC visibility in scope, and this isn't a class 9108 // member, set the visibility of this function. 9109 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9110 AddPushedVisibilityAttribute(NewFD); 9111 9112 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9113 // marking the function. 9114 AddCFAuditedAttribute(NewFD); 9115 9116 // If this is a function definition, check if we have to apply optnone due to 9117 // a pragma. 9118 if(D.isFunctionDefinition()) 9119 AddRangeBasedOptnone(NewFD); 9120 9121 // If this is the first declaration of an extern C variable, update 9122 // the map of such variables. 9123 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9124 isIncompleteDeclExternC(*this, NewFD)) 9125 RegisterLocallyScopedExternCDecl(NewFD, S); 9126 9127 // Set this FunctionDecl's range up to the right paren. 9128 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9129 9130 if (D.isRedeclaration() && !Previous.empty()) { 9131 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9132 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9133 isMemberSpecialization || 9134 isFunctionTemplateSpecialization, 9135 D.isFunctionDefinition()); 9136 } 9137 9138 if (getLangOpts().CUDA) { 9139 IdentifierInfo *II = NewFD->getIdentifier(); 9140 if (II && 9141 II->isStr(getLangOpts().HIP ? "hipConfigureCall" 9142 : "cudaConfigureCall") && 9143 !NewFD->isInvalidDecl() && 9144 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9145 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9146 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9147 Context.setcudaConfigureCallDecl(NewFD); 9148 } 9149 9150 // Variadic functions, other than a *declaration* of printf, are not allowed 9151 // in device-side CUDA code, unless someone passed 9152 // -fcuda-allow-variadic-functions. 9153 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9154 (NewFD->hasAttr<CUDADeviceAttr>() || 9155 NewFD->hasAttr<CUDAGlobalAttr>()) && 9156 !(II && II->isStr("printf") && NewFD->isExternC() && 9157 !D.isFunctionDefinition())) { 9158 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9159 } 9160 } 9161 9162 MarkUnusedFileScopedDecl(NewFD); 9163 9164 if (getLangOpts().CPlusPlus) { 9165 if (FunctionTemplate) { 9166 if (NewFD->isInvalidDecl()) 9167 FunctionTemplate->setInvalidDecl(); 9168 return FunctionTemplate; 9169 } 9170 9171 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9172 CompleteMemberSpecialization(NewFD, Previous); 9173 } 9174 9175 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9176 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9177 if ((getLangOpts().OpenCLVersion >= 120) 9178 && (SC == SC_Static)) { 9179 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9180 D.setInvalidType(); 9181 } 9182 9183 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9184 if (!NewFD->getReturnType()->isVoidType()) { 9185 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9186 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9187 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9188 : FixItHint()); 9189 D.setInvalidType(); 9190 } 9191 9192 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9193 for (auto Param : NewFD->parameters()) 9194 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9195 } 9196 for (const ParmVarDecl *Param : NewFD->parameters()) { 9197 QualType PT = Param->getType(); 9198 9199 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9200 // types. 9201 if (getLangOpts().OpenCLVersion >= 200) { 9202 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9203 QualType ElemTy = PipeTy->getElementType(); 9204 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9205 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9206 D.setInvalidType(); 9207 } 9208 } 9209 } 9210 } 9211 9212 // Here we have an function template explicit specialization at class scope. 9213 // The actual specialization will be postponed to template instatiation 9214 // time via the ClassScopeFunctionSpecializationDecl node. 9215 if (isDependentClassScopeExplicitSpecialization) { 9216 ClassScopeFunctionSpecializationDecl *NewSpec = 9217 ClassScopeFunctionSpecializationDecl::Create( 9218 Context, CurContext, NewFD->getLocation(), 9219 cast<CXXMethodDecl>(NewFD), 9220 HasExplicitTemplateArgs, TemplateArgs); 9221 CurContext->addDecl(NewSpec); 9222 AddToScope = false; 9223 } 9224 9225 // Diagnose availability attributes. Availability cannot be used on functions 9226 // that are run during load/unload. 9227 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9228 if (NewFD->hasAttr<ConstructorAttr>()) { 9229 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9230 << 1; 9231 NewFD->dropAttr<AvailabilityAttr>(); 9232 } 9233 if (NewFD->hasAttr<DestructorAttr>()) { 9234 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9235 << 2; 9236 NewFD->dropAttr<AvailabilityAttr>(); 9237 } 9238 } 9239 9240 return NewFD; 9241 } 9242 9243 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9244 /// when __declspec(code_seg) "is applied to a class, all member functions of 9245 /// the class and nested classes -- this includes compiler-generated special 9246 /// member functions -- are put in the specified segment." 9247 /// The actual behavior is a little more complicated. The Microsoft compiler 9248 /// won't check outer classes if there is an active value from #pragma code_seg. 9249 /// The CodeSeg is always applied from the direct parent but only from outer 9250 /// classes when the #pragma code_seg stack is empty. See: 9251 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9252 /// available since MS has removed the page. 9253 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9254 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9255 if (!Method) 9256 return nullptr; 9257 const CXXRecordDecl *Parent = Method->getParent(); 9258 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9259 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9260 NewAttr->setImplicit(true); 9261 return NewAttr; 9262 } 9263 9264 // The Microsoft compiler won't check outer classes for the CodeSeg 9265 // when the #pragma code_seg stack is active. 9266 if (S.CodeSegStack.CurrentValue) 9267 return nullptr; 9268 9269 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9270 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9271 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9272 NewAttr->setImplicit(true); 9273 return NewAttr; 9274 } 9275 } 9276 return nullptr; 9277 } 9278 9279 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9280 /// containing class. Otherwise it will return implicit SectionAttr if the 9281 /// function is a definition and there is an active value on CodeSegStack 9282 /// (from the current #pragma code-seg value). 9283 /// 9284 /// \param FD Function being declared. 9285 /// \param IsDefinition Whether it is a definition or just a declarartion. 9286 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9287 /// nullptr if no attribute should be added. 9288 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9289 bool IsDefinition) { 9290 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9291 return A; 9292 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9293 CodeSegStack.CurrentValue) { 9294 return SectionAttr::CreateImplicit(getASTContext(), 9295 SectionAttr::Declspec_allocate, 9296 CodeSegStack.CurrentValue->getString(), 9297 CodeSegStack.CurrentPragmaLocation); 9298 } 9299 return nullptr; 9300 } 9301 9302 /// Determines if we can perform a correct type check for \p D as a 9303 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9304 /// best-effort check. 9305 /// 9306 /// \param NewD The new declaration. 9307 /// \param OldD The old declaration. 9308 /// \param NewT The portion of the type of the new declaration to check. 9309 /// \param OldT The portion of the type of the old declaration to check. 9310 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9311 QualType NewT, QualType OldT) { 9312 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9313 return true; 9314 9315 // For dependently-typed local extern declarations and friends, we can't 9316 // perform a correct type check in general until instantiation: 9317 // 9318 // int f(); 9319 // template<typename T> void g() { T f(); } 9320 // 9321 // (valid if g() is only instantiated with T = int). 9322 if (NewT->isDependentType() && 9323 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9324 return false; 9325 9326 // Similarly, if the previous declaration was a dependent local extern 9327 // declaration, we don't really know its type yet. 9328 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9329 return false; 9330 9331 return true; 9332 } 9333 9334 /// Checks if the new declaration declared in dependent context must be 9335 /// put in the same redeclaration chain as the specified declaration. 9336 /// 9337 /// \param D Declaration that is checked. 9338 /// \param PrevDecl Previous declaration found with proper lookup method for the 9339 /// same declaration name. 9340 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9341 /// belongs to. 9342 /// 9343 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9344 if (!D->getLexicalDeclContext()->isDependentContext()) 9345 return true; 9346 9347 // Don't chain dependent friend function definitions until instantiation, to 9348 // permit cases like 9349 // 9350 // void func(); 9351 // template<typename T> class C1 { friend void func() {} }; 9352 // template<typename T> class C2 { friend void func() {} }; 9353 // 9354 // ... which is valid if only one of C1 and C2 is ever instantiated. 9355 // 9356 // FIXME: This need only apply to function definitions. For now, we proxy 9357 // this by checking for a file-scope function. We do not want this to apply 9358 // to friend declarations nominating member functions, because that gets in 9359 // the way of access checks. 9360 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9361 return false; 9362 9363 auto *VD = dyn_cast<ValueDecl>(D); 9364 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9365 return !VD || !PrevVD || 9366 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9367 PrevVD->getType()); 9368 } 9369 9370 /// Check the target attribute of the function for MultiVersion 9371 /// validity. 9372 /// 9373 /// Returns true if there was an error, false otherwise. 9374 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9375 const auto *TA = FD->getAttr<TargetAttr>(); 9376 assert(TA && "MultiVersion Candidate requires a target attribute"); 9377 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9378 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9379 enum ErrType { Feature = 0, Architecture = 1 }; 9380 9381 if (!ParseInfo.Architecture.empty() && 9382 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9383 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9384 << Architecture << ParseInfo.Architecture; 9385 return true; 9386 } 9387 9388 for (const auto &Feat : ParseInfo.Features) { 9389 auto BareFeat = StringRef{Feat}.substr(1); 9390 if (Feat[0] == '-') { 9391 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9392 << Feature << ("no-" + BareFeat).str(); 9393 return true; 9394 } 9395 9396 if (!TargetInfo.validateCpuSupports(BareFeat) || 9397 !TargetInfo.isValidFeatureName(BareFeat)) { 9398 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9399 << Feature << BareFeat; 9400 return true; 9401 } 9402 } 9403 return false; 9404 } 9405 9406 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9407 MultiVersionKind MVType) { 9408 for (const Attr *A : FD->attrs()) { 9409 switch (A->getKind()) { 9410 case attr::CPUDispatch: 9411 case attr::CPUSpecific: 9412 if (MVType != MultiVersionKind::CPUDispatch && 9413 MVType != MultiVersionKind::CPUSpecific) 9414 return true; 9415 break; 9416 case attr::Target: 9417 if (MVType != MultiVersionKind::Target) 9418 return true; 9419 break; 9420 default: 9421 return true; 9422 } 9423 } 9424 return false; 9425 } 9426 9427 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9428 const FunctionDecl *NewFD, 9429 bool CausesMV, 9430 MultiVersionKind MVType) { 9431 enum DoesntSupport { 9432 FuncTemplates = 0, 9433 VirtFuncs = 1, 9434 DeducedReturn = 2, 9435 Constructors = 3, 9436 Destructors = 4, 9437 DeletedFuncs = 5, 9438 DefaultedFuncs = 6, 9439 ConstexprFuncs = 7, 9440 }; 9441 enum Different { 9442 CallingConv = 0, 9443 ReturnType = 1, 9444 ConstexprSpec = 2, 9445 InlineSpec = 3, 9446 StorageClass = 4, 9447 Linkage = 5 9448 }; 9449 9450 bool IsCPUSpecificCPUDispatchMVType = 9451 MVType == MultiVersionKind::CPUDispatch || 9452 MVType == MultiVersionKind::CPUSpecific; 9453 9454 if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) { 9455 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9456 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9457 return true; 9458 } 9459 9460 if (!NewFD->getType()->getAs<FunctionProtoType>()) 9461 return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9462 9463 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9464 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9465 if (OldFD) 9466 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9467 return true; 9468 } 9469 9470 // For now, disallow all other attributes. These should be opt-in, but 9471 // an analysis of all of them is a future FIXME. 9472 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 9473 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 9474 << IsCPUSpecificCPUDispatchMVType; 9475 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9476 return true; 9477 } 9478 9479 if (HasNonMultiVersionAttributes(NewFD, MVType)) 9480 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 9481 << IsCPUSpecificCPUDispatchMVType; 9482 9483 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9484 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9485 << IsCPUSpecificCPUDispatchMVType << FuncTemplates; 9486 9487 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9488 if (NewCXXFD->isVirtual()) 9489 return S.Diag(NewCXXFD->getLocation(), 9490 diag::err_multiversion_doesnt_support) 9491 << IsCPUSpecificCPUDispatchMVType << VirtFuncs; 9492 9493 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9494 return S.Diag(NewCXXCtor->getLocation(), 9495 diag::err_multiversion_doesnt_support) 9496 << IsCPUSpecificCPUDispatchMVType << Constructors; 9497 9498 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9499 return S.Diag(NewCXXDtor->getLocation(), 9500 diag::err_multiversion_doesnt_support) 9501 << IsCPUSpecificCPUDispatchMVType << Destructors; 9502 } 9503 9504 if (NewFD->isDeleted()) 9505 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9506 << IsCPUSpecificCPUDispatchMVType << DeletedFuncs; 9507 9508 if (NewFD->isDefaulted()) 9509 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9510 << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs; 9511 9512 if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch || 9513 MVType == MultiVersionKind::CPUSpecific)) 9514 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9515 << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs; 9516 9517 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9518 const auto *NewType = cast<FunctionType>(NewQType); 9519 QualType NewReturnType = NewType->getReturnType(); 9520 9521 if (NewReturnType->isUndeducedType()) 9522 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9523 << IsCPUSpecificCPUDispatchMVType << DeducedReturn; 9524 9525 // Only allow transition to MultiVersion if it hasn't been used. 9526 if (OldFD && CausesMV && OldFD->isUsed(false)) 9527 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9528 9529 // Ensure the return type is identical. 9530 if (OldFD) { 9531 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9532 const auto *OldType = cast<FunctionType>(OldQType); 9533 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9534 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9535 9536 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9537 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9538 << CallingConv; 9539 9540 QualType OldReturnType = OldType->getReturnType(); 9541 9542 if (OldReturnType != NewReturnType) 9543 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9544 << ReturnType; 9545 9546 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9547 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9548 << ConstexprSpec; 9549 9550 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9551 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9552 << InlineSpec; 9553 9554 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9555 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9556 << StorageClass; 9557 9558 if (OldFD->isExternC() != NewFD->isExternC()) 9559 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9560 << Linkage; 9561 9562 if (S.CheckEquivalentExceptionSpec( 9563 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9564 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9565 return true; 9566 } 9567 return false; 9568 } 9569 9570 /// Check the validity of a multiversion function declaration that is the 9571 /// first of its kind. Also sets the multiversion'ness' of the function itself. 9572 /// 9573 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9574 /// 9575 /// Returns true if there was an error, false otherwise. 9576 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 9577 MultiVersionKind MVType, 9578 const TargetAttr *TA, 9579 const CPUDispatchAttr *CPUDisp, 9580 const CPUSpecificAttr *CPUSpec) { 9581 assert(MVType != MultiVersionKind::None && 9582 "Function lacks multiversion attribute"); 9583 9584 // Target only causes MV if it is default, otherwise this is a normal 9585 // function. 9586 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 9587 return false; 9588 9589 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 9590 FD->setInvalidDecl(); 9591 return true; 9592 } 9593 9594 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 9595 FD->setInvalidDecl(); 9596 return true; 9597 } 9598 9599 FD->setIsMultiVersion(); 9600 return false; 9601 } 9602 9603 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 9604 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 9605 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 9606 return true; 9607 } 9608 9609 return false; 9610 } 9611 9612 static bool CheckTargetCausesMultiVersioning( 9613 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 9614 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9615 LookupResult &Previous) { 9616 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9617 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9618 // Sort order doesn't matter, it just needs to be consistent. 9619 llvm::sort(NewParsed.Features); 9620 9621 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9622 // to change, this is a simple redeclaration. 9623 if (!NewTA->isDefaultVersion() && 9624 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 9625 return false; 9626 9627 // Otherwise, this decl causes MultiVersioning. 9628 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9629 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9630 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9631 NewFD->setInvalidDecl(); 9632 return true; 9633 } 9634 9635 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 9636 MultiVersionKind::Target)) { 9637 NewFD->setInvalidDecl(); 9638 return true; 9639 } 9640 9641 if (CheckMultiVersionValue(S, NewFD)) { 9642 NewFD->setInvalidDecl(); 9643 return true; 9644 } 9645 9646 // If this is 'default', permit the forward declaration. 9647 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 9648 Redeclaration = true; 9649 OldDecl = OldFD; 9650 OldFD->setIsMultiVersion(); 9651 NewFD->setIsMultiVersion(); 9652 return false; 9653 } 9654 9655 if (CheckMultiVersionValue(S, OldFD)) { 9656 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9657 NewFD->setInvalidDecl(); 9658 return true; 9659 } 9660 9661 TargetAttr::ParsedTargetAttr OldParsed = 9662 OldTA->parse(std::less<std::string>()); 9663 9664 if (OldParsed == NewParsed) { 9665 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9666 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9667 NewFD->setInvalidDecl(); 9668 return true; 9669 } 9670 9671 for (const auto *FD : OldFD->redecls()) { 9672 const auto *CurTA = FD->getAttr<TargetAttr>(); 9673 // We allow forward declarations before ANY multiversioning attributes, but 9674 // nothing after the fact. 9675 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 9676 (!CurTA || CurTA->isInherited())) { 9677 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 9678 << 0; 9679 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9680 NewFD->setInvalidDecl(); 9681 return true; 9682 } 9683 } 9684 9685 OldFD->setIsMultiVersion(); 9686 NewFD->setIsMultiVersion(); 9687 Redeclaration = false; 9688 MergeTypeWithPrevious = false; 9689 OldDecl = nullptr; 9690 Previous.clear(); 9691 return false; 9692 } 9693 9694 /// Check the validity of a new function declaration being added to an existing 9695 /// multiversioned declaration collection. 9696 static bool CheckMultiVersionAdditionalDecl( 9697 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 9698 MultiVersionKind NewMVType, const TargetAttr *NewTA, 9699 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 9700 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 9701 LookupResult &Previous) { 9702 9703 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 9704 // Disallow mixing of multiversioning types. 9705 if ((OldMVType == MultiVersionKind::Target && 9706 NewMVType != MultiVersionKind::Target) || 9707 (NewMVType == MultiVersionKind::Target && 9708 OldMVType != MultiVersionKind::Target)) { 9709 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9710 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9711 NewFD->setInvalidDecl(); 9712 return true; 9713 } 9714 9715 TargetAttr::ParsedTargetAttr NewParsed; 9716 if (NewTA) { 9717 NewParsed = NewTA->parse(); 9718 llvm::sort(NewParsed.Features); 9719 } 9720 9721 bool UseMemberUsingDeclRules = 9722 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9723 9724 // Next, check ALL non-overloads to see if this is a redeclaration of a 9725 // previous member of the MultiVersion set. 9726 for (NamedDecl *ND : Previous) { 9727 FunctionDecl *CurFD = ND->getAsFunction(); 9728 if (!CurFD) 9729 continue; 9730 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9731 continue; 9732 9733 if (NewMVType == MultiVersionKind::Target) { 9734 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9735 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9736 NewFD->setIsMultiVersion(); 9737 Redeclaration = true; 9738 OldDecl = ND; 9739 return false; 9740 } 9741 9742 TargetAttr::ParsedTargetAttr CurParsed = 9743 CurTA->parse(std::less<std::string>()); 9744 if (CurParsed == NewParsed) { 9745 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9746 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9747 NewFD->setInvalidDecl(); 9748 return true; 9749 } 9750 } else { 9751 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 9752 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 9753 // Handle CPUDispatch/CPUSpecific versions. 9754 // Only 1 CPUDispatch function is allowed, this will make it go through 9755 // the redeclaration errors. 9756 if (NewMVType == MultiVersionKind::CPUDispatch && 9757 CurFD->hasAttr<CPUDispatchAttr>()) { 9758 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 9759 std::equal( 9760 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 9761 NewCPUDisp->cpus_begin(), 9762 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9763 return Cur->getName() == New->getName(); 9764 })) { 9765 NewFD->setIsMultiVersion(); 9766 Redeclaration = true; 9767 OldDecl = ND; 9768 return false; 9769 } 9770 9771 // If the declarations don't match, this is an error condition. 9772 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 9773 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9774 NewFD->setInvalidDecl(); 9775 return true; 9776 } 9777 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 9778 9779 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 9780 std::equal( 9781 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 9782 NewCPUSpec->cpus_begin(), 9783 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 9784 return Cur->getName() == New->getName(); 9785 })) { 9786 NewFD->setIsMultiVersion(); 9787 Redeclaration = true; 9788 OldDecl = ND; 9789 return false; 9790 } 9791 9792 // Only 1 version of CPUSpecific is allowed for each CPU. 9793 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 9794 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 9795 if (CurII == NewII) { 9796 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 9797 << NewII; 9798 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9799 NewFD->setInvalidDecl(); 9800 return true; 9801 } 9802 } 9803 } 9804 } 9805 // If the two decls aren't the same MVType, there is no possible error 9806 // condition. 9807 } 9808 } 9809 9810 // Else, this is simply a non-redecl case. Checking the 'value' is only 9811 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 9812 // handled in the attribute adding step. 9813 if (NewMVType == MultiVersionKind::Target && 9814 CheckMultiVersionValue(S, NewFD)) { 9815 NewFD->setInvalidDecl(); 9816 return true; 9817 } 9818 9819 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 9820 !OldFD->isMultiVersion(), NewMVType)) { 9821 NewFD->setInvalidDecl(); 9822 return true; 9823 } 9824 9825 // Permit forward declarations in the case where these two are compatible. 9826 if (!OldFD->isMultiVersion()) { 9827 OldFD->setIsMultiVersion(); 9828 NewFD->setIsMultiVersion(); 9829 Redeclaration = true; 9830 OldDecl = OldFD; 9831 return false; 9832 } 9833 9834 NewFD->setIsMultiVersion(); 9835 Redeclaration = false; 9836 MergeTypeWithPrevious = false; 9837 OldDecl = nullptr; 9838 Previous.clear(); 9839 return false; 9840 } 9841 9842 9843 /// Check the validity of a mulitversion function declaration. 9844 /// Also sets the multiversion'ness' of the function itself. 9845 /// 9846 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9847 /// 9848 /// Returns true if there was an error, false otherwise. 9849 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9850 bool &Redeclaration, NamedDecl *&OldDecl, 9851 bool &MergeTypeWithPrevious, 9852 LookupResult &Previous) { 9853 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9854 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 9855 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 9856 9857 // Mixing Multiversioning types is prohibited. 9858 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 9859 (NewCPUDisp && NewCPUSpec)) { 9860 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 9861 NewFD->setInvalidDecl(); 9862 return true; 9863 } 9864 9865 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 9866 9867 // Main isn't allowed to become a multiversion function, however it IS 9868 // permitted to have 'main' be marked with the 'target' optimization hint. 9869 if (NewFD->isMain()) { 9870 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 9871 MVType == MultiVersionKind::CPUDispatch || 9872 MVType == MultiVersionKind::CPUSpecific) { 9873 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9874 NewFD->setInvalidDecl(); 9875 return true; 9876 } 9877 return false; 9878 } 9879 9880 if (!OldDecl || !OldDecl->getAsFunction() || 9881 OldDecl->getDeclContext()->getRedeclContext() != 9882 NewFD->getDeclContext()->getRedeclContext()) { 9883 // If there's no previous declaration, AND this isn't attempting to cause 9884 // multiversioning, this isn't an error condition. 9885 if (MVType == MultiVersionKind::None) 9886 return false; 9887 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp, 9888 NewCPUSpec); 9889 } 9890 9891 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9892 9893 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 9894 return false; 9895 9896 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 9897 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 9898 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 9899 NewFD->setInvalidDecl(); 9900 return true; 9901 } 9902 9903 // Handle the target potentially causes multiversioning case. 9904 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 9905 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 9906 Redeclaration, OldDecl, 9907 MergeTypeWithPrevious, Previous); 9908 9909 // At this point, we have a multiversion function decl (in OldFD) AND an 9910 // appropriate attribute in the current function decl. Resolve that these are 9911 // still compatible with previous declarations. 9912 return CheckMultiVersionAdditionalDecl( 9913 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 9914 OldDecl, MergeTypeWithPrevious, Previous); 9915 } 9916 9917 /// Perform semantic checking of a new function declaration. 9918 /// 9919 /// Performs semantic analysis of the new function declaration 9920 /// NewFD. This routine performs all semantic checking that does not 9921 /// require the actual declarator involved in the declaration, and is 9922 /// used both for the declaration of functions as they are parsed 9923 /// (called via ActOnDeclarator) and for the declaration of functions 9924 /// that have been instantiated via C++ template instantiation (called 9925 /// via InstantiateDecl). 9926 /// 9927 /// \param IsMemberSpecialization whether this new function declaration is 9928 /// a member specialization (that replaces any definition provided by the 9929 /// previous declaration). 9930 /// 9931 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9932 /// 9933 /// \returns true if the function declaration is a redeclaration. 9934 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9935 LookupResult &Previous, 9936 bool IsMemberSpecialization) { 9937 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9938 "Variably modified return types are not handled here"); 9939 9940 // Determine whether the type of this function should be merged with 9941 // a previous visible declaration. This never happens for functions in C++, 9942 // and always happens in C if the previous declaration was visible. 9943 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9944 !Previous.isShadowed(); 9945 9946 bool Redeclaration = false; 9947 NamedDecl *OldDecl = nullptr; 9948 bool MayNeedOverloadableChecks = false; 9949 9950 // Merge or overload the declaration with an existing declaration of 9951 // the same name, if appropriate. 9952 if (!Previous.empty()) { 9953 // Determine whether NewFD is an overload of PrevDecl or 9954 // a declaration that requires merging. If it's an overload, 9955 // there's no more work to do here; we'll just add the new 9956 // function to the scope. 9957 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9958 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9959 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9960 Redeclaration = true; 9961 OldDecl = Candidate; 9962 } 9963 } else { 9964 MayNeedOverloadableChecks = true; 9965 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9966 /*NewIsUsingDecl*/ false)) { 9967 case Ovl_Match: 9968 Redeclaration = true; 9969 break; 9970 9971 case Ovl_NonFunction: 9972 Redeclaration = true; 9973 break; 9974 9975 case Ovl_Overload: 9976 Redeclaration = false; 9977 break; 9978 } 9979 } 9980 } 9981 9982 // Check for a previous extern "C" declaration with this name. 9983 if (!Redeclaration && 9984 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9985 if (!Previous.empty()) { 9986 // This is an extern "C" declaration with the same name as a previous 9987 // declaration, and thus redeclares that entity... 9988 Redeclaration = true; 9989 OldDecl = Previous.getFoundDecl(); 9990 MergeTypeWithPrevious = false; 9991 9992 // ... except in the presence of __attribute__((overloadable)). 9993 if (OldDecl->hasAttr<OverloadableAttr>() || 9994 NewFD->hasAttr<OverloadableAttr>()) { 9995 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9996 MayNeedOverloadableChecks = true; 9997 Redeclaration = false; 9998 OldDecl = nullptr; 9999 } 10000 } 10001 } 10002 } 10003 10004 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10005 MergeTypeWithPrevious, Previous)) 10006 return Redeclaration; 10007 10008 // C++11 [dcl.constexpr]p8: 10009 // A constexpr specifier for a non-static member function that is not 10010 // a constructor declares that member function to be const. 10011 // 10012 // This needs to be delayed until we know whether this is an out-of-line 10013 // definition of a static member function. 10014 // 10015 // This rule is not present in C++1y, so we produce a backwards 10016 // compatibility warning whenever it happens in C++11. 10017 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10018 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10019 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10020 !MD->getTypeQualifiers().hasConst()) { 10021 CXXMethodDecl *OldMD = nullptr; 10022 if (OldDecl) 10023 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10024 if (!OldMD || !OldMD->isStatic()) { 10025 const FunctionProtoType *FPT = 10026 MD->getType()->castAs<FunctionProtoType>(); 10027 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10028 EPI.TypeQuals.addConst(); 10029 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10030 FPT->getParamTypes(), EPI)); 10031 10032 // Warn that we did this, if we're not performing template instantiation. 10033 // In that case, we'll have warned already when the template was defined. 10034 if (!inTemplateInstantiation()) { 10035 SourceLocation AddConstLoc; 10036 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10037 .IgnoreParens().getAs<FunctionTypeLoc>()) 10038 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10039 10040 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10041 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10042 } 10043 } 10044 } 10045 10046 if (Redeclaration) { 10047 // NewFD and OldDecl represent declarations that need to be 10048 // merged. 10049 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10050 NewFD->setInvalidDecl(); 10051 return Redeclaration; 10052 } 10053 10054 Previous.clear(); 10055 Previous.addDecl(OldDecl); 10056 10057 if (FunctionTemplateDecl *OldTemplateDecl = 10058 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10059 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10060 FunctionTemplateDecl *NewTemplateDecl 10061 = NewFD->getDescribedFunctionTemplate(); 10062 assert(NewTemplateDecl && "Template/non-template mismatch"); 10063 10064 // The call to MergeFunctionDecl above may have created some state in 10065 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10066 // can add it as a redeclaration. 10067 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10068 10069 NewFD->setPreviousDeclaration(OldFD); 10070 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10071 if (NewFD->isCXXClassMember()) { 10072 NewFD->setAccess(OldTemplateDecl->getAccess()); 10073 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10074 } 10075 10076 // If this is an explicit specialization of a member that is a function 10077 // template, mark it as a member specialization. 10078 if (IsMemberSpecialization && 10079 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10080 NewTemplateDecl->setMemberSpecialization(); 10081 assert(OldTemplateDecl->isMemberSpecialization()); 10082 // Explicit specializations of a member template do not inherit deleted 10083 // status from the parent member template that they are specializing. 10084 if (OldFD->isDeleted()) { 10085 // FIXME: This assert will not hold in the presence of modules. 10086 assert(OldFD->getCanonicalDecl() == OldFD); 10087 // FIXME: We need an update record for this AST mutation. 10088 OldFD->setDeletedAsWritten(false); 10089 } 10090 } 10091 10092 } else { 10093 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10094 auto *OldFD = cast<FunctionDecl>(OldDecl); 10095 // This needs to happen first so that 'inline' propagates. 10096 NewFD->setPreviousDeclaration(OldFD); 10097 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10098 if (NewFD->isCXXClassMember()) 10099 NewFD->setAccess(OldFD->getAccess()); 10100 } 10101 } 10102 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10103 !NewFD->getAttr<OverloadableAttr>()) { 10104 assert((Previous.empty() || 10105 llvm::any_of(Previous, 10106 [](const NamedDecl *ND) { 10107 return ND->hasAttr<OverloadableAttr>(); 10108 })) && 10109 "Non-redecls shouldn't happen without overloadable present"); 10110 10111 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10112 const auto *FD = dyn_cast<FunctionDecl>(ND); 10113 return FD && !FD->hasAttr<OverloadableAttr>(); 10114 }); 10115 10116 if (OtherUnmarkedIter != Previous.end()) { 10117 Diag(NewFD->getLocation(), 10118 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10119 Diag((*OtherUnmarkedIter)->getLocation(), 10120 diag::note_attribute_overloadable_prev_overload) 10121 << false; 10122 10123 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10124 } 10125 } 10126 10127 // Semantic checking for this function declaration (in isolation). 10128 10129 if (getLangOpts().CPlusPlus) { 10130 // C++-specific checks. 10131 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10132 CheckConstructor(Constructor); 10133 } else if (CXXDestructorDecl *Destructor = 10134 dyn_cast<CXXDestructorDecl>(NewFD)) { 10135 CXXRecordDecl *Record = Destructor->getParent(); 10136 QualType ClassType = Context.getTypeDeclType(Record); 10137 10138 // FIXME: Shouldn't we be able to perform this check even when the class 10139 // type is dependent? Both gcc and edg can handle that. 10140 if (!ClassType->isDependentType()) { 10141 DeclarationName Name 10142 = Context.DeclarationNames.getCXXDestructorName( 10143 Context.getCanonicalType(ClassType)); 10144 if (NewFD->getDeclName() != Name) { 10145 Diag(NewFD->getLocation(), diag::err_destructor_name); 10146 NewFD->setInvalidDecl(); 10147 return Redeclaration; 10148 } 10149 } 10150 } else if (CXXConversionDecl *Conversion 10151 = dyn_cast<CXXConversionDecl>(NewFD)) { 10152 ActOnConversionDeclarator(Conversion); 10153 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10154 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10155 CheckDeductionGuideTemplate(TD); 10156 10157 // A deduction guide is not on the list of entities that can be 10158 // explicitly specialized. 10159 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10160 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10161 << /*explicit specialization*/ 1; 10162 } 10163 10164 // Find any virtual functions that this function overrides. 10165 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10166 if (!Method->isFunctionTemplateSpecialization() && 10167 !Method->getDescribedFunctionTemplate() && 10168 Method->isCanonicalDecl()) { 10169 if (AddOverriddenMethods(Method->getParent(), Method)) { 10170 // If the function was marked as "static", we have a problem. 10171 if (NewFD->getStorageClass() == SC_Static) { 10172 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10173 } 10174 } 10175 } 10176 10177 if (Method->isStatic()) 10178 checkThisInStaticMemberFunctionType(Method); 10179 } 10180 10181 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10182 if (NewFD->isOverloadedOperator() && 10183 CheckOverloadedOperatorDeclaration(NewFD)) { 10184 NewFD->setInvalidDecl(); 10185 return Redeclaration; 10186 } 10187 10188 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10189 if (NewFD->getLiteralIdentifier() && 10190 CheckLiteralOperatorDeclaration(NewFD)) { 10191 NewFD->setInvalidDecl(); 10192 return Redeclaration; 10193 } 10194 10195 // In C++, check default arguments now that we have merged decls. Unless 10196 // the lexical context is the class, because in this case this is done 10197 // during delayed parsing anyway. 10198 if (!CurContext->isRecord()) 10199 CheckCXXDefaultArguments(NewFD); 10200 10201 // If this function declares a builtin function, check the type of this 10202 // declaration against the expected type for the builtin. 10203 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10204 ASTContext::GetBuiltinTypeError Error; 10205 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10206 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10207 // If the type of the builtin differs only in its exception 10208 // specification, that's OK. 10209 // FIXME: If the types do differ in this way, it would be better to 10210 // retain the 'noexcept' form of the type. 10211 if (!T.isNull() && 10212 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10213 NewFD->getType())) 10214 // The type of this function differs from the type of the builtin, 10215 // so forget about the builtin entirely. 10216 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10217 } 10218 10219 // If this function is declared as being extern "C", then check to see if 10220 // the function returns a UDT (class, struct, or union type) that is not C 10221 // compatible, and if it does, warn the user. 10222 // But, issue any diagnostic on the first declaration only. 10223 if (Previous.empty() && NewFD->isExternC()) { 10224 QualType R = NewFD->getReturnType(); 10225 if (R->isIncompleteType() && !R->isVoidType()) 10226 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10227 << NewFD << R; 10228 else if (!R.isPODType(Context) && !R->isVoidType() && 10229 !R->isObjCObjectPointerType()) 10230 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10231 } 10232 10233 // C++1z [dcl.fct]p6: 10234 // [...] whether the function has a non-throwing exception-specification 10235 // [is] part of the function type 10236 // 10237 // This results in an ABI break between C++14 and C++17 for functions whose 10238 // declared type includes an exception-specification in a parameter or 10239 // return type. (Exception specifications on the function itself are OK in 10240 // most cases, and exception specifications are not permitted in most other 10241 // contexts where they could make it into a mangling.) 10242 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10243 auto HasNoexcept = [&](QualType T) -> bool { 10244 // Strip off declarator chunks that could be between us and a function 10245 // type. We don't need to look far, exception specifications are very 10246 // restricted prior to C++17. 10247 if (auto *RT = T->getAs<ReferenceType>()) 10248 T = RT->getPointeeType(); 10249 else if (T->isAnyPointerType()) 10250 T = T->getPointeeType(); 10251 else if (auto *MPT = T->getAs<MemberPointerType>()) 10252 T = MPT->getPointeeType(); 10253 if (auto *FPT = T->getAs<FunctionProtoType>()) 10254 if (FPT->isNothrow()) 10255 return true; 10256 return false; 10257 }; 10258 10259 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10260 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10261 for (QualType T : FPT->param_types()) 10262 AnyNoexcept |= HasNoexcept(T); 10263 if (AnyNoexcept) 10264 Diag(NewFD->getLocation(), 10265 diag::warn_cxx17_compat_exception_spec_in_signature) 10266 << NewFD; 10267 } 10268 10269 if (!Redeclaration && LangOpts.CUDA) 10270 checkCUDATargetOverload(NewFD, Previous); 10271 } 10272 return Redeclaration; 10273 } 10274 10275 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10276 // C++11 [basic.start.main]p3: 10277 // A program that [...] declares main to be inline, static or 10278 // constexpr is ill-formed. 10279 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10280 // appear in a declaration of main. 10281 // static main is not an error under C99, but we should warn about it. 10282 // We accept _Noreturn main as an extension. 10283 if (FD->getStorageClass() == SC_Static) 10284 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10285 ? diag::err_static_main : diag::warn_static_main) 10286 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10287 if (FD->isInlineSpecified()) 10288 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10289 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10290 if (DS.isNoreturnSpecified()) { 10291 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10292 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10293 Diag(NoreturnLoc, diag::ext_noreturn_main); 10294 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10295 << FixItHint::CreateRemoval(NoreturnRange); 10296 } 10297 if (FD->isConstexpr()) { 10298 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10299 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10300 FD->setConstexpr(false); 10301 } 10302 10303 if (getLangOpts().OpenCL) { 10304 Diag(FD->getLocation(), diag::err_opencl_no_main) 10305 << FD->hasAttr<OpenCLKernelAttr>(); 10306 FD->setInvalidDecl(); 10307 return; 10308 } 10309 10310 QualType T = FD->getType(); 10311 assert(T->isFunctionType() && "function decl is not of function type"); 10312 const FunctionType* FT = T->castAs<FunctionType>(); 10313 10314 // Set default calling convention for main() 10315 if (FT->getCallConv() != CC_C) { 10316 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10317 FD->setType(QualType(FT, 0)); 10318 T = Context.getCanonicalType(FD->getType()); 10319 } 10320 10321 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10322 // In C with GNU extensions we allow main() to have non-integer return 10323 // type, but we should warn about the extension, and we disable the 10324 // implicit-return-zero rule. 10325 10326 // GCC in C mode accepts qualified 'int'. 10327 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10328 FD->setHasImplicitReturnZero(true); 10329 else { 10330 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10331 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10332 if (RTRange.isValid()) 10333 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10334 << FixItHint::CreateReplacement(RTRange, "int"); 10335 } 10336 } else { 10337 // In C and C++, main magically returns 0 if you fall off the end; 10338 // set the flag which tells us that. 10339 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10340 10341 // All the standards say that main() should return 'int'. 10342 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10343 FD->setHasImplicitReturnZero(true); 10344 else { 10345 // Otherwise, this is just a flat-out error. 10346 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10347 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10348 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10349 : FixItHint()); 10350 FD->setInvalidDecl(true); 10351 } 10352 } 10353 10354 // Treat protoless main() as nullary. 10355 if (isa<FunctionNoProtoType>(FT)) return; 10356 10357 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10358 unsigned nparams = FTP->getNumParams(); 10359 assert(FD->getNumParams() == nparams); 10360 10361 bool HasExtraParameters = (nparams > 3); 10362 10363 if (FTP->isVariadic()) { 10364 Diag(FD->getLocation(), diag::ext_variadic_main); 10365 // FIXME: if we had information about the location of the ellipsis, we 10366 // could add a FixIt hint to remove it as a parameter. 10367 } 10368 10369 // Darwin passes an undocumented fourth argument of type char**. If 10370 // other platforms start sprouting these, the logic below will start 10371 // getting shifty. 10372 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10373 HasExtraParameters = false; 10374 10375 if (HasExtraParameters) { 10376 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10377 FD->setInvalidDecl(true); 10378 nparams = 3; 10379 } 10380 10381 // FIXME: a lot of the following diagnostics would be improved 10382 // if we had some location information about types. 10383 10384 QualType CharPP = 10385 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10386 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10387 10388 for (unsigned i = 0; i < nparams; ++i) { 10389 QualType AT = FTP->getParamType(i); 10390 10391 bool mismatch = true; 10392 10393 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10394 mismatch = false; 10395 else if (Expected[i] == CharPP) { 10396 // As an extension, the following forms are okay: 10397 // char const ** 10398 // char const * const * 10399 // char * const * 10400 10401 QualifierCollector qs; 10402 const PointerType* PT; 10403 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10404 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10405 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10406 Context.CharTy)) { 10407 qs.removeConst(); 10408 mismatch = !qs.empty(); 10409 } 10410 } 10411 10412 if (mismatch) { 10413 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10414 // TODO: suggest replacing given type with expected type 10415 FD->setInvalidDecl(true); 10416 } 10417 } 10418 10419 if (nparams == 1 && !FD->isInvalidDecl()) { 10420 Diag(FD->getLocation(), diag::warn_main_one_arg); 10421 } 10422 10423 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10424 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10425 FD->setInvalidDecl(); 10426 } 10427 } 10428 10429 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10430 QualType T = FD->getType(); 10431 assert(T->isFunctionType() && "function decl is not of function type"); 10432 const FunctionType *FT = T->castAs<FunctionType>(); 10433 10434 // Set an implicit return of 'zero' if the function can return some integral, 10435 // enumeration, pointer or nullptr type. 10436 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10437 FT->getReturnType()->isAnyPointerType() || 10438 FT->getReturnType()->isNullPtrType()) 10439 // DllMain is exempt because a return value of zero means it failed. 10440 if (FD->getName() != "DllMain") 10441 FD->setHasImplicitReturnZero(true); 10442 10443 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10444 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10445 FD->setInvalidDecl(); 10446 } 10447 } 10448 10449 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10450 // FIXME: Need strict checking. In C89, we need to check for 10451 // any assignment, increment, decrement, function-calls, or 10452 // commas outside of a sizeof. In C99, it's the same list, 10453 // except that the aforementioned are allowed in unevaluated 10454 // expressions. Everything else falls under the 10455 // "may accept other forms of constant expressions" exception. 10456 // (We never end up here for C++, so the constant expression 10457 // rules there don't matter.) 10458 const Expr *Culprit; 10459 if (Init->isConstantInitializer(Context, false, &Culprit)) 10460 return false; 10461 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10462 << Culprit->getSourceRange(); 10463 return true; 10464 } 10465 10466 namespace { 10467 // Visits an initialization expression to see if OrigDecl is evaluated in 10468 // its own initialization and throws a warning if it does. 10469 class SelfReferenceChecker 10470 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10471 Sema &S; 10472 Decl *OrigDecl; 10473 bool isRecordType; 10474 bool isPODType; 10475 bool isReferenceType; 10476 10477 bool isInitList; 10478 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10479 10480 public: 10481 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10482 10483 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10484 S(S), OrigDecl(OrigDecl) { 10485 isPODType = false; 10486 isRecordType = false; 10487 isReferenceType = false; 10488 isInitList = false; 10489 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10490 isPODType = VD->getType().isPODType(S.Context); 10491 isRecordType = VD->getType()->isRecordType(); 10492 isReferenceType = VD->getType()->isReferenceType(); 10493 } 10494 } 10495 10496 // For most expressions, just call the visitor. For initializer lists, 10497 // track the index of the field being initialized since fields are 10498 // initialized in order allowing use of previously initialized fields. 10499 void CheckExpr(Expr *E) { 10500 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10501 if (!InitList) { 10502 Visit(E); 10503 return; 10504 } 10505 10506 // Track and increment the index here. 10507 isInitList = true; 10508 InitFieldIndex.push_back(0); 10509 for (auto Child : InitList->children()) { 10510 CheckExpr(cast<Expr>(Child)); 10511 ++InitFieldIndex.back(); 10512 } 10513 InitFieldIndex.pop_back(); 10514 } 10515 10516 // Returns true if MemberExpr is checked and no further checking is needed. 10517 // Returns false if additional checking is required. 10518 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10519 llvm::SmallVector<FieldDecl*, 4> Fields; 10520 Expr *Base = E; 10521 bool ReferenceField = false; 10522 10523 // Get the field members used. 10524 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10525 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10526 if (!FD) 10527 return false; 10528 Fields.push_back(FD); 10529 if (FD->getType()->isReferenceType()) 10530 ReferenceField = true; 10531 Base = ME->getBase()->IgnoreParenImpCasts(); 10532 } 10533 10534 // Keep checking only if the base Decl is the same. 10535 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10536 if (!DRE || DRE->getDecl() != OrigDecl) 10537 return false; 10538 10539 // A reference field can be bound to an unininitialized field. 10540 if (CheckReference && !ReferenceField) 10541 return true; 10542 10543 // Convert FieldDecls to their index number. 10544 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10545 for (const FieldDecl *I : llvm::reverse(Fields)) 10546 UsedFieldIndex.push_back(I->getFieldIndex()); 10547 10548 // See if a warning is needed by checking the first difference in index 10549 // numbers. If field being used has index less than the field being 10550 // initialized, then the use is safe. 10551 for (auto UsedIter = UsedFieldIndex.begin(), 10552 UsedEnd = UsedFieldIndex.end(), 10553 OrigIter = InitFieldIndex.begin(), 10554 OrigEnd = InitFieldIndex.end(); 10555 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10556 if (*UsedIter < *OrigIter) 10557 return true; 10558 if (*UsedIter > *OrigIter) 10559 break; 10560 } 10561 10562 // TODO: Add a different warning which will print the field names. 10563 HandleDeclRefExpr(DRE); 10564 return true; 10565 } 10566 10567 // For most expressions, the cast is directly above the DeclRefExpr. 10568 // For conditional operators, the cast can be outside the conditional 10569 // operator if both expressions are DeclRefExpr's. 10570 void HandleValue(Expr *E) { 10571 E = E->IgnoreParens(); 10572 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10573 HandleDeclRefExpr(DRE); 10574 return; 10575 } 10576 10577 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10578 Visit(CO->getCond()); 10579 HandleValue(CO->getTrueExpr()); 10580 HandleValue(CO->getFalseExpr()); 10581 return; 10582 } 10583 10584 if (BinaryConditionalOperator *BCO = 10585 dyn_cast<BinaryConditionalOperator>(E)) { 10586 Visit(BCO->getCond()); 10587 HandleValue(BCO->getFalseExpr()); 10588 return; 10589 } 10590 10591 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10592 HandleValue(OVE->getSourceExpr()); 10593 return; 10594 } 10595 10596 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10597 if (BO->getOpcode() == BO_Comma) { 10598 Visit(BO->getLHS()); 10599 HandleValue(BO->getRHS()); 10600 return; 10601 } 10602 } 10603 10604 if (isa<MemberExpr>(E)) { 10605 if (isInitList) { 10606 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10607 false /*CheckReference*/)) 10608 return; 10609 } 10610 10611 Expr *Base = E->IgnoreParenImpCasts(); 10612 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10613 // Check for static member variables and don't warn on them. 10614 if (!isa<FieldDecl>(ME->getMemberDecl())) 10615 return; 10616 Base = ME->getBase()->IgnoreParenImpCasts(); 10617 } 10618 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10619 HandleDeclRefExpr(DRE); 10620 return; 10621 } 10622 10623 Visit(E); 10624 } 10625 10626 // Reference types not handled in HandleValue are handled here since all 10627 // uses of references are bad, not just r-value uses. 10628 void VisitDeclRefExpr(DeclRefExpr *E) { 10629 if (isReferenceType) 10630 HandleDeclRefExpr(E); 10631 } 10632 10633 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10634 if (E->getCastKind() == CK_LValueToRValue) { 10635 HandleValue(E->getSubExpr()); 10636 return; 10637 } 10638 10639 Inherited::VisitImplicitCastExpr(E); 10640 } 10641 10642 void VisitMemberExpr(MemberExpr *E) { 10643 if (isInitList) { 10644 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10645 return; 10646 } 10647 10648 // Don't warn on arrays since they can be treated as pointers. 10649 if (E->getType()->canDecayToPointerType()) return; 10650 10651 // Warn when a non-static method call is followed by non-static member 10652 // field accesses, which is followed by a DeclRefExpr. 10653 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10654 bool Warn = (MD && !MD->isStatic()); 10655 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10656 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10657 if (!isa<FieldDecl>(ME->getMemberDecl())) 10658 Warn = false; 10659 Base = ME->getBase()->IgnoreParenImpCasts(); 10660 } 10661 10662 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10663 if (Warn) 10664 HandleDeclRefExpr(DRE); 10665 return; 10666 } 10667 10668 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10669 // Visit that expression. 10670 Visit(Base); 10671 } 10672 10673 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10674 Expr *Callee = E->getCallee(); 10675 10676 if (isa<UnresolvedLookupExpr>(Callee)) 10677 return Inherited::VisitCXXOperatorCallExpr(E); 10678 10679 Visit(Callee); 10680 for (auto Arg: E->arguments()) 10681 HandleValue(Arg->IgnoreParenImpCasts()); 10682 } 10683 10684 void VisitUnaryOperator(UnaryOperator *E) { 10685 // For POD record types, addresses of its own members are well-defined. 10686 if (E->getOpcode() == UO_AddrOf && isRecordType && 10687 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10688 if (!isPODType) 10689 HandleValue(E->getSubExpr()); 10690 return; 10691 } 10692 10693 if (E->isIncrementDecrementOp()) { 10694 HandleValue(E->getSubExpr()); 10695 return; 10696 } 10697 10698 Inherited::VisitUnaryOperator(E); 10699 } 10700 10701 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10702 10703 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10704 if (E->getConstructor()->isCopyConstructor()) { 10705 Expr *ArgExpr = E->getArg(0); 10706 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10707 if (ILE->getNumInits() == 1) 10708 ArgExpr = ILE->getInit(0); 10709 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10710 if (ICE->getCastKind() == CK_NoOp) 10711 ArgExpr = ICE->getSubExpr(); 10712 HandleValue(ArgExpr); 10713 return; 10714 } 10715 Inherited::VisitCXXConstructExpr(E); 10716 } 10717 10718 void VisitCallExpr(CallExpr *E) { 10719 // Treat std::move as a use. 10720 if (E->isCallToStdMove()) { 10721 HandleValue(E->getArg(0)); 10722 return; 10723 } 10724 10725 Inherited::VisitCallExpr(E); 10726 } 10727 10728 void VisitBinaryOperator(BinaryOperator *E) { 10729 if (E->isCompoundAssignmentOp()) { 10730 HandleValue(E->getLHS()); 10731 Visit(E->getRHS()); 10732 return; 10733 } 10734 10735 Inherited::VisitBinaryOperator(E); 10736 } 10737 10738 // A custom visitor for BinaryConditionalOperator is needed because the 10739 // regular visitor would check the condition and true expression separately 10740 // but both point to the same place giving duplicate diagnostics. 10741 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10742 Visit(E->getCond()); 10743 Visit(E->getFalseExpr()); 10744 } 10745 10746 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10747 Decl* ReferenceDecl = DRE->getDecl(); 10748 if (OrigDecl != ReferenceDecl) return; 10749 unsigned diag; 10750 if (isReferenceType) { 10751 diag = diag::warn_uninit_self_reference_in_reference_init; 10752 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10753 diag = diag::warn_static_self_reference_in_init; 10754 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10755 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10756 DRE->getDecl()->getType()->isRecordType()) { 10757 diag = diag::warn_uninit_self_reference_in_init; 10758 } else { 10759 // Local variables will be handled by the CFG analysis. 10760 return; 10761 } 10762 10763 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 10764 S.PDiag(diag) 10765 << DRE->getDecl() << OrigDecl->getLocation() 10766 << DRE->getSourceRange()); 10767 } 10768 }; 10769 10770 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10771 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10772 bool DirectInit) { 10773 // Parameters arguments are occassionially constructed with itself, 10774 // for instance, in recursive functions. Skip them. 10775 if (isa<ParmVarDecl>(OrigDecl)) 10776 return; 10777 10778 E = E->IgnoreParens(); 10779 10780 // Skip checking T a = a where T is not a record or reference type. 10781 // Doing so is a way to silence uninitialized warnings. 10782 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10783 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10784 if (ICE->getCastKind() == CK_LValueToRValue) 10785 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10786 if (DRE->getDecl() == OrigDecl) 10787 return; 10788 10789 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10790 } 10791 } // end anonymous namespace 10792 10793 namespace { 10794 // Simple wrapper to add the name of a variable or (if no variable is 10795 // available) a DeclarationName into a diagnostic. 10796 struct VarDeclOrName { 10797 VarDecl *VDecl; 10798 DeclarationName Name; 10799 10800 friend const Sema::SemaDiagnosticBuilder & 10801 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10802 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10803 } 10804 }; 10805 } // end anonymous namespace 10806 10807 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10808 DeclarationName Name, QualType Type, 10809 TypeSourceInfo *TSI, 10810 SourceRange Range, bool DirectInit, 10811 Expr *&Init) { 10812 bool IsInitCapture = !VDecl; 10813 assert((!VDecl || !VDecl->isInitCapture()) && 10814 "init captures are expected to be deduced prior to initialization"); 10815 10816 VarDeclOrName VN{VDecl, Name}; 10817 10818 DeducedType *Deduced = Type->getContainedDeducedType(); 10819 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10820 10821 // C++11 [dcl.spec.auto]p3 10822 if (!Init) { 10823 assert(VDecl && "no init for init capture deduction?"); 10824 10825 // Except for class argument deduction, and then for an initializing 10826 // declaration only, i.e. no static at class scope or extern. 10827 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10828 VDecl->hasExternalStorage() || 10829 VDecl->isStaticDataMember()) { 10830 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10831 << VDecl->getDeclName() << Type; 10832 return QualType(); 10833 } 10834 } 10835 10836 ArrayRef<Expr*> DeduceInits; 10837 if (Init) 10838 DeduceInits = Init; 10839 10840 if (DirectInit) { 10841 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10842 DeduceInits = PL->exprs(); 10843 } 10844 10845 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10846 assert(VDecl && "non-auto type for init capture deduction?"); 10847 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10848 InitializationKind Kind = InitializationKind::CreateForInit( 10849 VDecl->getLocation(), DirectInit, Init); 10850 // FIXME: Initialization should not be taking a mutable list of inits. 10851 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10852 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10853 InitsCopy); 10854 } 10855 10856 if (DirectInit) { 10857 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10858 DeduceInits = IL->inits(); 10859 } 10860 10861 // Deduction only works if we have exactly one source expression. 10862 if (DeduceInits.empty()) { 10863 // It isn't possible to write this directly, but it is possible to 10864 // end up in this situation with "auto x(some_pack...);" 10865 Diag(Init->getBeginLoc(), IsInitCapture 10866 ? diag::err_init_capture_no_expression 10867 : diag::err_auto_var_init_no_expression) 10868 << VN << Type << Range; 10869 return QualType(); 10870 } 10871 10872 if (DeduceInits.size() > 1) { 10873 Diag(DeduceInits[1]->getBeginLoc(), 10874 IsInitCapture ? diag::err_init_capture_multiple_expressions 10875 : diag::err_auto_var_init_multiple_expressions) 10876 << VN << Type << Range; 10877 return QualType(); 10878 } 10879 10880 Expr *DeduceInit = DeduceInits[0]; 10881 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10882 Diag(Init->getBeginLoc(), IsInitCapture 10883 ? diag::err_init_capture_paren_braces 10884 : diag::err_auto_var_init_paren_braces) 10885 << isa<InitListExpr>(Init) << VN << Type << Range; 10886 return QualType(); 10887 } 10888 10889 // Expressions default to 'id' when we're in a debugger. 10890 bool DefaultedAnyToId = false; 10891 if (getLangOpts().DebuggerCastResultToId && 10892 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10893 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10894 if (Result.isInvalid()) { 10895 return QualType(); 10896 } 10897 Init = Result.get(); 10898 DefaultedAnyToId = true; 10899 } 10900 10901 // C++ [dcl.decomp]p1: 10902 // If the assignment-expression [...] has array type A and no ref-qualifier 10903 // is present, e has type cv A 10904 if (VDecl && isa<DecompositionDecl>(VDecl) && 10905 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10906 DeduceInit->getType()->isConstantArrayType()) 10907 return Context.getQualifiedType(DeduceInit->getType(), 10908 Type.getQualifiers()); 10909 10910 QualType DeducedType; 10911 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10912 if (!IsInitCapture) 10913 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10914 else if (isa<InitListExpr>(Init)) 10915 Diag(Range.getBegin(), 10916 diag::err_init_capture_deduction_failure_from_init_list) 10917 << VN 10918 << (DeduceInit->getType().isNull() ? TSI->getType() 10919 : DeduceInit->getType()) 10920 << DeduceInit->getSourceRange(); 10921 else 10922 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10923 << VN << TSI->getType() 10924 << (DeduceInit->getType().isNull() ? TSI->getType() 10925 : DeduceInit->getType()) 10926 << DeduceInit->getSourceRange(); 10927 } else 10928 Init = DeduceInit; 10929 10930 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10931 // 'id' instead of a specific object type prevents most of our usual 10932 // checks. 10933 // We only want to warn outside of template instantiations, though: 10934 // inside a template, the 'id' could have come from a parameter. 10935 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10936 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10937 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10938 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10939 } 10940 10941 return DeducedType; 10942 } 10943 10944 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10945 Expr *&Init) { 10946 QualType DeducedType = deduceVarTypeFromInitializer( 10947 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10948 VDecl->getSourceRange(), DirectInit, Init); 10949 if (DeducedType.isNull()) { 10950 VDecl->setInvalidDecl(); 10951 return true; 10952 } 10953 10954 VDecl->setType(DeducedType); 10955 assert(VDecl->isLinkageValid()); 10956 10957 // In ARC, infer lifetime. 10958 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10959 VDecl->setInvalidDecl(); 10960 10961 // If this is a redeclaration, check that the type we just deduced matches 10962 // the previously declared type. 10963 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10964 // We never need to merge the type, because we cannot form an incomplete 10965 // array of auto, nor deduce such a type. 10966 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10967 } 10968 10969 // Check the deduced type is valid for a variable declaration. 10970 CheckVariableDeclarationType(VDecl); 10971 return VDecl->isInvalidDecl(); 10972 } 10973 10974 /// AddInitializerToDecl - Adds the initializer Init to the 10975 /// declaration dcl. If DirectInit is true, this is C++ direct 10976 /// initialization rather than copy initialization. 10977 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10978 // If there is no declaration, there was an error parsing it. Just ignore 10979 // the initializer. 10980 if (!RealDecl || RealDecl->isInvalidDecl()) { 10981 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10982 return; 10983 } 10984 10985 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10986 // Pure-specifiers are handled in ActOnPureSpecifier. 10987 Diag(Method->getLocation(), diag::err_member_function_initialization) 10988 << Method->getDeclName() << Init->getSourceRange(); 10989 Method->setInvalidDecl(); 10990 return; 10991 } 10992 10993 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10994 if (!VDecl) { 10995 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10996 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10997 RealDecl->setInvalidDecl(); 10998 return; 10999 } 11000 11001 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11002 if (VDecl->getType()->isUndeducedType()) { 11003 // Attempt typo correction early so that the type of the init expression can 11004 // be deduced based on the chosen correction if the original init contains a 11005 // TypoExpr. 11006 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11007 if (!Res.isUsable()) { 11008 RealDecl->setInvalidDecl(); 11009 return; 11010 } 11011 Init = Res.get(); 11012 11013 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11014 return; 11015 } 11016 11017 // dllimport cannot be used on variable definitions. 11018 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11019 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11020 VDecl->setInvalidDecl(); 11021 return; 11022 } 11023 11024 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11025 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11026 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11027 VDecl->setInvalidDecl(); 11028 return; 11029 } 11030 11031 if (!VDecl->getType()->isDependentType()) { 11032 // A definition must end up with a complete type, which means it must be 11033 // complete with the restriction that an array type might be completed by 11034 // the initializer; note that later code assumes this restriction. 11035 QualType BaseDeclType = VDecl->getType(); 11036 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11037 BaseDeclType = Array->getElementType(); 11038 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11039 diag::err_typecheck_decl_incomplete_type)) { 11040 RealDecl->setInvalidDecl(); 11041 return; 11042 } 11043 11044 // The variable can not have an abstract class type. 11045 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11046 diag::err_abstract_type_in_decl, 11047 AbstractVariableType)) 11048 VDecl->setInvalidDecl(); 11049 } 11050 11051 // If adding the initializer will turn this declaration into a definition, 11052 // and we already have a definition for this variable, diagnose or otherwise 11053 // handle the situation. 11054 VarDecl *Def; 11055 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11056 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11057 !VDecl->isThisDeclarationADemotedDefinition() && 11058 checkVarDeclRedefinition(Def, VDecl)) 11059 return; 11060 11061 if (getLangOpts().CPlusPlus) { 11062 // C++ [class.static.data]p4 11063 // If a static data member is of const integral or const 11064 // enumeration type, its declaration in the class definition can 11065 // specify a constant-initializer which shall be an integral 11066 // constant expression (5.19). In that case, the member can appear 11067 // in integral constant expressions. The member shall still be 11068 // defined in a namespace scope if it is used in the program and the 11069 // namespace scope definition shall not contain an initializer. 11070 // 11071 // We already performed a redefinition check above, but for static 11072 // data members we also need to check whether there was an in-class 11073 // declaration with an initializer. 11074 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11075 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11076 << VDecl->getDeclName(); 11077 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11078 diag::note_previous_initializer) 11079 << 0; 11080 return; 11081 } 11082 11083 if (VDecl->hasLocalStorage()) 11084 setFunctionHasBranchProtectedScope(); 11085 11086 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11087 VDecl->setInvalidDecl(); 11088 return; 11089 } 11090 } 11091 11092 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11093 // a kernel function cannot be initialized." 11094 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11095 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11096 VDecl->setInvalidDecl(); 11097 return; 11098 } 11099 11100 // Get the decls type and save a reference for later, since 11101 // CheckInitializerTypes may change it. 11102 QualType DclT = VDecl->getType(), SavT = DclT; 11103 11104 // Expressions default to 'id' when we're in a debugger 11105 // and we are assigning it to a variable of Objective-C pointer type. 11106 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11107 Init->getType() == Context.UnknownAnyTy) { 11108 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11109 if (Result.isInvalid()) { 11110 VDecl->setInvalidDecl(); 11111 return; 11112 } 11113 Init = Result.get(); 11114 } 11115 11116 // Perform the initialization. 11117 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11118 if (!VDecl->isInvalidDecl()) { 11119 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11120 InitializationKind Kind = InitializationKind::CreateForInit( 11121 VDecl->getLocation(), DirectInit, Init); 11122 11123 MultiExprArg Args = Init; 11124 if (CXXDirectInit) 11125 Args = MultiExprArg(CXXDirectInit->getExprs(), 11126 CXXDirectInit->getNumExprs()); 11127 11128 // Try to correct any TypoExprs in the initialization arguments. 11129 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11130 ExprResult Res = CorrectDelayedTyposInExpr( 11131 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11132 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11133 return Init.Failed() ? ExprError() : E; 11134 }); 11135 if (Res.isInvalid()) { 11136 VDecl->setInvalidDecl(); 11137 } else if (Res.get() != Args[Idx]) { 11138 Args[Idx] = Res.get(); 11139 } 11140 } 11141 if (VDecl->isInvalidDecl()) 11142 return; 11143 11144 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11145 /*TopLevelOfInitList=*/false, 11146 /*TreatUnavailableAsInvalid=*/false); 11147 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11148 if (Result.isInvalid()) { 11149 VDecl->setInvalidDecl(); 11150 return; 11151 } 11152 11153 Init = Result.getAs<Expr>(); 11154 } 11155 11156 // Check for self-references within variable initializers. 11157 // Variables declared within a function/method body (except for references) 11158 // are handled by a dataflow analysis. 11159 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11160 VDecl->getType()->isReferenceType()) { 11161 CheckSelfReference(*this, RealDecl, Init, DirectInit); 11162 } 11163 11164 // If the type changed, it means we had an incomplete type that was 11165 // completed by the initializer. For example: 11166 // int ary[] = { 1, 3, 5 }; 11167 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 11168 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 11169 VDecl->setType(DclT); 11170 11171 if (!VDecl->isInvalidDecl()) { 11172 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 11173 11174 if (VDecl->hasAttr<BlocksAttr>()) 11175 checkRetainCycles(VDecl, Init); 11176 11177 // It is safe to assign a weak reference into a strong variable. 11178 // Although this code can still have problems: 11179 // id x = self.weakProp; 11180 // id y = self.weakProp; 11181 // we do not warn to warn spuriously when 'x' and 'y' are on separate 11182 // paths through the function. This should be revisited if 11183 // -Wrepeated-use-of-weak is made flow-sensitive. 11184 if (FunctionScopeInfo *FSI = getCurFunction()) 11185 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 11186 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 11187 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 11188 Init->getBeginLoc())) 11189 FSI->markSafeWeakUse(Init); 11190 } 11191 11192 // The initialization is usually a full-expression. 11193 // 11194 // FIXME: If this is a braced initialization of an aggregate, it is not 11195 // an expression, and each individual field initializer is a separate 11196 // full-expression. For instance, in: 11197 // 11198 // struct Temp { ~Temp(); }; 11199 // struct S { S(Temp); }; 11200 // struct T { S a, b; } t = { Temp(), Temp() } 11201 // 11202 // we should destroy the first Temp before constructing the second. 11203 ExprResult Result = 11204 ActOnFinishFullExpr(Init, VDecl->getLocation(), 11205 /*DiscardedValue*/ false, VDecl->isConstexpr()); 11206 if (Result.isInvalid()) { 11207 VDecl->setInvalidDecl(); 11208 return; 11209 } 11210 Init = Result.get(); 11211 11212 // Attach the initializer to the decl. 11213 VDecl->setInit(Init); 11214 11215 if (VDecl->isLocalVarDecl()) { 11216 // Don't check the initializer if the declaration is malformed. 11217 if (VDecl->isInvalidDecl()) { 11218 // do nothing 11219 11220 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 11221 // This is true even in OpenCL C++. 11222 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 11223 CheckForConstantInitializer(Init, DclT); 11224 11225 // Otherwise, C++ does not restrict the initializer. 11226 } else if (getLangOpts().CPlusPlus) { 11227 // do nothing 11228 11229 // C99 6.7.8p4: All the expressions in an initializer for an object that has 11230 // static storage duration shall be constant expressions or string literals. 11231 } else if (VDecl->getStorageClass() == SC_Static) { 11232 CheckForConstantInitializer(Init, DclT); 11233 11234 // C89 is stricter than C99 for aggregate initializers. 11235 // C89 6.5.7p3: All the expressions [...] in an initializer list 11236 // for an object that has aggregate or union type shall be 11237 // constant expressions. 11238 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 11239 isa<InitListExpr>(Init)) { 11240 const Expr *Culprit; 11241 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 11242 Diag(Culprit->getExprLoc(), 11243 diag::ext_aggregate_init_not_constant) 11244 << Culprit->getSourceRange(); 11245 } 11246 } 11247 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 11248 VDecl->getLexicalDeclContext()->isRecord()) { 11249 // This is an in-class initialization for a static data member, e.g., 11250 // 11251 // struct S { 11252 // static const int value = 17; 11253 // }; 11254 11255 // C++ [class.mem]p4: 11256 // A member-declarator can contain a constant-initializer only 11257 // if it declares a static member (9.4) of const integral or 11258 // const enumeration type, see 9.4.2. 11259 // 11260 // C++11 [class.static.data]p3: 11261 // If a non-volatile non-inline const static data member is of integral 11262 // or enumeration type, its declaration in the class definition can 11263 // specify a brace-or-equal-initializer in which every initializer-clause 11264 // that is an assignment-expression is a constant expression. A static 11265 // data member of literal type can be declared in the class definition 11266 // with the constexpr specifier; if so, its declaration shall specify a 11267 // brace-or-equal-initializer in which every initializer-clause that is 11268 // an assignment-expression is a constant expression. 11269 11270 // Do nothing on dependent types. 11271 if (DclT->isDependentType()) { 11272 11273 // Allow any 'static constexpr' members, whether or not they are of literal 11274 // type. We separately check that every constexpr variable is of literal 11275 // type. 11276 } else if (VDecl->isConstexpr()) { 11277 11278 // Require constness. 11279 } else if (!DclT.isConstQualified()) { 11280 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 11281 << Init->getSourceRange(); 11282 VDecl->setInvalidDecl(); 11283 11284 // We allow integer constant expressions in all cases. 11285 } else if (DclT->isIntegralOrEnumerationType()) { 11286 // Check whether the expression is a constant expression. 11287 SourceLocation Loc; 11288 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 11289 // In C++11, a non-constexpr const static data member with an 11290 // in-class initializer cannot be volatile. 11291 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 11292 else if (Init->isValueDependent()) 11293 ; // Nothing to check. 11294 else if (Init->isIntegerConstantExpr(Context, &Loc)) 11295 ; // Ok, it's an ICE! 11296 else if (Init->getType()->isScopedEnumeralType() && 11297 Init->isCXX11ConstantExpr(Context)) 11298 ; // Ok, it is a scoped-enum constant expression. 11299 else if (Init->isEvaluatable(Context)) { 11300 // If we can constant fold the initializer through heroics, accept it, 11301 // but report this as a use of an extension for -pedantic. 11302 Diag(Loc, diag::ext_in_class_initializer_non_constant) 11303 << Init->getSourceRange(); 11304 } else { 11305 // Otherwise, this is some crazy unknown case. Report the issue at the 11306 // location provided by the isIntegerConstantExpr failed check. 11307 Diag(Loc, diag::err_in_class_initializer_non_constant) 11308 << Init->getSourceRange(); 11309 VDecl->setInvalidDecl(); 11310 } 11311 11312 // We allow foldable floating-point constants as an extension. 11313 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 11314 // In C++98, this is a GNU extension. In C++11, it is not, but we support 11315 // it anyway and provide a fixit to add the 'constexpr'. 11316 if (getLangOpts().CPlusPlus11) { 11317 Diag(VDecl->getLocation(), 11318 diag::ext_in_class_initializer_float_type_cxx11) 11319 << DclT << Init->getSourceRange(); 11320 Diag(VDecl->getBeginLoc(), 11321 diag::note_in_class_initializer_float_type_cxx11) 11322 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11323 } else { 11324 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 11325 << DclT << Init->getSourceRange(); 11326 11327 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 11328 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 11329 << Init->getSourceRange(); 11330 VDecl->setInvalidDecl(); 11331 } 11332 } 11333 11334 // Suggest adding 'constexpr' in C++11 for literal types. 11335 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 11336 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 11337 << DclT << Init->getSourceRange() 11338 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 11339 VDecl->setConstexpr(true); 11340 11341 } else { 11342 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 11343 << DclT << Init->getSourceRange(); 11344 VDecl->setInvalidDecl(); 11345 } 11346 } else if (VDecl->isFileVarDecl()) { 11347 // In C, extern is typically used to avoid tentative definitions when 11348 // declaring variables in headers, but adding an intializer makes it a 11349 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 11350 // In C++, extern is often used to give implictly static const variables 11351 // external linkage, so don't warn in that case. If selectany is present, 11352 // this might be header code intended for C and C++ inclusion, so apply the 11353 // C++ rules. 11354 if (VDecl->getStorageClass() == SC_Extern && 11355 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 11356 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 11357 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 11358 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 11359 Diag(VDecl->getLocation(), diag::warn_extern_init); 11360 11361 // C99 6.7.8p4. All file scoped initializers need to be constant. 11362 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 11363 CheckForConstantInitializer(Init, DclT); 11364 } 11365 11366 // We will represent direct-initialization similarly to copy-initialization: 11367 // int x(1); -as-> int x = 1; 11368 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 11369 // 11370 // Clients that want to distinguish between the two forms, can check for 11371 // direct initializer using VarDecl::getInitStyle(). 11372 // A major benefit is that clients that don't particularly care about which 11373 // exactly form was it (like the CodeGen) can handle both cases without 11374 // special case code. 11375 11376 // C++ 8.5p11: 11377 // The form of initialization (using parentheses or '=') is generally 11378 // insignificant, but does matter when the entity being initialized has a 11379 // class type. 11380 if (CXXDirectInit) { 11381 assert(DirectInit && "Call-style initializer must be direct init."); 11382 VDecl->setInitStyle(VarDecl::CallInit); 11383 } else if (DirectInit) { 11384 // This must be list-initialization. No other way is direct-initialization. 11385 VDecl->setInitStyle(VarDecl::ListInit); 11386 } 11387 11388 CheckCompleteVariableDeclaration(VDecl); 11389 } 11390 11391 /// ActOnInitializerError - Given that there was an error parsing an 11392 /// initializer for the given declaration, try to return to some form 11393 /// of sanity. 11394 void Sema::ActOnInitializerError(Decl *D) { 11395 // Our main concern here is re-establishing invariants like "a 11396 // variable's type is either dependent or complete". 11397 if (!D || D->isInvalidDecl()) return; 11398 11399 VarDecl *VD = dyn_cast<VarDecl>(D); 11400 if (!VD) return; 11401 11402 // Bindings are not usable if we can't make sense of the initializer. 11403 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11404 for (auto *BD : DD->bindings()) 11405 BD->setInvalidDecl(); 11406 11407 // Auto types are meaningless if we can't make sense of the initializer. 11408 if (ParsingInitForAutoVars.count(D)) { 11409 D->setInvalidDecl(); 11410 return; 11411 } 11412 11413 QualType Ty = VD->getType(); 11414 if (Ty->isDependentType()) return; 11415 11416 // Require a complete type. 11417 if (RequireCompleteType(VD->getLocation(), 11418 Context.getBaseElementType(Ty), 11419 diag::err_typecheck_decl_incomplete_type)) { 11420 VD->setInvalidDecl(); 11421 return; 11422 } 11423 11424 // Require a non-abstract type. 11425 if (RequireNonAbstractType(VD->getLocation(), Ty, 11426 diag::err_abstract_type_in_decl, 11427 AbstractVariableType)) { 11428 VD->setInvalidDecl(); 11429 return; 11430 } 11431 11432 // Don't bother complaining about constructors or destructors, 11433 // though. 11434 } 11435 11436 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11437 // If there is no declaration, there was an error parsing it. Just ignore it. 11438 if (!RealDecl) 11439 return; 11440 11441 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11442 QualType Type = Var->getType(); 11443 11444 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11445 if (isa<DecompositionDecl>(RealDecl)) { 11446 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11447 Var->setInvalidDecl(); 11448 return; 11449 } 11450 11451 Expr *TmpInit = nullptr; 11452 if (Type->isUndeducedType() && 11453 DeduceVariableDeclarationType(Var, false, TmpInit)) 11454 return; 11455 11456 // C++11 [class.static.data]p3: A static data member can be declared with 11457 // the constexpr specifier; if so, its declaration shall specify 11458 // a brace-or-equal-initializer. 11459 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11460 // the definition of a variable [...] or the declaration of a static data 11461 // member. 11462 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11463 !Var->isThisDeclarationADemotedDefinition()) { 11464 if (Var->isStaticDataMember()) { 11465 // C++1z removes the relevant rule; the in-class declaration is always 11466 // a definition there. 11467 if (!getLangOpts().CPlusPlus17) { 11468 Diag(Var->getLocation(), 11469 diag::err_constexpr_static_mem_var_requires_init) 11470 << Var->getDeclName(); 11471 Var->setInvalidDecl(); 11472 return; 11473 } 11474 } else { 11475 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11476 Var->setInvalidDecl(); 11477 return; 11478 } 11479 } 11480 11481 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11482 // be initialized. 11483 if (!Var->isInvalidDecl() && 11484 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11485 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11486 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11487 Var->setInvalidDecl(); 11488 return; 11489 } 11490 11491 switch (Var->isThisDeclarationADefinition()) { 11492 case VarDecl::Definition: 11493 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11494 break; 11495 11496 // We have an out-of-line definition of a static data member 11497 // that has an in-class initializer, so we type-check this like 11498 // a declaration. 11499 // 11500 LLVM_FALLTHROUGH; 11501 11502 case VarDecl::DeclarationOnly: 11503 // It's only a declaration. 11504 11505 // Block scope. C99 6.7p7: If an identifier for an object is 11506 // declared with no linkage (C99 6.2.2p6), the type for the 11507 // object shall be complete. 11508 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11509 !Var->hasLinkage() && !Var->isInvalidDecl() && 11510 RequireCompleteType(Var->getLocation(), Type, 11511 diag::err_typecheck_decl_incomplete_type)) 11512 Var->setInvalidDecl(); 11513 11514 // Make sure that the type is not abstract. 11515 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11516 RequireNonAbstractType(Var->getLocation(), Type, 11517 diag::err_abstract_type_in_decl, 11518 AbstractVariableType)) 11519 Var->setInvalidDecl(); 11520 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11521 Var->getStorageClass() == SC_PrivateExtern) { 11522 Diag(Var->getLocation(), diag::warn_private_extern); 11523 Diag(Var->getLocation(), diag::note_private_extern); 11524 } 11525 11526 return; 11527 11528 case VarDecl::TentativeDefinition: 11529 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11530 // object that has file scope without an initializer, and without a 11531 // storage-class specifier or with the storage-class specifier "static", 11532 // constitutes a tentative definition. Note: A tentative definition with 11533 // external linkage is valid (C99 6.2.2p5). 11534 if (!Var->isInvalidDecl()) { 11535 if (const IncompleteArrayType *ArrayT 11536 = Context.getAsIncompleteArrayType(Type)) { 11537 if (RequireCompleteType(Var->getLocation(), 11538 ArrayT->getElementType(), 11539 diag::err_illegal_decl_array_incomplete_type)) 11540 Var->setInvalidDecl(); 11541 } else if (Var->getStorageClass() == SC_Static) { 11542 // C99 6.9.2p3: If the declaration of an identifier for an object is 11543 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11544 // declared type shall not be an incomplete type. 11545 // NOTE: code such as the following 11546 // static struct s; 11547 // struct s { int a; }; 11548 // is accepted by gcc. Hence here we issue a warning instead of 11549 // an error and we do not invalidate the static declaration. 11550 // NOTE: to avoid multiple warnings, only check the first declaration. 11551 if (Var->isFirstDecl()) 11552 RequireCompleteType(Var->getLocation(), Type, 11553 diag::ext_typecheck_decl_incomplete_type); 11554 } 11555 } 11556 11557 // Record the tentative definition; we're done. 11558 if (!Var->isInvalidDecl()) 11559 TentativeDefinitions.push_back(Var); 11560 return; 11561 } 11562 11563 // Provide a specific diagnostic for uninitialized variable 11564 // definitions with incomplete array type. 11565 if (Type->isIncompleteArrayType()) { 11566 Diag(Var->getLocation(), 11567 diag::err_typecheck_incomplete_array_needs_initializer); 11568 Var->setInvalidDecl(); 11569 return; 11570 } 11571 11572 // Provide a specific diagnostic for uninitialized variable 11573 // definitions with reference type. 11574 if (Type->isReferenceType()) { 11575 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11576 << Var->getDeclName() 11577 << SourceRange(Var->getLocation(), Var->getLocation()); 11578 Var->setInvalidDecl(); 11579 return; 11580 } 11581 11582 // Do not attempt to type-check the default initializer for a 11583 // variable with dependent type. 11584 if (Type->isDependentType()) 11585 return; 11586 11587 if (Var->isInvalidDecl()) 11588 return; 11589 11590 if (!Var->hasAttr<AliasAttr>()) { 11591 if (RequireCompleteType(Var->getLocation(), 11592 Context.getBaseElementType(Type), 11593 diag::err_typecheck_decl_incomplete_type)) { 11594 Var->setInvalidDecl(); 11595 return; 11596 } 11597 } else { 11598 return; 11599 } 11600 11601 // The variable can not have an abstract class type. 11602 if (RequireNonAbstractType(Var->getLocation(), Type, 11603 diag::err_abstract_type_in_decl, 11604 AbstractVariableType)) { 11605 Var->setInvalidDecl(); 11606 return; 11607 } 11608 11609 // Check for jumps past the implicit initializer. C++0x 11610 // clarifies that this applies to a "variable with automatic 11611 // storage duration", not a "local variable". 11612 // C++11 [stmt.dcl]p3 11613 // A program that jumps from a point where a variable with automatic 11614 // storage duration is not in scope to a point where it is in scope is 11615 // ill-formed unless the variable has scalar type, class type with a 11616 // trivial default constructor and a trivial destructor, a cv-qualified 11617 // version of one of these types, or an array of one of the preceding 11618 // types and is declared without an initializer. 11619 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11620 if (const RecordType *Record 11621 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11622 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11623 // Mark the function (if we're in one) for further checking even if the 11624 // looser rules of C++11 do not require such checks, so that we can 11625 // diagnose incompatibilities with C++98. 11626 if (!CXXRecord->isPOD()) 11627 setFunctionHasBranchProtectedScope(); 11628 } 11629 } 11630 11631 // C++03 [dcl.init]p9: 11632 // If no initializer is specified for an object, and the 11633 // object is of (possibly cv-qualified) non-POD class type (or 11634 // array thereof), the object shall be default-initialized; if 11635 // the object is of const-qualified type, the underlying class 11636 // type shall have a user-declared default 11637 // constructor. Otherwise, if no initializer is specified for 11638 // a non- static object, the object and its subobjects, if 11639 // any, have an indeterminate initial value); if the object 11640 // or any of its subobjects are of const-qualified type, the 11641 // program is ill-formed. 11642 // C++0x [dcl.init]p11: 11643 // If no initializer is specified for an object, the object is 11644 // default-initialized; [...]. 11645 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11646 InitializationKind Kind 11647 = InitializationKind::CreateDefault(Var->getLocation()); 11648 11649 InitializationSequence InitSeq(*this, Entity, Kind, None); 11650 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11651 if (Init.isInvalid()) 11652 Var->setInvalidDecl(); 11653 else if (Init.get()) { 11654 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11655 // This is important for template substitution. 11656 Var->setInitStyle(VarDecl::CallInit); 11657 } 11658 11659 CheckCompleteVariableDeclaration(Var); 11660 } 11661 } 11662 11663 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11664 // If there is no declaration, there was an error parsing it. Ignore it. 11665 if (!D) 11666 return; 11667 11668 VarDecl *VD = dyn_cast<VarDecl>(D); 11669 if (!VD) { 11670 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11671 D->setInvalidDecl(); 11672 return; 11673 } 11674 11675 VD->setCXXForRangeDecl(true); 11676 11677 // for-range-declaration cannot be given a storage class specifier. 11678 int Error = -1; 11679 switch (VD->getStorageClass()) { 11680 case SC_None: 11681 break; 11682 case SC_Extern: 11683 Error = 0; 11684 break; 11685 case SC_Static: 11686 Error = 1; 11687 break; 11688 case SC_PrivateExtern: 11689 Error = 2; 11690 break; 11691 case SC_Auto: 11692 Error = 3; 11693 break; 11694 case SC_Register: 11695 Error = 4; 11696 break; 11697 } 11698 if (Error != -1) { 11699 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11700 << VD->getDeclName() << Error; 11701 D->setInvalidDecl(); 11702 } 11703 } 11704 11705 StmtResult 11706 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11707 IdentifierInfo *Ident, 11708 ParsedAttributes &Attrs, 11709 SourceLocation AttrEnd) { 11710 // C++1y [stmt.iter]p1: 11711 // A range-based for statement of the form 11712 // for ( for-range-identifier : for-range-initializer ) statement 11713 // is equivalent to 11714 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11715 DeclSpec DS(Attrs.getPool().getFactory()); 11716 11717 const char *PrevSpec; 11718 unsigned DiagID; 11719 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11720 getPrintingPolicy()); 11721 11722 Declarator D(DS, DeclaratorContext::ForContext); 11723 D.SetIdentifier(Ident, IdentLoc); 11724 D.takeAttributes(Attrs, AttrEnd); 11725 11726 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11727 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 11728 IdentLoc); 11729 Decl *Var = ActOnDeclarator(S, D); 11730 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11731 FinalizeDeclaration(Var); 11732 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11733 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11734 } 11735 11736 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11737 if (var->isInvalidDecl()) return; 11738 11739 if (getLangOpts().OpenCL) { 11740 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11741 // initialiser 11742 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11743 !var->hasInit()) { 11744 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11745 << 1 /*Init*/; 11746 var->setInvalidDecl(); 11747 return; 11748 } 11749 } 11750 11751 // In Objective-C, don't allow jumps past the implicit initialization of a 11752 // local retaining variable. 11753 if (getLangOpts().ObjC && 11754 var->hasLocalStorage()) { 11755 switch (var->getType().getObjCLifetime()) { 11756 case Qualifiers::OCL_None: 11757 case Qualifiers::OCL_ExplicitNone: 11758 case Qualifiers::OCL_Autoreleasing: 11759 break; 11760 11761 case Qualifiers::OCL_Weak: 11762 case Qualifiers::OCL_Strong: 11763 setFunctionHasBranchProtectedScope(); 11764 break; 11765 } 11766 } 11767 11768 if (var->hasLocalStorage() && 11769 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11770 setFunctionHasBranchProtectedScope(); 11771 11772 // Warn about externally-visible variables being defined without a 11773 // prior declaration. We only want to do this for global 11774 // declarations, but we also specifically need to avoid doing it for 11775 // class members because the linkage of an anonymous class can 11776 // change if it's later given a typedef name. 11777 if (var->isThisDeclarationADefinition() && 11778 var->getDeclContext()->getRedeclContext()->isFileContext() && 11779 var->isExternallyVisible() && var->hasLinkage() && 11780 !var->isInline() && !var->getDescribedVarTemplate() && 11781 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11782 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11783 var->getLocation())) { 11784 // Find a previous declaration that's not a definition. 11785 VarDecl *prev = var->getPreviousDecl(); 11786 while (prev && prev->isThisDeclarationADefinition()) 11787 prev = prev->getPreviousDecl(); 11788 11789 if (!prev) 11790 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11791 } 11792 11793 // Cache the result of checking for constant initialization. 11794 Optional<bool> CacheHasConstInit; 11795 const Expr *CacheCulprit; 11796 auto checkConstInit = [&]() mutable { 11797 if (!CacheHasConstInit) 11798 CacheHasConstInit = var->getInit()->isConstantInitializer( 11799 Context, var->getType()->isReferenceType(), &CacheCulprit); 11800 return *CacheHasConstInit; 11801 }; 11802 11803 if (var->getTLSKind() == VarDecl::TLS_Static) { 11804 if (var->getType().isDestructedType()) { 11805 // GNU C++98 edits for __thread, [basic.start.term]p3: 11806 // The type of an object with thread storage duration shall not 11807 // have a non-trivial destructor. 11808 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11809 if (getLangOpts().CPlusPlus11) 11810 Diag(var->getLocation(), diag::note_use_thread_local); 11811 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11812 if (!checkConstInit()) { 11813 // GNU C++98 edits for __thread, [basic.start.init]p4: 11814 // An object of thread storage duration shall not require dynamic 11815 // initialization. 11816 // FIXME: Need strict checking here. 11817 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11818 << CacheCulprit->getSourceRange(); 11819 if (getLangOpts().CPlusPlus11) 11820 Diag(var->getLocation(), diag::note_use_thread_local); 11821 } 11822 } 11823 } 11824 11825 // Apply section attributes and pragmas to global variables. 11826 bool GlobalStorage = var->hasGlobalStorage(); 11827 if (GlobalStorage && var->isThisDeclarationADefinition() && 11828 !inTemplateInstantiation()) { 11829 PragmaStack<StringLiteral *> *Stack = nullptr; 11830 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11831 if (var->getType().isConstQualified()) 11832 Stack = &ConstSegStack; 11833 else if (!var->getInit()) { 11834 Stack = &BSSSegStack; 11835 SectionFlags |= ASTContext::PSF_Write; 11836 } else { 11837 Stack = &DataSegStack; 11838 SectionFlags |= ASTContext::PSF_Write; 11839 } 11840 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11841 var->addAttr(SectionAttr::CreateImplicit( 11842 Context, SectionAttr::Declspec_allocate, 11843 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11844 } 11845 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11846 if (UnifySection(SA->getName(), SectionFlags, var)) 11847 var->dropAttr<SectionAttr>(); 11848 11849 // Apply the init_seg attribute if this has an initializer. If the 11850 // initializer turns out to not be dynamic, we'll end up ignoring this 11851 // attribute. 11852 if (CurInitSeg && var->getInit()) 11853 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11854 CurInitSegLoc)); 11855 } 11856 11857 // All the following checks are C++ only. 11858 if (!getLangOpts().CPlusPlus) { 11859 // If this variable must be emitted, add it as an initializer for the 11860 // current module. 11861 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11862 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11863 return; 11864 } 11865 11866 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11867 CheckCompleteDecompositionDeclaration(DD); 11868 11869 QualType type = var->getType(); 11870 if (type->isDependentType()) return; 11871 11872 if (var->hasAttr<BlocksAttr>()) 11873 getCurFunction()->addByrefBlockVar(var); 11874 11875 Expr *Init = var->getInit(); 11876 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11877 QualType baseType = Context.getBaseElementType(type); 11878 11879 if (Init && !Init->isValueDependent()) { 11880 if (var->isConstexpr()) { 11881 SmallVector<PartialDiagnosticAt, 8> Notes; 11882 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11883 SourceLocation DiagLoc = var->getLocation(); 11884 // If the note doesn't add any useful information other than a source 11885 // location, fold it into the primary diagnostic. 11886 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11887 diag::note_invalid_subexpr_in_const_expr) { 11888 DiagLoc = Notes[0].first; 11889 Notes.clear(); 11890 } 11891 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11892 << var << Init->getSourceRange(); 11893 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11894 Diag(Notes[I].first, Notes[I].second); 11895 } 11896 } else if (var->isUsableInConstantExpressions(Context)) { 11897 // Check whether the initializer of a const variable of integral or 11898 // enumeration type is an ICE now, since we can't tell whether it was 11899 // initialized by a constant expression if we check later. 11900 var->checkInitIsICE(); 11901 } 11902 11903 // Don't emit further diagnostics about constexpr globals since they 11904 // were just diagnosed. 11905 if (!var->isConstexpr() && GlobalStorage && 11906 var->hasAttr<RequireConstantInitAttr>()) { 11907 // FIXME: Need strict checking in C++03 here. 11908 bool DiagErr = getLangOpts().CPlusPlus11 11909 ? !var->checkInitIsICE() : !checkConstInit(); 11910 if (DiagErr) { 11911 auto attr = var->getAttr<RequireConstantInitAttr>(); 11912 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11913 << Init->getSourceRange(); 11914 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11915 << attr->getRange(); 11916 if (getLangOpts().CPlusPlus11) { 11917 APValue Value; 11918 SmallVector<PartialDiagnosticAt, 8> Notes; 11919 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11920 for (auto &it : Notes) 11921 Diag(it.first, it.second); 11922 } else { 11923 Diag(CacheCulprit->getExprLoc(), 11924 diag::note_invalid_subexpr_in_const_expr) 11925 << CacheCulprit->getSourceRange(); 11926 } 11927 } 11928 } 11929 else if (!var->isConstexpr() && IsGlobal && 11930 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11931 var->getLocation())) { 11932 // Warn about globals which don't have a constant initializer. Don't 11933 // warn about globals with a non-trivial destructor because we already 11934 // warned about them. 11935 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11936 if (!(RD && !RD->hasTrivialDestructor())) { 11937 if (!checkConstInit()) 11938 Diag(var->getLocation(), diag::warn_global_constructor) 11939 << Init->getSourceRange(); 11940 } 11941 } 11942 } 11943 11944 // Require the destructor. 11945 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11946 FinalizeVarWithDestructor(var, recordType); 11947 11948 // If this variable must be emitted, add it as an initializer for the current 11949 // module. 11950 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11951 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11952 } 11953 11954 /// Determines if a variable's alignment is dependent. 11955 static bool hasDependentAlignment(VarDecl *VD) { 11956 if (VD->getType()->isDependentType()) 11957 return true; 11958 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11959 if (I->isAlignmentDependent()) 11960 return true; 11961 return false; 11962 } 11963 11964 /// Check if VD needs to be dllexport/dllimport due to being in a 11965 /// dllexport/import function. 11966 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 11967 assert(VD->isStaticLocal()); 11968 11969 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11970 11971 // Find outermost function when VD is in lambda function. 11972 while (FD && !getDLLAttr(FD) && 11973 !FD->hasAttr<DLLExportStaticLocalAttr>() && 11974 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 11975 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 11976 } 11977 11978 if (!FD) 11979 return; 11980 11981 // Static locals inherit dll attributes from their function. 11982 if (Attr *A = getDLLAttr(FD)) { 11983 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11984 NewAttr->setInherited(true); 11985 VD->addAttr(NewAttr); 11986 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 11987 auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(), 11988 getASTContext(), 11989 A->getSpellingListIndex()); 11990 NewAttr->setInherited(true); 11991 VD->addAttr(NewAttr); 11992 11993 // Export this function to enforce exporting this static variable even 11994 // if it is not used in this compilation unit. 11995 if (!FD->hasAttr<DLLExportAttr>()) 11996 FD->addAttr(NewAttr); 11997 11998 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 11999 auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(), 12000 getASTContext(), 12001 A->getSpellingListIndex()); 12002 NewAttr->setInherited(true); 12003 VD->addAttr(NewAttr); 12004 } 12005 } 12006 12007 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12008 /// any semantic actions necessary after any initializer has been attached. 12009 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12010 // Note that we are no longer parsing the initializer for this declaration. 12011 ParsingInitForAutoVars.erase(ThisDecl); 12012 12013 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12014 if (!VD) 12015 return; 12016 12017 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12018 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12019 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12020 if (PragmaClangBSSSection.Valid) 12021 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 12022 PragmaClangBSSSection.SectionName, 12023 PragmaClangBSSSection.PragmaLocation)); 12024 if (PragmaClangDataSection.Valid) 12025 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 12026 PragmaClangDataSection.SectionName, 12027 PragmaClangDataSection.PragmaLocation)); 12028 if (PragmaClangRodataSection.Valid) 12029 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 12030 PragmaClangRodataSection.SectionName, 12031 PragmaClangRodataSection.PragmaLocation)); 12032 } 12033 12034 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12035 for (auto *BD : DD->bindings()) { 12036 FinalizeDeclaration(BD); 12037 } 12038 } 12039 12040 checkAttributesAfterMerging(*this, *VD); 12041 12042 // Perform TLS alignment check here after attributes attached to the variable 12043 // which may affect the alignment have been processed. Only perform the check 12044 // if the target has a maximum TLS alignment (zero means no constraints). 12045 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12046 // Protect the check so that it's not performed on dependent types and 12047 // dependent alignments (we can't determine the alignment in that case). 12048 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12049 !VD->isInvalidDecl()) { 12050 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12051 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12052 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12053 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12054 << (unsigned)MaxAlignChars.getQuantity(); 12055 } 12056 } 12057 } 12058 12059 if (VD->isStaticLocal()) { 12060 CheckStaticLocalForDllExport(VD); 12061 12062 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12063 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12064 // function, only __shared__ variables or variables without any device 12065 // memory qualifiers may be declared with static storage class. 12066 // Note: It is unclear how a function-scope non-const static variable 12067 // without device memory qualifier is implemented, therefore only static 12068 // const variable without device memory qualifier is allowed. 12069 [&]() { 12070 if (!getLangOpts().CUDA) 12071 return; 12072 if (VD->hasAttr<CUDASharedAttr>()) 12073 return; 12074 if (VD->getType().isConstQualified() && 12075 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12076 return; 12077 if (CUDADiagIfDeviceCode(VD->getLocation(), 12078 diag::err_device_static_local_var) 12079 << CurrentCUDATarget()) 12080 VD->setInvalidDecl(); 12081 }(); 12082 } 12083 } 12084 12085 // Perform check for initializers of device-side global variables. 12086 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12087 // 7.5). We must also apply the same checks to all __shared__ 12088 // variables whether they are local or not. CUDA also allows 12089 // constant initializers for __constant__ and __device__ variables. 12090 if (getLangOpts().CUDA) 12091 checkAllowedCUDAInitializer(VD); 12092 12093 // Grab the dllimport or dllexport attribute off of the VarDecl. 12094 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12095 12096 // Imported static data members cannot be defined out-of-line. 12097 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12098 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12099 VD->isThisDeclarationADefinition()) { 12100 // We allow definitions of dllimport class template static data members 12101 // with a warning. 12102 CXXRecordDecl *Context = 12103 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12104 bool IsClassTemplateMember = 12105 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12106 Context->getDescribedClassTemplate(); 12107 12108 Diag(VD->getLocation(), 12109 IsClassTemplateMember 12110 ? diag::warn_attribute_dllimport_static_field_definition 12111 : diag::err_attribute_dllimport_static_field_definition); 12112 Diag(IA->getLocation(), diag::note_attribute); 12113 if (!IsClassTemplateMember) 12114 VD->setInvalidDecl(); 12115 } 12116 } 12117 12118 // dllimport/dllexport variables cannot be thread local, their TLS index 12119 // isn't exported with the variable. 12120 if (DLLAttr && VD->getTLSKind()) { 12121 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12122 if (F && getDLLAttr(F)) { 12123 assert(VD->isStaticLocal()); 12124 // But if this is a static local in a dlimport/dllexport function, the 12125 // function will never be inlined, which means the var would never be 12126 // imported, so having it marked import/export is safe. 12127 } else { 12128 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 12129 << DLLAttr; 12130 VD->setInvalidDecl(); 12131 } 12132 } 12133 12134 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 12135 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 12136 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 12137 VD->dropAttr<UsedAttr>(); 12138 } 12139 } 12140 12141 const DeclContext *DC = VD->getDeclContext(); 12142 // If there's a #pragma GCC visibility in scope, and this isn't a class 12143 // member, set the visibility of this variable. 12144 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 12145 AddPushedVisibilityAttribute(VD); 12146 12147 // FIXME: Warn on unused var template partial specializations. 12148 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 12149 MarkUnusedFileScopedDecl(VD); 12150 12151 // Now we have parsed the initializer and can update the table of magic 12152 // tag values. 12153 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 12154 !VD->getType()->isIntegralOrEnumerationType()) 12155 return; 12156 12157 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 12158 const Expr *MagicValueExpr = VD->getInit(); 12159 if (!MagicValueExpr) { 12160 continue; 12161 } 12162 llvm::APSInt MagicValueInt; 12163 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 12164 Diag(I->getRange().getBegin(), 12165 diag::err_type_tag_for_datatype_not_ice) 12166 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12167 continue; 12168 } 12169 if (MagicValueInt.getActiveBits() > 64) { 12170 Diag(I->getRange().getBegin(), 12171 diag::err_type_tag_for_datatype_too_large) 12172 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 12173 continue; 12174 } 12175 uint64_t MagicValue = MagicValueInt.getZExtValue(); 12176 RegisterTypeTagForDatatype(I->getArgumentKind(), 12177 MagicValue, 12178 I->getMatchingCType(), 12179 I->getLayoutCompatible(), 12180 I->getMustBeNull()); 12181 } 12182 } 12183 12184 static bool hasDeducedAuto(DeclaratorDecl *DD) { 12185 auto *VD = dyn_cast<VarDecl>(DD); 12186 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 12187 } 12188 12189 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 12190 ArrayRef<Decl *> Group) { 12191 SmallVector<Decl*, 8> Decls; 12192 12193 if (DS.isTypeSpecOwned()) 12194 Decls.push_back(DS.getRepAsDecl()); 12195 12196 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 12197 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 12198 bool DiagnosedMultipleDecomps = false; 12199 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 12200 bool DiagnosedNonDeducedAuto = false; 12201 12202 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12203 if (Decl *D = Group[i]) { 12204 // For declarators, there are some additional syntactic-ish checks we need 12205 // to perform. 12206 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 12207 if (!FirstDeclaratorInGroup) 12208 FirstDeclaratorInGroup = DD; 12209 if (!FirstDecompDeclaratorInGroup) 12210 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 12211 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 12212 !hasDeducedAuto(DD)) 12213 FirstNonDeducedAutoInGroup = DD; 12214 12215 if (FirstDeclaratorInGroup != DD) { 12216 // A decomposition declaration cannot be combined with any other 12217 // declaration in the same group. 12218 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 12219 Diag(FirstDecompDeclaratorInGroup->getLocation(), 12220 diag::err_decomp_decl_not_alone) 12221 << FirstDeclaratorInGroup->getSourceRange() 12222 << DD->getSourceRange(); 12223 DiagnosedMultipleDecomps = true; 12224 } 12225 12226 // A declarator that uses 'auto' in any way other than to declare a 12227 // variable with a deduced type cannot be combined with any other 12228 // declarator in the same group. 12229 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 12230 Diag(FirstNonDeducedAutoInGroup->getLocation(), 12231 diag::err_auto_non_deduced_not_alone) 12232 << FirstNonDeducedAutoInGroup->getType() 12233 ->hasAutoForTrailingReturnType() 12234 << FirstDeclaratorInGroup->getSourceRange() 12235 << DD->getSourceRange(); 12236 DiagnosedNonDeducedAuto = true; 12237 } 12238 } 12239 } 12240 12241 Decls.push_back(D); 12242 } 12243 } 12244 12245 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 12246 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 12247 handleTagNumbering(Tag, S); 12248 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 12249 getLangOpts().CPlusPlus) 12250 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 12251 } 12252 } 12253 12254 return BuildDeclaratorGroup(Decls); 12255 } 12256 12257 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 12258 /// group, performing any necessary semantic checking. 12259 Sema::DeclGroupPtrTy 12260 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 12261 // C++14 [dcl.spec.auto]p7: (DR1347) 12262 // If the type that replaces the placeholder type is not the same in each 12263 // deduction, the program is ill-formed. 12264 if (Group.size() > 1) { 12265 QualType Deduced; 12266 VarDecl *DeducedDecl = nullptr; 12267 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 12268 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 12269 if (!D || D->isInvalidDecl()) 12270 break; 12271 DeducedType *DT = D->getType()->getContainedDeducedType(); 12272 if (!DT || DT->getDeducedType().isNull()) 12273 continue; 12274 if (Deduced.isNull()) { 12275 Deduced = DT->getDeducedType(); 12276 DeducedDecl = D; 12277 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 12278 auto *AT = dyn_cast<AutoType>(DT); 12279 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 12280 diag::err_auto_different_deductions) 12281 << (AT ? (unsigned)AT->getKeyword() : 3) 12282 << Deduced << DeducedDecl->getDeclName() 12283 << DT->getDeducedType() << D->getDeclName() 12284 << DeducedDecl->getInit()->getSourceRange() 12285 << D->getInit()->getSourceRange(); 12286 D->setInvalidDecl(); 12287 break; 12288 } 12289 } 12290 } 12291 12292 ActOnDocumentableDecls(Group); 12293 12294 return DeclGroupPtrTy::make( 12295 DeclGroupRef::Create(Context, Group.data(), Group.size())); 12296 } 12297 12298 void Sema::ActOnDocumentableDecl(Decl *D) { 12299 ActOnDocumentableDecls(D); 12300 } 12301 12302 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 12303 // Don't parse the comment if Doxygen diagnostics are ignored. 12304 if (Group.empty() || !Group[0]) 12305 return; 12306 12307 if (Diags.isIgnored(diag::warn_doc_param_not_found, 12308 Group[0]->getLocation()) && 12309 Diags.isIgnored(diag::warn_unknown_comment_command_name, 12310 Group[0]->getLocation())) 12311 return; 12312 12313 if (Group.size() >= 2) { 12314 // This is a decl group. Normally it will contain only declarations 12315 // produced from declarator list. But in case we have any definitions or 12316 // additional declaration references: 12317 // 'typedef struct S {} S;' 12318 // 'typedef struct S *S;' 12319 // 'struct S *pS;' 12320 // FinalizeDeclaratorGroup adds these as separate declarations. 12321 Decl *MaybeTagDecl = Group[0]; 12322 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 12323 Group = Group.slice(1); 12324 } 12325 } 12326 12327 // See if there are any new comments that are not attached to a decl. 12328 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 12329 if (!Comments.empty() && 12330 !Comments.back()->isAttached()) { 12331 // There is at least one comment that not attached to a decl. 12332 // Maybe it should be attached to one of these decls? 12333 // 12334 // Note that this way we pick up not only comments that precede the 12335 // declaration, but also comments that *follow* the declaration -- thanks to 12336 // the lookahead in the lexer: we've consumed the semicolon and looked 12337 // ahead through comments. 12338 for (unsigned i = 0, e = Group.size(); i != e; ++i) 12339 Context.getCommentForDecl(Group[i], &PP); 12340 } 12341 } 12342 12343 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 12344 /// to introduce parameters into function prototype scope. 12345 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 12346 const DeclSpec &DS = D.getDeclSpec(); 12347 12348 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 12349 12350 // C++03 [dcl.stc]p2 also permits 'auto'. 12351 StorageClass SC = SC_None; 12352 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 12353 SC = SC_Register; 12354 // In C++11, the 'register' storage class specifier is deprecated. 12355 // In C++17, it is not allowed, but we tolerate it as an extension. 12356 if (getLangOpts().CPlusPlus11) { 12357 Diag(DS.getStorageClassSpecLoc(), 12358 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 12359 : diag::warn_deprecated_register) 12360 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12361 } 12362 } else if (getLangOpts().CPlusPlus && 12363 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 12364 SC = SC_Auto; 12365 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 12366 Diag(DS.getStorageClassSpecLoc(), 12367 diag::err_invalid_storage_class_in_func_decl); 12368 D.getMutableDeclSpec().ClearStorageClassSpecs(); 12369 } 12370 12371 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12372 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12373 << DeclSpec::getSpecifierName(TSCS); 12374 if (DS.isInlineSpecified()) 12375 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12376 << getLangOpts().CPlusPlus17; 12377 if (DS.isConstexprSpecified()) 12378 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12379 << 0; 12380 12381 DiagnoseFunctionSpecifiers(DS); 12382 12383 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12384 QualType parmDeclType = TInfo->getType(); 12385 12386 if (getLangOpts().CPlusPlus) { 12387 // Check that there are no default arguments inside the type of this 12388 // parameter. 12389 CheckExtraCXXDefaultArguments(D); 12390 12391 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12392 if (D.getCXXScopeSpec().isSet()) { 12393 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12394 << D.getCXXScopeSpec().getRange(); 12395 D.getCXXScopeSpec().clear(); 12396 } 12397 } 12398 12399 // Ensure we have a valid name 12400 IdentifierInfo *II = nullptr; 12401 if (D.hasName()) { 12402 II = D.getIdentifier(); 12403 if (!II) { 12404 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12405 << GetNameForDeclarator(D).getName(); 12406 D.setInvalidType(true); 12407 } 12408 } 12409 12410 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12411 if (II) { 12412 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12413 ForVisibleRedeclaration); 12414 LookupName(R, S); 12415 if (R.isSingleResult()) { 12416 NamedDecl *PrevDecl = R.getFoundDecl(); 12417 if (PrevDecl->isTemplateParameter()) { 12418 // Maybe we will complain about the shadowed template parameter. 12419 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12420 // Just pretend that we didn't see the previous declaration. 12421 PrevDecl = nullptr; 12422 } else if (S->isDeclScope(PrevDecl)) { 12423 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12424 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12425 12426 // Recover by removing the name 12427 II = nullptr; 12428 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12429 D.setInvalidType(true); 12430 } 12431 } 12432 } 12433 12434 // Temporarily put parameter variables in the translation unit, not 12435 // the enclosing context. This prevents them from accidentally 12436 // looking like class members in C++. 12437 ParmVarDecl *New = 12438 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 12439 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 12440 12441 if (D.isInvalidType()) 12442 New->setInvalidDecl(); 12443 12444 assert(S->isFunctionPrototypeScope()); 12445 assert(S->getFunctionPrototypeDepth() >= 1); 12446 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12447 S->getNextFunctionPrototypeIndex()); 12448 12449 // Add the parameter declaration into this scope. 12450 S->AddDecl(New); 12451 if (II) 12452 IdResolver.AddDecl(New); 12453 12454 ProcessDeclAttributes(S, New, D); 12455 12456 if (D.getDeclSpec().isModulePrivateSpecified()) 12457 Diag(New->getLocation(), diag::err_module_private_local) 12458 << 1 << New->getDeclName() 12459 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12460 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12461 12462 if (New->hasAttr<BlocksAttr>()) { 12463 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12464 } 12465 return New; 12466 } 12467 12468 /// Synthesizes a variable for a parameter arising from a 12469 /// typedef. 12470 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12471 SourceLocation Loc, 12472 QualType T) { 12473 /* FIXME: setting StartLoc == Loc. 12474 Would it be worth to modify callers so as to provide proper source 12475 location for the unnamed parameters, embedding the parameter's type? */ 12476 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12477 T, Context.getTrivialTypeSourceInfo(T, Loc), 12478 SC_None, nullptr); 12479 Param->setImplicit(); 12480 return Param; 12481 } 12482 12483 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12484 // Don't diagnose unused-parameter errors in template instantiations; we 12485 // will already have done so in the template itself. 12486 if (inTemplateInstantiation()) 12487 return; 12488 12489 for (const ParmVarDecl *Parameter : Parameters) { 12490 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12491 !Parameter->hasAttr<UnusedAttr>()) { 12492 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12493 << Parameter->getDeclName(); 12494 } 12495 } 12496 } 12497 12498 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12499 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12500 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12501 return; 12502 12503 // Warn if the return value is pass-by-value and larger than the specified 12504 // threshold. 12505 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12506 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12507 if (Size > LangOpts.NumLargeByValueCopy) 12508 Diag(D->getLocation(), diag::warn_return_value_size) 12509 << D->getDeclName() << Size; 12510 } 12511 12512 // Warn if any parameter is pass-by-value and larger than the specified 12513 // threshold. 12514 for (const ParmVarDecl *Parameter : Parameters) { 12515 QualType T = Parameter->getType(); 12516 if (T->isDependentType() || !T.isPODType(Context)) 12517 continue; 12518 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12519 if (Size > LangOpts.NumLargeByValueCopy) 12520 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12521 << Parameter->getDeclName() << Size; 12522 } 12523 } 12524 12525 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12526 SourceLocation NameLoc, IdentifierInfo *Name, 12527 QualType T, TypeSourceInfo *TSInfo, 12528 StorageClass SC) { 12529 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12530 if (getLangOpts().ObjCAutoRefCount && 12531 T.getObjCLifetime() == Qualifiers::OCL_None && 12532 T->isObjCLifetimeType()) { 12533 12534 Qualifiers::ObjCLifetime lifetime; 12535 12536 // Special cases for arrays: 12537 // - if it's const, use __unsafe_unretained 12538 // - otherwise, it's an error 12539 if (T->isArrayType()) { 12540 if (!T.isConstQualified()) { 12541 DelayedDiagnostics.add( 12542 sema::DelayedDiagnostic::makeForbiddenType( 12543 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12544 } 12545 lifetime = Qualifiers::OCL_ExplicitNone; 12546 } else { 12547 lifetime = T->getObjCARCImplicitLifetime(); 12548 } 12549 T = Context.getLifetimeQualifiedType(T, lifetime); 12550 } 12551 12552 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12553 Context.getAdjustedParameterType(T), 12554 TSInfo, SC, nullptr); 12555 12556 // Parameters can not be abstract class types. 12557 // For record types, this is done by the AbstractClassUsageDiagnoser once 12558 // the class has been completely parsed. 12559 if (!CurContext->isRecord() && 12560 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12561 AbstractParamType)) 12562 New->setInvalidDecl(); 12563 12564 // Parameter declarators cannot be interface types. All ObjC objects are 12565 // passed by reference. 12566 if (T->isObjCObjectType()) { 12567 SourceLocation TypeEndLoc = 12568 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 12569 Diag(NameLoc, 12570 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12571 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12572 T = Context.getObjCObjectPointerType(T); 12573 New->setType(T); 12574 } 12575 12576 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12577 // duration shall not be qualified by an address-space qualifier." 12578 // Since all parameters have automatic store duration, they can not have 12579 // an address space. 12580 if (T.getAddressSpace() != LangAS::Default && 12581 // OpenCL allows function arguments declared to be an array of a type 12582 // to be qualified with an address space. 12583 !(getLangOpts().OpenCL && 12584 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12585 Diag(NameLoc, diag::err_arg_with_address_space); 12586 New->setInvalidDecl(); 12587 } 12588 12589 return New; 12590 } 12591 12592 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12593 SourceLocation LocAfterDecls) { 12594 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12595 12596 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12597 // for a K&R function. 12598 if (!FTI.hasPrototype) { 12599 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12600 --i; 12601 if (FTI.Params[i].Param == nullptr) { 12602 SmallString<256> Code; 12603 llvm::raw_svector_ostream(Code) 12604 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12605 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12606 << FTI.Params[i].Ident 12607 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12608 12609 // Implicitly declare the argument as type 'int' for lack of a better 12610 // type. 12611 AttributeFactory attrs; 12612 DeclSpec DS(attrs); 12613 const char* PrevSpec; // unused 12614 unsigned DiagID; // unused 12615 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12616 DiagID, Context.getPrintingPolicy()); 12617 // Use the identifier location for the type source range. 12618 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12619 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12620 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12621 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12622 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12623 } 12624 } 12625 } 12626 } 12627 12628 Decl * 12629 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12630 MultiTemplateParamsArg TemplateParameterLists, 12631 SkipBodyInfo *SkipBody) { 12632 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12633 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12634 Scope *ParentScope = FnBodyScope->getParent(); 12635 12636 D.setFunctionDefinitionKind(FDK_Definition); 12637 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12638 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12639 } 12640 12641 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12642 Consumer.HandleInlineFunctionDefinition(D); 12643 } 12644 12645 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12646 const FunctionDecl*& PossibleZeroParamPrototype) { 12647 // Don't warn about invalid declarations. 12648 if (FD->isInvalidDecl()) 12649 return false; 12650 12651 // Or declarations that aren't global. 12652 if (!FD->isGlobal()) 12653 return false; 12654 12655 // Don't warn about C++ member functions. 12656 if (isa<CXXMethodDecl>(FD)) 12657 return false; 12658 12659 // Don't warn about 'main'. 12660 if (FD->isMain()) 12661 return false; 12662 12663 // Don't warn about inline functions. 12664 if (FD->isInlined()) 12665 return false; 12666 12667 // Don't warn about function templates. 12668 if (FD->getDescribedFunctionTemplate()) 12669 return false; 12670 12671 // Don't warn about function template specializations. 12672 if (FD->isFunctionTemplateSpecialization()) 12673 return false; 12674 12675 // Don't warn for OpenCL kernels. 12676 if (FD->hasAttr<OpenCLKernelAttr>()) 12677 return false; 12678 12679 // Don't warn on explicitly deleted functions. 12680 if (FD->isDeleted()) 12681 return false; 12682 12683 bool MissingPrototype = true; 12684 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12685 Prev; Prev = Prev->getPreviousDecl()) { 12686 // Ignore any declarations that occur in function or method 12687 // scope, because they aren't visible from the header. 12688 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12689 continue; 12690 12691 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12692 if (FD->getNumParams() == 0) 12693 PossibleZeroParamPrototype = Prev; 12694 break; 12695 } 12696 12697 return MissingPrototype; 12698 } 12699 12700 void 12701 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12702 const FunctionDecl *EffectiveDefinition, 12703 SkipBodyInfo *SkipBody) { 12704 const FunctionDecl *Definition = EffectiveDefinition; 12705 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12706 // If this is a friend function defined in a class template, it does not 12707 // have a body until it is used, nevertheless it is a definition, see 12708 // [temp.inst]p2: 12709 // 12710 // ... for the purpose of determining whether an instantiated redeclaration 12711 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12712 // corresponds to a definition in the template is considered to be a 12713 // definition. 12714 // 12715 // The following code must produce redefinition error: 12716 // 12717 // template<typename T> struct C20 { friend void func_20() {} }; 12718 // C20<int> c20i; 12719 // void func_20() {} 12720 // 12721 for (auto I : FD->redecls()) { 12722 if (I != FD && !I->isInvalidDecl() && 12723 I->getFriendObjectKind() != Decl::FOK_None) { 12724 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12725 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12726 // A merged copy of the same function, instantiated as a member of 12727 // the same class, is OK. 12728 if (declaresSameEntity(OrigFD, Original) && 12729 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12730 cast<Decl>(FD->getLexicalDeclContext()))) 12731 continue; 12732 } 12733 12734 if (Original->isThisDeclarationADefinition()) { 12735 Definition = I; 12736 break; 12737 } 12738 } 12739 } 12740 } 12741 } 12742 12743 if (!Definition) 12744 // Similar to friend functions a friend function template may be a 12745 // definition and do not have a body if it is instantiated in a class 12746 // template. 12747 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 12748 for (auto I : FTD->redecls()) { 12749 auto D = cast<FunctionTemplateDecl>(I); 12750 if (D != FTD) { 12751 assert(!D->isThisDeclarationADefinition() && 12752 "More than one definition in redeclaration chain"); 12753 if (D->getFriendObjectKind() != Decl::FOK_None) 12754 if (FunctionTemplateDecl *FT = 12755 D->getInstantiatedFromMemberTemplate()) { 12756 if (FT->isThisDeclarationADefinition()) { 12757 Definition = D->getTemplatedDecl(); 12758 break; 12759 } 12760 } 12761 } 12762 } 12763 } 12764 12765 if (!Definition) 12766 return; 12767 12768 if (canRedefineFunction(Definition, getLangOpts())) 12769 return; 12770 12771 // Don't emit an error when this is redefinition of a typo-corrected 12772 // definition. 12773 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12774 return; 12775 12776 // If we don't have a visible definition of the function, and it's inline or 12777 // a template, skip the new definition. 12778 if (SkipBody && !hasVisibleDefinition(Definition) && 12779 (Definition->getFormalLinkage() == InternalLinkage || 12780 Definition->isInlined() || 12781 Definition->getDescribedFunctionTemplate() || 12782 Definition->getNumTemplateParameterLists())) { 12783 SkipBody->ShouldSkip = true; 12784 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 12785 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12786 makeMergedDefinitionVisible(TD); 12787 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12788 return; 12789 } 12790 12791 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12792 Definition->getStorageClass() == SC_Extern) 12793 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12794 << FD->getDeclName() << getLangOpts().CPlusPlus; 12795 else 12796 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12797 12798 Diag(Definition->getLocation(), diag::note_previous_definition); 12799 FD->setInvalidDecl(); 12800 } 12801 12802 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12803 Sema &S) { 12804 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12805 12806 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12807 LSI->CallOperator = CallOperator; 12808 LSI->Lambda = LambdaClass; 12809 LSI->ReturnType = CallOperator->getReturnType(); 12810 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12811 12812 if (LCD == LCD_None) 12813 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12814 else if (LCD == LCD_ByCopy) 12815 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12816 else if (LCD == LCD_ByRef) 12817 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12818 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12819 12820 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12821 LSI->Mutable = !CallOperator->isConst(); 12822 12823 // Add the captures to the LSI so they can be noted as already 12824 // captured within tryCaptureVar. 12825 auto I = LambdaClass->field_begin(); 12826 for (const auto &C : LambdaClass->captures()) { 12827 if (C.capturesVariable()) { 12828 VarDecl *VD = C.getCapturedVar(); 12829 if (VD->isInitCapture()) 12830 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12831 QualType CaptureType = VD->getType(); 12832 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12833 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12834 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12835 /*EllipsisLoc*/C.isPackExpansion() 12836 ? C.getEllipsisLoc() : SourceLocation(), 12837 CaptureType, /*Expr*/ nullptr); 12838 12839 } else if (C.capturesThis()) { 12840 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12841 /*Expr*/ nullptr, 12842 C.getCaptureKind() == LCK_StarThis); 12843 } else { 12844 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12845 } 12846 ++I; 12847 } 12848 } 12849 12850 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12851 SkipBodyInfo *SkipBody) { 12852 if (!D) { 12853 // Parsing the function declaration failed in some way. Push on a fake scope 12854 // anyway so we can try to parse the function body. 12855 PushFunctionScope(); 12856 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12857 return D; 12858 } 12859 12860 FunctionDecl *FD = nullptr; 12861 12862 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12863 FD = FunTmpl->getTemplatedDecl(); 12864 else 12865 FD = cast<FunctionDecl>(D); 12866 12867 // Do not push if it is a lambda because one is already pushed when building 12868 // the lambda in ActOnStartOfLambdaDefinition(). 12869 if (!isLambdaCallOperator(FD)) 12870 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 12871 12872 // Check for defining attributes before the check for redefinition. 12873 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12874 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12875 FD->dropAttr<AliasAttr>(); 12876 FD->setInvalidDecl(); 12877 } 12878 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12879 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12880 FD->dropAttr<IFuncAttr>(); 12881 FD->setInvalidDecl(); 12882 } 12883 12884 // See if this is a redefinition. If 'will have body' is already set, then 12885 // these checks were already performed when it was set. 12886 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12887 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12888 12889 // If we're skipping the body, we're done. Don't enter the scope. 12890 if (SkipBody && SkipBody->ShouldSkip) 12891 return D; 12892 } 12893 12894 // Mark this function as "will have a body eventually". This lets users to 12895 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12896 // this function. 12897 FD->setWillHaveBody(); 12898 12899 // If we are instantiating a generic lambda call operator, push 12900 // a LambdaScopeInfo onto the function stack. But use the information 12901 // that's already been calculated (ActOnLambdaExpr) to prime the current 12902 // LambdaScopeInfo. 12903 // When the template operator is being specialized, the LambdaScopeInfo, 12904 // has to be properly restored so that tryCaptureVariable doesn't try 12905 // and capture any new variables. In addition when calculating potential 12906 // captures during transformation of nested lambdas, it is necessary to 12907 // have the LSI properly restored. 12908 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12909 assert(inTemplateInstantiation() && 12910 "There should be an active template instantiation on the stack " 12911 "when instantiating a generic lambda!"); 12912 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12913 } else { 12914 // Enter a new function scope 12915 PushFunctionScope(); 12916 } 12917 12918 // Builtin functions cannot be defined. 12919 if (unsigned BuiltinID = FD->getBuiltinID()) { 12920 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12921 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12922 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12923 FD->setInvalidDecl(); 12924 } 12925 } 12926 12927 // The return type of a function definition must be complete 12928 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12929 QualType ResultType = FD->getReturnType(); 12930 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12931 !FD->isInvalidDecl() && 12932 RequireCompleteType(FD->getLocation(), ResultType, 12933 diag::err_func_def_incomplete_result)) 12934 FD->setInvalidDecl(); 12935 12936 if (FnBodyScope) 12937 PushDeclContext(FnBodyScope, FD); 12938 12939 // Check the validity of our function parameters 12940 CheckParmsForFunctionDef(FD->parameters(), 12941 /*CheckParameterNames=*/true); 12942 12943 // Add non-parameter declarations already in the function to the current 12944 // scope. 12945 if (FnBodyScope) { 12946 for (Decl *NPD : FD->decls()) { 12947 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12948 if (!NonParmDecl) 12949 continue; 12950 assert(!isa<ParmVarDecl>(NonParmDecl) && 12951 "parameters should not be in newly created FD yet"); 12952 12953 // If the decl has a name, make it accessible in the current scope. 12954 if (NonParmDecl->getDeclName()) 12955 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12956 12957 // Similarly, dive into enums and fish their constants out, making them 12958 // accessible in this scope. 12959 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12960 for (auto *EI : ED->enumerators()) 12961 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12962 } 12963 } 12964 } 12965 12966 // Introduce our parameters into the function scope 12967 for (auto Param : FD->parameters()) { 12968 Param->setOwningFunction(FD); 12969 12970 // If this has an identifier, add it to the scope stack. 12971 if (Param->getIdentifier() && FnBodyScope) { 12972 CheckShadow(FnBodyScope, Param); 12973 12974 PushOnScopeChains(Param, FnBodyScope); 12975 } 12976 } 12977 12978 // Ensure that the function's exception specification is instantiated. 12979 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12980 ResolveExceptionSpec(D->getLocation(), FPT); 12981 12982 // dllimport cannot be applied to non-inline function definitions. 12983 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12984 !FD->isTemplateInstantiation()) { 12985 assert(!FD->hasAttr<DLLExportAttr>()); 12986 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12987 FD->setInvalidDecl(); 12988 return D; 12989 } 12990 // We want to attach documentation to original Decl (which might be 12991 // a function template). 12992 ActOnDocumentableDecl(D); 12993 if (getCurLexicalContext()->isObjCContainer() && 12994 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12995 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12996 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12997 12998 return D; 12999 } 13000 13001 /// Given the set of return statements within a function body, 13002 /// compute the variables that are subject to the named return value 13003 /// optimization. 13004 /// 13005 /// Each of the variables that is subject to the named return value 13006 /// optimization will be marked as NRVO variables in the AST, and any 13007 /// return statement that has a marked NRVO variable as its NRVO candidate can 13008 /// use the named return value optimization. 13009 /// 13010 /// This function applies a very simplistic algorithm for NRVO: if every return 13011 /// statement in the scope of a variable has the same NRVO candidate, that 13012 /// candidate is an NRVO variable. 13013 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13014 ReturnStmt **Returns = Scope->Returns.data(); 13015 13016 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13017 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13018 if (!NRVOCandidate->isNRVOVariable()) 13019 Returns[I]->setNRVOCandidate(nullptr); 13020 } 13021 } 13022 } 13023 13024 bool Sema::canDelayFunctionBody(const Declarator &D) { 13025 // We can't delay parsing the body of a constexpr function template (yet). 13026 if (D.getDeclSpec().isConstexprSpecified()) 13027 return false; 13028 13029 // We can't delay parsing the body of a function template with a deduced 13030 // return type (yet). 13031 if (D.getDeclSpec().hasAutoTypeSpec()) { 13032 // If the placeholder introduces a non-deduced trailing return type, 13033 // we can still delay parsing it. 13034 if (D.getNumTypeObjects()) { 13035 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13036 if (Outer.Kind == DeclaratorChunk::Function && 13037 Outer.Fun.hasTrailingReturnType()) { 13038 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13039 return Ty.isNull() || !Ty->isUndeducedType(); 13040 } 13041 } 13042 return false; 13043 } 13044 13045 return true; 13046 } 13047 13048 bool Sema::canSkipFunctionBody(Decl *D) { 13049 // We cannot skip the body of a function (or function template) which is 13050 // constexpr, since we may need to evaluate its body in order to parse the 13051 // rest of the file. 13052 // We cannot skip the body of a function with an undeduced return type, 13053 // because any callers of that function need to know the type. 13054 if (const FunctionDecl *FD = D->getAsFunction()) { 13055 if (FD->isConstexpr()) 13056 return false; 13057 // We can't simply call Type::isUndeducedType here, because inside template 13058 // auto can be deduced to a dependent type, which is not considered 13059 // "undeduced". 13060 if (FD->getReturnType()->getContainedDeducedType()) 13061 return false; 13062 } 13063 return Consumer.shouldSkipFunctionBody(D); 13064 } 13065 13066 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13067 if (!Decl) 13068 return nullptr; 13069 if (FunctionDecl *FD = Decl->getAsFunction()) 13070 FD->setHasSkippedBody(); 13071 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13072 MD->setHasSkippedBody(); 13073 return Decl; 13074 } 13075 13076 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13077 return ActOnFinishFunctionBody(D, BodyArg, false); 13078 } 13079 13080 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13081 /// body. 13082 class ExitFunctionBodyRAII { 13083 public: 13084 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13085 ~ExitFunctionBodyRAII() { 13086 if (!IsLambda) 13087 S.PopExpressionEvaluationContext(); 13088 } 13089 13090 private: 13091 Sema &S; 13092 bool IsLambda = false; 13093 }; 13094 13095 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 13096 bool IsInstantiation) { 13097 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 13098 13099 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 13100 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 13101 13102 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 13103 CheckCompletedCoroutineBody(FD, Body); 13104 13105 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 13106 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 13107 // meant to pop the context added in ActOnStartOfFunctionDef(). 13108 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 13109 13110 if (FD) { 13111 FD->setBody(Body); 13112 FD->setWillHaveBody(false); 13113 13114 if (getLangOpts().CPlusPlus14) { 13115 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 13116 FD->getReturnType()->isUndeducedType()) { 13117 // If the function has a deduced result type but contains no 'return' 13118 // statements, the result type as written must be exactly 'auto', and 13119 // the deduced result type is 'void'. 13120 if (!FD->getReturnType()->getAs<AutoType>()) { 13121 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 13122 << FD->getReturnType(); 13123 FD->setInvalidDecl(); 13124 } else { 13125 // Substitute 'void' for the 'auto' in the type. 13126 TypeLoc ResultType = getReturnTypeLoc(FD); 13127 Context.adjustDeducedFunctionResultType( 13128 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 13129 } 13130 } 13131 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 13132 // In C++11, we don't use 'auto' deduction rules for lambda call 13133 // operators because we don't support return type deduction. 13134 auto *LSI = getCurLambda(); 13135 if (LSI->HasImplicitReturnType) { 13136 deduceClosureReturnType(*LSI); 13137 13138 // C++11 [expr.prim.lambda]p4: 13139 // [...] if there are no return statements in the compound-statement 13140 // [the deduced type is] the type void 13141 QualType RetType = 13142 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 13143 13144 // Update the return type to the deduced type. 13145 const FunctionProtoType *Proto = 13146 FD->getType()->getAs<FunctionProtoType>(); 13147 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 13148 Proto->getExtProtoInfo())); 13149 } 13150 } 13151 13152 // If the function implicitly returns zero (like 'main') or is naked, 13153 // don't complain about missing return statements. 13154 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 13155 WP.disableCheckFallThrough(); 13156 13157 // MSVC permits the use of pure specifier (=0) on function definition, 13158 // defined at class scope, warn about this non-standard construct. 13159 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 13160 Diag(FD->getLocation(), diag::ext_pure_function_definition); 13161 13162 if (!FD->isInvalidDecl()) { 13163 // Don't diagnose unused parameters of defaulted or deleted functions. 13164 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 13165 DiagnoseUnusedParameters(FD->parameters()); 13166 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 13167 FD->getReturnType(), FD); 13168 13169 // If this is a structor, we need a vtable. 13170 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 13171 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 13172 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 13173 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 13174 13175 // Try to apply the named return value optimization. We have to check 13176 // if we can do this here because lambdas keep return statements around 13177 // to deduce an implicit return type. 13178 if (FD->getReturnType()->isRecordType() && 13179 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 13180 computeNRVO(Body, getCurFunction()); 13181 } 13182 13183 // GNU warning -Wmissing-prototypes: 13184 // Warn if a global function is defined without a previous 13185 // prototype declaration. This warning is issued even if the 13186 // definition itself provides a prototype. The aim is to detect 13187 // global functions that fail to be declared in header files. 13188 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 13189 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 13190 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 13191 13192 if (PossibleZeroParamPrototype) { 13193 // We found a declaration that is not a prototype, 13194 // but that could be a zero-parameter prototype 13195 if (TypeSourceInfo *TI = 13196 PossibleZeroParamPrototype->getTypeSourceInfo()) { 13197 TypeLoc TL = TI->getTypeLoc(); 13198 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 13199 Diag(PossibleZeroParamPrototype->getLocation(), 13200 diag::note_declaration_not_a_prototype) 13201 << PossibleZeroParamPrototype 13202 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 13203 } 13204 } 13205 13206 // GNU warning -Wstrict-prototypes 13207 // Warn if K&R function is defined without a previous declaration. 13208 // This warning is issued only if the definition itself does not provide 13209 // a prototype. Only K&R definitions do not provide a prototype. 13210 // An empty list in a function declarator that is part of a definition 13211 // of that function specifies that the function has no parameters 13212 // (C99 6.7.5.3p14) 13213 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 13214 !LangOpts.CPlusPlus) { 13215 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 13216 TypeLoc TL = TI->getTypeLoc(); 13217 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 13218 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 13219 } 13220 } 13221 13222 // Warn on CPUDispatch with an actual body. 13223 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 13224 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 13225 if (!CmpndBody->body_empty()) 13226 Diag(CmpndBody->body_front()->getBeginLoc(), 13227 diag::warn_dispatch_body_ignored); 13228 13229 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 13230 const CXXMethodDecl *KeyFunction; 13231 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 13232 MD->isVirtual() && 13233 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 13234 MD == KeyFunction->getCanonicalDecl()) { 13235 // Update the key-function state if necessary for this ABI. 13236 if (FD->isInlined() && 13237 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 13238 Context.setNonKeyFunction(MD); 13239 13240 // If the newly-chosen key function is already defined, then we 13241 // need to mark the vtable as used retroactively. 13242 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 13243 const FunctionDecl *Definition; 13244 if (KeyFunction && KeyFunction->isDefined(Definition)) 13245 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 13246 } else { 13247 // We just defined they key function; mark the vtable as used. 13248 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 13249 } 13250 } 13251 } 13252 13253 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 13254 "Function parsing confused"); 13255 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 13256 assert(MD == getCurMethodDecl() && "Method parsing confused"); 13257 MD->setBody(Body); 13258 if (!MD->isInvalidDecl()) { 13259 if (!MD->hasSkippedBody()) 13260 DiagnoseUnusedParameters(MD->parameters()); 13261 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 13262 MD->getReturnType(), MD); 13263 13264 if (Body) 13265 computeNRVO(Body, getCurFunction()); 13266 } 13267 if (getCurFunction()->ObjCShouldCallSuper) { 13268 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 13269 << MD->getSelector().getAsString(); 13270 getCurFunction()->ObjCShouldCallSuper = false; 13271 } 13272 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 13273 const ObjCMethodDecl *InitMethod = nullptr; 13274 bool isDesignated = 13275 MD->isDesignatedInitializerForTheInterface(&InitMethod); 13276 assert(isDesignated && InitMethod); 13277 (void)isDesignated; 13278 13279 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 13280 auto IFace = MD->getClassInterface(); 13281 if (!IFace) 13282 return false; 13283 auto SuperD = IFace->getSuperClass(); 13284 if (!SuperD) 13285 return false; 13286 return SuperD->getIdentifier() == 13287 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 13288 }; 13289 // Don't issue this warning for unavailable inits or direct subclasses 13290 // of NSObject. 13291 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 13292 Diag(MD->getLocation(), 13293 diag::warn_objc_designated_init_missing_super_call); 13294 Diag(InitMethod->getLocation(), 13295 diag::note_objc_designated_init_marked_here); 13296 } 13297 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 13298 } 13299 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 13300 // Don't issue this warning for unavaialable inits. 13301 if (!MD->isUnavailable()) 13302 Diag(MD->getLocation(), 13303 diag::warn_objc_secondary_init_missing_init_call); 13304 getCurFunction()->ObjCWarnForNoInitDelegation = false; 13305 } 13306 } else { 13307 // Parsing the function declaration failed in some way. Pop the fake scope 13308 // we pushed on. 13309 PopFunctionScopeInfo(ActivePolicy, dcl); 13310 return nullptr; 13311 } 13312 13313 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 13314 DiagnoseUnguardedAvailabilityViolations(dcl); 13315 13316 assert(!getCurFunction()->ObjCShouldCallSuper && 13317 "This should only be set for ObjC methods, which should have been " 13318 "handled in the block above."); 13319 13320 // Verify and clean out per-function state. 13321 if (Body && (!FD || !FD->isDefaulted())) { 13322 // C++ constructors that have function-try-blocks can't have return 13323 // statements in the handlers of that block. (C++ [except.handle]p14) 13324 // Verify this. 13325 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 13326 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 13327 13328 // Verify that gotos and switch cases don't jump into scopes illegally. 13329 if (getCurFunction()->NeedsScopeChecking() && 13330 !PP.isCodeCompletionEnabled()) 13331 DiagnoseInvalidJumps(Body); 13332 13333 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 13334 if (!Destructor->getParent()->isDependentType()) 13335 CheckDestructor(Destructor); 13336 13337 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 13338 Destructor->getParent()); 13339 } 13340 13341 // If any errors have occurred, clear out any temporaries that may have 13342 // been leftover. This ensures that these temporaries won't be picked up for 13343 // deletion in some later function. 13344 if (getDiagnostics().hasErrorOccurred() || 13345 getDiagnostics().getSuppressAllDiagnostics()) { 13346 DiscardCleanupsInEvaluationContext(); 13347 } 13348 if (!getDiagnostics().hasUncompilableErrorOccurred() && 13349 !isa<FunctionTemplateDecl>(dcl)) { 13350 // Since the body is valid, issue any analysis-based warnings that are 13351 // enabled. 13352 ActivePolicy = &WP; 13353 } 13354 13355 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 13356 (!CheckConstexprFunctionDecl(FD) || 13357 !CheckConstexprFunctionBody(FD, Body))) 13358 FD->setInvalidDecl(); 13359 13360 if (FD && FD->hasAttr<NakedAttr>()) { 13361 for (const Stmt *S : Body->children()) { 13362 // Allow local register variables without initializer as they don't 13363 // require prologue. 13364 bool RegisterVariables = false; 13365 if (auto *DS = dyn_cast<DeclStmt>(S)) { 13366 for (const auto *Decl : DS->decls()) { 13367 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 13368 RegisterVariables = 13369 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 13370 if (!RegisterVariables) 13371 break; 13372 } 13373 } 13374 } 13375 if (RegisterVariables) 13376 continue; 13377 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 13378 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 13379 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 13380 FD->setInvalidDecl(); 13381 break; 13382 } 13383 } 13384 } 13385 13386 assert(ExprCleanupObjects.size() == 13387 ExprEvalContexts.back().NumCleanupObjects && 13388 "Leftover temporaries in function"); 13389 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 13390 assert(MaybeODRUseExprs.empty() && 13391 "Leftover expressions for odr-use checking"); 13392 } 13393 13394 if (!IsInstantiation) 13395 PopDeclContext(); 13396 13397 PopFunctionScopeInfo(ActivePolicy, dcl); 13398 // If any errors have occurred, clear out any temporaries that may have 13399 // been leftover. This ensures that these temporaries won't be picked up for 13400 // deletion in some later function. 13401 if (getDiagnostics().hasErrorOccurred()) { 13402 DiscardCleanupsInEvaluationContext(); 13403 } 13404 13405 return dcl; 13406 } 13407 13408 /// When we finish delayed parsing of an attribute, we must attach it to the 13409 /// relevant Decl. 13410 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 13411 ParsedAttributes &Attrs) { 13412 // Always attach attributes to the underlying decl. 13413 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 13414 D = TD->getTemplatedDecl(); 13415 ProcessDeclAttributeList(S, D, Attrs); 13416 13417 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 13418 if (Method->isStatic()) 13419 checkThisInStaticMemberFunctionAttributes(Method); 13420 } 13421 13422 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 13423 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 13424 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 13425 IdentifierInfo &II, Scope *S) { 13426 // Find the scope in which the identifier is injected and the corresponding 13427 // DeclContext. 13428 // FIXME: C89 does not say what happens if there is no enclosing block scope. 13429 // In that case, we inject the declaration into the translation unit scope 13430 // instead. 13431 Scope *BlockScope = S; 13432 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 13433 BlockScope = BlockScope->getParent(); 13434 13435 Scope *ContextScope = BlockScope; 13436 while (!ContextScope->getEntity()) 13437 ContextScope = ContextScope->getParent(); 13438 ContextRAII SavedContext(*this, ContextScope->getEntity()); 13439 13440 // Before we produce a declaration for an implicitly defined 13441 // function, see whether there was a locally-scoped declaration of 13442 // this name as a function or variable. If so, use that 13443 // (non-visible) declaration, and complain about it. 13444 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 13445 if (ExternCPrev) { 13446 // We still need to inject the function into the enclosing block scope so 13447 // that later (non-call) uses can see it. 13448 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13449 13450 // C89 footnote 38: 13451 // If in fact it is not defined as having type "function returning int", 13452 // the behavior is undefined. 13453 if (!isa<FunctionDecl>(ExternCPrev) || 13454 !Context.typesAreCompatible( 13455 cast<FunctionDecl>(ExternCPrev)->getType(), 13456 Context.getFunctionNoProtoType(Context.IntTy))) { 13457 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13458 << ExternCPrev << !getLangOpts().C99; 13459 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13460 return ExternCPrev; 13461 } 13462 } 13463 13464 // Extension in C99. Legal in C90, but warn about it. 13465 unsigned diag_id; 13466 if (II.getName().startswith("__builtin_")) 13467 diag_id = diag::warn_builtin_unknown; 13468 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13469 else if (getLangOpts().OpenCL) 13470 diag_id = diag::err_opencl_implicit_function_decl; 13471 else if (getLangOpts().C99) 13472 diag_id = diag::ext_implicit_function_decl; 13473 else 13474 diag_id = diag::warn_implicit_function_decl; 13475 Diag(Loc, diag_id) << &II; 13476 13477 // If we found a prior declaration of this function, don't bother building 13478 // another one. We've already pushed that one into scope, so there's nothing 13479 // more to do. 13480 if (ExternCPrev) 13481 return ExternCPrev; 13482 13483 // Because typo correction is expensive, only do it if the implicit 13484 // function declaration is going to be treated as an error. 13485 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13486 TypoCorrection Corrected; 13487 if (S && 13488 (Corrected = CorrectTypo( 13489 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 13490 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 13491 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13492 /*ErrorRecovery*/false); 13493 } 13494 13495 // Set a Declarator for the implicit definition: int foo(); 13496 const char *Dummy; 13497 AttributeFactory attrFactory; 13498 DeclSpec DS(attrFactory); 13499 unsigned DiagID; 13500 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13501 Context.getPrintingPolicy()); 13502 (void)Error; // Silence warning. 13503 assert(!Error && "Error setting up implicit decl!"); 13504 SourceLocation NoLoc; 13505 Declarator D(DS, DeclaratorContext::BlockContext); 13506 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13507 /*IsAmbiguous=*/false, 13508 /*LParenLoc=*/NoLoc, 13509 /*Params=*/nullptr, 13510 /*NumParams=*/0, 13511 /*EllipsisLoc=*/NoLoc, 13512 /*RParenLoc=*/NoLoc, 13513 /*RefQualifierIsLvalueRef=*/true, 13514 /*RefQualifierLoc=*/NoLoc, 13515 /*MutableLoc=*/NoLoc, EST_None, 13516 /*ESpecRange=*/SourceRange(), 13517 /*Exceptions=*/nullptr, 13518 /*ExceptionRanges=*/nullptr, 13519 /*NumExceptions=*/0, 13520 /*NoexceptExpr=*/nullptr, 13521 /*ExceptionSpecTokens=*/nullptr, 13522 /*DeclsInPrototype=*/None, Loc, 13523 Loc, D), 13524 std::move(DS.getAttributes()), SourceLocation()); 13525 D.SetIdentifier(&II, Loc); 13526 13527 // Insert this function into the enclosing block scope. 13528 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13529 FD->setImplicit(); 13530 13531 AddKnownFunctionAttributes(FD); 13532 13533 return FD; 13534 } 13535 13536 /// Adds any function attributes that we know a priori based on 13537 /// the declaration of this function. 13538 /// 13539 /// These attributes can apply both to implicitly-declared builtins 13540 /// (like __builtin___printf_chk) or to library-declared functions 13541 /// like NSLog or printf. 13542 /// 13543 /// We need to check for duplicate attributes both here and where user-written 13544 /// attributes are applied to declarations. 13545 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13546 if (FD->isInvalidDecl()) 13547 return; 13548 13549 // If this is a built-in function, map its builtin attributes to 13550 // actual attributes. 13551 if (unsigned BuiltinID = FD->getBuiltinID()) { 13552 // Handle printf-formatting attributes. 13553 unsigned FormatIdx; 13554 bool HasVAListArg; 13555 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13556 if (!FD->hasAttr<FormatAttr>()) { 13557 const char *fmt = "printf"; 13558 unsigned int NumParams = FD->getNumParams(); 13559 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13560 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13561 fmt = "NSString"; 13562 FD->addAttr(FormatAttr::CreateImplicit(Context, 13563 &Context.Idents.get(fmt), 13564 FormatIdx+1, 13565 HasVAListArg ? 0 : FormatIdx+2, 13566 FD->getLocation())); 13567 } 13568 } 13569 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13570 HasVAListArg)) { 13571 if (!FD->hasAttr<FormatAttr>()) 13572 FD->addAttr(FormatAttr::CreateImplicit(Context, 13573 &Context.Idents.get("scanf"), 13574 FormatIdx+1, 13575 HasVAListArg ? 0 : FormatIdx+2, 13576 FD->getLocation())); 13577 } 13578 13579 // Mark const if we don't care about errno and that is the only thing 13580 // preventing the function from being const. This allows IRgen to use LLVM 13581 // intrinsics for such functions. 13582 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13583 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13584 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13585 13586 // We make "fma" on some platforms const because we know it does not set 13587 // errno in those environments even though it could set errno based on the 13588 // C standard. 13589 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13590 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13591 !FD->hasAttr<ConstAttr>()) { 13592 switch (BuiltinID) { 13593 case Builtin::BI__builtin_fma: 13594 case Builtin::BI__builtin_fmaf: 13595 case Builtin::BI__builtin_fmal: 13596 case Builtin::BIfma: 13597 case Builtin::BIfmaf: 13598 case Builtin::BIfmal: 13599 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13600 break; 13601 default: 13602 break; 13603 } 13604 } 13605 13606 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13607 !FD->hasAttr<ReturnsTwiceAttr>()) 13608 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13609 FD->getLocation())); 13610 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13611 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13612 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13613 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13614 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13615 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13616 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13617 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13618 // Add the appropriate attribute, depending on the CUDA compilation mode 13619 // and which target the builtin belongs to. For example, during host 13620 // compilation, aux builtins are __device__, while the rest are __host__. 13621 if (getLangOpts().CUDAIsDevice != 13622 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13623 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13624 else 13625 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13626 } 13627 } 13628 13629 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13630 // throw, add an implicit nothrow attribute to any extern "C" function we come 13631 // across. 13632 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13633 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13634 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13635 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13636 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13637 } 13638 13639 IdentifierInfo *Name = FD->getIdentifier(); 13640 if (!Name) 13641 return; 13642 if ((!getLangOpts().CPlusPlus && 13643 FD->getDeclContext()->isTranslationUnit()) || 13644 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13645 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13646 LinkageSpecDecl::lang_c)) { 13647 // Okay: this could be a libc/libm/Objective-C function we know 13648 // about. 13649 } else 13650 return; 13651 13652 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13653 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13654 // target-specific builtins, perhaps? 13655 if (!FD->hasAttr<FormatAttr>()) 13656 FD->addAttr(FormatAttr::CreateImplicit(Context, 13657 &Context.Idents.get("printf"), 2, 13658 Name->isStr("vasprintf") ? 0 : 3, 13659 FD->getLocation())); 13660 } 13661 13662 if (Name->isStr("__CFStringMakeConstantString")) { 13663 // We already have a __builtin___CFStringMakeConstantString, 13664 // but builds that use -fno-constant-cfstrings don't go through that. 13665 if (!FD->hasAttr<FormatArgAttr>()) 13666 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13667 FD->getLocation())); 13668 } 13669 } 13670 13671 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13672 TypeSourceInfo *TInfo) { 13673 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13674 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13675 13676 if (!TInfo) { 13677 assert(D.isInvalidType() && "no declarator info for valid type"); 13678 TInfo = Context.getTrivialTypeSourceInfo(T); 13679 } 13680 13681 // Scope manipulation handled by caller. 13682 TypedefDecl *NewTD = 13683 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 13684 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 13685 13686 // Bail out immediately if we have an invalid declaration. 13687 if (D.isInvalidType()) { 13688 NewTD->setInvalidDecl(); 13689 return NewTD; 13690 } 13691 13692 if (D.getDeclSpec().isModulePrivateSpecified()) { 13693 if (CurContext->isFunctionOrMethod()) 13694 Diag(NewTD->getLocation(), diag::err_module_private_local) 13695 << 2 << NewTD->getDeclName() 13696 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13697 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13698 else 13699 NewTD->setModulePrivate(); 13700 } 13701 13702 // C++ [dcl.typedef]p8: 13703 // If the typedef declaration defines an unnamed class (or 13704 // enum), the first typedef-name declared by the declaration 13705 // to be that class type (or enum type) is used to denote the 13706 // class type (or enum type) for linkage purposes only. 13707 // We need to check whether the type was declared in the declaration. 13708 switch (D.getDeclSpec().getTypeSpecType()) { 13709 case TST_enum: 13710 case TST_struct: 13711 case TST_interface: 13712 case TST_union: 13713 case TST_class: { 13714 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13715 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13716 break; 13717 } 13718 13719 default: 13720 break; 13721 } 13722 13723 return NewTD; 13724 } 13725 13726 /// Check that this is a valid underlying type for an enum declaration. 13727 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13728 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13729 QualType T = TI->getType(); 13730 13731 if (T->isDependentType()) 13732 return false; 13733 13734 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13735 if (BT->isInteger()) 13736 return false; 13737 13738 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13739 return true; 13740 } 13741 13742 /// Check whether this is a valid redeclaration of a previous enumeration. 13743 /// \return true if the redeclaration was invalid. 13744 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13745 QualType EnumUnderlyingTy, bool IsFixed, 13746 const EnumDecl *Prev) { 13747 if (IsScoped != Prev->isScoped()) { 13748 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13749 << Prev->isScoped(); 13750 Diag(Prev->getLocation(), diag::note_previous_declaration); 13751 return true; 13752 } 13753 13754 if (IsFixed && Prev->isFixed()) { 13755 if (!EnumUnderlyingTy->isDependentType() && 13756 !Prev->getIntegerType()->isDependentType() && 13757 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13758 Prev->getIntegerType())) { 13759 // TODO: Highlight the underlying type of the redeclaration. 13760 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13761 << EnumUnderlyingTy << Prev->getIntegerType(); 13762 Diag(Prev->getLocation(), diag::note_previous_declaration) 13763 << Prev->getIntegerTypeRange(); 13764 return true; 13765 } 13766 } else if (IsFixed != Prev->isFixed()) { 13767 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13768 << Prev->isFixed(); 13769 Diag(Prev->getLocation(), diag::note_previous_declaration); 13770 return true; 13771 } 13772 13773 return false; 13774 } 13775 13776 /// Get diagnostic %select index for tag kind for 13777 /// redeclaration diagnostic message. 13778 /// WARNING: Indexes apply to particular diagnostics only! 13779 /// 13780 /// \returns diagnostic %select index. 13781 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13782 switch (Tag) { 13783 case TTK_Struct: return 0; 13784 case TTK_Interface: return 1; 13785 case TTK_Class: return 2; 13786 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13787 } 13788 } 13789 13790 /// Determine if tag kind is a class-key compatible with 13791 /// class for redeclaration (class, struct, or __interface). 13792 /// 13793 /// \returns true iff the tag kind is compatible. 13794 static bool isClassCompatTagKind(TagTypeKind Tag) 13795 { 13796 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13797 } 13798 13799 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13800 TagTypeKind TTK) { 13801 if (isa<TypedefDecl>(PrevDecl)) 13802 return NTK_Typedef; 13803 else if (isa<TypeAliasDecl>(PrevDecl)) 13804 return NTK_TypeAlias; 13805 else if (isa<ClassTemplateDecl>(PrevDecl)) 13806 return NTK_Template; 13807 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13808 return NTK_TypeAliasTemplate; 13809 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13810 return NTK_TemplateTemplateArgument; 13811 switch (TTK) { 13812 case TTK_Struct: 13813 case TTK_Interface: 13814 case TTK_Class: 13815 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13816 case TTK_Union: 13817 return NTK_NonUnion; 13818 case TTK_Enum: 13819 return NTK_NonEnum; 13820 } 13821 llvm_unreachable("invalid TTK"); 13822 } 13823 13824 /// Determine whether a tag with a given kind is acceptable 13825 /// as a redeclaration of the given tag declaration. 13826 /// 13827 /// \returns true if the new tag kind is acceptable, false otherwise. 13828 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13829 TagTypeKind NewTag, bool isDefinition, 13830 SourceLocation NewTagLoc, 13831 const IdentifierInfo *Name) { 13832 // C++ [dcl.type.elab]p3: 13833 // The class-key or enum keyword present in the 13834 // elaborated-type-specifier shall agree in kind with the 13835 // declaration to which the name in the elaborated-type-specifier 13836 // refers. This rule also applies to the form of 13837 // elaborated-type-specifier that declares a class-name or 13838 // friend class since it can be construed as referring to the 13839 // definition of the class. Thus, in any 13840 // elaborated-type-specifier, the enum keyword shall be used to 13841 // refer to an enumeration (7.2), the union class-key shall be 13842 // used to refer to a union (clause 9), and either the class or 13843 // struct class-key shall be used to refer to a class (clause 9) 13844 // declared using the class or struct class-key. 13845 TagTypeKind OldTag = Previous->getTagKind(); 13846 if (OldTag != NewTag && 13847 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 13848 return false; 13849 13850 // Tags are compatible, but we might still want to warn on mismatched tags. 13851 // Non-class tags can't be mismatched at this point. 13852 if (!isClassCompatTagKind(NewTag)) 13853 return true; 13854 13855 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 13856 // by our warning analysis. We don't want to warn about mismatches with (eg) 13857 // declarations in system headers that are designed to be specialized, but if 13858 // a user asks us to warn, we should warn if their code contains mismatched 13859 // declarations. 13860 auto IsIgnoredLoc = [&](SourceLocation Loc) { 13861 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 13862 Loc); 13863 }; 13864 if (IsIgnoredLoc(NewTagLoc)) 13865 return true; 13866 13867 auto IsIgnored = [&](const TagDecl *Tag) { 13868 return IsIgnoredLoc(Tag->getLocation()); 13869 }; 13870 while (IsIgnored(Previous)) { 13871 Previous = Previous->getPreviousDecl(); 13872 if (!Previous) 13873 return true; 13874 OldTag = Previous->getTagKind(); 13875 } 13876 13877 bool isTemplate = false; 13878 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13879 isTemplate = Record->getDescribedClassTemplate(); 13880 13881 if (inTemplateInstantiation()) { 13882 if (OldTag != NewTag) { 13883 // In a template instantiation, do not offer fix-its for tag mismatches 13884 // since they usually mess up the template instead of fixing the problem. 13885 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13886 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13887 << getRedeclDiagFromTagKind(OldTag); 13888 // FIXME: Note previous location? 13889 } 13890 return true; 13891 } 13892 13893 if (isDefinition) { 13894 // On definitions, check all previous tags and issue a fix-it for each 13895 // one that doesn't match the current tag. 13896 if (Previous->getDefinition()) { 13897 // Don't suggest fix-its for redefinitions. 13898 return true; 13899 } 13900 13901 bool previousMismatch = false; 13902 for (const TagDecl *I : Previous->redecls()) { 13903 if (I->getTagKind() != NewTag) { 13904 // Ignore previous declarations for which the warning was disabled. 13905 if (IsIgnored(I)) 13906 continue; 13907 13908 if (!previousMismatch) { 13909 previousMismatch = true; 13910 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13911 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13912 << getRedeclDiagFromTagKind(I->getTagKind()); 13913 } 13914 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13915 << getRedeclDiagFromTagKind(NewTag) 13916 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13917 TypeWithKeyword::getTagTypeKindName(NewTag)); 13918 } 13919 } 13920 return true; 13921 } 13922 13923 // Identify the prevailing tag kind: this is the kind of the definition (if 13924 // there is a non-ignored definition), or otherwise the kind of the prior 13925 // (non-ignored) declaration. 13926 const TagDecl *PrevDef = Previous->getDefinition(); 13927 if (PrevDef && IsIgnored(PrevDef)) 13928 PrevDef = nullptr; 13929 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 13930 if (Redecl->getTagKind() != NewTag) { 13931 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13932 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13933 << getRedeclDiagFromTagKind(OldTag); 13934 Diag(Redecl->getLocation(), diag::note_previous_use); 13935 13936 // If there is a previous definition, suggest a fix-it. 13937 if (PrevDef) { 13938 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13939 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13940 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13941 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13942 } 13943 } 13944 13945 return true; 13946 } 13947 13948 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13949 /// from an outer enclosing namespace or file scope inside a friend declaration. 13950 /// This should provide the commented out code in the following snippet: 13951 /// namespace N { 13952 /// struct X; 13953 /// namespace M { 13954 /// struct Y { friend struct /*N::*/ X; }; 13955 /// } 13956 /// } 13957 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13958 SourceLocation NameLoc) { 13959 // While the decl is in a namespace, do repeated lookup of that name and see 13960 // if we get the same namespace back. If we do not, continue until 13961 // translation unit scope, at which point we have a fully qualified NNS. 13962 SmallVector<IdentifierInfo *, 4> Namespaces; 13963 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13964 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13965 // This tag should be declared in a namespace, which can only be enclosed by 13966 // other namespaces. Bail if there's an anonymous namespace in the chain. 13967 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13968 if (!Namespace || Namespace->isAnonymousNamespace()) 13969 return FixItHint(); 13970 IdentifierInfo *II = Namespace->getIdentifier(); 13971 Namespaces.push_back(II); 13972 NamedDecl *Lookup = SemaRef.LookupSingleName( 13973 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13974 if (Lookup == Namespace) 13975 break; 13976 } 13977 13978 // Once we have all the namespaces, reverse them to go outermost first, and 13979 // build an NNS. 13980 SmallString<64> Insertion; 13981 llvm::raw_svector_ostream OS(Insertion); 13982 if (DC->isTranslationUnit()) 13983 OS << "::"; 13984 std::reverse(Namespaces.begin(), Namespaces.end()); 13985 for (auto *II : Namespaces) 13986 OS << II->getName() << "::"; 13987 return FixItHint::CreateInsertion(NameLoc, Insertion); 13988 } 13989 13990 /// Determine whether a tag originally declared in context \p OldDC can 13991 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 13992 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13993 /// using-declaration). 13994 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13995 DeclContext *NewDC) { 13996 OldDC = OldDC->getRedeclContext(); 13997 NewDC = NewDC->getRedeclContext(); 13998 13999 if (OldDC->Equals(NewDC)) 14000 return true; 14001 14002 // In MSVC mode, we allow a redeclaration if the contexts are related (either 14003 // encloses the other). 14004 if (S.getLangOpts().MSVCCompat && 14005 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 14006 return true; 14007 14008 return false; 14009 } 14010 14011 /// This is invoked when we see 'struct foo' or 'struct {'. In the 14012 /// former case, Name will be non-null. In the later case, Name will be null. 14013 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 14014 /// reference/declaration/definition of a tag. 14015 /// 14016 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 14017 /// trailing-type-specifier) other than one in an alias-declaration. 14018 /// 14019 /// \param SkipBody If non-null, will be set to indicate if the caller should 14020 /// skip the definition of this tag and treat it as if it were a declaration. 14021 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 14022 SourceLocation KWLoc, CXXScopeSpec &SS, 14023 IdentifierInfo *Name, SourceLocation NameLoc, 14024 const ParsedAttributesView &Attrs, AccessSpecifier AS, 14025 SourceLocation ModulePrivateLoc, 14026 MultiTemplateParamsArg TemplateParameterLists, 14027 bool &OwnedDecl, bool &IsDependent, 14028 SourceLocation ScopedEnumKWLoc, 14029 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 14030 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 14031 SkipBodyInfo *SkipBody) { 14032 // If this is not a definition, it must have a name. 14033 IdentifierInfo *OrigName = Name; 14034 assert((Name != nullptr || TUK == TUK_Definition) && 14035 "Nameless record must be a definition!"); 14036 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 14037 14038 OwnedDecl = false; 14039 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 14040 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 14041 14042 // FIXME: Check member specializations more carefully. 14043 bool isMemberSpecialization = false; 14044 bool Invalid = false; 14045 14046 // We only need to do this matching if we have template parameters 14047 // or a scope specifier, which also conveniently avoids this work 14048 // for non-C++ cases. 14049 if (TemplateParameterLists.size() > 0 || 14050 (SS.isNotEmpty() && TUK != TUK_Reference)) { 14051 if (TemplateParameterList *TemplateParams = 14052 MatchTemplateParametersToScopeSpecifier( 14053 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 14054 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 14055 if (Kind == TTK_Enum) { 14056 Diag(KWLoc, diag::err_enum_template); 14057 return nullptr; 14058 } 14059 14060 if (TemplateParams->size() > 0) { 14061 // This is a declaration or definition of a class template (which may 14062 // be a member of another template). 14063 14064 if (Invalid) 14065 return nullptr; 14066 14067 OwnedDecl = false; 14068 DeclResult Result = CheckClassTemplate( 14069 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 14070 AS, ModulePrivateLoc, 14071 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 14072 TemplateParameterLists.data(), SkipBody); 14073 return Result.get(); 14074 } else { 14075 // The "template<>" header is extraneous. 14076 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 14077 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 14078 isMemberSpecialization = true; 14079 } 14080 } 14081 } 14082 14083 // Figure out the underlying type if this a enum declaration. We need to do 14084 // this early, because it's needed to detect if this is an incompatible 14085 // redeclaration. 14086 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 14087 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 14088 14089 if (Kind == TTK_Enum) { 14090 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 14091 // No underlying type explicitly specified, or we failed to parse the 14092 // type, default to int. 14093 EnumUnderlying = Context.IntTy.getTypePtr(); 14094 } else if (UnderlyingType.get()) { 14095 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 14096 // integral type; any cv-qualification is ignored. 14097 TypeSourceInfo *TI = nullptr; 14098 GetTypeFromParser(UnderlyingType.get(), &TI); 14099 EnumUnderlying = TI; 14100 14101 if (CheckEnumUnderlyingType(TI)) 14102 // Recover by falling back to int. 14103 EnumUnderlying = Context.IntTy.getTypePtr(); 14104 14105 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 14106 UPPC_FixedUnderlyingType)) 14107 EnumUnderlying = Context.IntTy.getTypePtr(); 14108 14109 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 14110 // For MSVC ABI compatibility, unfixed enums must use an underlying type 14111 // of 'int'. However, if this is an unfixed forward declaration, don't set 14112 // the underlying type unless the user enables -fms-compatibility. This 14113 // makes unfixed forward declared enums incomplete and is more conforming. 14114 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 14115 EnumUnderlying = Context.IntTy.getTypePtr(); 14116 } 14117 } 14118 14119 DeclContext *SearchDC = CurContext; 14120 DeclContext *DC = CurContext; 14121 bool isStdBadAlloc = false; 14122 bool isStdAlignValT = false; 14123 14124 RedeclarationKind Redecl = forRedeclarationInCurContext(); 14125 if (TUK == TUK_Friend || TUK == TUK_Reference) 14126 Redecl = NotForRedeclaration; 14127 14128 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 14129 /// implemented asks for structural equivalence checking, the returned decl 14130 /// here is passed back to the parser, allowing the tag body to be parsed. 14131 auto createTagFromNewDecl = [&]() -> TagDecl * { 14132 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 14133 // If there is an identifier, use the location of the identifier as the 14134 // location of the decl, otherwise use the location of the struct/union 14135 // keyword. 14136 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14137 TagDecl *New = nullptr; 14138 14139 if (Kind == TTK_Enum) { 14140 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 14141 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 14142 // If this is an undefined enum, bail. 14143 if (TUK != TUK_Definition && !Invalid) 14144 return nullptr; 14145 if (EnumUnderlying) { 14146 EnumDecl *ED = cast<EnumDecl>(New); 14147 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 14148 ED->setIntegerTypeSourceInfo(TI); 14149 else 14150 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 14151 ED->setPromotionType(ED->getIntegerType()); 14152 } 14153 } else { // struct/union 14154 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14155 nullptr); 14156 } 14157 14158 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14159 // Add alignment attributes if necessary; these attributes are checked 14160 // when the ASTContext lays out the structure. 14161 // 14162 // It is important for implementing the correct semantics that this 14163 // happen here (in ActOnTag). The #pragma pack stack is 14164 // maintained as a result of parser callbacks which can occur at 14165 // many points during the parsing of a struct declaration (because 14166 // the #pragma tokens are effectively skipped over during the 14167 // parsing of the struct). 14168 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14169 AddAlignmentAttributesForRecord(RD); 14170 AddMsStructLayoutForRecord(RD); 14171 } 14172 } 14173 New->setLexicalDeclContext(CurContext); 14174 return New; 14175 }; 14176 14177 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 14178 if (Name && SS.isNotEmpty()) { 14179 // We have a nested-name tag ('struct foo::bar'). 14180 14181 // Check for invalid 'foo::'. 14182 if (SS.isInvalid()) { 14183 Name = nullptr; 14184 goto CreateNewDecl; 14185 } 14186 14187 // If this is a friend or a reference to a class in a dependent 14188 // context, don't try to make a decl for it. 14189 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14190 DC = computeDeclContext(SS, false); 14191 if (!DC) { 14192 IsDependent = true; 14193 return nullptr; 14194 } 14195 } else { 14196 DC = computeDeclContext(SS, true); 14197 if (!DC) { 14198 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 14199 << SS.getRange(); 14200 return nullptr; 14201 } 14202 } 14203 14204 if (RequireCompleteDeclContext(SS, DC)) 14205 return nullptr; 14206 14207 SearchDC = DC; 14208 // Look-up name inside 'foo::'. 14209 LookupQualifiedName(Previous, DC); 14210 14211 if (Previous.isAmbiguous()) 14212 return nullptr; 14213 14214 if (Previous.empty()) { 14215 // Name lookup did not find anything. However, if the 14216 // nested-name-specifier refers to the current instantiation, 14217 // and that current instantiation has any dependent base 14218 // classes, we might find something at instantiation time: treat 14219 // this as a dependent elaborated-type-specifier. 14220 // But this only makes any sense for reference-like lookups. 14221 if (Previous.wasNotFoundInCurrentInstantiation() && 14222 (TUK == TUK_Reference || TUK == TUK_Friend)) { 14223 IsDependent = true; 14224 return nullptr; 14225 } 14226 14227 // A tag 'foo::bar' must already exist. 14228 Diag(NameLoc, diag::err_not_tag_in_scope) 14229 << Kind << Name << DC << SS.getRange(); 14230 Name = nullptr; 14231 Invalid = true; 14232 goto CreateNewDecl; 14233 } 14234 } else if (Name) { 14235 // C++14 [class.mem]p14: 14236 // If T is the name of a class, then each of the following shall have a 14237 // name different from T: 14238 // -- every member of class T that is itself a type 14239 if (TUK != TUK_Reference && TUK != TUK_Friend && 14240 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 14241 return nullptr; 14242 14243 // If this is a named struct, check to see if there was a previous forward 14244 // declaration or definition. 14245 // FIXME: We're looking into outer scopes here, even when we 14246 // shouldn't be. Doing so can result in ambiguities that we 14247 // shouldn't be diagnosing. 14248 LookupName(Previous, S); 14249 14250 // When declaring or defining a tag, ignore ambiguities introduced 14251 // by types using'ed into this scope. 14252 if (Previous.isAmbiguous() && 14253 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 14254 LookupResult::Filter F = Previous.makeFilter(); 14255 while (F.hasNext()) { 14256 NamedDecl *ND = F.next(); 14257 if (!ND->getDeclContext()->getRedeclContext()->Equals( 14258 SearchDC->getRedeclContext())) 14259 F.erase(); 14260 } 14261 F.done(); 14262 } 14263 14264 // C++11 [namespace.memdef]p3: 14265 // If the name in a friend declaration is neither qualified nor 14266 // a template-id and the declaration is a function or an 14267 // elaborated-type-specifier, the lookup to determine whether 14268 // the entity has been previously declared shall not consider 14269 // any scopes outside the innermost enclosing namespace. 14270 // 14271 // MSVC doesn't implement the above rule for types, so a friend tag 14272 // declaration may be a redeclaration of a type declared in an enclosing 14273 // scope. They do implement this rule for friend functions. 14274 // 14275 // Does it matter that this should be by scope instead of by 14276 // semantic context? 14277 if (!Previous.empty() && TUK == TUK_Friend) { 14278 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 14279 LookupResult::Filter F = Previous.makeFilter(); 14280 bool FriendSawTagOutsideEnclosingNamespace = false; 14281 while (F.hasNext()) { 14282 NamedDecl *ND = F.next(); 14283 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14284 if (DC->isFileContext() && 14285 !EnclosingNS->Encloses(ND->getDeclContext())) { 14286 if (getLangOpts().MSVCCompat) 14287 FriendSawTagOutsideEnclosingNamespace = true; 14288 else 14289 F.erase(); 14290 } 14291 } 14292 F.done(); 14293 14294 // Diagnose this MSVC extension in the easy case where lookup would have 14295 // unambiguously found something outside the enclosing namespace. 14296 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 14297 NamedDecl *ND = Previous.getFoundDecl(); 14298 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 14299 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 14300 } 14301 } 14302 14303 // Note: there used to be some attempt at recovery here. 14304 if (Previous.isAmbiguous()) 14305 return nullptr; 14306 14307 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 14308 // FIXME: This makes sure that we ignore the contexts associated 14309 // with C structs, unions, and enums when looking for a matching 14310 // tag declaration or definition. See the similar lookup tweak 14311 // in Sema::LookupName; is there a better way to deal with this? 14312 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 14313 SearchDC = SearchDC->getParent(); 14314 } 14315 } 14316 14317 if (Previous.isSingleResult() && 14318 Previous.getFoundDecl()->isTemplateParameter()) { 14319 // Maybe we will complain about the shadowed template parameter. 14320 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 14321 // Just pretend that we didn't see the previous declaration. 14322 Previous.clear(); 14323 } 14324 14325 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 14326 DC->Equals(getStdNamespace())) { 14327 if (Name->isStr("bad_alloc")) { 14328 // This is a declaration of or a reference to "std::bad_alloc". 14329 isStdBadAlloc = true; 14330 14331 // If std::bad_alloc has been implicitly declared (but made invisible to 14332 // name lookup), fill in this implicit declaration as the previous 14333 // declaration, so that the declarations get chained appropriately. 14334 if (Previous.empty() && StdBadAlloc) 14335 Previous.addDecl(getStdBadAlloc()); 14336 } else if (Name->isStr("align_val_t")) { 14337 isStdAlignValT = true; 14338 if (Previous.empty() && StdAlignValT) 14339 Previous.addDecl(getStdAlignValT()); 14340 } 14341 } 14342 14343 // If we didn't find a previous declaration, and this is a reference 14344 // (or friend reference), move to the correct scope. In C++, we 14345 // also need to do a redeclaration lookup there, just in case 14346 // there's a shadow friend decl. 14347 if (Name && Previous.empty() && 14348 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 14349 if (Invalid) goto CreateNewDecl; 14350 assert(SS.isEmpty()); 14351 14352 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 14353 // C++ [basic.scope.pdecl]p5: 14354 // -- for an elaborated-type-specifier of the form 14355 // 14356 // class-key identifier 14357 // 14358 // if the elaborated-type-specifier is used in the 14359 // decl-specifier-seq or parameter-declaration-clause of a 14360 // function defined in namespace scope, the identifier is 14361 // declared as a class-name in the namespace that contains 14362 // the declaration; otherwise, except as a friend 14363 // declaration, the identifier is declared in the smallest 14364 // non-class, non-function-prototype scope that contains the 14365 // declaration. 14366 // 14367 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 14368 // C structs and unions. 14369 // 14370 // It is an error in C++ to declare (rather than define) an enum 14371 // type, including via an elaborated type specifier. We'll 14372 // diagnose that later; for now, declare the enum in the same 14373 // scope as we would have picked for any other tag type. 14374 // 14375 // GNU C also supports this behavior as part of its incomplete 14376 // enum types extension, while GNU C++ does not. 14377 // 14378 // Find the context where we'll be declaring the tag. 14379 // FIXME: We would like to maintain the current DeclContext as the 14380 // lexical context, 14381 SearchDC = getTagInjectionContext(SearchDC); 14382 14383 // Find the scope where we'll be declaring the tag. 14384 S = getTagInjectionScope(S, getLangOpts()); 14385 } else { 14386 assert(TUK == TUK_Friend); 14387 // C++ [namespace.memdef]p3: 14388 // If a friend declaration in a non-local class first declares a 14389 // class or function, the friend class or function is a member of 14390 // the innermost enclosing namespace. 14391 SearchDC = SearchDC->getEnclosingNamespaceContext(); 14392 } 14393 14394 // In C++, we need to do a redeclaration lookup to properly 14395 // diagnose some problems. 14396 // FIXME: redeclaration lookup is also used (with and without C++) to find a 14397 // hidden declaration so that we don't get ambiguity errors when using a 14398 // type declared by an elaborated-type-specifier. In C that is not correct 14399 // and we should instead merge compatible types found by lookup. 14400 if (getLangOpts().CPlusPlus) { 14401 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14402 LookupQualifiedName(Previous, SearchDC); 14403 } else { 14404 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 14405 LookupName(Previous, S); 14406 } 14407 } 14408 14409 // If we have a known previous declaration to use, then use it. 14410 if (Previous.empty() && SkipBody && SkipBody->Previous) 14411 Previous.addDecl(SkipBody->Previous); 14412 14413 if (!Previous.empty()) { 14414 NamedDecl *PrevDecl = Previous.getFoundDecl(); 14415 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 14416 14417 // It's okay to have a tag decl in the same scope as a typedef 14418 // which hides a tag decl in the same scope. Finding this 14419 // insanity with a redeclaration lookup can only actually happen 14420 // in C++. 14421 // 14422 // This is also okay for elaborated-type-specifiers, which is 14423 // technically forbidden by the current standard but which is 14424 // okay according to the likely resolution of an open issue; 14425 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 14426 if (getLangOpts().CPlusPlus) { 14427 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14428 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 14429 TagDecl *Tag = TT->getDecl(); 14430 if (Tag->getDeclName() == Name && 14431 Tag->getDeclContext()->getRedeclContext() 14432 ->Equals(TD->getDeclContext()->getRedeclContext())) { 14433 PrevDecl = Tag; 14434 Previous.clear(); 14435 Previous.addDecl(Tag); 14436 Previous.resolveKind(); 14437 } 14438 } 14439 } 14440 } 14441 14442 // If this is a redeclaration of a using shadow declaration, it must 14443 // declare a tag in the same context. In MSVC mode, we allow a 14444 // redefinition if either context is within the other. 14445 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 14446 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 14447 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 14448 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 14449 !(OldTag && isAcceptableTagRedeclContext( 14450 *this, OldTag->getDeclContext(), SearchDC))) { 14451 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 14452 Diag(Shadow->getTargetDecl()->getLocation(), 14453 diag::note_using_decl_target); 14454 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 14455 << 0; 14456 // Recover by ignoring the old declaration. 14457 Previous.clear(); 14458 goto CreateNewDecl; 14459 } 14460 } 14461 14462 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 14463 // If this is a use of a previous tag, or if the tag is already declared 14464 // in the same scope (so that the definition/declaration completes or 14465 // rementions the tag), reuse the decl. 14466 if (TUK == TUK_Reference || TUK == TUK_Friend || 14467 isDeclInScope(DirectPrevDecl, SearchDC, S, 14468 SS.isNotEmpty() || isMemberSpecialization)) { 14469 // Make sure that this wasn't declared as an enum and now used as a 14470 // struct or something similar. 14471 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14472 TUK == TUK_Definition, KWLoc, 14473 Name)) { 14474 bool SafeToContinue 14475 = (PrevTagDecl->getTagKind() != TTK_Enum && 14476 Kind != TTK_Enum); 14477 if (SafeToContinue) 14478 Diag(KWLoc, diag::err_use_with_wrong_tag) 14479 << Name 14480 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14481 PrevTagDecl->getKindName()); 14482 else 14483 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14484 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14485 14486 if (SafeToContinue) 14487 Kind = PrevTagDecl->getTagKind(); 14488 else { 14489 // Recover by making this an anonymous redefinition. 14490 Name = nullptr; 14491 Previous.clear(); 14492 Invalid = true; 14493 } 14494 } 14495 14496 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14497 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14498 14499 // If this is an elaborated-type-specifier for a scoped enumeration, 14500 // the 'class' keyword is not necessary and not permitted. 14501 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14502 if (ScopedEnum) 14503 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14504 << PrevEnum->isScoped() 14505 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14506 return PrevTagDecl; 14507 } 14508 14509 QualType EnumUnderlyingTy; 14510 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14511 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14512 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14513 EnumUnderlyingTy = QualType(T, 0); 14514 14515 // All conflicts with previous declarations are recovered by 14516 // returning the previous declaration, unless this is a definition, 14517 // in which case we want the caller to bail out. 14518 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14519 ScopedEnum, EnumUnderlyingTy, 14520 IsFixed, PrevEnum)) 14521 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14522 } 14523 14524 // C++11 [class.mem]p1: 14525 // A member shall not be declared twice in the member-specification, 14526 // except that a nested class or member class template can be declared 14527 // and then later defined. 14528 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14529 S->isDeclScope(PrevDecl)) { 14530 Diag(NameLoc, diag::ext_member_redeclared); 14531 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14532 } 14533 14534 if (!Invalid) { 14535 // If this is a use, just return the declaration we found, unless 14536 // we have attributes. 14537 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14538 if (!Attrs.empty()) { 14539 // FIXME: Diagnose these attributes. For now, we create a new 14540 // declaration to hold them. 14541 } else if (TUK == TUK_Reference && 14542 (PrevTagDecl->getFriendObjectKind() == 14543 Decl::FOK_Undeclared || 14544 PrevDecl->getOwningModule() != getCurrentModule()) && 14545 SS.isEmpty()) { 14546 // This declaration is a reference to an existing entity, but 14547 // has different visibility from that entity: it either makes 14548 // a friend visible or it makes a type visible in a new module. 14549 // In either case, create a new declaration. We only do this if 14550 // the declaration would have meant the same thing if no prior 14551 // declaration were found, that is, if it was found in the same 14552 // scope where we would have injected a declaration. 14553 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14554 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14555 return PrevTagDecl; 14556 // This is in the injected scope, create a new declaration in 14557 // that scope. 14558 S = getTagInjectionScope(S, getLangOpts()); 14559 } else { 14560 return PrevTagDecl; 14561 } 14562 } 14563 14564 // Diagnose attempts to redefine a tag. 14565 if (TUK == TUK_Definition) { 14566 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14567 // If we're defining a specialization and the previous definition 14568 // is from an implicit instantiation, don't emit an error 14569 // here; we'll catch this in the general case below. 14570 bool IsExplicitSpecializationAfterInstantiation = false; 14571 if (isMemberSpecialization) { 14572 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14573 IsExplicitSpecializationAfterInstantiation = 14574 RD->getTemplateSpecializationKind() != 14575 TSK_ExplicitSpecialization; 14576 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14577 IsExplicitSpecializationAfterInstantiation = 14578 ED->getTemplateSpecializationKind() != 14579 TSK_ExplicitSpecialization; 14580 } 14581 14582 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14583 // not keep more that one definition around (merge them). However, 14584 // ensure the decl passes the structural compatibility check in 14585 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14586 NamedDecl *Hidden = nullptr; 14587 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14588 // There is a definition of this tag, but it is not visible. We 14589 // explicitly make use of C++'s one definition rule here, and 14590 // assume that this definition is identical to the hidden one 14591 // we already have. Make the existing definition visible and 14592 // use it in place of this one. 14593 if (!getLangOpts().CPlusPlus) { 14594 // Postpone making the old definition visible until after we 14595 // complete parsing the new one and do the structural 14596 // comparison. 14597 SkipBody->CheckSameAsPrevious = true; 14598 SkipBody->New = createTagFromNewDecl(); 14599 SkipBody->Previous = Def; 14600 return Def; 14601 } else { 14602 SkipBody->ShouldSkip = true; 14603 SkipBody->Previous = Def; 14604 makeMergedDefinitionVisible(Hidden); 14605 // Carry on and handle it like a normal definition. We'll 14606 // skip starting the definitiion later. 14607 } 14608 } else if (!IsExplicitSpecializationAfterInstantiation) { 14609 // A redeclaration in function prototype scope in C isn't 14610 // visible elsewhere, so merely issue a warning. 14611 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14612 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14613 else 14614 Diag(NameLoc, diag::err_redefinition) << Name; 14615 notePreviousDefinition(Def, 14616 NameLoc.isValid() ? NameLoc : KWLoc); 14617 // If this is a redefinition, recover by making this 14618 // struct be anonymous, which will make any later 14619 // references get the previous definition. 14620 Name = nullptr; 14621 Previous.clear(); 14622 Invalid = true; 14623 } 14624 } else { 14625 // If the type is currently being defined, complain 14626 // about a nested redefinition. 14627 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14628 if (TD->isBeingDefined()) { 14629 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14630 Diag(PrevTagDecl->getLocation(), 14631 diag::note_previous_definition); 14632 Name = nullptr; 14633 Previous.clear(); 14634 Invalid = true; 14635 } 14636 } 14637 14638 // Okay, this is definition of a previously declared or referenced 14639 // tag. We're going to create a new Decl for it. 14640 } 14641 14642 // Okay, we're going to make a redeclaration. If this is some kind 14643 // of reference, make sure we build the redeclaration in the same DC 14644 // as the original, and ignore the current access specifier. 14645 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14646 SearchDC = PrevTagDecl->getDeclContext(); 14647 AS = AS_none; 14648 } 14649 } 14650 // If we get here we have (another) forward declaration or we 14651 // have a definition. Just create a new decl. 14652 14653 } else { 14654 // If we get here, this is a definition of a new tag type in a nested 14655 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14656 // new decl/type. We set PrevDecl to NULL so that the entities 14657 // have distinct types. 14658 Previous.clear(); 14659 } 14660 // If we get here, we're going to create a new Decl. If PrevDecl 14661 // is non-NULL, it's a definition of the tag declared by 14662 // PrevDecl. If it's NULL, we have a new definition. 14663 14664 // Otherwise, PrevDecl is not a tag, but was found with tag 14665 // lookup. This is only actually possible in C++, where a few 14666 // things like templates still live in the tag namespace. 14667 } else { 14668 // Use a better diagnostic if an elaborated-type-specifier 14669 // found the wrong kind of type on the first 14670 // (non-redeclaration) lookup. 14671 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14672 !Previous.isForRedeclaration()) { 14673 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14674 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14675 << Kind; 14676 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14677 Invalid = true; 14678 14679 // Otherwise, only diagnose if the declaration is in scope. 14680 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14681 SS.isNotEmpty() || isMemberSpecialization)) { 14682 // do nothing 14683 14684 // Diagnose implicit declarations introduced by elaborated types. 14685 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14686 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14687 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14688 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14689 Invalid = true; 14690 14691 // Otherwise it's a declaration. Call out a particularly common 14692 // case here. 14693 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14694 unsigned Kind = 0; 14695 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14696 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14697 << Name << Kind << TND->getUnderlyingType(); 14698 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14699 Invalid = true; 14700 14701 // Otherwise, diagnose. 14702 } else { 14703 // The tag name clashes with something else in the target scope, 14704 // issue an error and recover by making this tag be anonymous. 14705 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14706 notePreviousDefinition(PrevDecl, NameLoc); 14707 Name = nullptr; 14708 Invalid = true; 14709 } 14710 14711 // The existing declaration isn't relevant to us; we're in a 14712 // new scope, so clear out the previous declaration. 14713 Previous.clear(); 14714 } 14715 } 14716 14717 CreateNewDecl: 14718 14719 TagDecl *PrevDecl = nullptr; 14720 if (Previous.isSingleResult()) 14721 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14722 14723 // If there is an identifier, use the location of the identifier as the 14724 // location of the decl, otherwise use the location of the struct/union 14725 // keyword. 14726 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14727 14728 // Otherwise, create a new declaration. If there is a previous 14729 // declaration of the same entity, the two will be linked via 14730 // PrevDecl. 14731 TagDecl *New; 14732 14733 if (Kind == TTK_Enum) { 14734 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14735 // enum X { A, B, C } D; D should chain to X. 14736 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14737 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14738 ScopedEnumUsesClassTag, IsFixed); 14739 14740 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14741 StdAlignValT = cast<EnumDecl>(New); 14742 14743 // If this is an undefined enum, warn. 14744 if (TUK != TUK_Definition && !Invalid) { 14745 TagDecl *Def; 14746 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC) && 14747 cast<EnumDecl>(New)->isFixed()) { 14748 // C++0x: 7.2p2: opaque-enum-declaration. 14749 // Conflicts are diagnosed above. Do nothing. 14750 } 14751 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14752 Diag(Loc, diag::ext_forward_ref_enum_def) 14753 << New; 14754 Diag(Def->getLocation(), diag::note_previous_definition); 14755 } else { 14756 unsigned DiagID = diag::ext_forward_ref_enum; 14757 if (getLangOpts().MSVCCompat) 14758 DiagID = diag::ext_ms_forward_ref_enum; 14759 else if (getLangOpts().CPlusPlus) 14760 DiagID = diag::err_forward_ref_enum; 14761 Diag(Loc, DiagID); 14762 } 14763 } 14764 14765 if (EnumUnderlying) { 14766 EnumDecl *ED = cast<EnumDecl>(New); 14767 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14768 ED->setIntegerTypeSourceInfo(TI); 14769 else 14770 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14771 ED->setPromotionType(ED->getIntegerType()); 14772 assert(ED->isComplete() && "enum with type should be complete"); 14773 } 14774 } else { 14775 // struct/union/class 14776 14777 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14778 // struct X { int A; } D; D should chain to X. 14779 if (getLangOpts().CPlusPlus) { 14780 // FIXME: Look for a way to use RecordDecl for simple structs. 14781 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14782 cast_or_null<CXXRecordDecl>(PrevDecl)); 14783 14784 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14785 StdBadAlloc = cast<CXXRecordDecl>(New); 14786 } else 14787 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14788 cast_or_null<RecordDecl>(PrevDecl)); 14789 } 14790 14791 // C++11 [dcl.type]p3: 14792 // A type-specifier-seq shall not define a class or enumeration [...]. 14793 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14794 TUK == TUK_Definition) { 14795 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14796 << Context.getTagDeclType(New); 14797 Invalid = true; 14798 } 14799 14800 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14801 DC->getDeclKind() == Decl::Enum) { 14802 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14803 << Context.getTagDeclType(New); 14804 Invalid = true; 14805 } 14806 14807 // Maybe add qualifier info. 14808 if (SS.isNotEmpty()) { 14809 if (SS.isSet()) { 14810 // If this is either a declaration or a definition, check the 14811 // nested-name-specifier against the current context. 14812 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14813 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14814 isMemberSpecialization)) 14815 Invalid = true; 14816 14817 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14818 if (TemplateParameterLists.size() > 0) { 14819 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14820 } 14821 } 14822 else 14823 Invalid = true; 14824 } 14825 14826 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14827 // Add alignment attributes if necessary; these attributes are checked when 14828 // the ASTContext lays out the structure. 14829 // 14830 // It is important for implementing the correct semantics that this 14831 // happen here (in ActOnTag). The #pragma pack stack is 14832 // maintained as a result of parser callbacks which can occur at 14833 // many points during the parsing of a struct declaration (because 14834 // the #pragma tokens are effectively skipped over during the 14835 // parsing of the struct). 14836 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 14837 AddAlignmentAttributesForRecord(RD); 14838 AddMsStructLayoutForRecord(RD); 14839 } 14840 } 14841 14842 if (ModulePrivateLoc.isValid()) { 14843 if (isMemberSpecialization) 14844 Diag(New->getLocation(), diag::err_module_private_specialization) 14845 << 2 14846 << FixItHint::CreateRemoval(ModulePrivateLoc); 14847 // __module_private__ does not apply to local classes. However, we only 14848 // diagnose this as an error when the declaration specifiers are 14849 // freestanding. Here, we just ignore the __module_private__. 14850 else if (!SearchDC->isFunctionOrMethod()) 14851 New->setModulePrivate(); 14852 } 14853 14854 // If this is a specialization of a member class (of a class template), 14855 // check the specialization. 14856 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14857 Invalid = true; 14858 14859 // If we're declaring or defining a tag in function prototype scope in C, 14860 // note that this type can only be used within the function and add it to 14861 // the list of decls to inject into the function definition scope. 14862 if ((Name || Kind == TTK_Enum) && 14863 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14864 if (getLangOpts().CPlusPlus) { 14865 // C++ [dcl.fct]p6: 14866 // Types shall not be defined in return or parameter types. 14867 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14868 Diag(Loc, diag::err_type_defined_in_param_type) 14869 << Name; 14870 Invalid = true; 14871 } 14872 } else if (!PrevDecl) { 14873 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14874 } 14875 } 14876 14877 if (Invalid) 14878 New->setInvalidDecl(); 14879 14880 // Set the lexical context. If the tag has a C++ scope specifier, the 14881 // lexical context will be different from the semantic context. 14882 New->setLexicalDeclContext(CurContext); 14883 14884 // Mark this as a friend decl if applicable. 14885 // In Microsoft mode, a friend declaration also acts as a forward 14886 // declaration so we always pass true to setObjectOfFriendDecl to make 14887 // the tag name visible. 14888 if (TUK == TUK_Friend) 14889 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14890 14891 // Set the access specifier. 14892 if (!Invalid && SearchDC->isRecord()) 14893 SetMemberAccessSpecifier(New, PrevDecl, AS); 14894 14895 if (PrevDecl) 14896 CheckRedeclarationModuleOwnership(New, PrevDecl); 14897 14898 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 14899 New->startDefinition(); 14900 14901 ProcessDeclAttributeList(S, New, Attrs); 14902 AddPragmaAttributes(S, New); 14903 14904 // If this has an identifier, add it to the scope stack. 14905 if (TUK == TUK_Friend) { 14906 // We might be replacing an existing declaration in the lookup tables; 14907 // if so, borrow its access specifier. 14908 if (PrevDecl) 14909 New->setAccess(PrevDecl->getAccess()); 14910 14911 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14912 DC->makeDeclVisibleInContext(New); 14913 if (Name) // can be null along some error paths 14914 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14915 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14916 } else if (Name) { 14917 S = getNonFieldDeclScope(S); 14918 PushOnScopeChains(New, S, true); 14919 } else { 14920 CurContext->addDecl(New); 14921 } 14922 14923 // If this is the C FILE type, notify the AST context. 14924 if (IdentifierInfo *II = New->getIdentifier()) 14925 if (!New->isInvalidDecl() && 14926 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14927 II->isStr("FILE")) 14928 Context.setFILEDecl(New); 14929 14930 if (PrevDecl) 14931 mergeDeclAttributes(New, PrevDecl); 14932 14933 // If there's a #pragma GCC visibility in scope, set the visibility of this 14934 // record. 14935 AddPushedVisibilityAttribute(New); 14936 14937 if (isMemberSpecialization && !New->isInvalidDecl()) 14938 CompleteMemberSpecialization(New, Previous); 14939 14940 OwnedDecl = true; 14941 // In C++, don't return an invalid declaration. We can't recover well from 14942 // the cases where we make the type anonymous. 14943 if (Invalid && getLangOpts().CPlusPlus) { 14944 if (New->isBeingDefined()) 14945 if (auto RD = dyn_cast<RecordDecl>(New)) 14946 RD->completeDefinition(); 14947 return nullptr; 14948 } else if (SkipBody && SkipBody->ShouldSkip) { 14949 return SkipBody->Previous; 14950 } else { 14951 return New; 14952 } 14953 } 14954 14955 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14956 AdjustDeclIfTemplate(TagD); 14957 TagDecl *Tag = cast<TagDecl>(TagD); 14958 14959 // Enter the tag context. 14960 PushDeclContext(S, Tag); 14961 14962 ActOnDocumentableDecl(TagD); 14963 14964 // If there's a #pragma GCC visibility in scope, set the visibility of this 14965 // record. 14966 AddPushedVisibilityAttribute(Tag); 14967 } 14968 14969 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14970 SkipBodyInfo &SkipBody) { 14971 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14972 return false; 14973 14974 // Make the previous decl visible. 14975 makeMergedDefinitionVisible(SkipBody.Previous); 14976 return true; 14977 } 14978 14979 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14980 assert(isa<ObjCContainerDecl>(IDecl) && 14981 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14982 DeclContext *OCD = cast<DeclContext>(IDecl); 14983 assert(getContainingDC(OCD) == CurContext && 14984 "The next DeclContext should be lexically contained in the current one."); 14985 CurContext = OCD; 14986 return IDecl; 14987 } 14988 14989 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14990 SourceLocation FinalLoc, 14991 bool IsFinalSpelledSealed, 14992 SourceLocation LBraceLoc) { 14993 AdjustDeclIfTemplate(TagD); 14994 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14995 14996 FieldCollector->StartClass(); 14997 14998 if (!Record->getIdentifier()) 14999 return; 15000 15001 if (FinalLoc.isValid()) 15002 Record->addAttr(new (Context) 15003 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 15004 15005 // C++ [class]p2: 15006 // [...] The class-name is also inserted into the scope of the 15007 // class itself; this is known as the injected-class-name. For 15008 // purposes of access checking, the injected-class-name is treated 15009 // as if it were a public member name. 15010 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 15011 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 15012 Record->getLocation(), Record->getIdentifier(), 15013 /*PrevDecl=*/nullptr, 15014 /*DelayTypeCreation=*/true); 15015 Context.getTypeDeclType(InjectedClassName, Record); 15016 InjectedClassName->setImplicit(); 15017 InjectedClassName->setAccess(AS_public); 15018 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 15019 InjectedClassName->setDescribedClassTemplate(Template); 15020 PushOnScopeChains(InjectedClassName, S); 15021 assert(InjectedClassName->isInjectedClassName() && 15022 "Broken injected-class-name"); 15023 } 15024 15025 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 15026 SourceRange BraceRange) { 15027 AdjustDeclIfTemplate(TagD); 15028 TagDecl *Tag = cast<TagDecl>(TagD); 15029 Tag->setBraceRange(BraceRange); 15030 15031 // Make sure we "complete" the definition even it is invalid. 15032 if (Tag->isBeingDefined()) { 15033 assert(Tag->isInvalidDecl() && "We should already have completed it"); 15034 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15035 RD->completeDefinition(); 15036 } 15037 15038 if (isa<CXXRecordDecl>(Tag)) { 15039 FieldCollector->FinishClass(); 15040 } 15041 15042 // Exit this scope of this tag's definition. 15043 PopDeclContext(); 15044 15045 if (getCurLexicalContext()->isObjCContainer() && 15046 Tag->getDeclContext()->isFileContext()) 15047 Tag->setTopLevelDeclInObjCContainer(); 15048 15049 // Notify the consumer that we've defined a tag. 15050 if (!Tag->isInvalidDecl()) 15051 Consumer.HandleTagDeclDefinition(Tag); 15052 } 15053 15054 void Sema::ActOnObjCContainerFinishDefinition() { 15055 // Exit this scope of this interface definition. 15056 PopDeclContext(); 15057 } 15058 15059 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 15060 assert(DC == CurContext && "Mismatch of container contexts"); 15061 OriginalLexicalContext = DC; 15062 ActOnObjCContainerFinishDefinition(); 15063 } 15064 15065 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 15066 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 15067 OriginalLexicalContext = nullptr; 15068 } 15069 15070 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 15071 AdjustDeclIfTemplate(TagD); 15072 TagDecl *Tag = cast<TagDecl>(TagD); 15073 Tag->setInvalidDecl(); 15074 15075 // Make sure we "complete" the definition even it is invalid. 15076 if (Tag->isBeingDefined()) { 15077 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 15078 RD->completeDefinition(); 15079 } 15080 15081 // We're undoing ActOnTagStartDefinition here, not 15082 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 15083 // the FieldCollector. 15084 15085 PopDeclContext(); 15086 } 15087 15088 // Note that FieldName may be null for anonymous bitfields. 15089 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 15090 IdentifierInfo *FieldName, 15091 QualType FieldTy, bool IsMsStruct, 15092 Expr *BitWidth, bool *ZeroWidth) { 15093 // Default to true; that shouldn't confuse checks for emptiness 15094 if (ZeroWidth) 15095 *ZeroWidth = true; 15096 15097 // C99 6.7.2.1p4 - verify the field type. 15098 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 15099 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 15100 // Handle incomplete types with specific error. 15101 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 15102 return ExprError(); 15103 if (FieldName) 15104 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 15105 << FieldName << FieldTy << BitWidth->getSourceRange(); 15106 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 15107 << FieldTy << BitWidth->getSourceRange(); 15108 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 15109 UPPC_BitFieldWidth)) 15110 return ExprError(); 15111 15112 // If the bit-width is type- or value-dependent, don't try to check 15113 // it now. 15114 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 15115 return BitWidth; 15116 15117 llvm::APSInt Value; 15118 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 15119 if (ICE.isInvalid()) 15120 return ICE; 15121 BitWidth = ICE.get(); 15122 15123 if (Value != 0 && ZeroWidth) 15124 *ZeroWidth = false; 15125 15126 // Zero-width bitfield is ok for anonymous field. 15127 if (Value == 0 && FieldName) 15128 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 15129 15130 if (Value.isSigned() && Value.isNegative()) { 15131 if (FieldName) 15132 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 15133 << FieldName << Value.toString(10); 15134 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 15135 << Value.toString(10); 15136 } 15137 15138 if (!FieldTy->isDependentType()) { 15139 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 15140 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 15141 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 15142 15143 // Over-wide bitfields are an error in C or when using the MSVC bitfield 15144 // ABI. 15145 bool CStdConstraintViolation = 15146 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 15147 bool MSBitfieldViolation = 15148 Value.ugt(TypeStorageSize) && 15149 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 15150 if (CStdConstraintViolation || MSBitfieldViolation) { 15151 unsigned DiagWidth = 15152 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 15153 if (FieldName) 15154 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 15155 << FieldName << (unsigned)Value.getZExtValue() 15156 << !CStdConstraintViolation << DiagWidth; 15157 15158 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 15159 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 15160 << DiagWidth; 15161 } 15162 15163 // Warn on types where the user might conceivably expect to get all 15164 // specified bits as value bits: that's all integral types other than 15165 // 'bool'. 15166 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 15167 if (FieldName) 15168 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 15169 << FieldName << (unsigned)Value.getZExtValue() 15170 << (unsigned)TypeWidth; 15171 else 15172 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 15173 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 15174 } 15175 } 15176 15177 return BitWidth; 15178 } 15179 15180 /// ActOnField - Each field of a C struct/union is passed into this in order 15181 /// to create a FieldDecl object for it. 15182 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 15183 Declarator &D, Expr *BitfieldWidth) { 15184 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 15185 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 15186 /*InitStyle=*/ICIS_NoInit, AS_public); 15187 return Res; 15188 } 15189 15190 /// HandleField - Analyze a field of a C struct or a C++ data member. 15191 /// 15192 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 15193 SourceLocation DeclStart, 15194 Declarator &D, Expr *BitWidth, 15195 InClassInitStyle InitStyle, 15196 AccessSpecifier AS) { 15197 if (D.isDecompositionDeclarator()) { 15198 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 15199 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 15200 << Decomp.getSourceRange(); 15201 return nullptr; 15202 } 15203 15204 IdentifierInfo *II = D.getIdentifier(); 15205 SourceLocation Loc = DeclStart; 15206 if (II) Loc = D.getIdentifierLoc(); 15207 15208 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15209 QualType T = TInfo->getType(); 15210 if (getLangOpts().CPlusPlus) { 15211 CheckExtraCXXDefaultArguments(D); 15212 15213 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 15214 UPPC_DataMemberType)) { 15215 D.setInvalidType(); 15216 T = Context.IntTy; 15217 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 15218 } 15219 } 15220 15221 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 15222 15223 if (D.getDeclSpec().isInlineSpecified()) 15224 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 15225 << getLangOpts().CPlusPlus17; 15226 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 15227 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 15228 diag::err_invalid_thread) 15229 << DeclSpec::getSpecifierName(TSCS); 15230 15231 // Check to see if this name was declared as a member previously 15232 NamedDecl *PrevDecl = nullptr; 15233 LookupResult Previous(*this, II, Loc, LookupMemberName, 15234 ForVisibleRedeclaration); 15235 LookupName(Previous, S); 15236 switch (Previous.getResultKind()) { 15237 case LookupResult::Found: 15238 case LookupResult::FoundUnresolvedValue: 15239 PrevDecl = Previous.getAsSingle<NamedDecl>(); 15240 break; 15241 15242 case LookupResult::FoundOverloaded: 15243 PrevDecl = Previous.getRepresentativeDecl(); 15244 break; 15245 15246 case LookupResult::NotFound: 15247 case LookupResult::NotFoundInCurrentInstantiation: 15248 case LookupResult::Ambiguous: 15249 break; 15250 } 15251 Previous.suppressDiagnostics(); 15252 15253 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15254 // Maybe we will complain about the shadowed template parameter. 15255 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 15256 // Just pretend that we didn't see the previous declaration. 15257 PrevDecl = nullptr; 15258 } 15259 15260 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 15261 PrevDecl = nullptr; 15262 15263 bool Mutable 15264 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 15265 SourceLocation TSSL = D.getBeginLoc(); 15266 FieldDecl *NewFD 15267 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 15268 TSSL, AS, PrevDecl, &D); 15269 15270 if (NewFD->isInvalidDecl()) 15271 Record->setInvalidDecl(); 15272 15273 if (D.getDeclSpec().isModulePrivateSpecified()) 15274 NewFD->setModulePrivate(); 15275 15276 if (NewFD->isInvalidDecl() && PrevDecl) { 15277 // Don't introduce NewFD into scope; there's already something 15278 // with the same name in the same scope. 15279 } else if (II) { 15280 PushOnScopeChains(NewFD, S); 15281 } else 15282 Record->addDecl(NewFD); 15283 15284 return NewFD; 15285 } 15286 15287 /// Build a new FieldDecl and check its well-formedness. 15288 /// 15289 /// This routine builds a new FieldDecl given the fields name, type, 15290 /// record, etc. \p PrevDecl should refer to any previous declaration 15291 /// with the same name and in the same scope as the field to be 15292 /// created. 15293 /// 15294 /// \returns a new FieldDecl. 15295 /// 15296 /// \todo The Declarator argument is a hack. It will be removed once 15297 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 15298 TypeSourceInfo *TInfo, 15299 RecordDecl *Record, SourceLocation Loc, 15300 bool Mutable, Expr *BitWidth, 15301 InClassInitStyle InitStyle, 15302 SourceLocation TSSL, 15303 AccessSpecifier AS, NamedDecl *PrevDecl, 15304 Declarator *D) { 15305 IdentifierInfo *II = Name.getAsIdentifierInfo(); 15306 bool InvalidDecl = false; 15307 if (D) InvalidDecl = D->isInvalidType(); 15308 15309 // If we receive a broken type, recover by assuming 'int' and 15310 // marking this declaration as invalid. 15311 if (T.isNull()) { 15312 InvalidDecl = true; 15313 T = Context.IntTy; 15314 } 15315 15316 QualType EltTy = Context.getBaseElementType(T); 15317 if (!EltTy->isDependentType()) { 15318 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 15319 // Fields of incomplete type force their record to be invalid. 15320 Record->setInvalidDecl(); 15321 InvalidDecl = true; 15322 } else { 15323 NamedDecl *Def; 15324 EltTy->isIncompleteType(&Def); 15325 if (Def && Def->isInvalidDecl()) { 15326 Record->setInvalidDecl(); 15327 InvalidDecl = true; 15328 } 15329 } 15330 } 15331 15332 // TR 18037 does not allow fields to be declared with address space 15333 if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() || 15334 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 15335 Diag(Loc, diag::err_field_with_address_space); 15336 Record->setInvalidDecl(); 15337 InvalidDecl = true; 15338 } 15339 15340 if (LangOpts.OpenCL) { 15341 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 15342 // used as structure or union field: image, sampler, event or block types. 15343 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 15344 T->isBlockPointerType()) { 15345 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 15346 Record->setInvalidDecl(); 15347 InvalidDecl = true; 15348 } 15349 // OpenCL v1.2 s6.9.c: bitfields are not supported. 15350 if (BitWidth) { 15351 Diag(Loc, diag::err_opencl_bitfields); 15352 InvalidDecl = true; 15353 } 15354 } 15355 15356 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 15357 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 15358 T.hasQualifiers()) { 15359 InvalidDecl = true; 15360 Diag(Loc, diag::err_anon_bitfield_qualifiers); 15361 } 15362 15363 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15364 // than a variably modified type. 15365 if (!InvalidDecl && T->isVariablyModifiedType()) { 15366 bool SizeIsNegative; 15367 llvm::APSInt Oversized; 15368 15369 TypeSourceInfo *FixedTInfo = 15370 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 15371 SizeIsNegative, 15372 Oversized); 15373 if (FixedTInfo) { 15374 Diag(Loc, diag::warn_illegal_constant_array_size); 15375 TInfo = FixedTInfo; 15376 T = FixedTInfo->getType(); 15377 } else { 15378 if (SizeIsNegative) 15379 Diag(Loc, diag::err_typecheck_negative_array_size); 15380 else if (Oversized.getBoolValue()) 15381 Diag(Loc, diag::err_array_too_large) 15382 << Oversized.toString(10); 15383 else 15384 Diag(Loc, diag::err_typecheck_field_variable_size); 15385 InvalidDecl = true; 15386 } 15387 } 15388 15389 // Fields can not have abstract class types 15390 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 15391 diag::err_abstract_type_in_decl, 15392 AbstractFieldType)) 15393 InvalidDecl = true; 15394 15395 bool ZeroWidth = false; 15396 if (InvalidDecl) 15397 BitWidth = nullptr; 15398 // If this is declared as a bit-field, check the bit-field. 15399 if (BitWidth) { 15400 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 15401 &ZeroWidth).get(); 15402 if (!BitWidth) { 15403 InvalidDecl = true; 15404 BitWidth = nullptr; 15405 ZeroWidth = false; 15406 } 15407 } 15408 15409 // Check that 'mutable' is consistent with the type of the declaration. 15410 if (!InvalidDecl && Mutable) { 15411 unsigned DiagID = 0; 15412 if (T->isReferenceType()) 15413 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 15414 : diag::err_mutable_reference; 15415 else if (T.isConstQualified()) 15416 DiagID = diag::err_mutable_const; 15417 15418 if (DiagID) { 15419 SourceLocation ErrLoc = Loc; 15420 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 15421 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 15422 Diag(ErrLoc, DiagID); 15423 if (DiagID != diag::ext_mutable_reference) { 15424 Mutable = false; 15425 InvalidDecl = true; 15426 } 15427 } 15428 } 15429 15430 // C++11 [class.union]p8 (DR1460): 15431 // At most one variant member of a union may have a 15432 // brace-or-equal-initializer. 15433 if (InitStyle != ICIS_NoInit) 15434 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 15435 15436 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 15437 BitWidth, Mutable, InitStyle); 15438 if (InvalidDecl) 15439 NewFD->setInvalidDecl(); 15440 15441 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 15442 Diag(Loc, diag::err_duplicate_member) << II; 15443 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15444 NewFD->setInvalidDecl(); 15445 } 15446 15447 if (!InvalidDecl && getLangOpts().CPlusPlus) { 15448 if (Record->isUnion()) { 15449 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15450 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15451 if (RDecl->getDefinition()) { 15452 // C++ [class.union]p1: An object of a class with a non-trivial 15453 // constructor, a non-trivial copy constructor, a non-trivial 15454 // destructor, or a non-trivial copy assignment operator 15455 // cannot be a member of a union, nor can an array of such 15456 // objects. 15457 if (CheckNontrivialField(NewFD)) 15458 NewFD->setInvalidDecl(); 15459 } 15460 } 15461 15462 // C++ [class.union]p1: If a union contains a member of reference type, 15463 // the program is ill-formed, except when compiling with MSVC extensions 15464 // enabled. 15465 if (EltTy->isReferenceType()) { 15466 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15467 diag::ext_union_member_of_reference_type : 15468 diag::err_union_member_of_reference_type) 15469 << NewFD->getDeclName() << EltTy; 15470 if (!getLangOpts().MicrosoftExt) 15471 NewFD->setInvalidDecl(); 15472 } 15473 } 15474 } 15475 15476 // FIXME: We need to pass in the attributes given an AST 15477 // representation, not a parser representation. 15478 if (D) { 15479 // FIXME: The current scope is almost... but not entirely... correct here. 15480 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15481 15482 if (NewFD->hasAttrs()) 15483 CheckAlignasUnderalignment(NewFD); 15484 } 15485 15486 // In auto-retain/release, infer strong retension for fields of 15487 // retainable type. 15488 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15489 NewFD->setInvalidDecl(); 15490 15491 if (T.isObjCGCWeak()) 15492 Diag(Loc, diag::warn_attribute_weak_on_field); 15493 15494 NewFD->setAccess(AS); 15495 return NewFD; 15496 } 15497 15498 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15499 assert(FD); 15500 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15501 15502 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15503 return false; 15504 15505 QualType EltTy = Context.getBaseElementType(FD->getType()); 15506 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15507 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15508 if (RDecl->getDefinition()) { 15509 // We check for copy constructors before constructors 15510 // because otherwise we'll never get complaints about 15511 // copy constructors. 15512 15513 CXXSpecialMember member = CXXInvalid; 15514 // We're required to check for any non-trivial constructors. Since the 15515 // implicit default constructor is suppressed if there are any 15516 // user-declared constructors, we just need to check that there is a 15517 // trivial default constructor and a trivial copy constructor. (We don't 15518 // worry about move constructors here, since this is a C++98 check.) 15519 if (RDecl->hasNonTrivialCopyConstructor()) 15520 member = CXXCopyConstructor; 15521 else if (!RDecl->hasTrivialDefaultConstructor()) 15522 member = CXXDefaultConstructor; 15523 else if (RDecl->hasNonTrivialCopyAssignment()) 15524 member = CXXCopyAssignment; 15525 else if (RDecl->hasNonTrivialDestructor()) 15526 member = CXXDestructor; 15527 15528 if (member != CXXInvalid) { 15529 if (!getLangOpts().CPlusPlus11 && 15530 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15531 // Objective-C++ ARC: it is an error to have a non-trivial field of 15532 // a union. However, system headers in Objective-C programs 15533 // occasionally have Objective-C lifetime objects within unions, 15534 // and rather than cause the program to fail, we make those 15535 // members unavailable. 15536 SourceLocation Loc = FD->getLocation(); 15537 if (getSourceManager().isInSystemHeader(Loc)) { 15538 if (!FD->hasAttr<UnavailableAttr>()) 15539 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15540 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15541 return false; 15542 } 15543 } 15544 15545 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15546 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15547 diag::err_illegal_union_or_anon_struct_member) 15548 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15549 DiagnoseNontrivial(RDecl, member); 15550 return !getLangOpts().CPlusPlus11; 15551 } 15552 } 15553 } 15554 15555 return false; 15556 } 15557 15558 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15559 /// AST enum value. 15560 static ObjCIvarDecl::AccessControl 15561 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15562 switch (ivarVisibility) { 15563 default: llvm_unreachable("Unknown visitibility kind"); 15564 case tok::objc_private: return ObjCIvarDecl::Private; 15565 case tok::objc_public: return ObjCIvarDecl::Public; 15566 case tok::objc_protected: return ObjCIvarDecl::Protected; 15567 case tok::objc_package: return ObjCIvarDecl::Package; 15568 } 15569 } 15570 15571 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15572 /// in order to create an IvarDecl object for it. 15573 Decl *Sema::ActOnIvar(Scope *S, 15574 SourceLocation DeclStart, 15575 Declarator &D, Expr *BitfieldWidth, 15576 tok::ObjCKeywordKind Visibility) { 15577 15578 IdentifierInfo *II = D.getIdentifier(); 15579 Expr *BitWidth = (Expr*)BitfieldWidth; 15580 SourceLocation Loc = DeclStart; 15581 if (II) Loc = D.getIdentifierLoc(); 15582 15583 // FIXME: Unnamed fields can be handled in various different ways, for 15584 // example, unnamed unions inject all members into the struct namespace! 15585 15586 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15587 QualType T = TInfo->getType(); 15588 15589 if (BitWidth) { 15590 // 6.7.2.1p3, 6.7.2.1p4 15591 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15592 if (!BitWidth) 15593 D.setInvalidType(); 15594 } else { 15595 // Not a bitfield. 15596 15597 // validate II. 15598 15599 } 15600 if (T->isReferenceType()) { 15601 Diag(Loc, diag::err_ivar_reference_type); 15602 D.setInvalidType(); 15603 } 15604 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15605 // than a variably modified type. 15606 else if (T->isVariablyModifiedType()) { 15607 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15608 D.setInvalidType(); 15609 } 15610 15611 // Get the visibility (access control) for this ivar. 15612 ObjCIvarDecl::AccessControl ac = 15613 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15614 : ObjCIvarDecl::None; 15615 // Must set ivar's DeclContext to its enclosing interface. 15616 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15617 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15618 return nullptr; 15619 ObjCContainerDecl *EnclosingContext; 15620 if (ObjCImplementationDecl *IMPDecl = 15621 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15622 if (LangOpts.ObjCRuntime.isFragile()) { 15623 // Case of ivar declared in an implementation. Context is that of its class. 15624 EnclosingContext = IMPDecl->getClassInterface(); 15625 assert(EnclosingContext && "Implementation has no class interface!"); 15626 } 15627 else 15628 EnclosingContext = EnclosingDecl; 15629 } else { 15630 if (ObjCCategoryDecl *CDecl = 15631 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15632 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15633 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15634 return nullptr; 15635 } 15636 } 15637 EnclosingContext = EnclosingDecl; 15638 } 15639 15640 // Construct the decl. 15641 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15642 DeclStart, Loc, II, T, 15643 TInfo, ac, (Expr *)BitfieldWidth); 15644 15645 if (II) { 15646 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15647 ForVisibleRedeclaration); 15648 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15649 && !isa<TagDecl>(PrevDecl)) { 15650 Diag(Loc, diag::err_duplicate_member) << II; 15651 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15652 NewID->setInvalidDecl(); 15653 } 15654 } 15655 15656 // Process attributes attached to the ivar. 15657 ProcessDeclAttributes(S, NewID, D); 15658 15659 if (D.isInvalidType()) 15660 NewID->setInvalidDecl(); 15661 15662 // In ARC, infer 'retaining' for ivars of retainable type. 15663 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15664 NewID->setInvalidDecl(); 15665 15666 if (D.getDeclSpec().isModulePrivateSpecified()) 15667 NewID->setModulePrivate(); 15668 15669 if (II) { 15670 // FIXME: When interfaces are DeclContexts, we'll need to add 15671 // these to the interface. 15672 S->AddDecl(NewID); 15673 IdResolver.AddDecl(NewID); 15674 } 15675 15676 if (LangOpts.ObjCRuntime.isNonFragile() && 15677 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15678 Diag(Loc, diag::warn_ivars_in_interface); 15679 15680 return NewID; 15681 } 15682 15683 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15684 /// class and class extensions. For every class \@interface and class 15685 /// extension \@interface, if the last ivar is a bitfield of any type, 15686 /// then add an implicit `char :0` ivar to the end of that interface. 15687 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15688 SmallVectorImpl<Decl *> &AllIvarDecls) { 15689 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15690 return; 15691 15692 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15693 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15694 15695 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15696 return; 15697 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15698 if (!ID) { 15699 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15700 if (!CD->IsClassExtension()) 15701 return; 15702 } 15703 // No need to add this to end of @implementation. 15704 else 15705 return; 15706 } 15707 // All conditions are met. Add a new bitfield to the tail end of ivars. 15708 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15709 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15710 15711 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15712 DeclLoc, DeclLoc, nullptr, 15713 Context.CharTy, 15714 Context.getTrivialTypeSourceInfo(Context.CharTy, 15715 DeclLoc), 15716 ObjCIvarDecl::Private, BW, 15717 true); 15718 AllIvarDecls.push_back(Ivar); 15719 } 15720 15721 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15722 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15723 SourceLocation RBrac, 15724 const ParsedAttributesView &Attrs) { 15725 assert(EnclosingDecl && "missing record or interface decl"); 15726 15727 // If this is an Objective-C @implementation or category and we have 15728 // new fields here we should reset the layout of the interface since 15729 // it will now change. 15730 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15731 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15732 switch (DC->getKind()) { 15733 default: break; 15734 case Decl::ObjCCategory: 15735 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15736 break; 15737 case Decl::ObjCImplementation: 15738 Context. 15739 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15740 break; 15741 } 15742 } 15743 15744 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15745 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 15746 15747 // Start counting up the number of named members; make sure to include 15748 // members of anonymous structs and unions in the total. 15749 unsigned NumNamedMembers = 0; 15750 if (Record) { 15751 for (const auto *I : Record->decls()) { 15752 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15753 if (IFD->getDeclName()) 15754 ++NumNamedMembers; 15755 } 15756 } 15757 15758 // Verify that all the fields are okay. 15759 SmallVector<FieldDecl*, 32> RecFields; 15760 15761 bool ObjCFieldLifetimeErrReported = false; 15762 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15763 i != end; ++i) { 15764 FieldDecl *FD = cast<FieldDecl>(*i); 15765 15766 // Get the type for the field. 15767 const Type *FDTy = FD->getType().getTypePtr(); 15768 15769 if (!FD->isAnonymousStructOrUnion()) { 15770 // Remember all fields written by the user. 15771 RecFields.push_back(FD); 15772 } 15773 15774 // If the field is already invalid for some reason, don't emit more 15775 // diagnostics about it. 15776 if (FD->isInvalidDecl()) { 15777 EnclosingDecl->setInvalidDecl(); 15778 continue; 15779 } 15780 15781 // C99 6.7.2.1p2: 15782 // A structure or union shall not contain a member with 15783 // incomplete or function type (hence, a structure shall not 15784 // contain an instance of itself, but may contain a pointer to 15785 // an instance of itself), except that the last member of a 15786 // structure with more than one named member may have incomplete 15787 // array type; such a structure (and any union containing, 15788 // possibly recursively, a member that is such a structure) 15789 // shall not be a member of a structure or an element of an 15790 // array. 15791 bool IsLastField = (i + 1 == Fields.end()); 15792 if (FDTy->isFunctionType()) { 15793 // Field declared as a function. 15794 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15795 << FD->getDeclName(); 15796 FD->setInvalidDecl(); 15797 EnclosingDecl->setInvalidDecl(); 15798 continue; 15799 } else if (FDTy->isIncompleteArrayType() && 15800 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15801 if (Record) { 15802 // Flexible array member. 15803 // Microsoft and g++ is more permissive regarding flexible array. 15804 // It will accept flexible array in union and also 15805 // as the sole element of a struct/class. 15806 unsigned DiagID = 0; 15807 if (!Record->isUnion() && !IsLastField) { 15808 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15809 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15810 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15811 FD->setInvalidDecl(); 15812 EnclosingDecl->setInvalidDecl(); 15813 continue; 15814 } else if (Record->isUnion()) 15815 DiagID = getLangOpts().MicrosoftExt 15816 ? diag::ext_flexible_array_union_ms 15817 : getLangOpts().CPlusPlus 15818 ? diag::ext_flexible_array_union_gnu 15819 : diag::err_flexible_array_union; 15820 else if (NumNamedMembers < 1) 15821 DiagID = getLangOpts().MicrosoftExt 15822 ? diag::ext_flexible_array_empty_aggregate_ms 15823 : getLangOpts().CPlusPlus 15824 ? diag::ext_flexible_array_empty_aggregate_gnu 15825 : diag::err_flexible_array_empty_aggregate; 15826 15827 if (DiagID) 15828 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15829 << Record->getTagKind(); 15830 // While the layout of types that contain virtual bases is not specified 15831 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15832 // virtual bases after the derived members. This would make a flexible 15833 // array member declared at the end of an object not adjacent to the end 15834 // of the type. 15835 if (CXXRecord && CXXRecord->getNumVBases() != 0) 15836 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15837 << FD->getDeclName() << Record->getTagKind(); 15838 if (!getLangOpts().C99) 15839 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15840 << FD->getDeclName() << Record->getTagKind(); 15841 15842 // If the element type has a non-trivial destructor, we would not 15843 // implicitly destroy the elements, so disallow it for now. 15844 // 15845 // FIXME: GCC allows this. We should probably either implicitly delete 15846 // the destructor of the containing class, or just allow this. 15847 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15848 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15849 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15850 << FD->getDeclName() << FD->getType(); 15851 FD->setInvalidDecl(); 15852 EnclosingDecl->setInvalidDecl(); 15853 continue; 15854 } 15855 // Okay, we have a legal flexible array member at the end of the struct. 15856 Record->setHasFlexibleArrayMember(true); 15857 } else { 15858 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15859 // unless they are followed by another ivar. That check is done 15860 // elsewhere, after synthesized ivars are known. 15861 } 15862 } else if (!FDTy->isDependentType() && 15863 RequireCompleteType(FD->getLocation(), FD->getType(), 15864 diag::err_field_incomplete)) { 15865 // Incomplete type 15866 FD->setInvalidDecl(); 15867 EnclosingDecl->setInvalidDecl(); 15868 continue; 15869 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15870 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15871 // A type which contains a flexible array member is considered to be a 15872 // flexible array member. 15873 Record->setHasFlexibleArrayMember(true); 15874 if (!Record->isUnion()) { 15875 // If this is a struct/class and this is not the last element, reject 15876 // it. Note that GCC supports variable sized arrays in the middle of 15877 // structures. 15878 if (!IsLastField) 15879 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15880 << FD->getDeclName() << FD->getType(); 15881 else { 15882 // We support flexible arrays at the end of structs in 15883 // other structs as an extension. 15884 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15885 << FD->getDeclName(); 15886 } 15887 } 15888 } 15889 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15890 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15891 diag::err_abstract_type_in_decl, 15892 AbstractIvarType)) { 15893 // Ivars can not have abstract class types 15894 FD->setInvalidDecl(); 15895 } 15896 if (Record && FDTTy->getDecl()->hasObjectMember()) 15897 Record->setHasObjectMember(true); 15898 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15899 Record->setHasVolatileMember(true); 15900 } else if (FDTy->isObjCObjectType()) { 15901 /// A field cannot be an Objective-c object 15902 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15903 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15904 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15905 FD->setType(T); 15906 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15907 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { 15908 // It's an error in ARC or Weak if a field has lifetime. 15909 // We don't want to report this in a system header, though, 15910 // so we just make the field unavailable. 15911 // FIXME: that's really not sufficient; we need to make the type 15912 // itself invalid to, say, initialize or copy. 15913 QualType T = FD->getType(); 15914 if (T.hasNonTrivialObjCLifetime()) { 15915 SourceLocation loc = FD->getLocation(); 15916 if (getSourceManager().isInSystemHeader(loc)) { 15917 if (!FD->hasAttr<UnavailableAttr>()) { 15918 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15919 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15920 } 15921 } else { 15922 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15923 << T->isBlockPointerType() << Record->getTagKind(); 15924 } 15925 ObjCFieldLifetimeErrReported = true; 15926 } 15927 } else if (getLangOpts().ObjC && 15928 getLangOpts().getGC() != LangOptions::NonGC && 15929 Record && !Record->hasObjectMember()) { 15930 if (FD->getType()->isObjCObjectPointerType() || 15931 FD->getType().isObjCGCStrong()) 15932 Record->setHasObjectMember(true); 15933 else if (Context.getAsArrayType(FD->getType())) { 15934 QualType BaseType = Context.getBaseElementType(FD->getType()); 15935 if (BaseType->isRecordType() && 15936 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15937 Record->setHasObjectMember(true); 15938 else if (BaseType->isObjCObjectPointerType() || 15939 BaseType.isObjCGCStrong()) 15940 Record->setHasObjectMember(true); 15941 } 15942 } 15943 15944 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 15945 QualType FT = FD->getType(); 15946 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 15947 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 15948 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 15949 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 15950 Record->setNonTrivialToPrimitiveCopy(true); 15951 if (FT.isDestructedType()) { 15952 Record->setNonTrivialToPrimitiveDestroy(true); 15953 Record->setParamDestroyedInCallee(true); 15954 } 15955 15956 if (const auto *RT = FT->getAs<RecordType>()) { 15957 if (RT->getDecl()->getArgPassingRestrictions() == 15958 RecordDecl::APK_CanNeverPassInRegs) 15959 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15960 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 15961 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15962 } 15963 15964 if (Record && FD->getType().isVolatileQualified()) 15965 Record->setHasVolatileMember(true); 15966 // Keep track of the number of named members. 15967 if (FD->getIdentifier()) 15968 ++NumNamedMembers; 15969 } 15970 15971 // Okay, we successfully defined 'Record'. 15972 if (Record) { 15973 bool Completed = false; 15974 if (CXXRecord) { 15975 if (!CXXRecord->isInvalidDecl()) { 15976 // Set access bits correctly on the directly-declared conversions. 15977 for (CXXRecordDecl::conversion_iterator 15978 I = CXXRecord->conversion_begin(), 15979 E = CXXRecord->conversion_end(); I != E; ++I) 15980 I.setAccess((*I)->getAccess()); 15981 } 15982 15983 if (!CXXRecord->isDependentType()) { 15984 // Add any implicitly-declared members to this class. 15985 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15986 15987 if (!CXXRecord->isInvalidDecl()) { 15988 // If we have virtual base classes, we may end up finding multiple 15989 // final overriders for a given virtual function. Check for this 15990 // problem now. 15991 if (CXXRecord->getNumVBases()) { 15992 CXXFinalOverriderMap FinalOverriders; 15993 CXXRecord->getFinalOverriders(FinalOverriders); 15994 15995 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15996 MEnd = FinalOverriders.end(); 15997 M != MEnd; ++M) { 15998 for (OverridingMethods::iterator SO = M->second.begin(), 15999 SOEnd = M->second.end(); 16000 SO != SOEnd; ++SO) { 16001 assert(SO->second.size() > 0 && 16002 "Virtual function without overriding functions?"); 16003 if (SO->second.size() == 1) 16004 continue; 16005 16006 // C++ [class.virtual]p2: 16007 // In a derived class, if a virtual member function of a base 16008 // class subobject has more than one final overrider the 16009 // program is ill-formed. 16010 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 16011 << (const NamedDecl *)M->first << Record; 16012 Diag(M->first->getLocation(), 16013 diag::note_overridden_virtual_function); 16014 for (OverridingMethods::overriding_iterator 16015 OM = SO->second.begin(), 16016 OMEnd = SO->second.end(); 16017 OM != OMEnd; ++OM) 16018 Diag(OM->Method->getLocation(), diag::note_final_overrider) 16019 << (const NamedDecl *)M->first << OM->Method->getParent(); 16020 16021 Record->setInvalidDecl(); 16022 } 16023 } 16024 CXXRecord->completeDefinition(&FinalOverriders); 16025 Completed = true; 16026 } 16027 } 16028 } 16029 } 16030 16031 if (!Completed) 16032 Record->completeDefinition(); 16033 16034 // Handle attributes before checking the layout. 16035 ProcessDeclAttributeList(S, Record, Attrs); 16036 16037 // We may have deferred checking for a deleted destructor. Check now. 16038 if (CXXRecord) { 16039 auto *Dtor = CXXRecord->getDestructor(); 16040 if (Dtor && Dtor->isImplicit() && 16041 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 16042 CXXRecord->setImplicitDestructorIsDeleted(); 16043 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 16044 } 16045 } 16046 16047 if (Record->hasAttrs()) { 16048 CheckAlignasUnderalignment(Record); 16049 16050 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 16051 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 16052 IA->getRange(), IA->getBestCase(), 16053 IA->getSemanticSpelling()); 16054 } 16055 16056 // Check if the structure/union declaration is a type that can have zero 16057 // size in C. For C this is a language extension, for C++ it may cause 16058 // compatibility problems. 16059 bool CheckForZeroSize; 16060 if (!getLangOpts().CPlusPlus) { 16061 CheckForZeroSize = true; 16062 } else { 16063 // For C++ filter out types that cannot be referenced in C code. 16064 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 16065 CheckForZeroSize = 16066 CXXRecord->getLexicalDeclContext()->isExternCContext() && 16067 !CXXRecord->isDependentType() && 16068 CXXRecord->isCLike(); 16069 } 16070 if (CheckForZeroSize) { 16071 bool ZeroSize = true; 16072 bool IsEmpty = true; 16073 unsigned NonBitFields = 0; 16074 for (RecordDecl::field_iterator I = Record->field_begin(), 16075 E = Record->field_end(); 16076 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 16077 IsEmpty = false; 16078 if (I->isUnnamedBitfield()) { 16079 if (!I->isZeroLengthBitField(Context)) 16080 ZeroSize = false; 16081 } else { 16082 ++NonBitFields; 16083 QualType FieldType = I->getType(); 16084 if (FieldType->isIncompleteType() || 16085 !Context.getTypeSizeInChars(FieldType).isZero()) 16086 ZeroSize = false; 16087 } 16088 } 16089 16090 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 16091 // allowed in C++, but warn if its declaration is inside 16092 // extern "C" block. 16093 if (ZeroSize) { 16094 Diag(RecLoc, getLangOpts().CPlusPlus ? 16095 diag::warn_zero_size_struct_union_in_extern_c : 16096 diag::warn_zero_size_struct_union_compat) 16097 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 16098 } 16099 16100 // Structs without named members are extension in C (C99 6.7.2.1p7), 16101 // but are accepted by GCC. 16102 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 16103 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 16104 diag::ext_no_named_members_in_struct_union) 16105 << Record->isUnion(); 16106 } 16107 } 16108 } else { 16109 ObjCIvarDecl **ClsFields = 16110 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 16111 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 16112 ID->setEndOfDefinitionLoc(RBrac); 16113 // Add ivar's to class's DeclContext. 16114 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16115 ClsFields[i]->setLexicalDeclContext(ID); 16116 ID->addDecl(ClsFields[i]); 16117 } 16118 // Must enforce the rule that ivars in the base classes may not be 16119 // duplicates. 16120 if (ID->getSuperClass()) 16121 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 16122 } else if (ObjCImplementationDecl *IMPDecl = 16123 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16124 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 16125 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 16126 // Ivar declared in @implementation never belongs to the implementation. 16127 // Only it is in implementation's lexical context. 16128 ClsFields[I]->setLexicalDeclContext(IMPDecl); 16129 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 16130 IMPDecl->setIvarLBraceLoc(LBrac); 16131 IMPDecl->setIvarRBraceLoc(RBrac); 16132 } else if (ObjCCategoryDecl *CDecl = 16133 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16134 // case of ivars in class extension; all other cases have been 16135 // reported as errors elsewhere. 16136 // FIXME. Class extension does not have a LocEnd field. 16137 // CDecl->setLocEnd(RBrac); 16138 // Add ivar's to class extension's DeclContext. 16139 // Diagnose redeclaration of private ivars. 16140 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 16141 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 16142 if (IDecl) { 16143 if (const ObjCIvarDecl *ClsIvar = 16144 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 16145 Diag(ClsFields[i]->getLocation(), 16146 diag::err_duplicate_ivar_declaration); 16147 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 16148 continue; 16149 } 16150 for (const auto *Ext : IDecl->known_extensions()) { 16151 if (const ObjCIvarDecl *ClsExtIvar 16152 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 16153 Diag(ClsFields[i]->getLocation(), 16154 diag::err_duplicate_ivar_declaration); 16155 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 16156 continue; 16157 } 16158 } 16159 } 16160 ClsFields[i]->setLexicalDeclContext(CDecl); 16161 CDecl->addDecl(ClsFields[i]); 16162 } 16163 CDecl->setIvarLBraceLoc(LBrac); 16164 CDecl->setIvarRBraceLoc(RBrac); 16165 } 16166 } 16167 } 16168 16169 /// Determine whether the given integral value is representable within 16170 /// the given type T. 16171 static bool isRepresentableIntegerValue(ASTContext &Context, 16172 llvm::APSInt &Value, 16173 QualType T) { 16174 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 16175 "Integral type required!"); 16176 unsigned BitWidth = Context.getIntWidth(T); 16177 16178 if (Value.isUnsigned() || Value.isNonNegative()) { 16179 if (T->isSignedIntegerOrEnumerationType()) 16180 --BitWidth; 16181 return Value.getActiveBits() <= BitWidth; 16182 } 16183 return Value.getMinSignedBits() <= BitWidth; 16184 } 16185 16186 // Given an integral type, return the next larger integral type 16187 // (or a NULL type of no such type exists). 16188 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 16189 // FIXME: Int128/UInt128 support, which also needs to be introduced into 16190 // enum checking below. 16191 assert((T->isIntegralType(Context) || 16192 T->isEnumeralType()) && "Integral type required!"); 16193 const unsigned NumTypes = 4; 16194 QualType SignedIntegralTypes[NumTypes] = { 16195 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 16196 }; 16197 QualType UnsignedIntegralTypes[NumTypes] = { 16198 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 16199 Context.UnsignedLongLongTy 16200 }; 16201 16202 unsigned BitWidth = Context.getTypeSize(T); 16203 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 16204 : UnsignedIntegralTypes; 16205 for (unsigned I = 0; I != NumTypes; ++I) 16206 if (Context.getTypeSize(Types[I]) > BitWidth) 16207 return Types[I]; 16208 16209 return QualType(); 16210 } 16211 16212 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 16213 EnumConstantDecl *LastEnumConst, 16214 SourceLocation IdLoc, 16215 IdentifierInfo *Id, 16216 Expr *Val) { 16217 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16218 llvm::APSInt EnumVal(IntWidth); 16219 QualType EltTy; 16220 16221 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 16222 Val = nullptr; 16223 16224 if (Val) 16225 Val = DefaultLvalueConversion(Val).get(); 16226 16227 if (Val) { 16228 if (Enum->isDependentType() || Val->isTypeDependent()) 16229 EltTy = Context.DependentTy; 16230 else { 16231 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 16232 !getLangOpts().MSVCCompat) { 16233 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 16234 // constant-expression in the enumerator-definition shall be a converted 16235 // constant expression of the underlying type. 16236 EltTy = Enum->getIntegerType(); 16237 ExprResult Converted = 16238 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 16239 CCEK_Enumerator); 16240 if (Converted.isInvalid()) 16241 Val = nullptr; 16242 else 16243 Val = Converted.get(); 16244 } else if (!Val->isValueDependent() && 16245 !(Val = VerifyIntegerConstantExpression(Val, 16246 &EnumVal).get())) { 16247 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 16248 } else { 16249 if (Enum->isComplete()) { 16250 EltTy = Enum->getIntegerType(); 16251 16252 // In Obj-C and Microsoft mode, require the enumeration value to be 16253 // representable in the underlying type of the enumeration. In C++11, 16254 // we perform a non-narrowing conversion as part of converted constant 16255 // expression checking. 16256 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16257 if (getLangOpts().MSVCCompat) { 16258 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 16259 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 16260 } else 16261 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 16262 } else 16263 Val = ImpCastExprToType(Val, EltTy, 16264 EltTy->isBooleanType() ? 16265 CK_IntegralToBoolean : CK_IntegralCast) 16266 .get(); 16267 } else if (getLangOpts().CPlusPlus) { 16268 // C++11 [dcl.enum]p5: 16269 // If the underlying type is not fixed, the type of each enumerator 16270 // is the type of its initializing value: 16271 // - If an initializer is specified for an enumerator, the 16272 // initializing value has the same type as the expression. 16273 EltTy = Val->getType(); 16274 } else { 16275 // C99 6.7.2.2p2: 16276 // The expression that defines the value of an enumeration constant 16277 // shall be an integer constant expression that has a value 16278 // representable as an int. 16279 16280 // Complain if the value is not representable in an int. 16281 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 16282 Diag(IdLoc, diag::ext_enum_value_not_int) 16283 << EnumVal.toString(10) << Val->getSourceRange() 16284 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 16285 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 16286 // Force the type of the expression to 'int'. 16287 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 16288 } 16289 EltTy = Val->getType(); 16290 } 16291 } 16292 } 16293 } 16294 16295 if (!Val) { 16296 if (Enum->isDependentType()) 16297 EltTy = Context.DependentTy; 16298 else if (!LastEnumConst) { 16299 // C++0x [dcl.enum]p5: 16300 // If the underlying type is not fixed, the type of each enumerator 16301 // is the type of its initializing value: 16302 // - If no initializer is specified for the first enumerator, the 16303 // initializing value has an unspecified integral type. 16304 // 16305 // GCC uses 'int' for its unspecified integral type, as does 16306 // C99 6.7.2.2p3. 16307 if (Enum->isFixed()) { 16308 EltTy = Enum->getIntegerType(); 16309 } 16310 else { 16311 EltTy = Context.IntTy; 16312 } 16313 } else { 16314 // Assign the last value + 1. 16315 EnumVal = LastEnumConst->getInitVal(); 16316 ++EnumVal; 16317 EltTy = LastEnumConst->getType(); 16318 16319 // Check for overflow on increment. 16320 if (EnumVal < LastEnumConst->getInitVal()) { 16321 // C++0x [dcl.enum]p5: 16322 // If the underlying type is not fixed, the type of each enumerator 16323 // is the type of its initializing value: 16324 // 16325 // - Otherwise the type of the initializing value is the same as 16326 // the type of the initializing value of the preceding enumerator 16327 // unless the incremented value is not representable in that type, 16328 // in which case the type is an unspecified integral type 16329 // sufficient to contain the incremented value. If no such type 16330 // exists, the program is ill-formed. 16331 QualType T = getNextLargerIntegralType(Context, EltTy); 16332 if (T.isNull() || Enum->isFixed()) { 16333 // There is no integral type larger enough to represent this 16334 // value. Complain, then allow the value to wrap around. 16335 EnumVal = LastEnumConst->getInitVal(); 16336 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 16337 ++EnumVal; 16338 if (Enum->isFixed()) 16339 // When the underlying type is fixed, this is ill-formed. 16340 Diag(IdLoc, diag::err_enumerator_wrapped) 16341 << EnumVal.toString(10) 16342 << EltTy; 16343 else 16344 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 16345 << EnumVal.toString(10); 16346 } else { 16347 EltTy = T; 16348 } 16349 16350 // Retrieve the last enumerator's value, extent that type to the 16351 // type that is supposed to be large enough to represent the incremented 16352 // value, then increment. 16353 EnumVal = LastEnumConst->getInitVal(); 16354 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16355 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 16356 ++EnumVal; 16357 16358 // If we're not in C++, diagnose the overflow of enumerator values, 16359 // which in C99 means that the enumerator value is not representable in 16360 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 16361 // permits enumerator values that are representable in some larger 16362 // integral type. 16363 if (!getLangOpts().CPlusPlus && !T.isNull()) 16364 Diag(IdLoc, diag::warn_enum_value_overflow); 16365 } else if (!getLangOpts().CPlusPlus && 16366 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 16367 // Enforce C99 6.7.2.2p2 even when we compute the next value. 16368 Diag(IdLoc, diag::ext_enum_value_not_int) 16369 << EnumVal.toString(10) << 1; 16370 } 16371 } 16372 } 16373 16374 if (!EltTy->isDependentType()) { 16375 // Make the enumerator value match the signedness and size of the 16376 // enumerator's type. 16377 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 16378 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 16379 } 16380 16381 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 16382 Val, EnumVal); 16383 } 16384 16385 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 16386 SourceLocation IILoc) { 16387 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 16388 !getLangOpts().CPlusPlus) 16389 return SkipBodyInfo(); 16390 16391 // We have an anonymous enum definition. Look up the first enumerator to 16392 // determine if we should merge the definition with an existing one and 16393 // skip the body. 16394 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 16395 forRedeclarationInCurContext()); 16396 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 16397 if (!PrevECD) 16398 return SkipBodyInfo(); 16399 16400 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 16401 NamedDecl *Hidden; 16402 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 16403 SkipBodyInfo Skip; 16404 Skip.Previous = Hidden; 16405 return Skip; 16406 } 16407 16408 return SkipBodyInfo(); 16409 } 16410 16411 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 16412 SourceLocation IdLoc, IdentifierInfo *Id, 16413 const ParsedAttributesView &Attrs, 16414 SourceLocation EqualLoc, Expr *Val) { 16415 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 16416 EnumConstantDecl *LastEnumConst = 16417 cast_or_null<EnumConstantDecl>(lastEnumConst); 16418 16419 // The scope passed in may not be a decl scope. Zip up the scope tree until 16420 // we find one that is. 16421 S = getNonFieldDeclScope(S); 16422 16423 // Verify that there isn't already something declared with this name in this 16424 // scope. 16425 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 16426 LookupName(R, S); 16427 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 16428 16429 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16430 // Maybe we will complain about the shadowed template parameter. 16431 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 16432 // Just pretend that we didn't see the previous declaration. 16433 PrevDecl = nullptr; 16434 } 16435 16436 // C++ [class.mem]p15: 16437 // If T is the name of a class, then each of the following shall have a name 16438 // different from T: 16439 // - every enumerator of every member of class T that is an unscoped 16440 // enumerated type 16441 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 16442 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 16443 DeclarationNameInfo(Id, IdLoc)); 16444 16445 EnumConstantDecl *New = 16446 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 16447 if (!New) 16448 return nullptr; 16449 16450 if (PrevDecl) { 16451 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 16452 // Check for other kinds of shadowing not already handled. 16453 CheckShadow(New, PrevDecl, R); 16454 } 16455 16456 // When in C++, we may get a TagDecl with the same name; in this case the 16457 // enum constant will 'hide' the tag. 16458 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 16459 "Received TagDecl when not in C++!"); 16460 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 16461 if (isa<EnumConstantDecl>(PrevDecl)) 16462 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 16463 else 16464 Diag(IdLoc, diag::err_redefinition) << Id; 16465 notePreviousDefinition(PrevDecl, IdLoc); 16466 return nullptr; 16467 } 16468 } 16469 16470 // Process attributes. 16471 ProcessDeclAttributeList(S, New, Attrs); 16472 AddPragmaAttributes(S, New); 16473 16474 // Register this decl in the current scope stack. 16475 New->setAccess(TheEnumDecl->getAccess()); 16476 PushOnScopeChains(New, S); 16477 16478 ActOnDocumentableDecl(New); 16479 16480 return New; 16481 } 16482 16483 // Returns true when the enum initial expression does not trigger the 16484 // duplicate enum warning. A few common cases are exempted as follows: 16485 // Element2 = Element1 16486 // Element2 = Element1 + 1 16487 // Element2 = Element1 - 1 16488 // Where Element2 and Element1 are from the same enum. 16489 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16490 Expr *InitExpr = ECD->getInitExpr(); 16491 if (!InitExpr) 16492 return true; 16493 InitExpr = InitExpr->IgnoreImpCasts(); 16494 16495 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16496 if (!BO->isAdditiveOp()) 16497 return true; 16498 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16499 if (!IL) 16500 return true; 16501 if (IL->getValue() != 1) 16502 return true; 16503 16504 InitExpr = BO->getLHS(); 16505 } 16506 16507 // This checks if the elements are from the same enum. 16508 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16509 if (!DRE) 16510 return true; 16511 16512 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16513 if (!EnumConstant) 16514 return true; 16515 16516 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16517 Enum) 16518 return true; 16519 16520 return false; 16521 } 16522 16523 // Emits a warning when an element is implicitly set a value that 16524 // a previous element has already been set to. 16525 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16526 EnumDecl *Enum, QualType EnumType) { 16527 // Avoid anonymous enums 16528 if (!Enum->getIdentifier()) 16529 return; 16530 16531 // Only check for small enums. 16532 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16533 return; 16534 16535 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16536 return; 16537 16538 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16539 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16540 16541 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16542 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 16543 16544 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16545 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16546 llvm::APSInt Val = D->getInitVal(); 16547 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16548 }; 16549 16550 DuplicatesVector DupVector; 16551 ValueToVectorMap EnumMap; 16552 16553 // Populate the EnumMap with all values represented by enum constants without 16554 // an initializer. 16555 for (auto *Element : Elements) { 16556 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16557 16558 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16559 // this constant. Skip this enum since it may be ill-formed. 16560 if (!ECD) { 16561 return; 16562 } 16563 16564 // Constants with initalizers are handled in the next loop. 16565 if (ECD->getInitExpr()) 16566 continue; 16567 16568 // Duplicate values are handled in the next loop. 16569 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16570 } 16571 16572 if (EnumMap.size() == 0) 16573 return; 16574 16575 // Create vectors for any values that has duplicates. 16576 for (auto *Element : Elements) { 16577 // The last loop returned if any constant was null. 16578 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16579 if (!ValidDuplicateEnum(ECD, Enum)) 16580 continue; 16581 16582 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16583 if (Iter == EnumMap.end()) 16584 continue; 16585 16586 DeclOrVector& Entry = Iter->second; 16587 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16588 // Ensure constants are different. 16589 if (D == ECD) 16590 continue; 16591 16592 // Create new vector and push values onto it. 16593 auto Vec = llvm::make_unique<ECDVector>(); 16594 Vec->push_back(D); 16595 Vec->push_back(ECD); 16596 16597 // Update entry to point to the duplicates vector. 16598 Entry = Vec.get(); 16599 16600 // Store the vector somewhere we can consult later for quick emission of 16601 // diagnostics. 16602 DupVector.emplace_back(std::move(Vec)); 16603 continue; 16604 } 16605 16606 ECDVector *Vec = Entry.get<ECDVector*>(); 16607 // Make sure constants are not added more than once. 16608 if (*Vec->begin() == ECD) 16609 continue; 16610 16611 Vec->push_back(ECD); 16612 } 16613 16614 // Emit diagnostics. 16615 for (const auto &Vec : DupVector) { 16616 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16617 16618 // Emit warning for one enum constant. 16619 auto *FirstECD = Vec->front(); 16620 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16621 << FirstECD << FirstECD->getInitVal().toString(10) 16622 << FirstECD->getSourceRange(); 16623 16624 // Emit one note for each of the remaining enum constants with 16625 // the same value. 16626 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16627 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16628 << ECD << ECD->getInitVal().toString(10) 16629 << ECD->getSourceRange(); 16630 } 16631 } 16632 16633 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16634 bool AllowMask) const { 16635 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16636 assert(ED->isCompleteDefinition() && "expected enum definition"); 16637 16638 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16639 llvm::APInt &FlagBits = R.first->second; 16640 16641 if (R.second) { 16642 for (auto *E : ED->enumerators()) { 16643 const auto &EVal = E->getInitVal(); 16644 // Only single-bit enumerators introduce new flag values. 16645 if (EVal.isPowerOf2()) 16646 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16647 } 16648 } 16649 16650 // A value is in a flag enum if either its bits are a subset of the enum's 16651 // flag bits (the first condition) or we are allowing masks and the same is 16652 // true of its complement (the second condition). When masks are allowed, we 16653 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16654 // 16655 // While it's true that any value could be used as a mask, the assumption is 16656 // that a mask will have all of the insignificant bits set. Anything else is 16657 // likely a logic error. 16658 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16659 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16660 } 16661 16662 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16663 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 16664 const ParsedAttributesView &Attrs) { 16665 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16666 QualType EnumType = Context.getTypeDeclType(Enum); 16667 16668 ProcessDeclAttributeList(S, Enum, Attrs); 16669 16670 if (Enum->isDependentType()) { 16671 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16672 EnumConstantDecl *ECD = 16673 cast_or_null<EnumConstantDecl>(Elements[i]); 16674 if (!ECD) continue; 16675 16676 ECD->setType(EnumType); 16677 } 16678 16679 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16680 return; 16681 } 16682 16683 // TODO: If the result value doesn't fit in an int, it must be a long or long 16684 // long value. ISO C does not support this, but GCC does as an extension, 16685 // emit a warning. 16686 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16687 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16688 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16689 16690 // Verify that all the values are okay, compute the size of the values, and 16691 // reverse the list. 16692 unsigned NumNegativeBits = 0; 16693 unsigned NumPositiveBits = 0; 16694 16695 // Keep track of whether all elements have type int. 16696 bool AllElementsInt = true; 16697 16698 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16699 EnumConstantDecl *ECD = 16700 cast_or_null<EnumConstantDecl>(Elements[i]); 16701 if (!ECD) continue; // Already issued a diagnostic. 16702 16703 const llvm::APSInt &InitVal = ECD->getInitVal(); 16704 16705 // Keep track of the size of positive and negative values. 16706 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16707 NumPositiveBits = std::max(NumPositiveBits, 16708 (unsigned)InitVal.getActiveBits()); 16709 else 16710 NumNegativeBits = std::max(NumNegativeBits, 16711 (unsigned)InitVal.getMinSignedBits()); 16712 16713 // Keep track of whether every enum element has type int (very common). 16714 if (AllElementsInt) 16715 AllElementsInt = ECD->getType() == Context.IntTy; 16716 } 16717 16718 // Figure out the type that should be used for this enum. 16719 QualType BestType; 16720 unsigned BestWidth; 16721 16722 // C++0x N3000 [conv.prom]p3: 16723 // An rvalue of an unscoped enumeration type whose underlying 16724 // type is not fixed can be converted to an rvalue of the first 16725 // of the following types that can represent all the values of 16726 // the enumeration: int, unsigned int, long int, unsigned long 16727 // int, long long int, or unsigned long long int. 16728 // C99 6.4.4.3p2: 16729 // An identifier declared as an enumeration constant has type int. 16730 // The C99 rule is modified by a gcc extension 16731 QualType BestPromotionType; 16732 16733 bool Packed = Enum->hasAttr<PackedAttr>(); 16734 // -fshort-enums is the equivalent to specifying the packed attribute on all 16735 // enum definitions. 16736 if (LangOpts.ShortEnums) 16737 Packed = true; 16738 16739 // If the enum already has a type because it is fixed or dictated by the 16740 // target, promote that type instead of analyzing the enumerators. 16741 if (Enum->isComplete()) { 16742 BestType = Enum->getIntegerType(); 16743 if (BestType->isPromotableIntegerType()) 16744 BestPromotionType = Context.getPromotedIntegerType(BestType); 16745 else 16746 BestPromotionType = BestType; 16747 16748 BestWidth = Context.getIntWidth(BestType); 16749 } 16750 else if (NumNegativeBits) { 16751 // If there is a negative value, figure out the smallest integer type (of 16752 // int/long/longlong) that fits. 16753 // If it's packed, check also if it fits a char or a short. 16754 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16755 BestType = Context.SignedCharTy; 16756 BestWidth = CharWidth; 16757 } else if (Packed && NumNegativeBits <= ShortWidth && 16758 NumPositiveBits < ShortWidth) { 16759 BestType = Context.ShortTy; 16760 BestWidth = ShortWidth; 16761 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16762 BestType = Context.IntTy; 16763 BestWidth = IntWidth; 16764 } else { 16765 BestWidth = Context.getTargetInfo().getLongWidth(); 16766 16767 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16768 BestType = Context.LongTy; 16769 } else { 16770 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16771 16772 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16773 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16774 BestType = Context.LongLongTy; 16775 } 16776 } 16777 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16778 } else { 16779 // If there is no negative value, figure out the smallest type that fits 16780 // all of the enumerator values. 16781 // If it's packed, check also if it fits a char or a short. 16782 if (Packed && NumPositiveBits <= CharWidth) { 16783 BestType = Context.UnsignedCharTy; 16784 BestPromotionType = Context.IntTy; 16785 BestWidth = CharWidth; 16786 } else if (Packed && NumPositiveBits <= ShortWidth) { 16787 BestType = Context.UnsignedShortTy; 16788 BestPromotionType = Context.IntTy; 16789 BestWidth = ShortWidth; 16790 } else if (NumPositiveBits <= IntWidth) { 16791 BestType = Context.UnsignedIntTy; 16792 BestWidth = IntWidth; 16793 BestPromotionType 16794 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16795 ? Context.UnsignedIntTy : Context.IntTy; 16796 } else if (NumPositiveBits <= 16797 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16798 BestType = Context.UnsignedLongTy; 16799 BestPromotionType 16800 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16801 ? Context.UnsignedLongTy : Context.LongTy; 16802 } else { 16803 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16804 assert(NumPositiveBits <= BestWidth && 16805 "How could an initializer get larger than ULL?"); 16806 BestType = Context.UnsignedLongLongTy; 16807 BestPromotionType 16808 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16809 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16810 } 16811 } 16812 16813 // Loop over all of the enumerator constants, changing their types to match 16814 // the type of the enum if needed. 16815 for (auto *D : Elements) { 16816 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16817 if (!ECD) continue; // Already issued a diagnostic. 16818 16819 // Standard C says the enumerators have int type, but we allow, as an 16820 // extension, the enumerators to be larger than int size. If each 16821 // enumerator value fits in an int, type it as an int, otherwise type it the 16822 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16823 // that X has type 'int', not 'unsigned'. 16824 16825 // Determine whether the value fits into an int. 16826 llvm::APSInt InitVal = ECD->getInitVal(); 16827 16828 // If it fits into an integer type, force it. Otherwise force it to match 16829 // the enum decl type. 16830 QualType NewTy; 16831 unsigned NewWidth; 16832 bool NewSign; 16833 if (!getLangOpts().CPlusPlus && 16834 !Enum->isFixed() && 16835 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16836 NewTy = Context.IntTy; 16837 NewWidth = IntWidth; 16838 NewSign = true; 16839 } else if (ECD->getType() == BestType) { 16840 // Already the right type! 16841 if (getLangOpts().CPlusPlus) 16842 // C++ [dcl.enum]p4: Following the closing brace of an 16843 // enum-specifier, each enumerator has the type of its 16844 // enumeration. 16845 ECD->setType(EnumType); 16846 continue; 16847 } else { 16848 NewTy = BestType; 16849 NewWidth = BestWidth; 16850 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16851 } 16852 16853 // Adjust the APSInt value. 16854 InitVal = InitVal.extOrTrunc(NewWidth); 16855 InitVal.setIsSigned(NewSign); 16856 ECD->setInitVal(InitVal); 16857 16858 // Adjust the Expr initializer and type. 16859 if (ECD->getInitExpr() && 16860 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16861 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16862 CK_IntegralCast, 16863 ECD->getInitExpr(), 16864 /*base paths*/ nullptr, 16865 VK_RValue)); 16866 if (getLangOpts().CPlusPlus) 16867 // C++ [dcl.enum]p4: Following the closing brace of an 16868 // enum-specifier, each enumerator has the type of its 16869 // enumeration. 16870 ECD->setType(EnumType); 16871 else 16872 ECD->setType(NewTy); 16873 } 16874 16875 Enum->completeDefinition(BestType, BestPromotionType, 16876 NumPositiveBits, NumNegativeBits); 16877 16878 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16879 16880 if (Enum->isClosedFlag()) { 16881 for (Decl *D : Elements) { 16882 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16883 if (!ECD) continue; // Already issued a diagnostic. 16884 16885 llvm::APSInt InitVal = ECD->getInitVal(); 16886 if (InitVal != 0 && !InitVal.isPowerOf2() && 16887 !IsValueInFlagEnum(Enum, InitVal, true)) 16888 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16889 << ECD << Enum; 16890 } 16891 } 16892 16893 // Now that the enum type is defined, ensure it's not been underaligned. 16894 if (Enum->hasAttrs()) 16895 CheckAlignasUnderalignment(Enum); 16896 } 16897 16898 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16899 SourceLocation StartLoc, 16900 SourceLocation EndLoc) { 16901 StringLiteral *AsmString = cast<StringLiteral>(expr); 16902 16903 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16904 AsmString, StartLoc, 16905 EndLoc); 16906 CurContext->addDecl(New); 16907 return New; 16908 } 16909 16910 static void checkModuleImportContext(Sema &S, Module *M, 16911 SourceLocation ImportLoc, DeclContext *DC, 16912 bool FromInclude = false) { 16913 SourceLocation ExternCLoc; 16914 16915 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16916 switch (LSD->getLanguage()) { 16917 case LinkageSpecDecl::lang_c: 16918 if (ExternCLoc.isInvalid()) 16919 ExternCLoc = LSD->getBeginLoc(); 16920 break; 16921 case LinkageSpecDecl::lang_cxx: 16922 break; 16923 } 16924 DC = LSD->getParent(); 16925 } 16926 16927 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 16928 DC = DC->getParent(); 16929 16930 if (!isa<TranslationUnitDecl>(DC)) { 16931 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16932 ? diag::ext_module_import_not_at_top_level_noop 16933 : diag::err_module_import_not_at_top_level_fatal) 16934 << M->getFullModuleName() << DC; 16935 S.Diag(cast<Decl>(DC)->getBeginLoc(), 16936 diag::note_module_import_not_at_top_level) 16937 << DC; 16938 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16939 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16940 << M->getFullModuleName(); 16941 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16942 } 16943 } 16944 16945 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16946 SourceLocation ModuleLoc, 16947 ModuleDeclKind MDK, 16948 ModuleIdPath Path) { 16949 assert(getLangOpts().ModulesTS && 16950 "should only have module decl in modules TS"); 16951 16952 // A module implementation unit requires that we are not compiling a module 16953 // of any kind. A module interface unit requires that we are not compiling a 16954 // module map. 16955 switch (getLangOpts().getCompilingModule()) { 16956 case LangOptions::CMK_None: 16957 // It's OK to compile a module interface as a normal translation unit. 16958 break; 16959 16960 case LangOptions::CMK_ModuleInterface: 16961 if (MDK != ModuleDeclKind::Implementation) 16962 break; 16963 16964 // We were asked to compile a module interface unit but this is a module 16965 // implementation unit. That indicates the 'export' is missing. 16966 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16967 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16968 MDK = ModuleDeclKind::Interface; 16969 break; 16970 16971 case LangOptions::CMK_ModuleMap: 16972 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16973 return nullptr; 16974 16975 case LangOptions::CMK_HeaderModule: 16976 Diag(ModuleLoc, diag::err_module_decl_in_header_module); 16977 return nullptr; 16978 } 16979 16980 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16981 16982 // FIXME: Most of this work should be done by the preprocessor rather than 16983 // here, in order to support macro import. 16984 16985 // Only one module-declaration is permitted per source file. 16986 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16987 Diag(ModuleLoc, diag::err_module_redeclaration); 16988 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16989 diag::note_prev_module_declaration); 16990 return nullptr; 16991 } 16992 16993 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16994 // modules, the dots here are just another character that can appear in a 16995 // module name. 16996 std::string ModuleName; 16997 for (auto &Piece : Path) { 16998 if (!ModuleName.empty()) 16999 ModuleName += "."; 17000 ModuleName += Piece.first->getName(); 17001 } 17002 17003 // If a module name was explicitly specified on the command line, it must be 17004 // correct. 17005 if (!getLangOpts().CurrentModule.empty() && 17006 getLangOpts().CurrentModule != ModuleName) { 17007 Diag(Path.front().second, diag::err_current_module_name_mismatch) 17008 << SourceRange(Path.front().second, Path.back().second) 17009 << getLangOpts().CurrentModule; 17010 return nullptr; 17011 } 17012 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 17013 17014 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 17015 Module *Mod; 17016 17017 switch (MDK) { 17018 case ModuleDeclKind::Interface: { 17019 // We can't have parsed or imported a definition of this module or parsed a 17020 // module map defining it already. 17021 if (auto *M = Map.findModule(ModuleName)) { 17022 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 17023 if (M->DefinitionLoc.isValid()) 17024 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 17025 else if (const auto *FE = M->getASTFile()) 17026 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 17027 << FE->getName(); 17028 Mod = M; 17029 break; 17030 } 17031 17032 // Create a Module for the module that we're defining. 17033 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 17034 ModuleScopes.front().Module); 17035 assert(Mod && "module creation should not fail"); 17036 break; 17037 } 17038 17039 case ModuleDeclKind::Partition: 17040 // FIXME: Check we are in a submodule of the named module. 17041 return nullptr; 17042 17043 case ModuleDeclKind::Implementation: 17044 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 17045 PP.getIdentifierInfo(ModuleName), Path[0].second); 17046 Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc}, 17047 Module::AllVisible, 17048 /*IsIncludeDirective=*/false); 17049 if (!Mod) { 17050 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 17051 // Create an empty module interface unit for error recovery. 17052 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 17053 ModuleScopes.front().Module); 17054 } 17055 break; 17056 } 17057 17058 // Switch from the global module to the named module. 17059 ModuleScopes.back().Module = Mod; 17060 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 17061 VisibleModules.setVisible(Mod, ModuleLoc); 17062 17063 // From now on, we have an owning module for all declarations we see. 17064 // However, those declarations are module-private unless explicitly 17065 // exported. 17066 auto *TU = Context.getTranslationUnitDecl(); 17067 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 17068 TU->setLocalOwningModule(Mod); 17069 17070 // FIXME: Create a ModuleDecl. 17071 return nullptr; 17072 } 17073 17074 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 17075 SourceLocation ImportLoc, 17076 ModuleIdPath Path) { 17077 // Flatten the module path for a Modules TS module name. 17078 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc; 17079 if (getLangOpts().ModulesTS) { 17080 std::string ModuleName; 17081 for (auto &Piece : Path) { 17082 if (!ModuleName.empty()) 17083 ModuleName += "."; 17084 ModuleName += Piece.first->getName(); 17085 } 17086 ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second}; 17087 Path = ModuleIdPath(ModuleNameLoc); 17088 } 17089 17090 Module *Mod = 17091 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 17092 /*IsIncludeDirective=*/false); 17093 if (!Mod) 17094 return true; 17095 17096 VisibleModules.setVisible(Mod, ImportLoc); 17097 17098 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 17099 17100 // FIXME: we should support importing a submodule within a different submodule 17101 // of the same top-level module. Until we do, make it an error rather than 17102 // silently ignoring the import. 17103 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 17104 // warn on a redundant import of the current module? 17105 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 17106 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 17107 Diag(ImportLoc, getLangOpts().isCompilingModule() 17108 ? diag::err_module_self_import 17109 : diag::err_module_import_in_implementation) 17110 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 17111 17112 SmallVector<SourceLocation, 2> IdentifierLocs; 17113 Module *ModCheck = Mod; 17114 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 17115 // If we've run out of module parents, just drop the remaining identifiers. 17116 // We need the length to be consistent. 17117 if (!ModCheck) 17118 break; 17119 ModCheck = ModCheck->Parent; 17120 17121 IdentifierLocs.push_back(Path[I].second); 17122 } 17123 17124 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 17125 Mod, IdentifierLocs); 17126 if (!ModuleScopes.empty()) 17127 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 17128 CurContext->addDecl(Import); 17129 17130 // Re-export the module if needed. 17131 if (Import->isExported() && 17132 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) 17133 getCurrentModule()->Exports.emplace_back(Mod, false); 17134 17135 return Import; 17136 } 17137 17138 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 17139 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 17140 BuildModuleInclude(DirectiveLoc, Mod); 17141 } 17142 17143 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 17144 // Determine whether we're in the #include buffer for a module. The #includes 17145 // in that buffer do not qualify as module imports; they're just an 17146 // implementation detail of us building the module. 17147 // 17148 // FIXME: Should we even get ActOnModuleInclude calls for those? 17149 bool IsInModuleIncludes = 17150 TUKind == TU_Module && 17151 getSourceManager().isWrittenInMainFile(DirectiveLoc); 17152 17153 bool ShouldAddImport = !IsInModuleIncludes; 17154 17155 // If this module import was due to an inclusion directive, create an 17156 // implicit import declaration to capture it in the AST. 17157 if (ShouldAddImport) { 17158 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 17159 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 17160 DirectiveLoc, Mod, 17161 DirectiveLoc); 17162 if (!ModuleScopes.empty()) 17163 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 17164 TU->addDecl(ImportD); 17165 Consumer.HandleImplicitImportDecl(ImportD); 17166 } 17167 17168 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 17169 VisibleModules.setVisible(Mod, DirectiveLoc); 17170 } 17171 17172 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 17173 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 17174 17175 ModuleScopes.push_back({}); 17176 ModuleScopes.back().Module = Mod; 17177 if (getLangOpts().ModulesLocalVisibility) 17178 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 17179 17180 VisibleModules.setVisible(Mod, DirectiveLoc); 17181 17182 // The enclosing context is now part of this module. 17183 // FIXME: Consider creating a child DeclContext to hold the entities 17184 // lexically within the module. 17185 if (getLangOpts().trackLocalOwningModule()) { 17186 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 17187 cast<Decl>(DC)->setModuleOwnershipKind( 17188 getLangOpts().ModulesLocalVisibility 17189 ? Decl::ModuleOwnershipKind::VisibleWhenImported 17190 : Decl::ModuleOwnershipKind::Visible); 17191 cast<Decl>(DC)->setLocalOwningModule(Mod); 17192 } 17193 } 17194 } 17195 17196 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 17197 if (getLangOpts().ModulesLocalVisibility) { 17198 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 17199 // Leaving a module hides namespace names, so our visible namespace cache 17200 // is now out of date. 17201 VisibleNamespaceCache.clear(); 17202 } 17203 17204 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 17205 "left the wrong module scope"); 17206 ModuleScopes.pop_back(); 17207 17208 // We got to the end of processing a local module. Create an 17209 // ImportDecl as we would for an imported module. 17210 FileID File = getSourceManager().getFileID(EomLoc); 17211 SourceLocation DirectiveLoc; 17212 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 17213 // We reached the end of a #included module header. Use the #include loc. 17214 assert(File != getSourceManager().getMainFileID() && 17215 "end of submodule in main source file"); 17216 DirectiveLoc = getSourceManager().getIncludeLoc(File); 17217 } else { 17218 // We reached an EOM pragma. Use the pragma location. 17219 DirectiveLoc = EomLoc; 17220 } 17221 BuildModuleInclude(DirectiveLoc, Mod); 17222 17223 // Any further declarations are in whatever module we returned to. 17224 if (getLangOpts().trackLocalOwningModule()) { 17225 // The parser guarantees that this is the same context that we entered 17226 // the module within. 17227 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 17228 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 17229 if (!getCurrentModule()) 17230 cast<Decl>(DC)->setModuleOwnershipKind( 17231 Decl::ModuleOwnershipKind::Unowned); 17232 } 17233 } 17234 } 17235 17236 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 17237 Module *Mod) { 17238 // Bail if we're not allowed to implicitly import a module here. 17239 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 17240 VisibleModules.isVisible(Mod)) 17241 return; 17242 17243 // Create the implicit import declaration. 17244 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 17245 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 17246 Loc, Mod, Loc); 17247 TU->addDecl(ImportD); 17248 Consumer.HandleImplicitImportDecl(ImportD); 17249 17250 // Make the module visible. 17251 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 17252 VisibleModules.setVisible(Mod, Loc); 17253 } 17254 17255 /// We have parsed the start of an export declaration, including the '{' 17256 /// (if present). 17257 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 17258 SourceLocation LBraceLoc) { 17259 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 17260 17261 // C++ Modules TS draft: 17262 // An export-declaration shall appear in the purview of a module other than 17263 // the global module. 17264 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 17265 Diag(ExportLoc, diag::err_export_not_in_module_interface); 17266 17267 // An export-declaration [...] shall not contain more than one 17268 // export keyword. 17269 // 17270 // The intent here is that an export-declaration cannot appear within another 17271 // export-declaration. 17272 if (D->isExported()) 17273 Diag(ExportLoc, diag::err_export_within_export); 17274 17275 CurContext->addDecl(D); 17276 PushDeclContext(S, D); 17277 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 17278 return D; 17279 } 17280 17281 /// Complete the definition of an export declaration. 17282 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 17283 auto *ED = cast<ExportDecl>(D); 17284 if (RBraceLoc.isValid()) 17285 ED->setRBraceLoc(RBraceLoc); 17286 17287 // FIXME: Diagnose export of internal-linkage declaration (including 17288 // anonymous namespace). 17289 17290 PopDeclContext(); 17291 return D; 17292 } 17293 17294 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17295 IdentifierInfo* AliasName, 17296 SourceLocation PragmaLoc, 17297 SourceLocation NameLoc, 17298 SourceLocation AliasNameLoc) { 17299 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17300 LookupOrdinaryName); 17301 AsmLabelAttr *Attr = 17302 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 17303 17304 // If a declaration that: 17305 // 1) declares a function or a variable 17306 // 2) has external linkage 17307 // already exists, add a label attribute to it. 17308 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17309 if (isDeclExternC(PrevDecl)) 17310 PrevDecl->addAttr(Attr); 17311 else 17312 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17313 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17314 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17315 } else 17316 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17317 } 17318 17319 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17320 SourceLocation PragmaLoc, 17321 SourceLocation NameLoc) { 17322 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17323 17324 if (PrevDecl) { 17325 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 17326 } else { 17327 (void)WeakUndeclaredIdentifiers.insert( 17328 std::pair<IdentifierInfo*,WeakInfo> 17329 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17330 } 17331 } 17332 17333 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17334 IdentifierInfo* AliasName, 17335 SourceLocation PragmaLoc, 17336 SourceLocation NameLoc, 17337 SourceLocation AliasNameLoc) { 17338 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17339 LookupOrdinaryName); 17340 WeakInfo W = WeakInfo(Name, NameLoc); 17341 17342 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17343 if (!PrevDecl->hasAttr<AliasAttr>()) 17344 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17345 DeclApplyPragmaWeak(TUScope, ND, W); 17346 } else { 17347 (void)WeakUndeclaredIdentifiers.insert( 17348 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 17349 } 17350 } 17351 17352 Decl *Sema::getObjCDeclContext() const { 17353 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 17354 } 17355