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(D->getLocEnd(), 1739 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1740 if (AfterColon.isInvalid()) 1741 return; 1742 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1743 getCharRange(D->getLocStart(), AfterColon)); 1744 } 1745 } 1746 1747 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1748 if (D->getTypeForDecl()->isDependentType()) 1749 return; 1750 1751 for (auto *TmpD : D->decls()) { 1752 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1753 DiagnoseUnusedDecl(T); 1754 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1755 DiagnoseUnusedNestedTypedefs(R); 1756 } 1757 } 1758 1759 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1760 /// unless they are marked attr(unused). 1761 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1762 if (!ShouldDiagnoseUnusedDecl(D)) 1763 return; 1764 1765 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1766 // typedefs can be referenced later on, so the diagnostics are emitted 1767 // at end-of-translation-unit. 1768 UnusedLocalTypedefNameCandidates.insert(TD); 1769 return; 1770 } 1771 1772 FixItHint Hint; 1773 GenerateFixForUnusedDecl(D, Context, Hint); 1774 1775 unsigned DiagID; 1776 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1777 DiagID = diag::warn_unused_exception_param; 1778 else if (isa<LabelDecl>(D)) 1779 DiagID = diag::warn_unused_label; 1780 else 1781 DiagID = diag::warn_unused_variable; 1782 1783 Diag(D->getLocation(), DiagID) << D << Hint; 1784 } 1785 1786 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1787 // Verify that we have no forward references left. If so, there was a goto 1788 // or address of a label taken, but no definition of it. Label fwd 1789 // definitions are indicated with a null substmt which is also not a resolved 1790 // MS inline assembly label name. 1791 bool Diagnose = false; 1792 if (L->isMSAsmLabel()) 1793 Diagnose = !L->isResolvedMSAsmLabel(); 1794 else 1795 Diagnose = L->getStmt() == nullptr; 1796 if (Diagnose) 1797 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1798 } 1799 1800 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1801 S->mergeNRVOIntoParent(); 1802 1803 if (S->decl_empty()) return; 1804 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1805 "Scope shouldn't contain decls!"); 1806 1807 for (auto *TmpD : S->decls()) { 1808 assert(TmpD && "This decl didn't get pushed??"); 1809 1810 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1811 NamedDecl *D = cast<NamedDecl>(TmpD); 1812 1813 // Diagnose unused variables in this scope. 1814 if (!S->hasUnrecoverableErrorOccurred()) { 1815 DiagnoseUnusedDecl(D); 1816 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1817 DiagnoseUnusedNestedTypedefs(RD); 1818 } 1819 1820 if (!D->getDeclName()) continue; 1821 1822 // If this was a forward reference to a label, verify it was defined. 1823 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1824 CheckPoppedLabel(LD, *this); 1825 1826 // Remove this name from our lexical scope, and warn on it if we haven't 1827 // already. 1828 IdResolver.RemoveDecl(D); 1829 auto ShadowI = ShadowingDecls.find(D); 1830 if (ShadowI != ShadowingDecls.end()) { 1831 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1832 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1833 << D << FD << FD->getParent(); 1834 Diag(FD->getLocation(), diag::note_previous_declaration); 1835 } 1836 ShadowingDecls.erase(ShadowI); 1837 } 1838 } 1839 } 1840 1841 /// Look for an Objective-C class in the translation unit. 1842 /// 1843 /// \param Id The name of the Objective-C class we're looking for. If 1844 /// typo-correction fixes this name, the Id will be updated 1845 /// to the fixed name. 1846 /// 1847 /// \param IdLoc The location of the name in the translation unit. 1848 /// 1849 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1850 /// if there is no class with the given name. 1851 /// 1852 /// \returns The declaration of the named Objective-C class, or NULL if the 1853 /// class could not be found. 1854 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1855 SourceLocation IdLoc, 1856 bool DoTypoCorrection) { 1857 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1858 // creation from this context. 1859 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1860 1861 if (!IDecl && DoTypoCorrection) { 1862 // Perform typo correction at the given location, but only if we 1863 // find an Objective-C class name. 1864 if (TypoCorrection C = CorrectTypo( 1865 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1866 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1867 CTK_ErrorRecovery)) { 1868 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1869 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1870 Id = IDecl->getIdentifier(); 1871 } 1872 } 1873 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1874 // This routine must always return a class definition, if any. 1875 if (Def && Def->getDefinition()) 1876 Def = Def->getDefinition(); 1877 return Def; 1878 } 1879 1880 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1881 /// from S, where a non-field would be declared. This routine copes 1882 /// with the difference between C and C++ scoping rules in structs and 1883 /// unions. For example, the following code is well-formed in C but 1884 /// ill-formed in C++: 1885 /// @code 1886 /// struct S6 { 1887 /// enum { BAR } e; 1888 /// }; 1889 /// 1890 /// void test_S6() { 1891 /// struct S6 a; 1892 /// a.e = BAR; 1893 /// } 1894 /// @endcode 1895 /// For the declaration of BAR, this routine will return a different 1896 /// scope. The scope S will be the scope of the unnamed enumeration 1897 /// within S6. In C++, this routine will return the scope associated 1898 /// with S6, because the enumeration's scope is a transparent 1899 /// context but structures can contain non-field names. In C, this 1900 /// routine will return the translation unit scope, since the 1901 /// enumeration's scope is a transparent context and structures cannot 1902 /// contain non-field names. 1903 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1904 while (((S->getFlags() & Scope::DeclScope) == 0) || 1905 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1906 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1907 S = S->getParent(); 1908 return S; 1909 } 1910 1911 /// Looks up the declaration of "struct objc_super" and 1912 /// saves it for later use in building builtin declaration of 1913 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1914 /// pre-existing declaration exists no action takes place. 1915 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1916 IdentifierInfo *II) { 1917 if (!II->isStr("objc_msgSendSuper")) 1918 return; 1919 ASTContext &Context = ThisSema.Context; 1920 1921 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1922 SourceLocation(), Sema::LookupTagName); 1923 ThisSema.LookupName(Result, S); 1924 if (Result.getResultKind() == LookupResult::Found) 1925 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1926 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1927 } 1928 1929 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1930 switch (Error) { 1931 case ASTContext::GE_None: 1932 return ""; 1933 case ASTContext::GE_Missing_stdio: 1934 return "stdio.h"; 1935 case ASTContext::GE_Missing_setjmp: 1936 return "setjmp.h"; 1937 case ASTContext::GE_Missing_ucontext: 1938 return "ucontext.h"; 1939 } 1940 llvm_unreachable("unhandled error kind"); 1941 } 1942 1943 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1944 /// file scope. lazily create a decl for it. ForRedeclaration is true 1945 /// if we're creating this built-in in anticipation of redeclaring the 1946 /// built-in. 1947 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1948 Scope *S, bool ForRedeclaration, 1949 SourceLocation Loc) { 1950 LookupPredefedObjCSuperType(*this, S, II); 1951 1952 ASTContext::GetBuiltinTypeError Error; 1953 QualType R = Context.GetBuiltinType(ID, Error); 1954 if (Error) { 1955 if (ForRedeclaration) 1956 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1957 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1958 return nullptr; 1959 } 1960 1961 if (!ForRedeclaration && 1962 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1963 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1964 Diag(Loc, diag::ext_implicit_lib_function_decl) 1965 << Context.BuiltinInfo.getName(ID) << R; 1966 if (Context.BuiltinInfo.getHeaderName(ID) && 1967 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1968 Diag(Loc, diag::note_include_header_or_declare) 1969 << Context.BuiltinInfo.getHeaderName(ID) 1970 << Context.BuiltinInfo.getName(ID); 1971 } 1972 1973 if (R.isNull()) 1974 return nullptr; 1975 1976 DeclContext *Parent = Context.getTranslationUnitDecl(); 1977 if (getLangOpts().CPlusPlus) { 1978 LinkageSpecDecl *CLinkageDecl = 1979 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1980 LinkageSpecDecl::lang_c, false); 1981 CLinkageDecl->setImplicit(); 1982 Parent->addDecl(CLinkageDecl); 1983 Parent = CLinkageDecl; 1984 } 1985 1986 FunctionDecl *New = FunctionDecl::Create(Context, 1987 Parent, 1988 Loc, Loc, II, R, /*TInfo=*/nullptr, 1989 SC_Extern, 1990 false, 1991 R->isFunctionProtoType()); 1992 New->setImplicit(); 1993 1994 // Create Decl objects for each parameter, adding them to the 1995 // FunctionDecl. 1996 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1997 SmallVector<ParmVarDecl*, 16> Params; 1998 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1999 ParmVarDecl *parm = 2000 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2001 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2002 SC_None, nullptr); 2003 parm->setScopeInfo(0, i); 2004 Params.push_back(parm); 2005 } 2006 New->setParams(Params); 2007 } 2008 2009 AddKnownFunctionAttributes(New); 2010 RegisterLocallyScopedExternCDecl(New, S); 2011 2012 // TUScope is the translation-unit scope to insert this function into. 2013 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2014 // relate Scopes to DeclContexts, and probably eliminate CurContext 2015 // entirely, but we're not there yet. 2016 DeclContext *SavedContext = CurContext; 2017 CurContext = Parent; 2018 PushOnScopeChains(New, TUScope); 2019 CurContext = SavedContext; 2020 return New; 2021 } 2022 2023 /// Typedef declarations don't have linkage, but they still denote the same 2024 /// entity if their types are the same. 2025 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2026 /// isSameEntity. 2027 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2028 TypedefNameDecl *Decl, 2029 LookupResult &Previous) { 2030 // This is only interesting when modules are enabled. 2031 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2032 return; 2033 2034 // Empty sets are uninteresting. 2035 if (Previous.empty()) 2036 return; 2037 2038 LookupResult::Filter Filter = Previous.makeFilter(); 2039 while (Filter.hasNext()) { 2040 NamedDecl *Old = Filter.next(); 2041 2042 // Non-hidden declarations are never ignored. 2043 if (S.isVisible(Old)) 2044 continue; 2045 2046 // Declarations of the same entity are not ignored, even if they have 2047 // different linkages. 2048 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2049 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2050 Decl->getUnderlyingType())) 2051 continue; 2052 2053 // If both declarations give a tag declaration a typedef name for linkage 2054 // purposes, then they declare the same entity. 2055 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2056 Decl->getAnonDeclWithTypedefName()) 2057 continue; 2058 } 2059 2060 Filter.erase(); 2061 } 2062 2063 Filter.done(); 2064 } 2065 2066 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2067 QualType OldType; 2068 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2069 OldType = OldTypedef->getUnderlyingType(); 2070 else 2071 OldType = Context.getTypeDeclType(Old); 2072 QualType NewType = New->getUnderlyingType(); 2073 2074 if (NewType->isVariablyModifiedType()) { 2075 // Must not redefine a typedef with a variably-modified type. 2076 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2077 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2078 << Kind << NewType; 2079 if (Old->getLocation().isValid()) 2080 notePreviousDefinition(Old, New->getLocation()); 2081 New->setInvalidDecl(); 2082 return true; 2083 } 2084 2085 if (OldType != NewType && 2086 !OldType->isDependentType() && 2087 !NewType->isDependentType() && 2088 !Context.hasSameType(OldType, NewType)) { 2089 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2090 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2091 << Kind << NewType << OldType; 2092 if (Old->getLocation().isValid()) 2093 notePreviousDefinition(Old, New->getLocation()); 2094 New->setInvalidDecl(); 2095 return true; 2096 } 2097 return false; 2098 } 2099 2100 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2101 /// same name and scope as a previous declaration 'Old'. Figure out 2102 /// how to resolve this situation, merging decls or emitting 2103 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2104 /// 2105 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2106 LookupResult &OldDecls) { 2107 // If the new decl is known invalid already, don't bother doing any 2108 // merging checks. 2109 if (New->isInvalidDecl()) return; 2110 2111 // Allow multiple definitions for ObjC built-in typedefs. 2112 // FIXME: Verify the underlying types are equivalent! 2113 if (getLangOpts().ObjC1) { 2114 const IdentifierInfo *TypeID = New->getIdentifier(); 2115 switch (TypeID->getLength()) { 2116 default: break; 2117 case 2: 2118 { 2119 if (!TypeID->isStr("id")) 2120 break; 2121 QualType T = New->getUnderlyingType(); 2122 if (!T->isPointerType()) 2123 break; 2124 if (!T->isVoidPointerType()) { 2125 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2126 if (!PT->isStructureType()) 2127 break; 2128 } 2129 Context.setObjCIdRedefinitionType(T); 2130 // Install the built-in type for 'id', ignoring the current definition. 2131 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2132 return; 2133 } 2134 case 5: 2135 if (!TypeID->isStr("Class")) 2136 break; 2137 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2138 // Install the built-in type for 'Class', ignoring the current definition. 2139 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2140 return; 2141 case 3: 2142 if (!TypeID->isStr("SEL")) 2143 break; 2144 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2145 // Install the built-in type for 'SEL', ignoring the current definition. 2146 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2147 return; 2148 } 2149 // Fall through - the typedef name was not a builtin type. 2150 } 2151 2152 // Verify the old decl was also a type. 2153 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2154 if (!Old) { 2155 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2156 << New->getDeclName(); 2157 2158 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2159 if (OldD->getLocation().isValid()) 2160 notePreviousDefinition(OldD, New->getLocation()); 2161 2162 return New->setInvalidDecl(); 2163 } 2164 2165 // If the old declaration is invalid, just give up here. 2166 if (Old->isInvalidDecl()) 2167 return New->setInvalidDecl(); 2168 2169 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2170 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2171 auto *NewTag = New->getAnonDeclWithTypedefName(); 2172 NamedDecl *Hidden = nullptr; 2173 if (OldTag && NewTag && 2174 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2175 !hasVisibleDefinition(OldTag, &Hidden)) { 2176 // There is a definition of this tag, but it is not visible. Use it 2177 // instead of our tag. 2178 New->setTypeForDecl(OldTD->getTypeForDecl()); 2179 if (OldTD->isModed()) 2180 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2181 OldTD->getUnderlyingType()); 2182 else 2183 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2184 2185 // Make the old tag definition visible. 2186 makeMergedDefinitionVisible(Hidden); 2187 2188 // If this was an unscoped enumeration, yank all of its enumerators 2189 // out of the scope. 2190 if (isa<EnumDecl>(NewTag)) { 2191 Scope *EnumScope = getNonFieldDeclScope(S); 2192 for (auto *D : NewTag->decls()) { 2193 auto *ED = cast<EnumConstantDecl>(D); 2194 assert(EnumScope->isDeclScope(ED)); 2195 EnumScope->RemoveDecl(ED); 2196 IdResolver.RemoveDecl(ED); 2197 ED->getLexicalDeclContext()->removeDecl(ED); 2198 } 2199 } 2200 } 2201 } 2202 2203 // If the typedef types are not identical, reject them in all languages and 2204 // with any extensions enabled. 2205 if (isIncompatibleTypedef(Old, New)) 2206 return; 2207 2208 // The types match. Link up the redeclaration chain and merge attributes if 2209 // the old declaration was a typedef. 2210 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2211 New->setPreviousDecl(Typedef); 2212 mergeDeclAttributes(New, Old); 2213 } 2214 2215 if (getLangOpts().MicrosoftExt) 2216 return; 2217 2218 if (getLangOpts().CPlusPlus) { 2219 // C++ [dcl.typedef]p2: 2220 // In a given non-class scope, a typedef specifier can be used to 2221 // redefine the name of any type declared in that scope to refer 2222 // to the type to which it already refers. 2223 if (!isa<CXXRecordDecl>(CurContext)) 2224 return; 2225 2226 // C++0x [dcl.typedef]p4: 2227 // In a given class scope, a typedef specifier can be used to redefine 2228 // any class-name declared in that scope that is not also a typedef-name 2229 // to refer to the type to which it already refers. 2230 // 2231 // This wording came in via DR424, which was a correction to the 2232 // wording in DR56, which accidentally banned code like: 2233 // 2234 // struct S { 2235 // typedef struct A { } A; 2236 // }; 2237 // 2238 // in the C++03 standard. We implement the C++0x semantics, which 2239 // allow the above but disallow 2240 // 2241 // struct S { 2242 // typedef int I; 2243 // typedef int I; 2244 // }; 2245 // 2246 // since that was the intent of DR56. 2247 if (!isa<TypedefNameDecl>(Old)) 2248 return; 2249 2250 Diag(New->getLocation(), diag::err_redefinition) 2251 << New->getDeclName(); 2252 notePreviousDefinition(Old, New->getLocation()); 2253 return New->setInvalidDecl(); 2254 } 2255 2256 // Modules always permit redefinition of typedefs, as does C11. 2257 if (getLangOpts().Modules || getLangOpts().C11) 2258 return; 2259 2260 // If we have a redefinition of a typedef in C, emit a warning. This warning 2261 // is normally mapped to an error, but can be controlled with 2262 // -Wtypedef-redefinition. If either the original or the redefinition is 2263 // in a system header, don't emit this for compatibility with GCC. 2264 if (getDiagnostics().getSuppressSystemWarnings() && 2265 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2266 (Old->isImplicit() || 2267 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2268 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2269 return; 2270 2271 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2272 << New->getDeclName(); 2273 notePreviousDefinition(Old, New->getLocation()); 2274 } 2275 2276 /// DeclhasAttr - returns true if decl Declaration already has the target 2277 /// attribute. 2278 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2279 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2280 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2281 for (const auto *i : D->attrs()) 2282 if (i->getKind() == A->getKind()) { 2283 if (Ann) { 2284 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2285 return true; 2286 continue; 2287 } 2288 // FIXME: Don't hardcode this check 2289 if (OA && isa<OwnershipAttr>(i)) 2290 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2291 return true; 2292 } 2293 2294 return false; 2295 } 2296 2297 static bool isAttributeTargetADefinition(Decl *D) { 2298 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2299 return VD->isThisDeclarationADefinition(); 2300 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2301 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2302 return true; 2303 } 2304 2305 /// Merge alignment attributes from \p Old to \p New, taking into account the 2306 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2307 /// 2308 /// \return \c true if any attributes were added to \p New. 2309 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2310 // Look for alignas attributes on Old, and pick out whichever attribute 2311 // specifies the strictest alignment requirement. 2312 AlignedAttr *OldAlignasAttr = nullptr; 2313 AlignedAttr *OldStrictestAlignAttr = nullptr; 2314 unsigned OldAlign = 0; 2315 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2316 // FIXME: We have no way of representing inherited dependent alignments 2317 // in a case like: 2318 // template<int A, int B> struct alignas(A) X; 2319 // template<int A, int B> struct alignas(B) X {}; 2320 // For now, we just ignore any alignas attributes which are not on the 2321 // definition in such a case. 2322 if (I->isAlignmentDependent()) 2323 return false; 2324 2325 if (I->isAlignas()) 2326 OldAlignasAttr = I; 2327 2328 unsigned Align = I->getAlignment(S.Context); 2329 if (Align > OldAlign) { 2330 OldAlign = Align; 2331 OldStrictestAlignAttr = I; 2332 } 2333 } 2334 2335 // Look for alignas attributes on New. 2336 AlignedAttr *NewAlignasAttr = nullptr; 2337 unsigned NewAlign = 0; 2338 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2339 if (I->isAlignmentDependent()) 2340 return false; 2341 2342 if (I->isAlignas()) 2343 NewAlignasAttr = I; 2344 2345 unsigned Align = I->getAlignment(S.Context); 2346 if (Align > NewAlign) 2347 NewAlign = Align; 2348 } 2349 2350 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2351 // Both declarations have 'alignas' attributes. We require them to match. 2352 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2353 // fall short. (If two declarations both have alignas, they must both match 2354 // every definition, and so must match each other if there is a definition.) 2355 2356 // If either declaration only contains 'alignas(0)' specifiers, then it 2357 // specifies the natural alignment for the type. 2358 if (OldAlign == 0 || NewAlign == 0) { 2359 QualType Ty; 2360 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2361 Ty = VD->getType(); 2362 else 2363 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2364 2365 if (OldAlign == 0) 2366 OldAlign = S.Context.getTypeAlign(Ty); 2367 if (NewAlign == 0) 2368 NewAlign = S.Context.getTypeAlign(Ty); 2369 } 2370 2371 if (OldAlign != NewAlign) { 2372 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2373 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2374 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2375 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2376 } 2377 } 2378 2379 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2380 // C++11 [dcl.align]p6: 2381 // if any declaration of an entity has an alignment-specifier, 2382 // every defining declaration of that entity shall specify an 2383 // equivalent alignment. 2384 // C11 6.7.5/7: 2385 // If the definition of an object does not have an alignment 2386 // specifier, any other declaration of that object shall also 2387 // have no alignment specifier. 2388 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2389 << OldAlignasAttr; 2390 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2391 << OldAlignasAttr; 2392 } 2393 2394 bool AnyAdded = false; 2395 2396 // Ensure we have an attribute representing the strictest alignment. 2397 if (OldAlign > NewAlign) { 2398 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2399 Clone->setInherited(true); 2400 New->addAttr(Clone); 2401 AnyAdded = true; 2402 } 2403 2404 // Ensure we have an alignas attribute if the old declaration had one. 2405 if (OldAlignasAttr && !NewAlignasAttr && 2406 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2407 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2408 Clone->setInherited(true); 2409 New->addAttr(Clone); 2410 AnyAdded = true; 2411 } 2412 2413 return AnyAdded; 2414 } 2415 2416 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2417 const InheritableAttr *Attr, 2418 Sema::AvailabilityMergeKind AMK) { 2419 // This function copies an attribute Attr from a previous declaration to the 2420 // new declaration D if the new declaration doesn't itself have that attribute 2421 // yet or if that attribute allows duplicates. 2422 // If you're adding a new attribute that requires logic different from 2423 // "use explicit attribute on decl if present, else use attribute from 2424 // previous decl", for example if the attribute needs to be consistent 2425 // between redeclarations, you need to call a custom merge function here. 2426 InheritableAttr *NewAttr = nullptr; 2427 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2428 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2429 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2430 AA->isImplicit(), AA->getIntroduced(), 2431 AA->getDeprecated(), 2432 AA->getObsoleted(), AA->getUnavailable(), 2433 AA->getMessage(), AA->getStrict(), 2434 AA->getReplacement(), AMK, 2435 AttrSpellingListIndex); 2436 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2437 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2438 AttrSpellingListIndex); 2439 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2440 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2441 AttrSpellingListIndex); 2442 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2443 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2444 AttrSpellingListIndex); 2445 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2446 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2447 AttrSpellingListIndex); 2448 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2449 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2450 FA->getFormatIdx(), FA->getFirstArg(), 2451 AttrSpellingListIndex); 2452 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2453 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2454 AttrSpellingListIndex); 2455 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2456 NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(), 2457 AttrSpellingListIndex); 2458 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2459 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2460 AttrSpellingListIndex, 2461 IA->getSemanticSpelling()); 2462 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2463 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2464 &S.Context.Idents.get(AA->getSpelling()), 2465 AttrSpellingListIndex); 2466 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2467 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2468 isa<CUDAGlobalAttr>(Attr))) { 2469 // CUDA target attributes are part of function signature for 2470 // overloading purposes and must not be merged. 2471 return false; 2472 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2473 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2474 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2475 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2476 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2477 NewAttr = S.mergeInternalLinkageAttr( 2478 D, InternalLinkageA->getRange(), 2479 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2480 AttrSpellingListIndex); 2481 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2482 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2483 &S.Context.Idents.get(CommonA->getSpelling()), 2484 AttrSpellingListIndex); 2485 else if (isa<AlignedAttr>(Attr)) 2486 // AlignedAttrs are handled separately, because we need to handle all 2487 // such attributes on a declaration at the same time. 2488 NewAttr = nullptr; 2489 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2490 (AMK == Sema::AMK_Override || 2491 AMK == Sema::AMK_ProtocolImplementation)) 2492 NewAttr = nullptr; 2493 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2494 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2495 UA->getGuid()); 2496 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2497 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2498 2499 if (NewAttr) { 2500 NewAttr->setInherited(true); 2501 D->addAttr(NewAttr); 2502 if (isa<MSInheritanceAttr>(NewAttr)) 2503 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2504 return true; 2505 } 2506 2507 return false; 2508 } 2509 2510 static const NamedDecl *getDefinition(const Decl *D) { 2511 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2512 return TD->getDefinition(); 2513 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2514 const VarDecl *Def = VD->getDefinition(); 2515 if (Def) 2516 return Def; 2517 return VD->getActingDefinition(); 2518 } 2519 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2520 return FD->getDefinition(); 2521 return nullptr; 2522 } 2523 2524 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2525 for (const auto *Attribute : D->attrs()) 2526 if (Attribute->getKind() == Kind) 2527 return true; 2528 return false; 2529 } 2530 2531 /// checkNewAttributesAfterDef - If we already have a definition, check that 2532 /// there are no new attributes in this declaration. 2533 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2534 if (!New->hasAttrs()) 2535 return; 2536 2537 const NamedDecl *Def = getDefinition(Old); 2538 if (!Def || Def == New) 2539 return; 2540 2541 AttrVec &NewAttributes = New->getAttrs(); 2542 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2543 const Attr *NewAttribute = NewAttributes[I]; 2544 2545 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2547 Sema::SkipBodyInfo SkipBody; 2548 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2549 2550 // If we're skipping this definition, drop the "alias" attribute. 2551 if (SkipBody.ShouldSkip) { 2552 NewAttributes.erase(NewAttributes.begin() + I); 2553 --E; 2554 continue; 2555 } 2556 } else { 2557 VarDecl *VD = cast<VarDecl>(New); 2558 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2559 VarDecl::TentativeDefinition 2560 ? diag::err_alias_after_tentative 2561 : diag::err_redefinition; 2562 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2563 if (Diag == diag::err_redefinition) 2564 S.notePreviousDefinition(Def, VD->getLocation()); 2565 else 2566 S.Diag(Def->getLocation(), diag::note_previous_definition); 2567 VD->setInvalidDecl(); 2568 } 2569 ++I; 2570 continue; 2571 } 2572 2573 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2574 // Tentative definitions are only interesting for the alias check above. 2575 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2576 ++I; 2577 continue; 2578 } 2579 } 2580 2581 if (hasAttribute(Def, NewAttribute->getKind())) { 2582 ++I; 2583 continue; // regular attr merging will take care of validating this. 2584 } 2585 2586 if (isa<C11NoReturnAttr>(NewAttribute)) { 2587 // C's _Noreturn is allowed to be added to a function after it is defined. 2588 ++I; 2589 continue; 2590 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2591 if (AA->isAlignas()) { 2592 // C++11 [dcl.align]p6: 2593 // if any declaration of an entity has an alignment-specifier, 2594 // every defining declaration of that entity shall specify an 2595 // equivalent alignment. 2596 // C11 6.7.5/7: 2597 // If the definition of an object does not have an alignment 2598 // specifier, any other declaration of that object shall also 2599 // have no alignment specifier. 2600 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2601 << AA; 2602 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2603 << AA; 2604 NewAttributes.erase(NewAttributes.begin() + I); 2605 --E; 2606 continue; 2607 } 2608 } 2609 2610 S.Diag(NewAttribute->getLocation(), 2611 diag::warn_attribute_precede_definition); 2612 S.Diag(Def->getLocation(), diag::note_previous_definition); 2613 NewAttributes.erase(NewAttributes.begin() + I); 2614 --E; 2615 } 2616 } 2617 2618 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2619 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2620 AvailabilityMergeKind AMK) { 2621 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2622 UsedAttr *NewAttr = OldAttr->clone(Context); 2623 NewAttr->setInherited(true); 2624 New->addAttr(NewAttr); 2625 } 2626 2627 if (!Old->hasAttrs() && !New->hasAttrs()) 2628 return; 2629 2630 // Attributes declared post-definition are currently ignored. 2631 checkNewAttributesAfterDef(*this, New, Old); 2632 2633 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2634 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2635 if (OldA->getLabel() != NewA->getLabel()) { 2636 // This redeclaration changes __asm__ label. 2637 Diag(New->getLocation(), diag::err_different_asm_label); 2638 Diag(OldA->getLocation(), diag::note_previous_declaration); 2639 } 2640 } else if (Old->isUsed()) { 2641 // This redeclaration adds an __asm__ label to a declaration that has 2642 // already been ODR-used. 2643 Diag(New->getLocation(), diag::err_late_asm_label_name) 2644 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2645 } 2646 } 2647 2648 // Re-declaration cannot add abi_tag's. 2649 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2650 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2651 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2652 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2653 NewTag) == OldAbiTagAttr->tags_end()) { 2654 Diag(NewAbiTagAttr->getLocation(), 2655 diag::err_new_abi_tag_on_redeclaration) 2656 << NewTag; 2657 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2658 } 2659 } 2660 } else { 2661 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2662 Diag(Old->getLocation(), diag::note_previous_declaration); 2663 } 2664 } 2665 2666 // This redeclaration adds a section attribute. 2667 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2668 if (auto *VD = dyn_cast<VarDecl>(New)) { 2669 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2670 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2671 Diag(Old->getLocation(), diag::note_previous_declaration); 2672 } 2673 } 2674 } 2675 2676 // Redeclaration adds code-seg attribute. 2677 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2678 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2679 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2680 Diag(New->getLocation(), diag::warn_mismatched_section) 2681 << 0 /*codeseg*/; 2682 Diag(Old->getLocation(), diag::note_previous_declaration); 2683 } 2684 2685 if (!Old->hasAttrs()) 2686 return; 2687 2688 bool foundAny = New->hasAttrs(); 2689 2690 // Ensure that any moving of objects within the allocated map is done before 2691 // we process them. 2692 if (!foundAny) New->setAttrs(AttrVec()); 2693 2694 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2695 // Ignore deprecated/unavailable/availability attributes if requested. 2696 AvailabilityMergeKind LocalAMK = AMK_None; 2697 if (isa<DeprecatedAttr>(I) || 2698 isa<UnavailableAttr>(I) || 2699 isa<AvailabilityAttr>(I)) { 2700 switch (AMK) { 2701 case AMK_None: 2702 continue; 2703 2704 case AMK_Redeclaration: 2705 case AMK_Override: 2706 case AMK_ProtocolImplementation: 2707 LocalAMK = AMK; 2708 break; 2709 } 2710 } 2711 2712 // Already handled. 2713 if (isa<UsedAttr>(I)) 2714 continue; 2715 2716 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2717 foundAny = true; 2718 } 2719 2720 if (mergeAlignedAttrs(*this, New, Old)) 2721 foundAny = true; 2722 2723 if (!foundAny) New->dropAttrs(); 2724 } 2725 2726 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2727 /// to the new one. 2728 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2729 const ParmVarDecl *oldDecl, 2730 Sema &S) { 2731 // C++11 [dcl.attr.depend]p2: 2732 // The first declaration of a function shall specify the 2733 // carries_dependency attribute for its declarator-id if any declaration 2734 // of the function specifies the carries_dependency attribute. 2735 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2736 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2737 S.Diag(CDA->getLocation(), 2738 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2739 // Find the first declaration of the parameter. 2740 // FIXME: Should we build redeclaration chains for function parameters? 2741 const FunctionDecl *FirstFD = 2742 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2743 const ParmVarDecl *FirstVD = 2744 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2745 S.Diag(FirstVD->getLocation(), 2746 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2747 } 2748 2749 if (!oldDecl->hasAttrs()) 2750 return; 2751 2752 bool foundAny = newDecl->hasAttrs(); 2753 2754 // Ensure that any moving of objects within the allocated map is 2755 // done before we process them. 2756 if (!foundAny) newDecl->setAttrs(AttrVec()); 2757 2758 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2759 if (!DeclHasAttr(newDecl, I)) { 2760 InheritableAttr *newAttr = 2761 cast<InheritableParamAttr>(I->clone(S.Context)); 2762 newAttr->setInherited(true); 2763 newDecl->addAttr(newAttr); 2764 foundAny = true; 2765 } 2766 } 2767 2768 if (!foundAny) newDecl->dropAttrs(); 2769 } 2770 2771 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2772 const ParmVarDecl *OldParam, 2773 Sema &S) { 2774 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2775 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2776 if (*Oldnullability != *Newnullability) { 2777 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2778 << DiagNullabilityKind( 2779 *Newnullability, 2780 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2781 != 0)) 2782 << DiagNullabilityKind( 2783 *Oldnullability, 2784 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2785 != 0)); 2786 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2787 } 2788 } else { 2789 QualType NewT = NewParam->getType(); 2790 NewT = S.Context.getAttributedType( 2791 AttributedType::getNullabilityAttrKind(*Oldnullability), 2792 NewT, NewT); 2793 NewParam->setType(NewT); 2794 } 2795 } 2796 } 2797 2798 namespace { 2799 2800 /// Used in MergeFunctionDecl to keep track of function parameters in 2801 /// C. 2802 struct GNUCompatibleParamWarning { 2803 ParmVarDecl *OldParm; 2804 ParmVarDecl *NewParm; 2805 QualType PromotedType; 2806 }; 2807 2808 } // end anonymous namespace 2809 2810 /// getSpecialMember - get the special member enum for a method. 2811 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2812 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2813 if (Ctor->isDefaultConstructor()) 2814 return Sema::CXXDefaultConstructor; 2815 2816 if (Ctor->isCopyConstructor()) 2817 return Sema::CXXCopyConstructor; 2818 2819 if (Ctor->isMoveConstructor()) 2820 return Sema::CXXMoveConstructor; 2821 } else if (isa<CXXDestructorDecl>(MD)) { 2822 return Sema::CXXDestructor; 2823 } else if (MD->isCopyAssignmentOperator()) { 2824 return Sema::CXXCopyAssignment; 2825 } else if (MD->isMoveAssignmentOperator()) { 2826 return Sema::CXXMoveAssignment; 2827 } 2828 2829 return Sema::CXXInvalid; 2830 } 2831 2832 // Determine whether the previous declaration was a definition, implicit 2833 // declaration, or a declaration. 2834 template <typename T> 2835 static std::pair<diag::kind, SourceLocation> 2836 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2837 diag::kind PrevDiag; 2838 SourceLocation OldLocation = Old->getLocation(); 2839 if (Old->isThisDeclarationADefinition()) 2840 PrevDiag = diag::note_previous_definition; 2841 else if (Old->isImplicit()) { 2842 PrevDiag = diag::note_previous_implicit_declaration; 2843 if (OldLocation.isInvalid()) 2844 OldLocation = New->getLocation(); 2845 } else 2846 PrevDiag = diag::note_previous_declaration; 2847 return std::make_pair(PrevDiag, OldLocation); 2848 } 2849 2850 /// canRedefineFunction - checks if a function can be redefined. Currently, 2851 /// only extern inline functions can be redefined, and even then only in 2852 /// GNU89 mode. 2853 static bool canRedefineFunction(const FunctionDecl *FD, 2854 const LangOptions& LangOpts) { 2855 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2856 !LangOpts.CPlusPlus && 2857 FD->isInlineSpecified() && 2858 FD->getStorageClass() == SC_Extern); 2859 } 2860 2861 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2862 const AttributedType *AT = T->getAs<AttributedType>(); 2863 while (AT && !AT->isCallingConv()) 2864 AT = AT->getModifiedType()->getAs<AttributedType>(); 2865 return AT; 2866 } 2867 2868 template <typename T> 2869 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2870 const DeclContext *DC = Old->getDeclContext(); 2871 if (DC->isRecord()) 2872 return false; 2873 2874 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2875 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2876 return true; 2877 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2878 return true; 2879 return false; 2880 } 2881 2882 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2883 static bool isExternC(VarTemplateDecl *) { return false; } 2884 2885 /// Check whether a redeclaration of an entity introduced by a 2886 /// using-declaration is valid, given that we know it's not an overload 2887 /// (nor a hidden tag declaration). 2888 template<typename ExpectedDecl> 2889 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2890 ExpectedDecl *New) { 2891 // C++11 [basic.scope.declarative]p4: 2892 // Given a set of declarations in a single declarative region, each of 2893 // which specifies the same unqualified name, 2894 // -- they shall all refer to the same entity, or all refer to functions 2895 // and function templates; or 2896 // -- exactly one declaration shall declare a class name or enumeration 2897 // name that is not a typedef name and the other declarations shall all 2898 // refer to the same variable or enumerator, or all refer to functions 2899 // and function templates; in this case the class name or enumeration 2900 // name is hidden (3.3.10). 2901 2902 // C++11 [namespace.udecl]p14: 2903 // If a function declaration in namespace scope or block scope has the 2904 // same name and the same parameter-type-list as a function introduced 2905 // by a using-declaration, and the declarations do not declare the same 2906 // function, the program is ill-formed. 2907 2908 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2909 if (Old && 2910 !Old->getDeclContext()->getRedeclContext()->Equals( 2911 New->getDeclContext()->getRedeclContext()) && 2912 !(isExternC(Old) && isExternC(New))) 2913 Old = nullptr; 2914 2915 if (!Old) { 2916 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2917 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2918 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2919 return true; 2920 } 2921 return false; 2922 } 2923 2924 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2925 const FunctionDecl *B) { 2926 assert(A->getNumParams() == B->getNumParams()); 2927 2928 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2929 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2930 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2931 if (AttrA == AttrB) 2932 return true; 2933 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2934 }; 2935 2936 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2937 } 2938 2939 /// If necessary, adjust the semantic declaration context for a qualified 2940 /// declaration to name the correct inline namespace within the qualifier. 2941 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2942 DeclaratorDecl *OldD) { 2943 // The only case where we need to update the DeclContext is when 2944 // redeclaration lookup for a qualified name finds a declaration 2945 // in an inline namespace within the context named by the qualifier: 2946 // 2947 // inline namespace N { int f(); } 2948 // int ::f(); // Sema DC needs adjusting from :: to N::. 2949 // 2950 // For unqualified declarations, the semantic context *can* change 2951 // along the redeclaration chain (for local extern declarations, 2952 // extern "C" declarations, and friend declarations in particular). 2953 if (!NewD->getQualifier()) 2954 return; 2955 2956 // NewD is probably already in the right context. 2957 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2958 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2959 if (NamedDC->Equals(SemaDC)) 2960 return; 2961 2962 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2963 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2964 "unexpected context for redeclaration"); 2965 2966 auto *LexDC = NewD->getLexicalDeclContext(); 2967 auto FixSemaDC = [=](NamedDecl *D) { 2968 if (!D) 2969 return; 2970 D->setDeclContext(SemaDC); 2971 D->setLexicalDeclContext(LexDC); 2972 }; 2973 2974 FixSemaDC(NewD); 2975 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 2976 FixSemaDC(FD->getDescribedFunctionTemplate()); 2977 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 2978 FixSemaDC(VD->getDescribedVarTemplate()); 2979 } 2980 2981 /// MergeFunctionDecl - We just parsed a function 'New' from 2982 /// declarator D which has the same name and scope as a previous 2983 /// declaration 'Old'. Figure out how to resolve this situation, 2984 /// merging decls or emitting diagnostics as appropriate. 2985 /// 2986 /// In C++, New and Old must be declarations that are not 2987 /// overloaded. Use IsOverload to determine whether New and Old are 2988 /// overloaded, and to select the Old declaration that New should be 2989 /// merged with. 2990 /// 2991 /// Returns true if there was an error, false otherwise. 2992 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2993 Scope *S, bool MergeTypeWithOld) { 2994 // Verify the old decl was also a function. 2995 FunctionDecl *Old = OldD->getAsFunction(); 2996 if (!Old) { 2997 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2998 if (New->getFriendObjectKind()) { 2999 Diag(New->getLocation(), diag::err_using_decl_friend); 3000 Diag(Shadow->getTargetDecl()->getLocation(), 3001 diag::note_using_decl_target); 3002 Diag(Shadow->getUsingDecl()->getLocation(), 3003 diag::note_using_decl) << 0; 3004 return true; 3005 } 3006 3007 // Check whether the two declarations might declare the same function. 3008 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3009 return true; 3010 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3011 } else { 3012 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3013 << New->getDeclName(); 3014 notePreviousDefinition(OldD, New->getLocation()); 3015 return true; 3016 } 3017 } 3018 3019 // If the old declaration is invalid, just give up here. 3020 if (Old->isInvalidDecl()) 3021 return true; 3022 3023 // Disallow redeclaration of some builtins. 3024 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3025 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3026 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3027 << Old << Old->getType(); 3028 return true; 3029 } 3030 3031 diag::kind PrevDiag; 3032 SourceLocation OldLocation; 3033 std::tie(PrevDiag, OldLocation) = 3034 getNoteDiagForInvalidRedeclaration(Old, New); 3035 3036 // Don't complain about this if we're in GNU89 mode and the old function 3037 // is an extern inline function. 3038 // Don't complain about specializations. They are not supposed to have 3039 // storage classes. 3040 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3041 New->getStorageClass() == SC_Static && 3042 Old->hasExternalFormalLinkage() && 3043 !New->getTemplateSpecializationInfo() && 3044 !canRedefineFunction(Old, getLangOpts())) { 3045 if (getLangOpts().MicrosoftExt) { 3046 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3047 Diag(OldLocation, PrevDiag); 3048 } else { 3049 Diag(New->getLocation(), diag::err_static_non_static) << New; 3050 Diag(OldLocation, PrevDiag); 3051 return true; 3052 } 3053 } 3054 3055 if (New->hasAttr<InternalLinkageAttr>() && 3056 !Old->hasAttr<InternalLinkageAttr>()) { 3057 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3058 << New->getDeclName(); 3059 notePreviousDefinition(Old, New->getLocation()); 3060 New->dropAttr<InternalLinkageAttr>(); 3061 } 3062 3063 if (CheckRedeclarationModuleOwnership(New, Old)) 3064 return true; 3065 3066 if (!getLangOpts().CPlusPlus) { 3067 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3068 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3069 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3070 << New << OldOvl; 3071 3072 // Try our best to find a decl that actually has the overloadable 3073 // attribute for the note. In most cases (e.g. programs with only one 3074 // broken declaration/definition), this won't matter. 3075 // 3076 // FIXME: We could do this if we juggled some extra state in 3077 // OverloadableAttr, rather than just removing it. 3078 const Decl *DiagOld = Old; 3079 if (OldOvl) { 3080 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3081 const auto *A = D->getAttr<OverloadableAttr>(); 3082 return A && !A->isImplicit(); 3083 }); 3084 // If we've implicitly added *all* of the overloadable attrs to this 3085 // chain, emitting a "previous redecl" note is pointless. 3086 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3087 } 3088 3089 if (DiagOld) 3090 Diag(DiagOld->getLocation(), 3091 diag::note_attribute_overloadable_prev_overload) 3092 << OldOvl; 3093 3094 if (OldOvl) 3095 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3096 else 3097 New->dropAttr<OverloadableAttr>(); 3098 } 3099 } 3100 3101 // If a function is first declared with a calling convention, but is later 3102 // declared or defined without one, all following decls assume the calling 3103 // convention of the first. 3104 // 3105 // It's OK if a function is first declared without a calling convention, 3106 // but is later declared or defined with the default calling convention. 3107 // 3108 // To test if either decl has an explicit calling convention, we look for 3109 // AttributedType sugar nodes on the type as written. If they are missing or 3110 // were canonicalized away, we assume the calling convention was implicit. 3111 // 3112 // Note also that we DO NOT return at this point, because we still have 3113 // other tests to run. 3114 QualType OldQType = Context.getCanonicalType(Old->getType()); 3115 QualType NewQType = Context.getCanonicalType(New->getType()); 3116 const FunctionType *OldType = cast<FunctionType>(OldQType); 3117 const FunctionType *NewType = cast<FunctionType>(NewQType); 3118 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3119 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3120 bool RequiresAdjustment = false; 3121 3122 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3123 FunctionDecl *First = Old->getFirstDecl(); 3124 const FunctionType *FT = 3125 First->getType().getCanonicalType()->castAs<FunctionType>(); 3126 FunctionType::ExtInfo FI = FT->getExtInfo(); 3127 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3128 if (!NewCCExplicit) { 3129 // Inherit the CC from the previous declaration if it was specified 3130 // there but not here. 3131 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3132 RequiresAdjustment = true; 3133 } else { 3134 // Calling conventions aren't compatible, so complain. 3135 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3136 Diag(New->getLocation(), diag::err_cconv_change) 3137 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3138 << !FirstCCExplicit 3139 << (!FirstCCExplicit ? "" : 3140 FunctionType::getNameForCallConv(FI.getCC())); 3141 3142 // Put the note on the first decl, since it is the one that matters. 3143 Diag(First->getLocation(), diag::note_previous_declaration); 3144 return true; 3145 } 3146 } 3147 3148 // FIXME: diagnose the other way around? 3149 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3150 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3151 RequiresAdjustment = true; 3152 } 3153 3154 // Merge regparm attribute. 3155 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3156 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3157 if (NewTypeInfo.getHasRegParm()) { 3158 Diag(New->getLocation(), diag::err_regparm_mismatch) 3159 << NewType->getRegParmType() 3160 << OldType->getRegParmType(); 3161 Diag(OldLocation, diag::note_previous_declaration); 3162 return true; 3163 } 3164 3165 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3166 RequiresAdjustment = true; 3167 } 3168 3169 // Merge ns_returns_retained attribute. 3170 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3171 if (NewTypeInfo.getProducesResult()) { 3172 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3173 << "'ns_returns_retained'"; 3174 Diag(OldLocation, diag::note_previous_declaration); 3175 return true; 3176 } 3177 3178 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3179 RequiresAdjustment = true; 3180 } 3181 3182 if (OldTypeInfo.getNoCallerSavedRegs() != 3183 NewTypeInfo.getNoCallerSavedRegs()) { 3184 if (NewTypeInfo.getNoCallerSavedRegs()) { 3185 AnyX86NoCallerSavedRegistersAttr *Attr = 3186 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3187 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3188 Diag(OldLocation, diag::note_previous_declaration); 3189 return true; 3190 } 3191 3192 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3193 RequiresAdjustment = true; 3194 } 3195 3196 if (RequiresAdjustment) { 3197 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3198 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3199 New->setType(QualType(AdjustedType, 0)); 3200 NewQType = Context.getCanonicalType(New->getType()); 3201 NewType = cast<FunctionType>(NewQType); 3202 } 3203 3204 // If this redeclaration makes the function inline, we may need to add it to 3205 // UndefinedButUsed. 3206 if (!Old->isInlined() && New->isInlined() && 3207 !New->hasAttr<GNUInlineAttr>() && 3208 !getLangOpts().GNUInline && 3209 Old->isUsed(false) && 3210 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3211 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3212 SourceLocation())); 3213 3214 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3215 // about it. 3216 if (New->hasAttr<GNUInlineAttr>() && 3217 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3218 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3219 } 3220 3221 // If pass_object_size params don't match up perfectly, this isn't a valid 3222 // redeclaration. 3223 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3224 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3225 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3226 << New->getDeclName(); 3227 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3228 return true; 3229 } 3230 3231 if (getLangOpts().CPlusPlus) { 3232 // C++1z [over.load]p2 3233 // Certain function declarations cannot be overloaded: 3234 // -- Function declarations that differ only in the return type, 3235 // the exception specification, or both cannot be overloaded. 3236 3237 // Check the exception specifications match. This may recompute the type of 3238 // both Old and New if it resolved exception specifications, so grab the 3239 // types again after this. Because this updates the type, we do this before 3240 // any of the other checks below, which may update the "de facto" NewQType 3241 // but do not necessarily update the type of New. 3242 if (CheckEquivalentExceptionSpec(Old, New)) 3243 return true; 3244 OldQType = Context.getCanonicalType(Old->getType()); 3245 NewQType = Context.getCanonicalType(New->getType()); 3246 3247 // Go back to the type source info to compare the declared return types, 3248 // per C++1y [dcl.type.auto]p13: 3249 // Redeclarations or specializations of a function or function template 3250 // with a declared return type that uses a placeholder type shall also 3251 // use that placeholder, not a deduced type. 3252 QualType OldDeclaredReturnType = 3253 (Old->getTypeSourceInfo() 3254 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3255 : OldType)->getReturnType(); 3256 QualType NewDeclaredReturnType = 3257 (New->getTypeSourceInfo() 3258 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3259 : NewType)->getReturnType(); 3260 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3261 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3262 New->isLocalExternDecl())) { 3263 QualType ResQT; 3264 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3265 OldDeclaredReturnType->isObjCObjectPointerType()) 3266 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3267 if (ResQT.isNull()) { 3268 if (New->isCXXClassMember() && New->isOutOfLine()) 3269 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3270 << New << New->getReturnTypeSourceRange(); 3271 else 3272 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3273 << New->getReturnTypeSourceRange(); 3274 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3275 << Old->getReturnTypeSourceRange(); 3276 return true; 3277 } 3278 else 3279 NewQType = ResQT; 3280 } 3281 3282 QualType OldReturnType = OldType->getReturnType(); 3283 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3284 if (OldReturnType != NewReturnType) { 3285 // If this function has a deduced return type and has already been 3286 // defined, copy the deduced value from the old declaration. 3287 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3288 if (OldAT && OldAT->isDeduced()) { 3289 New->setType( 3290 SubstAutoType(New->getType(), 3291 OldAT->isDependentType() ? Context.DependentTy 3292 : OldAT->getDeducedType())); 3293 NewQType = Context.getCanonicalType( 3294 SubstAutoType(NewQType, 3295 OldAT->isDependentType() ? Context.DependentTy 3296 : OldAT->getDeducedType())); 3297 } 3298 } 3299 3300 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3301 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3302 if (OldMethod && NewMethod) { 3303 // Preserve triviality. 3304 NewMethod->setTrivial(OldMethod->isTrivial()); 3305 3306 // MSVC allows explicit template specialization at class scope: 3307 // 2 CXXMethodDecls referring to the same function will be injected. 3308 // We don't want a redeclaration error. 3309 bool IsClassScopeExplicitSpecialization = 3310 OldMethod->isFunctionTemplateSpecialization() && 3311 NewMethod->isFunctionTemplateSpecialization(); 3312 bool isFriend = NewMethod->getFriendObjectKind(); 3313 3314 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3315 !IsClassScopeExplicitSpecialization) { 3316 // -- Member function declarations with the same name and the 3317 // same parameter types cannot be overloaded if any of them 3318 // is a static member function declaration. 3319 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3320 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3321 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3322 return true; 3323 } 3324 3325 // C++ [class.mem]p1: 3326 // [...] A member shall not be declared twice in the 3327 // member-specification, except that a nested class or member 3328 // class template can be declared and then later defined. 3329 if (!inTemplateInstantiation()) { 3330 unsigned NewDiag; 3331 if (isa<CXXConstructorDecl>(OldMethod)) 3332 NewDiag = diag::err_constructor_redeclared; 3333 else if (isa<CXXDestructorDecl>(NewMethod)) 3334 NewDiag = diag::err_destructor_redeclared; 3335 else if (isa<CXXConversionDecl>(NewMethod)) 3336 NewDiag = diag::err_conv_function_redeclared; 3337 else 3338 NewDiag = diag::err_member_redeclared; 3339 3340 Diag(New->getLocation(), NewDiag); 3341 } else { 3342 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3343 << New << New->getType(); 3344 } 3345 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3346 return true; 3347 3348 // Complain if this is an explicit declaration of a special 3349 // member that was initially declared implicitly. 3350 // 3351 // As an exception, it's okay to befriend such methods in order 3352 // to permit the implicit constructor/destructor/operator calls. 3353 } else if (OldMethod->isImplicit()) { 3354 if (isFriend) { 3355 NewMethod->setImplicit(); 3356 } else { 3357 Diag(NewMethod->getLocation(), 3358 diag::err_definition_of_implicitly_declared_member) 3359 << New << getSpecialMember(OldMethod); 3360 return true; 3361 } 3362 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3363 Diag(NewMethod->getLocation(), 3364 diag::err_definition_of_explicitly_defaulted_member) 3365 << getSpecialMember(OldMethod); 3366 return true; 3367 } 3368 } 3369 3370 // C++11 [dcl.attr.noreturn]p1: 3371 // The first declaration of a function shall specify the noreturn 3372 // attribute if any declaration of that function specifies the noreturn 3373 // attribute. 3374 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3375 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3376 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3377 Diag(Old->getFirstDecl()->getLocation(), 3378 diag::note_noreturn_missing_first_decl); 3379 } 3380 3381 // C++11 [dcl.attr.depend]p2: 3382 // The first declaration of a function shall specify the 3383 // carries_dependency attribute for its declarator-id if any declaration 3384 // of the function specifies the carries_dependency attribute. 3385 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3386 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3387 Diag(CDA->getLocation(), 3388 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3389 Diag(Old->getFirstDecl()->getLocation(), 3390 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3391 } 3392 3393 // (C++98 8.3.5p3): 3394 // All declarations for a function shall agree exactly in both the 3395 // return type and the parameter-type-list. 3396 // We also want to respect all the extended bits except noreturn. 3397 3398 // noreturn should now match unless the old type info didn't have it. 3399 QualType OldQTypeForComparison = OldQType; 3400 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3401 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3402 const FunctionType *OldTypeForComparison 3403 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3404 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3405 assert(OldQTypeForComparison.isCanonical()); 3406 } 3407 3408 if (haveIncompatibleLanguageLinkages(Old, New)) { 3409 // As a special case, retain the language linkage from previous 3410 // declarations of a friend function as an extension. 3411 // 3412 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3413 // and is useful because there's otherwise no way to specify language 3414 // linkage within class scope. 3415 // 3416 // Check cautiously as the friend object kind isn't yet complete. 3417 if (New->getFriendObjectKind() != Decl::FOK_None) { 3418 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3419 Diag(OldLocation, PrevDiag); 3420 } else { 3421 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3422 Diag(OldLocation, PrevDiag); 3423 return true; 3424 } 3425 } 3426 3427 if (OldQTypeForComparison == NewQType) 3428 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3429 3430 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3431 New->isLocalExternDecl()) { 3432 // It's OK if we couldn't merge types for a local function declaraton 3433 // if either the old or new type is dependent. We'll merge the types 3434 // when we instantiate the function. 3435 return false; 3436 } 3437 3438 // Fall through for conflicting redeclarations and redefinitions. 3439 } 3440 3441 // C: Function types need to be compatible, not identical. This handles 3442 // duplicate function decls like "void f(int); void f(enum X);" properly. 3443 if (!getLangOpts().CPlusPlus && 3444 Context.typesAreCompatible(OldQType, NewQType)) { 3445 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3446 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3447 const FunctionProtoType *OldProto = nullptr; 3448 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3449 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3450 // The old declaration provided a function prototype, but the 3451 // new declaration does not. Merge in the prototype. 3452 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3453 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3454 NewQType = 3455 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3456 OldProto->getExtProtoInfo()); 3457 New->setType(NewQType); 3458 New->setHasInheritedPrototype(); 3459 3460 // Synthesize parameters with the same types. 3461 SmallVector<ParmVarDecl*, 16> Params; 3462 for (const auto &ParamType : OldProto->param_types()) { 3463 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3464 SourceLocation(), nullptr, 3465 ParamType, /*TInfo=*/nullptr, 3466 SC_None, nullptr); 3467 Param->setScopeInfo(0, Params.size()); 3468 Param->setImplicit(); 3469 Params.push_back(Param); 3470 } 3471 3472 New->setParams(Params); 3473 } 3474 3475 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3476 } 3477 3478 // GNU C permits a K&R definition to follow a prototype declaration 3479 // if the declared types of the parameters in the K&R definition 3480 // match the types in the prototype declaration, even when the 3481 // promoted types of the parameters from the K&R definition differ 3482 // from the types in the prototype. GCC then keeps the types from 3483 // the prototype. 3484 // 3485 // If a variadic prototype is followed by a non-variadic K&R definition, 3486 // the K&R definition becomes variadic. This is sort of an edge case, but 3487 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3488 // C99 6.9.1p8. 3489 if (!getLangOpts().CPlusPlus && 3490 Old->hasPrototype() && !New->hasPrototype() && 3491 New->getType()->getAs<FunctionProtoType>() && 3492 Old->getNumParams() == New->getNumParams()) { 3493 SmallVector<QualType, 16> ArgTypes; 3494 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3495 const FunctionProtoType *OldProto 3496 = Old->getType()->getAs<FunctionProtoType>(); 3497 const FunctionProtoType *NewProto 3498 = New->getType()->getAs<FunctionProtoType>(); 3499 3500 // Determine whether this is the GNU C extension. 3501 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3502 NewProto->getReturnType()); 3503 bool LooseCompatible = !MergedReturn.isNull(); 3504 for (unsigned Idx = 0, End = Old->getNumParams(); 3505 LooseCompatible && Idx != End; ++Idx) { 3506 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3507 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3508 if (Context.typesAreCompatible(OldParm->getType(), 3509 NewProto->getParamType(Idx))) { 3510 ArgTypes.push_back(NewParm->getType()); 3511 } else if (Context.typesAreCompatible(OldParm->getType(), 3512 NewParm->getType(), 3513 /*CompareUnqualified=*/true)) { 3514 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3515 NewProto->getParamType(Idx) }; 3516 Warnings.push_back(Warn); 3517 ArgTypes.push_back(NewParm->getType()); 3518 } else 3519 LooseCompatible = false; 3520 } 3521 3522 if (LooseCompatible) { 3523 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3524 Diag(Warnings[Warn].NewParm->getLocation(), 3525 diag::ext_param_promoted_not_compatible_with_prototype) 3526 << Warnings[Warn].PromotedType 3527 << Warnings[Warn].OldParm->getType(); 3528 if (Warnings[Warn].OldParm->getLocation().isValid()) 3529 Diag(Warnings[Warn].OldParm->getLocation(), 3530 diag::note_previous_declaration); 3531 } 3532 3533 if (MergeTypeWithOld) 3534 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3535 OldProto->getExtProtoInfo())); 3536 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3537 } 3538 3539 // Fall through to diagnose conflicting types. 3540 } 3541 3542 // A function that has already been declared has been redeclared or 3543 // defined with a different type; show an appropriate diagnostic. 3544 3545 // If the previous declaration was an implicitly-generated builtin 3546 // declaration, then at the very least we should use a specialized note. 3547 unsigned BuiltinID; 3548 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3549 // If it's actually a library-defined builtin function like 'malloc' 3550 // or 'printf', just warn about the incompatible redeclaration. 3551 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3552 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3553 Diag(OldLocation, diag::note_previous_builtin_declaration) 3554 << Old << Old->getType(); 3555 3556 // If this is a global redeclaration, just forget hereafter 3557 // about the "builtin-ness" of the function. 3558 // 3559 // Doing this for local extern declarations is problematic. If 3560 // the builtin declaration remains visible, a second invalid 3561 // local declaration will produce a hard error; if it doesn't 3562 // remain visible, a single bogus local redeclaration (which is 3563 // actually only a warning) could break all the downstream code. 3564 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3565 New->getIdentifier()->revertBuiltin(); 3566 3567 return false; 3568 } 3569 3570 PrevDiag = diag::note_previous_builtin_declaration; 3571 } 3572 3573 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3574 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3575 return true; 3576 } 3577 3578 /// Completes the merge of two function declarations that are 3579 /// known to be compatible. 3580 /// 3581 /// This routine handles the merging of attributes and other 3582 /// properties of function declarations from the old declaration to 3583 /// the new declaration, once we know that New is in fact a 3584 /// redeclaration of Old. 3585 /// 3586 /// \returns false 3587 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3588 Scope *S, bool MergeTypeWithOld) { 3589 // Merge the attributes 3590 mergeDeclAttributes(New, Old); 3591 3592 // Merge "pure" flag. 3593 if (Old->isPure()) 3594 New->setPure(); 3595 3596 // Merge "used" flag. 3597 if (Old->getMostRecentDecl()->isUsed(false)) 3598 New->setIsUsed(); 3599 3600 // Merge attributes from the parameters. These can mismatch with K&R 3601 // declarations. 3602 if (New->getNumParams() == Old->getNumParams()) 3603 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3604 ParmVarDecl *NewParam = New->getParamDecl(i); 3605 ParmVarDecl *OldParam = Old->getParamDecl(i); 3606 mergeParamDeclAttributes(NewParam, OldParam, *this); 3607 mergeParamDeclTypes(NewParam, OldParam, *this); 3608 } 3609 3610 if (getLangOpts().CPlusPlus) 3611 return MergeCXXFunctionDecl(New, Old, S); 3612 3613 // Merge the function types so the we get the composite types for the return 3614 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3615 // was visible. 3616 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3617 if (!Merged.isNull() && MergeTypeWithOld) 3618 New->setType(Merged); 3619 3620 return false; 3621 } 3622 3623 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3624 ObjCMethodDecl *oldMethod) { 3625 // Merge the attributes, including deprecated/unavailable 3626 AvailabilityMergeKind MergeKind = 3627 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3628 ? AMK_ProtocolImplementation 3629 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3630 : AMK_Override; 3631 3632 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3633 3634 // Merge attributes from the parameters. 3635 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3636 oe = oldMethod->param_end(); 3637 for (ObjCMethodDecl::param_iterator 3638 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3639 ni != ne && oi != oe; ++ni, ++oi) 3640 mergeParamDeclAttributes(*ni, *oi, *this); 3641 3642 CheckObjCMethodOverride(newMethod, oldMethod); 3643 } 3644 3645 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3646 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3647 3648 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3649 ? diag::err_redefinition_different_type 3650 : diag::err_redeclaration_different_type) 3651 << New->getDeclName() << New->getType() << Old->getType(); 3652 3653 diag::kind PrevDiag; 3654 SourceLocation OldLocation; 3655 std::tie(PrevDiag, OldLocation) 3656 = getNoteDiagForInvalidRedeclaration(Old, New); 3657 S.Diag(OldLocation, PrevDiag); 3658 New->setInvalidDecl(); 3659 } 3660 3661 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3662 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3663 /// emitting diagnostics as appropriate. 3664 /// 3665 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3666 /// to here in AddInitializerToDecl. We can't check them before the initializer 3667 /// is attached. 3668 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3669 bool MergeTypeWithOld) { 3670 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3671 return; 3672 3673 QualType MergedT; 3674 if (getLangOpts().CPlusPlus) { 3675 if (New->getType()->isUndeducedType()) { 3676 // We don't know what the new type is until the initializer is attached. 3677 return; 3678 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3679 // These could still be something that needs exception specs checked. 3680 return MergeVarDeclExceptionSpecs(New, Old); 3681 } 3682 // C++ [basic.link]p10: 3683 // [...] the types specified by all declarations referring to a given 3684 // object or function shall be identical, except that declarations for an 3685 // array object can specify array types that differ by the presence or 3686 // absence of a major array bound (8.3.4). 3687 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3688 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3689 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3690 3691 // We are merging a variable declaration New into Old. If it has an array 3692 // bound, and that bound differs from Old's bound, we should diagnose the 3693 // mismatch. 3694 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3695 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3696 PrevVD = PrevVD->getPreviousDecl()) { 3697 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3698 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3699 continue; 3700 3701 if (!Context.hasSameType(NewArray, PrevVDTy)) 3702 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3703 } 3704 } 3705 3706 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3707 if (Context.hasSameType(OldArray->getElementType(), 3708 NewArray->getElementType())) 3709 MergedT = New->getType(); 3710 } 3711 // FIXME: Check visibility. New is hidden but has a complete type. If New 3712 // has no array bound, it should not inherit one from Old, if Old is not 3713 // visible. 3714 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3715 if (Context.hasSameType(OldArray->getElementType(), 3716 NewArray->getElementType())) 3717 MergedT = Old->getType(); 3718 } 3719 } 3720 else if (New->getType()->isObjCObjectPointerType() && 3721 Old->getType()->isObjCObjectPointerType()) { 3722 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3723 Old->getType()); 3724 } 3725 } else { 3726 // C 6.2.7p2: 3727 // All declarations that refer to the same object or function shall have 3728 // compatible type. 3729 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3730 } 3731 if (MergedT.isNull()) { 3732 // It's OK if we couldn't merge types if either type is dependent, for a 3733 // block-scope variable. In other cases (static data members of class 3734 // templates, variable templates, ...), we require the types to be 3735 // equivalent. 3736 // FIXME: The C++ standard doesn't say anything about this. 3737 if ((New->getType()->isDependentType() || 3738 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3739 // If the old type was dependent, we can't merge with it, so the new type 3740 // becomes dependent for now. We'll reproduce the original type when we 3741 // instantiate the TypeSourceInfo for the variable. 3742 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3743 New->setType(Context.DependentTy); 3744 return; 3745 } 3746 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3747 } 3748 3749 // Don't actually update the type on the new declaration if the old 3750 // declaration was an extern declaration in a different scope. 3751 if (MergeTypeWithOld) 3752 New->setType(MergedT); 3753 } 3754 3755 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3756 LookupResult &Previous) { 3757 // C11 6.2.7p4: 3758 // For an identifier with internal or external linkage declared 3759 // in a scope in which a prior declaration of that identifier is 3760 // visible, if the prior declaration specifies internal or 3761 // external linkage, the type of the identifier at the later 3762 // declaration becomes the composite type. 3763 // 3764 // If the variable isn't visible, we do not merge with its type. 3765 if (Previous.isShadowed()) 3766 return false; 3767 3768 if (S.getLangOpts().CPlusPlus) { 3769 // C++11 [dcl.array]p3: 3770 // If there is a preceding declaration of the entity in the same 3771 // scope in which the bound was specified, an omitted array bound 3772 // is taken to be the same as in that earlier declaration. 3773 return NewVD->isPreviousDeclInSameBlockScope() || 3774 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3775 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3776 } else { 3777 // If the old declaration was function-local, don't merge with its 3778 // type unless we're in the same function. 3779 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3780 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3781 } 3782 } 3783 3784 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3785 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3786 /// situation, merging decls or emitting diagnostics as appropriate. 3787 /// 3788 /// Tentative definition rules (C99 6.9.2p2) are checked by 3789 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3790 /// definitions here, since the initializer hasn't been attached. 3791 /// 3792 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3793 // If the new decl is already invalid, don't do any other checking. 3794 if (New->isInvalidDecl()) 3795 return; 3796 3797 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3798 return; 3799 3800 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3801 3802 // Verify the old decl was also a variable or variable template. 3803 VarDecl *Old = nullptr; 3804 VarTemplateDecl *OldTemplate = nullptr; 3805 if (Previous.isSingleResult()) { 3806 if (NewTemplate) { 3807 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3808 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3809 3810 if (auto *Shadow = 3811 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3812 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3813 return New->setInvalidDecl(); 3814 } else { 3815 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3816 3817 if (auto *Shadow = 3818 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3819 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3820 return New->setInvalidDecl(); 3821 } 3822 } 3823 if (!Old) { 3824 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3825 << New->getDeclName(); 3826 notePreviousDefinition(Previous.getRepresentativeDecl(), 3827 New->getLocation()); 3828 return New->setInvalidDecl(); 3829 } 3830 3831 // Ensure the template parameters are compatible. 3832 if (NewTemplate && 3833 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3834 OldTemplate->getTemplateParameters(), 3835 /*Complain=*/true, TPL_TemplateMatch)) 3836 return New->setInvalidDecl(); 3837 3838 // C++ [class.mem]p1: 3839 // A member shall not be declared twice in the member-specification [...] 3840 // 3841 // Here, we need only consider static data members. 3842 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3843 Diag(New->getLocation(), diag::err_duplicate_member) 3844 << New->getIdentifier(); 3845 Diag(Old->getLocation(), diag::note_previous_declaration); 3846 New->setInvalidDecl(); 3847 } 3848 3849 mergeDeclAttributes(New, Old); 3850 // Warn if an already-declared variable is made a weak_import in a subsequent 3851 // declaration 3852 if (New->hasAttr<WeakImportAttr>() && 3853 Old->getStorageClass() == SC_None && 3854 !Old->hasAttr<WeakImportAttr>()) { 3855 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3856 notePreviousDefinition(Old, New->getLocation()); 3857 // Remove weak_import attribute on new declaration. 3858 New->dropAttr<WeakImportAttr>(); 3859 } 3860 3861 if (New->hasAttr<InternalLinkageAttr>() && 3862 !Old->hasAttr<InternalLinkageAttr>()) { 3863 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3864 << New->getDeclName(); 3865 notePreviousDefinition(Old, New->getLocation()); 3866 New->dropAttr<InternalLinkageAttr>(); 3867 } 3868 3869 // Merge the types. 3870 VarDecl *MostRecent = Old->getMostRecentDecl(); 3871 if (MostRecent != Old) { 3872 MergeVarDeclTypes(New, MostRecent, 3873 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3874 if (New->isInvalidDecl()) 3875 return; 3876 } 3877 3878 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3879 if (New->isInvalidDecl()) 3880 return; 3881 3882 diag::kind PrevDiag; 3883 SourceLocation OldLocation; 3884 std::tie(PrevDiag, OldLocation) = 3885 getNoteDiagForInvalidRedeclaration(Old, New); 3886 3887 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3888 if (New->getStorageClass() == SC_Static && 3889 !New->isStaticDataMember() && 3890 Old->hasExternalFormalLinkage()) { 3891 if (getLangOpts().MicrosoftExt) { 3892 Diag(New->getLocation(), diag::ext_static_non_static) 3893 << New->getDeclName(); 3894 Diag(OldLocation, PrevDiag); 3895 } else { 3896 Diag(New->getLocation(), diag::err_static_non_static) 3897 << New->getDeclName(); 3898 Diag(OldLocation, PrevDiag); 3899 return New->setInvalidDecl(); 3900 } 3901 } 3902 // C99 6.2.2p4: 3903 // For an identifier declared with the storage-class specifier 3904 // extern in a scope in which a prior declaration of that 3905 // identifier is visible,23) if the prior declaration specifies 3906 // internal or external linkage, the linkage of the identifier at 3907 // the later declaration is the same as the linkage specified at 3908 // the prior declaration. If no prior declaration is visible, or 3909 // if the prior declaration specifies no linkage, then the 3910 // identifier has external linkage. 3911 if (New->hasExternalStorage() && Old->hasLinkage()) 3912 /* Okay */; 3913 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3914 !New->isStaticDataMember() && 3915 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3916 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3917 Diag(OldLocation, PrevDiag); 3918 return New->setInvalidDecl(); 3919 } 3920 3921 // Check if extern is followed by non-extern and vice-versa. 3922 if (New->hasExternalStorage() && 3923 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3924 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3925 Diag(OldLocation, PrevDiag); 3926 return New->setInvalidDecl(); 3927 } 3928 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3929 !New->hasExternalStorage()) { 3930 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3931 Diag(OldLocation, PrevDiag); 3932 return New->setInvalidDecl(); 3933 } 3934 3935 if (CheckRedeclarationModuleOwnership(New, Old)) 3936 return; 3937 3938 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3939 3940 // FIXME: The test for external storage here seems wrong? We still 3941 // need to check for mismatches. 3942 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3943 // Don't complain about out-of-line definitions of static members. 3944 !(Old->getLexicalDeclContext()->isRecord() && 3945 !New->getLexicalDeclContext()->isRecord())) { 3946 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3947 Diag(OldLocation, PrevDiag); 3948 return New->setInvalidDecl(); 3949 } 3950 3951 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3952 if (VarDecl *Def = Old->getDefinition()) { 3953 // C++1z [dcl.fcn.spec]p4: 3954 // If the definition of a variable appears in a translation unit before 3955 // its first declaration as inline, the program is ill-formed. 3956 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3957 Diag(Def->getLocation(), diag::note_previous_definition); 3958 } 3959 } 3960 3961 // If this redeclaration makes the variable inline, we may need to add it to 3962 // UndefinedButUsed. 3963 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3964 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3965 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3966 SourceLocation())); 3967 3968 if (New->getTLSKind() != Old->getTLSKind()) { 3969 if (!Old->getTLSKind()) { 3970 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3971 Diag(OldLocation, PrevDiag); 3972 } else if (!New->getTLSKind()) { 3973 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3974 Diag(OldLocation, PrevDiag); 3975 } else { 3976 // Do not allow redeclaration to change the variable between requiring 3977 // static and dynamic initialization. 3978 // FIXME: GCC allows this, but uses the TLS keyword on the first 3979 // declaration to determine the kind. Do we need to be compatible here? 3980 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3981 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3982 Diag(OldLocation, PrevDiag); 3983 } 3984 } 3985 3986 // C++ doesn't have tentative definitions, so go right ahead and check here. 3987 if (getLangOpts().CPlusPlus && 3988 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3989 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3990 Old->getCanonicalDecl()->isConstexpr()) { 3991 // This definition won't be a definition any more once it's been merged. 3992 Diag(New->getLocation(), 3993 diag::warn_deprecated_redundant_constexpr_static_def); 3994 } else if (VarDecl *Def = Old->getDefinition()) { 3995 if (checkVarDeclRedefinition(Def, New)) 3996 return; 3997 } 3998 } 3999 4000 if (haveIncompatibleLanguageLinkages(Old, New)) { 4001 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4002 Diag(OldLocation, PrevDiag); 4003 New->setInvalidDecl(); 4004 return; 4005 } 4006 4007 // Merge "used" flag. 4008 if (Old->getMostRecentDecl()->isUsed(false)) 4009 New->setIsUsed(); 4010 4011 // Keep a chain of previous declarations. 4012 New->setPreviousDecl(Old); 4013 if (NewTemplate) 4014 NewTemplate->setPreviousDecl(OldTemplate); 4015 adjustDeclContextForDeclaratorDecl(New, Old); 4016 4017 // Inherit access appropriately. 4018 New->setAccess(Old->getAccess()); 4019 if (NewTemplate) 4020 NewTemplate->setAccess(New->getAccess()); 4021 4022 if (Old->isInline()) 4023 New->setImplicitlyInline(); 4024 } 4025 4026 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4027 SourceManager &SrcMgr = getSourceManager(); 4028 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4029 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4030 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4031 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4032 auto &HSI = PP.getHeaderSearchInfo(); 4033 StringRef HdrFilename = 4034 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4035 4036 auto noteFromModuleOrInclude = [&](Module *Mod, 4037 SourceLocation IncLoc) -> bool { 4038 // Redefinition errors with modules are common with non modular mapped 4039 // headers, example: a non-modular header H in module A that also gets 4040 // included directly in a TU. Pointing twice to the same header/definition 4041 // is confusing, try to get better diagnostics when modules is on. 4042 if (IncLoc.isValid()) { 4043 if (Mod) { 4044 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4045 << HdrFilename.str() << Mod->getFullModuleName(); 4046 if (!Mod->DefinitionLoc.isInvalid()) 4047 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4048 << Mod->getFullModuleName(); 4049 } else { 4050 Diag(IncLoc, diag::note_redefinition_include_same_file) 4051 << HdrFilename.str(); 4052 } 4053 return true; 4054 } 4055 4056 return false; 4057 }; 4058 4059 // Is it the same file and same offset? Provide more information on why 4060 // this leads to a redefinition error. 4061 bool EmittedDiag = false; 4062 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4063 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4064 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4065 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4066 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4067 4068 // If the header has no guards, emit a note suggesting one. 4069 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4070 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4071 4072 if (EmittedDiag) 4073 return; 4074 } 4075 4076 // Redefinition coming from different files or couldn't do better above. 4077 if (Old->getLocation().isValid()) 4078 Diag(Old->getLocation(), diag::note_previous_definition); 4079 } 4080 4081 /// We've just determined that \p Old and \p New both appear to be definitions 4082 /// of the same variable. Either diagnose or fix the problem. 4083 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4084 if (!hasVisibleDefinition(Old) && 4085 (New->getFormalLinkage() == InternalLinkage || 4086 New->isInline() || 4087 New->getDescribedVarTemplate() || 4088 New->getNumTemplateParameterLists() || 4089 New->getDeclContext()->isDependentContext())) { 4090 // The previous definition is hidden, and multiple definitions are 4091 // permitted (in separate TUs). Demote this to a declaration. 4092 New->demoteThisDefinitionToDeclaration(); 4093 4094 // Make the canonical definition visible. 4095 if (auto *OldTD = Old->getDescribedVarTemplate()) 4096 makeMergedDefinitionVisible(OldTD); 4097 makeMergedDefinitionVisible(Old); 4098 return false; 4099 } else { 4100 Diag(New->getLocation(), diag::err_redefinition) << New; 4101 notePreviousDefinition(Old, New->getLocation()); 4102 New->setInvalidDecl(); 4103 return true; 4104 } 4105 } 4106 4107 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4108 /// no declarator (e.g. "struct foo;") is parsed. 4109 Decl * 4110 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4111 RecordDecl *&AnonRecord) { 4112 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4113 AnonRecord); 4114 } 4115 4116 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4117 // disambiguate entities defined in different scopes. 4118 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4119 // compatibility. 4120 // We will pick our mangling number depending on which version of MSVC is being 4121 // targeted. 4122 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4123 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4124 ? S->getMSCurManglingNumber() 4125 : S->getMSLastManglingNumber(); 4126 } 4127 4128 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4129 if (!Context.getLangOpts().CPlusPlus) 4130 return; 4131 4132 if (isa<CXXRecordDecl>(Tag->getParent())) { 4133 // If this tag is the direct child of a class, number it if 4134 // it is anonymous. 4135 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4136 return; 4137 MangleNumberingContext &MCtx = 4138 Context.getManglingNumberContext(Tag->getParent()); 4139 Context.setManglingNumber( 4140 Tag, MCtx.getManglingNumber( 4141 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4142 return; 4143 } 4144 4145 // If this tag isn't a direct child of a class, number it if it is local. 4146 Decl *ManglingContextDecl; 4147 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4148 Tag->getDeclContext(), ManglingContextDecl)) { 4149 Context.setManglingNumber( 4150 Tag, MCtx->getManglingNumber( 4151 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4152 } 4153 } 4154 4155 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4156 TypedefNameDecl *NewTD) { 4157 if (TagFromDeclSpec->isInvalidDecl()) 4158 return; 4159 4160 // Do nothing if the tag already has a name for linkage purposes. 4161 if (TagFromDeclSpec->hasNameForLinkage()) 4162 return; 4163 4164 // A well-formed anonymous tag must always be a TUK_Definition. 4165 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4166 4167 // The type must match the tag exactly; no qualifiers allowed. 4168 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4169 Context.getTagDeclType(TagFromDeclSpec))) { 4170 if (getLangOpts().CPlusPlus) 4171 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4172 return; 4173 } 4174 4175 // If we've already computed linkage for the anonymous tag, then 4176 // adding a typedef name for the anonymous decl can change that 4177 // linkage, which might be a serious problem. Diagnose this as 4178 // unsupported and ignore the typedef name. TODO: we should 4179 // pursue this as a language defect and establish a formal rule 4180 // for how to handle it. 4181 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4182 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4183 4184 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4185 tagLoc = getLocForEndOfToken(tagLoc); 4186 4187 llvm::SmallString<40> textToInsert; 4188 textToInsert += ' '; 4189 textToInsert += NewTD->getIdentifier()->getName(); 4190 Diag(tagLoc, diag::note_typedef_changes_linkage) 4191 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4192 return; 4193 } 4194 4195 // Otherwise, set this is the anon-decl typedef for the tag. 4196 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4197 } 4198 4199 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4200 switch (T) { 4201 case DeclSpec::TST_class: 4202 return 0; 4203 case DeclSpec::TST_struct: 4204 return 1; 4205 case DeclSpec::TST_interface: 4206 return 2; 4207 case DeclSpec::TST_union: 4208 return 3; 4209 case DeclSpec::TST_enum: 4210 return 4; 4211 default: 4212 llvm_unreachable("unexpected type specifier"); 4213 } 4214 } 4215 4216 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4217 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4218 /// parameters to cope with template friend declarations. 4219 Decl * 4220 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4221 MultiTemplateParamsArg TemplateParams, 4222 bool IsExplicitInstantiation, 4223 RecordDecl *&AnonRecord) { 4224 Decl *TagD = nullptr; 4225 TagDecl *Tag = nullptr; 4226 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4227 DS.getTypeSpecType() == DeclSpec::TST_struct || 4228 DS.getTypeSpecType() == DeclSpec::TST_interface || 4229 DS.getTypeSpecType() == DeclSpec::TST_union || 4230 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4231 TagD = DS.getRepAsDecl(); 4232 4233 if (!TagD) // We probably had an error 4234 return nullptr; 4235 4236 // Note that the above type specs guarantee that the 4237 // type rep is a Decl, whereas in many of the others 4238 // it's a Type. 4239 if (isa<TagDecl>(TagD)) 4240 Tag = cast<TagDecl>(TagD); 4241 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4242 Tag = CTD->getTemplatedDecl(); 4243 } 4244 4245 if (Tag) { 4246 handleTagNumbering(Tag, S); 4247 Tag->setFreeStanding(); 4248 if (Tag->isInvalidDecl()) 4249 return Tag; 4250 } 4251 4252 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4253 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4254 // or incomplete types shall not be restrict-qualified." 4255 if (TypeQuals & DeclSpec::TQ_restrict) 4256 Diag(DS.getRestrictSpecLoc(), 4257 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4258 << DS.getSourceRange(); 4259 } 4260 4261 if (DS.isInlineSpecified()) 4262 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4263 << getLangOpts().CPlusPlus17; 4264 4265 if (DS.isConstexprSpecified()) { 4266 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4267 // and definitions of functions and variables. 4268 if (Tag) 4269 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4270 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4271 else 4272 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4273 // Don't emit warnings after this error. 4274 return TagD; 4275 } 4276 4277 DiagnoseFunctionSpecifiers(DS); 4278 4279 if (DS.isFriendSpecified()) { 4280 // If we're dealing with a decl but not a TagDecl, assume that 4281 // whatever routines created it handled the friendship aspect. 4282 if (TagD && !Tag) 4283 return nullptr; 4284 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4285 } 4286 4287 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4288 bool IsExplicitSpecialization = 4289 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4290 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4291 !IsExplicitInstantiation && !IsExplicitSpecialization && 4292 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4293 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4294 // nested-name-specifier unless it is an explicit instantiation 4295 // or an explicit specialization. 4296 // 4297 // FIXME: We allow class template partial specializations here too, per the 4298 // obvious intent of DR1819. 4299 // 4300 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4301 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4302 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4303 return nullptr; 4304 } 4305 4306 // Track whether this decl-specifier declares anything. 4307 bool DeclaresAnything = true; 4308 4309 // Handle anonymous struct definitions. 4310 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4311 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4312 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4313 if (getLangOpts().CPlusPlus || 4314 Record->getDeclContext()->isRecord()) { 4315 // If CurContext is a DeclContext that can contain statements, 4316 // RecursiveASTVisitor won't visit the decls that 4317 // BuildAnonymousStructOrUnion() will put into CurContext. 4318 // Also store them here so that they can be part of the 4319 // DeclStmt that gets created in this case. 4320 // FIXME: Also return the IndirectFieldDecls created by 4321 // BuildAnonymousStructOr union, for the same reason? 4322 if (CurContext->isFunctionOrMethod()) 4323 AnonRecord = Record; 4324 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4325 Context.getPrintingPolicy()); 4326 } 4327 4328 DeclaresAnything = false; 4329 } 4330 } 4331 4332 // C11 6.7.2.1p2: 4333 // A struct-declaration that does not declare an anonymous structure or 4334 // anonymous union shall contain a struct-declarator-list. 4335 // 4336 // This rule also existed in C89 and C99; the grammar for struct-declaration 4337 // did not permit a struct-declaration without a struct-declarator-list. 4338 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4339 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4340 // Check for Microsoft C extension: anonymous struct/union member. 4341 // Handle 2 kinds of anonymous struct/union: 4342 // struct STRUCT; 4343 // union UNION; 4344 // and 4345 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4346 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4347 if ((Tag && Tag->getDeclName()) || 4348 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4349 RecordDecl *Record = nullptr; 4350 if (Tag) 4351 Record = dyn_cast<RecordDecl>(Tag); 4352 else if (const RecordType *RT = 4353 DS.getRepAsType().get()->getAsStructureType()) 4354 Record = RT->getDecl(); 4355 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4356 Record = UT->getDecl(); 4357 4358 if (Record && getLangOpts().MicrosoftExt) { 4359 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4360 << Record->isUnion() << DS.getSourceRange(); 4361 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4362 } 4363 4364 DeclaresAnything = false; 4365 } 4366 } 4367 4368 // Skip all the checks below if we have a type error. 4369 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4370 (TagD && TagD->isInvalidDecl())) 4371 return TagD; 4372 4373 if (getLangOpts().CPlusPlus && 4374 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4375 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4376 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4377 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4378 DeclaresAnything = false; 4379 4380 if (!DS.isMissingDeclaratorOk()) { 4381 // Customize diagnostic for a typedef missing a name. 4382 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4383 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4384 << DS.getSourceRange(); 4385 else 4386 DeclaresAnything = false; 4387 } 4388 4389 if (DS.isModulePrivateSpecified() && 4390 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4391 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4392 << Tag->getTagKind() 4393 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4394 4395 ActOnDocumentableDecl(TagD); 4396 4397 // C 6.7/2: 4398 // A declaration [...] shall declare at least a declarator [...], a tag, 4399 // or the members of an enumeration. 4400 // C++ [dcl.dcl]p3: 4401 // [If there are no declarators], and except for the declaration of an 4402 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4403 // names into the program, or shall redeclare a name introduced by a 4404 // previous declaration. 4405 if (!DeclaresAnything) { 4406 // In C, we allow this as a (popular) extension / bug. Don't bother 4407 // producing further diagnostics for redundant qualifiers after this. 4408 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4409 return TagD; 4410 } 4411 4412 // C++ [dcl.stc]p1: 4413 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4414 // init-declarator-list of the declaration shall not be empty. 4415 // C++ [dcl.fct.spec]p1: 4416 // If a cv-qualifier appears in a decl-specifier-seq, the 4417 // init-declarator-list of the declaration shall not be empty. 4418 // 4419 // Spurious qualifiers here appear to be valid in C. 4420 unsigned DiagID = diag::warn_standalone_specifier; 4421 if (getLangOpts().CPlusPlus) 4422 DiagID = diag::ext_standalone_specifier; 4423 4424 // Note that a linkage-specification sets a storage class, but 4425 // 'extern "C" struct foo;' is actually valid and not theoretically 4426 // useless. 4427 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4428 if (SCS == DeclSpec::SCS_mutable) 4429 // Since mutable is not a viable storage class specifier in C, there is 4430 // no reason to treat it as an extension. Instead, diagnose as an error. 4431 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4432 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4433 Diag(DS.getStorageClassSpecLoc(), DiagID) 4434 << DeclSpec::getSpecifierName(SCS); 4435 } 4436 4437 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4438 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4439 << DeclSpec::getSpecifierName(TSCS); 4440 if (DS.getTypeQualifiers()) { 4441 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4442 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4443 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4444 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4445 // Restrict is covered above. 4446 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4447 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4448 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4449 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4450 } 4451 4452 // Warn about ignored type attributes, for example: 4453 // __attribute__((aligned)) struct A; 4454 // Attributes should be placed after tag to apply to type declaration. 4455 if (!DS.getAttributes().empty()) { 4456 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4457 if (TypeSpecType == DeclSpec::TST_class || 4458 TypeSpecType == DeclSpec::TST_struct || 4459 TypeSpecType == DeclSpec::TST_interface || 4460 TypeSpecType == DeclSpec::TST_union || 4461 TypeSpecType == DeclSpec::TST_enum) { 4462 for (const ParsedAttr &AL : DS.getAttributes()) 4463 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4464 << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4465 } 4466 } 4467 4468 return TagD; 4469 } 4470 4471 /// We are trying to inject an anonymous member into the given scope; 4472 /// check if there's an existing declaration that can't be overloaded. 4473 /// 4474 /// \return true if this is a forbidden redeclaration 4475 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4476 Scope *S, 4477 DeclContext *Owner, 4478 DeclarationName Name, 4479 SourceLocation NameLoc, 4480 bool IsUnion) { 4481 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4482 Sema::ForVisibleRedeclaration); 4483 if (!SemaRef.LookupName(R, S)) return false; 4484 4485 // Pick a representative declaration. 4486 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4487 assert(PrevDecl && "Expected a non-null Decl"); 4488 4489 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4490 return false; 4491 4492 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4493 << IsUnion << Name; 4494 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4495 4496 return true; 4497 } 4498 4499 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4500 /// anonymous struct or union AnonRecord into the owning context Owner 4501 /// and scope S. This routine will be invoked just after we realize 4502 /// that an unnamed union or struct is actually an anonymous union or 4503 /// struct, e.g., 4504 /// 4505 /// @code 4506 /// union { 4507 /// int i; 4508 /// float f; 4509 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4510 /// // f into the surrounding scope.x 4511 /// @endcode 4512 /// 4513 /// This routine is recursive, injecting the names of nested anonymous 4514 /// structs/unions into the owning context and scope as well. 4515 static bool 4516 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4517 RecordDecl *AnonRecord, AccessSpecifier AS, 4518 SmallVectorImpl<NamedDecl *> &Chaining) { 4519 bool Invalid = false; 4520 4521 // Look every FieldDecl and IndirectFieldDecl with a name. 4522 for (auto *D : AnonRecord->decls()) { 4523 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4524 cast<NamedDecl>(D)->getDeclName()) { 4525 ValueDecl *VD = cast<ValueDecl>(D); 4526 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4527 VD->getLocation(), 4528 AnonRecord->isUnion())) { 4529 // C++ [class.union]p2: 4530 // The names of the members of an anonymous union shall be 4531 // distinct from the names of any other entity in the 4532 // scope in which the anonymous union is declared. 4533 Invalid = true; 4534 } else { 4535 // C++ [class.union]p2: 4536 // For the purpose of name lookup, after the anonymous union 4537 // definition, the members of the anonymous union are 4538 // considered to have been defined in the scope in which the 4539 // anonymous union is declared. 4540 unsigned OldChainingSize = Chaining.size(); 4541 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4542 Chaining.append(IF->chain_begin(), IF->chain_end()); 4543 else 4544 Chaining.push_back(VD); 4545 4546 assert(Chaining.size() >= 2); 4547 NamedDecl **NamedChain = 4548 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4549 for (unsigned i = 0; i < Chaining.size(); i++) 4550 NamedChain[i] = Chaining[i]; 4551 4552 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4553 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4554 VD->getType(), {NamedChain, Chaining.size()}); 4555 4556 for (const auto *Attr : VD->attrs()) 4557 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4558 4559 IndirectField->setAccess(AS); 4560 IndirectField->setImplicit(); 4561 SemaRef.PushOnScopeChains(IndirectField, S); 4562 4563 // That includes picking up the appropriate access specifier. 4564 if (AS != AS_none) IndirectField->setAccess(AS); 4565 4566 Chaining.resize(OldChainingSize); 4567 } 4568 } 4569 } 4570 4571 return Invalid; 4572 } 4573 4574 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4575 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4576 /// illegal input values are mapped to SC_None. 4577 static StorageClass 4578 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4579 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4580 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4581 "Parser allowed 'typedef' as storage class VarDecl."); 4582 switch (StorageClassSpec) { 4583 case DeclSpec::SCS_unspecified: return SC_None; 4584 case DeclSpec::SCS_extern: 4585 if (DS.isExternInLinkageSpec()) 4586 return SC_None; 4587 return SC_Extern; 4588 case DeclSpec::SCS_static: return SC_Static; 4589 case DeclSpec::SCS_auto: return SC_Auto; 4590 case DeclSpec::SCS_register: return SC_Register; 4591 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4592 // Illegal SCSs map to None: error reporting is up to the caller. 4593 case DeclSpec::SCS_mutable: // Fall through. 4594 case DeclSpec::SCS_typedef: return SC_None; 4595 } 4596 llvm_unreachable("unknown storage class specifier"); 4597 } 4598 4599 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4600 assert(Record->hasInClassInitializer()); 4601 4602 for (const auto *I : Record->decls()) { 4603 const auto *FD = dyn_cast<FieldDecl>(I); 4604 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4605 FD = IFD->getAnonField(); 4606 if (FD && FD->hasInClassInitializer()) 4607 return FD->getLocation(); 4608 } 4609 4610 llvm_unreachable("couldn't find in-class initializer"); 4611 } 4612 4613 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4614 SourceLocation DefaultInitLoc) { 4615 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4616 return; 4617 4618 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4619 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4620 } 4621 4622 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4623 CXXRecordDecl *AnonUnion) { 4624 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4625 return; 4626 4627 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4628 } 4629 4630 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4631 /// anonymous structure or union. Anonymous unions are a C++ feature 4632 /// (C++ [class.union]) and a C11 feature; anonymous structures 4633 /// are a C11 feature and GNU C++ extension. 4634 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4635 AccessSpecifier AS, 4636 RecordDecl *Record, 4637 const PrintingPolicy &Policy) { 4638 DeclContext *Owner = Record->getDeclContext(); 4639 4640 // Diagnose whether this anonymous struct/union is an extension. 4641 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4642 Diag(Record->getLocation(), diag::ext_anonymous_union); 4643 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4644 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4645 else if (!Record->isUnion() && !getLangOpts().C11) 4646 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4647 4648 // C and C++ require different kinds of checks for anonymous 4649 // structs/unions. 4650 bool Invalid = false; 4651 if (getLangOpts().CPlusPlus) { 4652 const char *PrevSpec = nullptr; 4653 unsigned DiagID; 4654 if (Record->isUnion()) { 4655 // C++ [class.union]p6: 4656 // C++17 [class.union.anon]p2: 4657 // Anonymous unions declared in a named namespace or in the 4658 // global namespace shall be declared static. 4659 DeclContext *OwnerScope = Owner->getRedeclContext(); 4660 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4661 (OwnerScope->isTranslationUnit() || 4662 (OwnerScope->isNamespace() && 4663 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4664 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4665 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4666 4667 // Recover by adding 'static'. 4668 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4669 PrevSpec, DiagID, Policy); 4670 } 4671 // C++ [class.union]p6: 4672 // A storage class is not allowed in a declaration of an 4673 // anonymous union in a class scope. 4674 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4675 isa<RecordDecl>(Owner)) { 4676 Diag(DS.getStorageClassSpecLoc(), 4677 diag::err_anonymous_union_with_storage_spec) 4678 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4679 4680 // Recover by removing the storage specifier. 4681 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4682 SourceLocation(), 4683 PrevSpec, DiagID, Context.getPrintingPolicy()); 4684 } 4685 } 4686 4687 // Ignore const/volatile/restrict qualifiers. 4688 if (DS.getTypeQualifiers()) { 4689 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4690 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4691 << Record->isUnion() << "const" 4692 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4693 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4694 Diag(DS.getVolatileSpecLoc(), 4695 diag::ext_anonymous_struct_union_qualified) 4696 << Record->isUnion() << "volatile" 4697 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4698 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4699 Diag(DS.getRestrictSpecLoc(), 4700 diag::ext_anonymous_struct_union_qualified) 4701 << Record->isUnion() << "restrict" 4702 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4703 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4704 Diag(DS.getAtomicSpecLoc(), 4705 diag::ext_anonymous_struct_union_qualified) 4706 << Record->isUnion() << "_Atomic" 4707 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4708 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4709 Diag(DS.getUnalignedSpecLoc(), 4710 diag::ext_anonymous_struct_union_qualified) 4711 << Record->isUnion() << "__unaligned" 4712 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4713 4714 DS.ClearTypeQualifiers(); 4715 } 4716 4717 // C++ [class.union]p2: 4718 // The member-specification of an anonymous union shall only 4719 // define non-static data members. [Note: nested types and 4720 // functions cannot be declared within an anonymous union. ] 4721 for (auto *Mem : Record->decls()) { 4722 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4723 // C++ [class.union]p3: 4724 // An anonymous union shall not have private or protected 4725 // members (clause 11). 4726 assert(FD->getAccess() != AS_none); 4727 if (FD->getAccess() != AS_public) { 4728 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4729 << Record->isUnion() << (FD->getAccess() == AS_protected); 4730 Invalid = true; 4731 } 4732 4733 // C++ [class.union]p1 4734 // An object of a class with a non-trivial constructor, a non-trivial 4735 // copy constructor, a non-trivial destructor, or a non-trivial copy 4736 // assignment operator cannot be a member of a union, nor can an 4737 // array of such objects. 4738 if (CheckNontrivialField(FD)) 4739 Invalid = true; 4740 } else if (Mem->isImplicit()) { 4741 // Any implicit members are fine. 4742 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4743 // This is a type that showed up in an 4744 // elaborated-type-specifier inside the anonymous struct or 4745 // union, but which actually declares a type outside of the 4746 // anonymous struct or union. It's okay. 4747 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4748 if (!MemRecord->isAnonymousStructOrUnion() && 4749 MemRecord->getDeclName()) { 4750 // Visual C++ allows type definition in anonymous struct or union. 4751 if (getLangOpts().MicrosoftExt) 4752 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4753 << Record->isUnion(); 4754 else { 4755 // This is a nested type declaration. 4756 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4757 << Record->isUnion(); 4758 Invalid = true; 4759 } 4760 } else { 4761 // This is an anonymous type definition within another anonymous type. 4762 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4763 // not part of standard C++. 4764 Diag(MemRecord->getLocation(), 4765 diag::ext_anonymous_record_with_anonymous_type) 4766 << Record->isUnion(); 4767 } 4768 } else if (isa<AccessSpecDecl>(Mem)) { 4769 // Any access specifier is fine. 4770 } else if (isa<StaticAssertDecl>(Mem)) { 4771 // In C++1z, static_assert declarations are also fine. 4772 } else { 4773 // We have something that isn't a non-static data 4774 // member. Complain about it. 4775 unsigned DK = diag::err_anonymous_record_bad_member; 4776 if (isa<TypeDecl>(Mem)) 4777 DK = diag::err_anonymous_record_with_type; 4778 else if (isa<FunctionDecl>(Mem)) 4779 DK = diag::err_anonymous_record_with_function; 4780 else if (isa<VarDecl>(Mem)) 4781 DK = diag::err_anonymous_record_with_static; 4782 4783 // Visual C++ allows type definition in anonymous struct or union. 4784 if (getLangOpts().MicrosoftExt && 4785 DK == diag::err_anonymous_record_with_type) 4786 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4787 << Record->isUnion(); 4788 else { 4789 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4790 Invalid = true; 4791 } 4792 } 4793 } 4794 4795 // C++11 [class.union]p8 (DR1460): 4796 // At most one variant member of a union may have a 4797 // brace-or-equal-initializer. 4798 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4799 Owner->isRecord()) 4800 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4801 cast<CXXRecordDecl>(Record)); 4802 } 4803 4804 if (!Record->isUnion() && !Owner->isRecord()) { 4805 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4806 << getLangOpts().CPlusPlus; 4807 Invalid = true; 4808 } 4809 4810 // Mock up a declarator. 4811 Declarator Dc(DS, DeclaratorContext::MemberContext); 4812 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4813 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4814 4815 // Create a declaration for this anonymous struct/union. 4816 NamedDecl *Anon = nullptr; 4817 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4818 Anon = FieldDecl::Create(Context, OwningClass, 4819 DS.getLocStart(), 4820 Record->getLocation(), 4821 /*IdentifierInfo=*/nullptr, 4822 Context.getTypeDeclType(Record), 4823 TInfo, 4824 /*BitWidth=*/nullptr, /*Mutable=*/false, 4825 /*InitStyle=*/ICIS_NoInit); 4826 Anon->setAccess(AS); 4827 if (getLangOpts().CPlusPlus) 4828 FieldCollector->Add(cast<FieldDecl>(Anon)); 4829 } else { 4830 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4831 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4832 if (SCSpec == DeclSpec::SCS_mutable) { 4833 // mutable can only appear on non-static class members, so it's always 4834 // an error here 4835 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4836 Invalid = true; 4837 SC = SC_None; 4838 } 4839 4840 Anon = VarDecl::Create(Context, Owner, 4841 DS.getLocStart(), 4842 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4843 Context.getTypeDeclType(Record), 4844 TInfo, SC); 4845 4846 // Default-initialize the implicit variable. This initialization will be 4847 // trivial in almost all cases, except if a union member has an in-class 4848 // initializer: 4849 // union { int n = 0; }; 4850 ActOnUninitializedDecl(Anon); 4851 } 4852 Anon->setImplicit(); 4853 4854 // Mark this as an anonymous struct/union type. 4855 Record->setAnonymousStructOrUnion(true); 4856 4857 // Add the anonymous struct/union object to the current 4858 // context. We'll be referencing this object when we refer to one of 4859 // its members. 4860 Owner->addDecl(Anon); 4861 4862 // Inject the members of the anonymous struct/union into the owning 4863 // context and into the identifier resolver chain for name lookup 4864 // purposes. 4865 SmallVector<NamedDecl*, 2> Chain; 4866 Chain.push_back(Anon); 4867 4868 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4869 Invalid = true; 4870 4871 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4872 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4873 Decl *ManglingContextDecl; 4874 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4875 NewVD->getDeclContext(), ManglingContextDecl)) { 4876 Context.setManglingNumber( 4877 NewVD, MCtx->getManglingNumber( 4878 NewVD, getMSManglingNumber(getLangOpts(), S))); 4879 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4880 } 4881 } 4882 } 4883 4884 if (Invalid) 4885 Anon->setInvalidDecl(); 4886 4887 return Anon; 4888 } 4889 4890 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4891 /// Microsoft C anonymous structure. 4892 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4893 /// Example: 4894 /// 4895 /// struct A { int a; }; 4896 /// struct B { struct A; int b; }; 4897 /// 4898 /// void foo() { 4899 /// B var; 4900 /// var.a = 3; 4901 /// } 4902 /// 4903 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4904 RecordDecl *Record) { 4905 assert(Record && "expected a record!"); 4906 4907 // Mock up a declarator. 4908 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4909 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4910 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4911 4912 auto *ParentDecl = cast<RecordDecl>(CurContext); 4913 QualType RecTy = Context.getTypeDeclType(Record); 4914 4915 // Create a declaration for this anonymous struct. 4916 NamedDecl *Anon = FieldDecl::Create(Context, 4917 ParentDecl, 4918 DS.getLocStart(), 4919 DS.getLocStart(), 4920 /*IdentifierInfo=*/nullptr, 4921 RecTy, 4922 TInfo, 4923 /*BitWidth=*/nullptr, /*Mutable=*/false, 4924 /*InitStyle=*/ICIS_NoInit); 4925 Anon->setImplicit(); 4926 4927 // Add the anonymous struct object to the current context. 4928 CurContext->addDecl(Anon); 4929 4930 // Inject the members of the anonymous struct into the current 4931 // context and into the identifier resolver chain for name lookup 4932 // purposes. 4933 SmallVector<NamedDecl*, 2> Chain; 4934 Chain.push_back(Anon); 4935 4936 RecordDecl *RecordDef = Record->getDefinition(); 4937 if (RequireCompleteType(Anon->getLocation(), RecTy, 4938 diag::err_field_incomplete) || 4939 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4940 AS_none, Chain)) { 4941 Anon->setInvalidDecl(); 4942 ParentDecl->setInvalidDecl(); 4943 } 4944 4945 return Anon; 4946 } 4947 4948 /// GetNameForDeclarator - Determine the full declaration name for the 4949 /// given Declarator. 4950 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4951 return GetNameFromUnqualifiedId(D.getName()); 4952 } 4953 4954 /// Retrieves the declaration name from a parsed unqualified-id. 4955 DeclarationNameInfo 4956 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4957 DeclarationNameInfo NameInfo; 4958 NameInfo.setLoc(Name.StartLocation); 4959 4960 switch (Name.getKind()) { 4961 4962 case UnqualifiedIdKind::IK_ImplicitSelfParam: 4963 case UnqualifiedIdKind::IK_Identifier: 4964 NameInfo.setName(Name.Identifier); 4965 NameInfo.setLoc(Name.StartLocation); 4966 return NameInfo; 4967 4968 case UnqualifiedIdKind::IK_DeductionGuideName: { 4969 // C++ [temp.deduct.guide]p3: 4970 // The simple-template-id shall name a class template specialization. 4971 // The template-name shall be the same identifier as the template-name 4972 // of the simple-template-id. 4973 // These together intend to imply that the template-name shall name a 4974 // class template. 4975 // FIXME: template<typename T> struct X {}; 4976 // template<typename T> using Y = X<T>; 4977 // Y(int) -> Y<int>; 4978 // satisfies these rules but does not name a class template. 4979 TemplateName TN = Name.TemplateName.get().get(); 4980 auto *Template = TN.getAsTemplateDecl(); 4981 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4982 Diag(Name.StartLocation, 4983 diag::err_deduction_guide_name_not_class_template) 4984 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4985 if (Template) 4986 Diag(Template->getLocation(), diag::note_template_decl_here); 4987 return DeclarationNameInfo(); 4988 } 4989 4990 NameInfo.setName( 4991 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4992 NameInfo.setLoc(Name.StartLocation); 4993 return NameInfo; 4994 } 4995 4996 case UnqualifiedIdKind::IK_OperatorFunctionId: 4997 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4998 Name.OperatorFunctionId.Operator)); 4999 NameInfo.setLoc(Name.StartLocation); 5000 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5001 = Name.OperatorFunctionId.SymbolLocations[0]; 5002 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5003 = Name.EndLocation.getRawEncoding(); 5004 return NameInfo; 5005 5006 case UnqualifiedIdKind::IK_LiteralOperatorId: 5007 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5008 Name.Identifier)); 5009 NameInfo.setLoc(Name.StartLocation); 5010 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5011 return NameInfo; 5012 5013 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5014 TypeSourceInfo *TInfo; 5015 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5016 if (Ty.isNull()) 5017 return DeclarationNameInfo(); 5018 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5019 Context.getCanonicalType(Ty))); 5020 NameInfo.setLoc(Name.StartLocation); 5021 NameInfo.setNamedTypeInfo(TInfo); 5022 return NameInfo; 5023 } 5024 5025 case UnqualifiedIdKind::IK_ConstructorName: { 5026 TypeSourceInfo *TInfo; 5027 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5028 if (Ty.isNull()) 5029 return DeclarationNameInfo(); 5030 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5031 Context.getCanonicalType(Ty))); 5032 NameInfo.setLoc(Name.StartLocation); 5033 NameInfo.setNamedTypeInfo(TInfo); 5034 return NameInfo; 5035 } 5036 5037 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5038 // In well-formed code, we can only have a constructor 5039 // template-id that refers to the current context, so go there 5040 // to find the actual type being constructed. 5041 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5042 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5043 return DeclarationNameInfo(); 5044 5045 // Determine the type of the class being constructed. 5046 QualType CurClassType = Context.getTypeDeclType(CurClass); 5047 5048 // FIXME: Check two things: that the template-id names the same type as 5049 // CurClassType, and that the template-id does not occur when the name 5050 // was qualified. 5051 5052 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5053 Context.getCanonicalType(CurClassType))); 5054 NameInfo.setLoc(Name.StartLocation); 5055 // FIXME: should we retrieve TypeSourceInfo? 5056 NameInfo.setNamedTypeInfo(nullptr); 5057 return NameInfo; 5058 } 5059 5060 case UnqualifiedIdKind::IK_DestructorName: { 5061 TypeSourceInfo *TInfo; 5062 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5063 if (Ty.isNull()) 5064 return DeclarationNameInfo(); 5065 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5066 Context.getCanonicalType(Ty))); 5067 NameInfo.setLoc(Name.StartLocation); 5068 NameInfo.setNamedTypeInfo(TInfo); 5069 return NameInfo; 5070 } 5071 5072 case UnqualifiedIdKind::IK_TemplateId: { 5073 TemplateName TName = Name.TemplateId->Template.get(); 5074 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5075 return Context.getNameForTemplate(TName, TNameLoc); 5076 } 5077 5078 } // switch (Name.getKind()) 5079 5080 llvm_unreachable("Unknown name kind"); 5081 } 5082 5083 static QualType getCoreType(QualType Ty) { 5084 do { 5085 if (Ty->isPointerType() || Ty->isReferenceType()) 5086 Ty = Ty->getPointeeType(); 5087 else if (Ty->isArrayType()) 5088 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5089 else 5090 return Ty.withoutLocalFastQualifiers(); 5091 } while (true); 5092 } 5093 5094 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5095 /// and Definition have "nearly" matching parameters. This heuristic is 5096 /// used to improve diagnostics in the case where an out-of-line function 5097 /// definition doesn't match any declaration within the class or namespace. 5098 /// Also sets Params to the list of indices to the parameters that differ 5099 /// between the declaration and the definition. If hasSimilarParameters 5100 /// returns true and Params is empty, then all of the parameters match. 5101 static bool hasSimilarParameters(ASTContext &Context, 5102 FunctionDecl *Declaration, 5103 FunctionDecl *Definition, 5104 SmallVectorImpl<unsigned> &Params) { 5105 Params.clear(); 5106 if (Declaration->param_size() != Definition->param_size()) 5107 return false; 5108 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5109 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5110 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5111 5112 // The parameter types are identical 5113 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5114 continue; 5115 5116 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5117 QualType DefParamBaseTy = getCoreType(DefParamTy); 5118 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5119 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5120 5121 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5122 (DeclTyName && DeclTyName == DefTyName)) 5123 Params.push_back(Idx); 5124 else // The two parameters aren't even close 5125 return false; 5126 } 5127 5128 return true; 5129 } 5130 5131 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5132 /// declarator needs to be rebuilt in the current instantiation. 5133 /// Any bits of declarator which appear before the name are valid for 5134 /// consideration here. That's specifically the type in the decl spec 5135 /// and the base type in any member-pointer chunks. 5136 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5137 DeclarationName Name) { 5138 // The types we specifically need to rebuild are: 5139 // - typenames, typeofs, and decltypes 5140 // - types which will become injected class names 5141 // Of course, we also need to rebuild any type referencing such a 5142 // type. It's safest to just say "dependent", but we call out a 5143 // few cases here. 5144 5145 DeclSpec &DS = D.getMutableDeclSpec(); 5146 switch (DS.getTypeSpecType()) { 5147 case DeclSpec::TST_typename: 5148 case DeclSpec::TST_typeofType: 5149 case DeclSpec::TST_underlyingType: 5150 case DeclSpec::TST_atomic: { 5151 // Grab the type from the parser. 5152 TypeSourceInfo *TSI = nullptr; 5153 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5154 if (T.isNull() || !T->isDependentType()) break; 5155 5156 // Make sure there's a type source info. This isn't really much 5157 // of a waste; most dependent types should have type source info 5158 // attached already. 5159 if (!TSI) 5160 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5161 5162 // Rebuild the type in the current instantiation. 5163 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5164 if (!TSI) return true; 5165 5166 // Store the new type back in the decl spec. 5167 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5168 DS.UpdateTypeRep(LocType); 5169 break; 5170 } 5171 5172 case DeclSpec::TST_decltype: 5173 case DeclSpec::TST_typeofExpr: { 5174 Expr *E = DS.getRepAsExpr(); 5175 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5176 if (Result.isInvalid()) return true; 5177 DS.UpdateExprRep(Result.get()); 5178 break; 5179 } 5180 5181 default: 5182 // Nothing to do for these decl specs. 5183 break; 5184 } 5185 5186 // It doesn't matter what order we do this in. 5187 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5188 DeclaratorChunk &Chunk = D.getTypeObject(I); 5189 5190 // The only type information in the declarator which can come 5191 // before the declaration name is the base type of a member 5192 // pointer. 5193 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5194 continue; 5195 5196 // Rebuild the scope specifier in-place. 5197 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5198 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5199 return true; 5200 } 5201 5202 return false; 5203 } 5204 5205 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5206 D.setFunctionDefinitionKind(FDK_Declaration); 5207 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5208 5209 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5210 Dcl && Dcl->getDeclContext()->isFileContext()) 5211 Dcl->setTopLevelDeclInObjCContainer(); 5212 5213 if (getLangOpts().OpenCL) 5214 setCurrentOpenCLExtensionForDecl(Dcl); 5215 5216 return Dcl; 5217 } 5218 5219 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5220 /// If T is the name of a class, then each of the following shall have a 5221 /// name different from T: 5222 /// - every static data member of class T; 5223 /// - every member function of class T 5224 /// - every member of class T that is itself a type; 5225 /// \returns true if the declaration name violates these rules. 5226 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5227 DeclarationNameInfo NameInfo) { 5228 DeclarationName Name = NameInfo.getName(); 5229 5230 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5231 while (Record && Record->isAnonymousStructOrUnion()) 5232 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5233 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5234 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5235 return true; 5236 } 5237 5238 return false; 5239 } 5240 5241 /// Diagnose a declaration whose declarator-id has the given 5242 /// nested-name-specifier. 5243 /// 5244 /// \param SS The nested-name-specifier of the declarator-id. 5245 /// 5246 /// \param DC The declaration context to which the nested-name-specifier 5247 /// resolves. 5248 /// 5249 /// \param Name The name of the entity being declared. 5250 /// 5251 /// \param Loc The location of the name of the entity being declared. 5252 /// 5253 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5254 /// we're declaring an explicit / partial specialization / instantiation. 5255 /// 5256 /// \returns true if we cannot safely recover from this error, false otherwise. 5257 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5258 DeclarationName Name, 5259 SourceLocation Loc, bool IsTemplateId) { 5260 DeclContext *Cur = CurContext; 5261 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5262 Cur = Cur->getParent(); 5263 5264 // If the user provided a superfluous scope specifier that refers back to the 5265 // class in which the entity is already declared, diagnose and ignore it. 5266 // 5267 // class X { 5268 // void X::f(); 5269 // }; 5270 // 5271 // Note, it was once ill-formed to give redundant qualification in all 5272 // contexts, but that rule was removed by DR482. 5273 if (Cur->Equals(DC)) { 5274 if (Cur->isRecord()) { 5275 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5276 : diag::err_member_extra_qualification) 5277 << Name << FixItHint::CreateRemoval(SS.getRange()); 5278 SS.clear(); 5279 } else { 5280 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5281 } 5282 return false; 5283 } 5284 5285 // Check whether the qualifying scope encloses the scope of the original 5286 // declaration. For a template-id, we perform the checks in 5287 // CheckTemplateSpecializationScope. 5288 if (!Cur->Encloses(DC) && !IsTemplateId) { 5289 if (Cur->isRecord()) 5290 Diag(Loc, diag::err_member_qualification) 5291 << Name << SS.getRange(); 5292 else if (isa<TranslationUnitDecl>(DC)) 5293 Diag(Loc, diag::err_invalid_declarator_global_scope) 5294 << Name << SS.getRange(); 5295 else if (isa<FunctionDecl>(Cur)) 5296 Diag(Loc, diag::err_invalid_declarator_in_function) 5297 << Name << SS.getRange(); 5298 else if (isa<BlockDecl>(Cur)) 5299 Diag(Loc, diag::err_invalid_declarator_in_block) 5300 << Name << SS.getRange(); 5301 else 5302 Diag(Loc, diag::err_invalid_declarator_scope) 5303 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5304 5305 return true; 5306 } 5307 5308 if (Cur->isRecord()) { 5309 // Cannot qualify members within a class. 5310 Diag(Loc, diag::err_member_qualification) 5311 << Name << SS.getRange(); 5312 SS.clear(); 5313 5314 // C++ constructors and destructors with incorrect scopes can break 5315 // our AST invariants by having the wrong underlying types. If 5316 // that's the case, then drop this declaration entirely. 5317 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5318 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5319 !Context.hasSameType(Name.getCXXNameType(), 5320 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5321 return true; 5322 5323 return false; 5324 } 5325 5326 // C++11 [dcl.meaning]p1: 5327 // [...] "The nested-name-specifier of the qualified declarator-id shall 5328 // not begin with a decltype-specifer" 5329 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5330 while (SpecLoc.getPrefix()) 5331 SpecLoc = SpecLoc.getPrefix(); 5332 if (dyn_cast_or_null<DecltypeType>( 5333 SpecLoc.getNestedNameSpecifier()->getAsType())) 5334 Diag(Loc, diag::err_decltype_in_declarator) 5335 << SpecLoc.getTypeLoc().getSourceRange(); 5336 5337 return false; 5338 } 5339 5340 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5341 MultiTemplateParamsArg TemplateParamLists) { 5342 // TODO: consider using NameInfo for diagnostic. 5343 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5344 DeclarationName Name = NameInfo.getName(); 5345 5346 // All of these full declarators require an identifier. If it doesn't have 5347 // one, the ParsedFreeStandingDeclSpec action should be used. 5348 if (D.isDecompositionDeclarator()) { 5349 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5350 } else if (!Name) { 5351 if (!D.isInvalidType()) // Reject this if we think it is valid. 5352 Diag(D.getDeclSpec().getLocStart(), 5353 diag::err_declarator_need_ident) 5354 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5355 return nullptr; 5356 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5357 return nullptr; 5358 5359 // The scope passed in may not be a decl scope. Zip up the scope tree until 5360 // we find one that is. 5361 while ((S->getFlags() & Scope::DeclScope) == 0 || 5362 (S->getFlags() & Scope::TemplateParamScope) != 0) 5363 S = S->getParent(); 5364 5365 DeclContext *DC = CurContext; 5366 if (D.getCXXScopeSpec().isInvalid()) 5367 D.setInvalidType(); 5368 else if (D.getCXXScopeSpec().isSet()) { 5369 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5370 UPPC_DeclarationQualifier)) 5371 return nullptr; 5372 5373 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5374 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5375 if (!DC || isa<EnumDecl>(DC)) { 5376 // If we could not compute the declaration context, it's because the 5377 // declaration context is dependent but does not refer to a class, 5378 // class template, or class template partial specialization. Complain 5379 // and return early, to avoid the coming semantic disaster. 5380 Diag(D.getIdentifierLoc(), 5381 diag::err_template_qualified_declarator_no_match) 5382 << D.getCXXScopeSpec().getScopeRep() 5383 << D.getCXXScopeSpec().getRange(); 5384 return nullptr; 5385 } 5386 bool IsDependentContext = DC->isDependentContext(); 5387 5388 if (!IsDependentContext && 5389 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5390 return nullptr; 5391 5392 // If a class is incomplete, do not parse entities inside it. 5393 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5394 Diag(D.getIdentifierLoc(), 5395 diag::err_member_def_undefined_record) 5396 << Name << DC << D.getCXXScopeSpec().getRange(); 5397 return nullptr; 5398 } 5399 if (!D.getDeclSpec().isFriendSpecified()) { 5400 if (diagnoseQualifiedDeclaration( 5401 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5402 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5403 if (DC->isRecord()) 5404 return nullptr; 5405 5406 D.setInvalidType(); 5407 } 5408 } 5409 5410 // Check whether we need to rebuild the type of the given 5411 // declaration in the current instantiation. 5412 if (EnteringContext && IsDependentContext && 5413 TemplateParamLists.size() != 0) { 5414 ContextRAII SavedContext(*this, DC); 5415 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5416 D.setInvalidType(); 5417 } 5418 } 5419 5420 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5421 QualType R = TInfo->getType(); 5422 5423 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5424 UPPC_DeclarationType)) 5425 D.setInvalidType(); 5426 5427 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5428 forRedeclarationInCurContext()); 5429 5430 // See if this is a redefinition of a variable in the same scope. 5431 if (!D.getCXXScopeSpec().isSet()) { 5432 bool IsLinkageLookup = false; 5433 bool CreateBuiltins = false; 5434 5435 // If the declaration we're planning to build will be a function 5436 // or object with linkage, then look for another declaration with 5437 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5438 // 5439 // If the declaration we're planning to build will be declared with 5440 // external linkage in the translation unit, create any builtin with 5441 // the same name. 5442 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5443 /* Do nothing*/; 5444 else if (CurContext->isFunctionOrMethod() && 5445 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5446 R->isFunctionType())) { 5447 IsLinkageLookup = true; 5448 CreateBuiltins = 5449 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5450 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5451 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5452 CreateBuiltins = true; 5453 5454 if (IsLinkageLookup) { 5455 Previous.clear(LookupRedeclarationWithLinkage); 5456 Previous.setRedeclarationKind(ForExternalRedeclaration); 5457 } 5458 5459 LookupName(Previous, S, CreateBuiltins); 5460 } else { // Something like "int foo::x;" 5461 LookupQualifiedName(Previous, DC); 5462 5463 // C++ [dcl.meaning]p1: 5464 // When the declarator-id is qualified, the declaration shall refer to a 5465 // previously declared member of the class or namespace to which the 5466 // qualifier refers (or, in the case of a namespace, of an element of the 5467 // inline namespace set of that namespace (7.3.1)) or to a specialization 5468 // thereof; [...] 5469 // 5470 // Note that we already checked the context above, and that we do not have 5471 // enough information to make sure that Previous contains the declaration 5472 // we want to match. For example, given: 5473 // 5474 // class X { 5475 // void f(); 5476 // void f(float); 5477 // }; 5478 // 5479 // void X::f(int) { } // ill-formed 5480 // 5481 // In this case, Previous will point to the overload set 5482 // containing the two f's declared in X, but neither of them 5483 // matches. 5484 5485 // C++ [dcl.meaning]p1: 5486 // [...] the member shall not merely have been introduced by a 5487 // using-declaration in the scope of the class or namespace nominated by 5488 // the nested-name-specifier of the declarator-id. 5489 RemoveUsingDecls(Previous); 5490 } 5491 5492 if (Previous.isSingleResult() && 5493 Previous.getFoundDecl()->isTemplateParameter()) { 5494 // Maybe we will complain about the shadowed template parameter. 5495 if (!D.isInvalidType()) 5496 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5497 Previous.getFoundDecl()); 5498 5499 // Just pretend that we didn't see the previous declaration. 5500 Previous.clear(); 5501 } 5502 5503 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5504 // Forget that the previous declaration is the injected-class-name. 5505 Previous.clear(); 5506 5507 // In C++, the previous declaration we find might be a tag type 5508 // (class or enum). In this case, the new declaration will hide the 5509 // tag type. Note that this applies to functions, function templates, and 5510 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5511 if (Previous.isSingleTagDecl() && 5512 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5513 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5514 Previous.clear(); 5515 5516 // Check that there are no default arguments other than in the parameters 5517 // of a function declaration (C++ only). 5518 if (getLangOpts().CPlusPlus) 5519 CheckExtraCXXDefaultArguments(D); 5520 5521 NamedDecl *New; 5522 5523 bool AddToScope = true; 5524 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5525 if (TemplateParamLists.size()) { 5526 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5527 return nullptr; 5528 } 5529 5530 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5531 } else if (R->isFunctionType()) { 5532 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5533 TemplateParamLists, 5534 AddToScope); 5535 } else { 5536 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5537 AddToScope); 5538 } 5539 5540 if (!New) 5541 return nullptr; 5542 5543 // If this has an identifier and is not a function template specialization, 5544 // add it to the scope stack. 5545 if (New->getDeclName() && AddToScope) { 5546 // Only make a locally-scoped extern declaration visible if it is the first 5547 // declaration of this entity. Qualified lookup for such an entity should 5548 // only find this declaration if there is no visible declaration of it. 5549 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5550 PushOnScopeChains(New, S, AddToContext); 5551 if (!AddToContext) 5552 CurContext->addHiddenDecl(New); 5553 } 5554 5555 if (isInOpenMPDeclareTargetContext()) 5556 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5557 5558 return New; 5559 } 5560 5561 /// Helper method to turn variable array types into constant array 5562 /// types in certain situations which would otherwise be errors (for 5563 /// GCC compatibility). 5564 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5565 ASTContext &Context, 5566 bool &SizeIsNegative, 5567 llvm::APSInt &Oversized) { 5568 // This method tries to turn a variable array into a constant 5569 // array even when the size isn't an ICE. This is necessary 5570 // for compatibility with code that depends on gcc's buggy 5571 // constant expression folding, like struct {char x[(int)(char*)2];} 5572 SizeIsNegative = false; 5573 Oversized = 0; 5574 5575 if (T->isDependentType()) 5576 return QualType(); 5577 5578 QualifierCollector Qs; 5579 const Type *Ty = Qs.strip(T); 5580 5581 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5582 QualType Pointee = PTy->getPointeeType(); 5583 QualType FixedType = 5584 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5585 Oversized); 5586 if (FixedType.isNull()) return FixedType; 5587 FixedType = Context.getPointerType(FixedType); 5588 return Qs.apply(Context, FixedType); 5589 } 5590 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5591 QualType Inner = PTy->getInnerType(); 5592 QualType FixedType = 5593 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5594 Oversized); 5595 if (FixedType.isNull()) return FixedType; 5596 FixedType = Context.getParenType(FixedType); 5597 return Qs.apply(Context, FixedType); 5598 } 5599 5600 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5601 if (!VLATy) 5602 return QualType(); 5603 // FIXME: We should probably handle this case 5604 if (VLATy->getElementType()->isVariablyModifiedType()) 5605 return QualType(); 5606 5607 llvm::APSInt Res; 5608 if (!VLATy->getSizeExpr() || 5609 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5610 return QualType(); 5611 5612 // Check whether the array size is negative. 5613 if (Res.isSigned() && Res.isNegative()) { 5614 SizeIsNegative = true; 5615 return QualType(); 5616 } 5617 5618 // Check whether the array is too large to be addressed. 5619 unsigned ActiveSizeBits 5620 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5621 Res); 5622 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5623 Oversized = Res; 5624 return QualType(); 5625 } 5626 5627 return Context.getConstantArrayType(VLATy->getElementType(), 5628 Res, ArrayType::Normal, 0); 5629 } 5630 5631 static void 5632 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5633 SrcTL = SrcTL.getUnqualifiedLoc(); 5634 DstTL = DstTL.getUnqualifiedLoc(); 5635 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5636 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5637 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5638 DstPTL.getPointeeLoc()); 5639 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5640 return; 5641 } 5642 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5643 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5644 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5645 DstPTL.getInnerLoc()); 5646 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5647 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5648 return; 5649 } 5650 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5651 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5652 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5653 TypeLoc DstElemTL = DstATL.getElementLoc(); 5654 DstElemTL.initializeFullCopy(SrcElemTL); 5655 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5656 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5657 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5658 } 5659 5660 /// Helper method to turn variable array types into constant array 5661 /// types in certain situations which would otherwise be errors (for 5662 /// GCC compatibility). 5663 static TypeSourceInfo* 5664 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5665 ASTContext &Context, 5666 bool &SizeIsNegative, 5667 llvm::APSInt &Oversized) { 5668 QualType FixedTy 5669 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5670 SizeIsNegative, Oversized); 5671 if (FixedTy.isNull()) 5672 return nullptr; 5673 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5674 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5675 FixedTInfo->getTypeLoc()); 5676 return FixedTInfo; 5677 } 5678 5679 /// Register the given locally-scoped extern "C" declaration so 5680 /// that it can be found later for redeclarations. We include any extern "C" 5681 /// declaration that is not visible in the translation unit here, not just 5682 /// function-scope declarations. 5683 void 5684 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5685 if (!getLangOpts().CPlusPlus && 5686 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5687 // Don't need to track declarations in the TU in C. 5688 return; 5689 5690 // Note that we have a locally-scoped external with this name. 5691 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5692 } 5693 5694 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5695 // FIXME: We can have multiple results via __attribute__((overloadable)). 5696 auto Result = Context.getExternCContextDecl()->lookup(Name); 5697 return Result.empty() ? nullptr : *Result.begin(); 5698 } 5699 5700 /// Diagnose function specifiers on a declaration of an identifier that 5701 /// does not identify a function. 5702 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5703 // FIXME: We should probably indicate the identifier in question to avoid 5704 // confusion for constructs like "virtual int a(), b;" 5705 if (DS.isVirtualSpecified()) 5706 Diag(DS.getVirtualSpecLoc(), 5707 diag::err_virtual_non_function); 5708 5709 if (DS.isExplicitSpecified()) 5710 Diag(DS.getExplicitSpecLoc(), 5711 diag::err_explicit_non_function); 5712 5713 if (DS.isNoreturnSpecified()) 5714 Diag(DS.getNoreturnSpecLoc(), 5715 diag::err_noreturn_non_function); 5716 } 5717 5718 NamedDecl* 5719 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5720 TypeSourceInfo *TInfo, LookupResult &Previous) { 5721 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5722 if (D.getCXXScopeSpec().isSet()) { 5723 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5724 << D.getCXXScopeSpec().getRange(); 5725 D.setInvalidType(); 5726 // Pretend we didn't see the scope specifier. 5727 DC = CurContext; 5728 Previous.clear(); 5729 } 5730 5731 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5732 5733 if (D.getDeclSpec().isInlineSpecified()) 5734 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5735 << getLangOpts().CPlusPlus17; 5736 if (D.getDeclSpec().isConstexprSpecified()) 5737 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5738 << 1; 5739 5740 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5741 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5742 Diag(D.getName().StartLocation, 5743 diag::err_deduction_guide_invalid_specifier) 5744 << "typedef"; 5745 else 5746 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5747 << D.getName().getSourceRange(); 5748 return nullptr; 5749 } 5750 5751 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5752 if (!NewTD) return nullptr; 5753 5754 // Handle attributes prior to checking for duplicates in MergeVarDecl 5755 ProcessDeclAttributes(S, NewTD, D); 5756 5757 CheckTypedefForVariablyModifiedType(S, NewTD); 5758 5759 bool Redeclaration = D.isRedeclaration(); 5760 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5761 D.setRedeclaration(Redeclaration); 5762 return ND; 5763 } 5764 5765 void 5766 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5767 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5768 // then it shall have block scope. 5769 // Note that variably modified types must be fixed before merging the decl so 5770 // that redeclarations will match. 5771 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5772 QualType T = TInfo->getType(); 5773 if (T->isVariablyModifiedType()) { 5774 setFunctionHasBranchProtectedScope(); 5775 5776 if (S->getFnParent() == nullptr) { 5777 bool SizeIsNegative; 5778 llvm::APSInt Oversized; 5779 TypeSourceInfo *FixedTInfo = 5780 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5781 SizeIsNegative, 5782 Oversized); 5783 if (FixedTInfo) { 5784 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5785 NewTD->setTypeSourceInfo(FixedTInfo); 5786 } else { 5787 if (SizeIsNegative) 5788 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5789 else if (T->isVariableArrayType()) 5790 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5791 else if (Oversized.getBoolValue()) 5792 Diag(NewTD->getLocation(), diag::err_array_too_large) 5793 << Oversized.toString(10); 5794 else 5795 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5796 NewTD->setInvalidDecl(); 5797 } 5798 } 5799 } 5800 } 5801 5802 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5803 /// declares a typedef-name, either using the 'typedef' type specifier or via 5804 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5805 NamedDecl* 5806 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5807 LookupResult &Previous, bool &Redeclaration) { 5808 5809 // Find the shadowed declaration before filtering for scope. 5810 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5811 5812 // Merge the decl with the existing one if appropriate. If the decl is 5813 // in an outer scope, it isn't the same thing. 5814 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5815 /*AllowInlineNamespace*/false); 5816 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5817 if (!Previous.empty()) { 5818 Redeclaration = true; 5819 MergeTypedefNameDecl(S, NewTD, Previous); 5820 } 5821 5822 if (ShadowedDecl && !Redeclaration) 5823 CheckShadow(NewTD, ShadowedDecl, Previous); 5824 5825 // If this is the C FILE type, notify the AST context. 5826 if (IdentifierInfo *II = NewTD->getIdentifier()) 5827 if (!NewTD->isInvalidDecl() && 5828 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5829 if (II->isStr("FILE")) 5830 Context.setFILEDecl(NewTD); 5831 else if (II->isStr("jmp_buf")) 5832 Context.setjmp_bufDecl(NewTD); 5833 else if (II->isStr("sigjmp_buf")) 5834 Context.setsigjmp_bufDecl(NewTD); 5835 else if (II->isStr("ucontext_t")) 5836 Context.setucontext_tDecl(NewTD); 5837 } 5838 5839 return NewTD; 5840 } 5841 5842 /// Determines whether the given declaration is an out-of-scope 5843 /// previous declaration. 5844 /// 5845 /// This routine should be invoked when name lookup has found a 5846 /// previous declaration (PrevDecl) that is not in the scope where a 5847 /// new declaration by the same name is being introduced. If the new 5848 /// declaration occurs in a local scope, previous declarations with 5849 /// linkage may still be considered previous declarations (C99 5850 /// 6.2.2p4-5, C++ [basic.link]p6). 5851 /// 5852 /// \param PrevDecl the previous declaration found by name 5853 /// lookup 5854 /// 5855 /// \param DC the context in which the new declaration is being 5856 /// declared. 5857 /// 5858 /// \returns true if PrevDecl is an out-of-scope previous declaration 5859 /// for a new delcaration with the same name. 5860 static bool 5861 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5862 ASTContext &Context) { 5863 if (!PrevDecl) 5864 return false; 5865 5866 if (!PrevDecl->hasLinkage()) 5867 return false; 5868 5869 if (Context.getLangOpts().CPlusPlus) { 5870 // C++ [basic.link]p6: 5871 // If there is a visible declaration of an entity with linkage 5872 // having the same name and type, ignoring entities declared 5873 // outside the innermost enclosing namespace scope, the block 5874 // scope declaration declares that same entity and receives the 5875 // linkage of the previous declaration. 5876 DeclContext *OuterContext = DC->getRedeclContext(); 5877 if (!OuterContext->isFunctionOrMethod()) 5878 // This rule only applies to block-scope declarations. 5879 return false; 5880 5881 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5882 if (PrevOuterContext->isRecord()) 5883 // We found a member function: ignore it. 5884 return false; 5885 5886 // Find the innermost enclosing namespace for the new and 5887 // previous declarations. 5888 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5889 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5890 5891 // The previous declaration is in a different namespace, so it 5892 // isn't the same function. 5893 if (!OuterContext->Equals(PrevOuterContext)) 5894 return false; 5895 } 5896 5897 return true; 5898 } 5899 5900 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5901 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5902 if (!SS.isSet()) return; 5903 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5904 } 5905 5906 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5907 QualType type = decl->getType(); 5908 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5909 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5910 // Various kinds of declaration aren't allowed to be __autoreleasing. 5911 unsigned kind = -1U; 5912 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5913 if (var->hasAttr<BlocksAttr>()) 5914 kind = 0; // __block 5915 else if (!var->hasLocalStorage()) 5916 kind = 1; // global 5917 } else if (isa<ObjCIvarDecl>(decl)) { 5918 kind = 3; // ivar 5919 } else if (isa<FieldDecl>(decl)) { 5920 kind = 2; // field 5921 } 5922 5923 if (kind != -1U) { 5924 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5925 << kind; 5926 } 5927 } else if (lifetime == Qualifiers::OCL_None) { 5928 // Try to infer lifetime. 5929 if (!type->isObjCLifetimeType()) 5930 return false; 5931 5932 lifetime = type->getObjCARCImplicitLifetime(); 5933 type = Context.getLifetimeQualifiedType(type, lifetime); 5934 decl->setType(type); 5935 } 5936 5937 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5938 // Thread-local variables cannot have lifetime. 5939 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5940 var->getTLSKind()) { 5941 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5942 << var->getType(); 5943 return true; 5944 } 5945 } 5946 5947 return false; 5948 } 5949 5950 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5951 // Ensure that an auto decl is deduced otherwise the checks below might cache 5952 // the wrong linkage. 5953 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5954 5955 // 'weak' only applies to declarations with external linkage. 5956 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5957 if (!ND.isExternallyVisible()) { 5958 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5959 ND.dropAttr<WeakAttr>(); 5960 } 5961 } 5962 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5963 if (ND.isExternallyVisible()) { 5964 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5965 ND.dropAttr<WeakRefAttr>(); 5966 ND.dropAttr<AliasAttr>(); 5967 } 5968 } 5969 5970 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5971 if (VD->hasInit()) { 5972 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5973 assert(VD->isThisDeclarationADefinition() && 5974 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5975 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5976 VD->dropAttr<AliasAttr>(); 5977 } 5978 } 5979 } 5980 5981 // 'selectany' only applies to externally visible variable declarations. 5982 // It does not apply to functions. 5983 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5984 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5985 S.Diag(Attr->getLocation(), 5986 diag::err_attribute_selectany_non_extern_data); 5987 ND.dropAttr<SelectAnyAttr>(); 5988 } 5989 } 5990 5991 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5992 // dll attributes require external linkage. Static locals may have external 5993 // linkage but still cannot be explicitly imported or exported. 5994 auto *VD = dyn_cast<VarDecl>(&ND); 5995 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5996 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5997 << &ND << Attr; 5998 ND.setInvalidDecl(); 5999 } 6000 } 6001 6002 // Virtual functions cannot be marked as 'notail'. 6003 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6004 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6005 if (MD->isVirtual()) { 6006 S.Diag(ND.getLocation(), 6007 diag::err_invalid_attribute_on_virtual_function) 6008 << Attr; 6009 ND.dropAttr<NotTailCalledAttr>(); 6010 } 6011 } 6012 6013 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6014 NamedDecl *NewDecl, 6015 bool IsSpecialization, 6016 bool IsDefinition) { 6017 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6018 return; 6019 6020 bool IsTemplate = false; 6021 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6022 OldDecl = OldTD->getTemplatedDecl(); 6023 IsTemplate = true; 6024 if (!IsSpecialization) 6025 IsDefinition = false; 6026 } 6027 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6028 NewDecl = NewTD->getTemplatedDecl(); 6029 IsTemplate = true; 6030 } 6031 6032 if (!OldDecl || !NewDecl) 6033 return; 6034 6035 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6036 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6037 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6038 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6039 6040 // dllimport and dllexport are inheritable attributes so we have to exclude 6041 // inherited attribute instances. 6042 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6043 (NewExportAttr && !NewExportAttr->isInherited()); 6044 6045 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6046 // the only exception being explicit specializations. 6047 // Implicitly generated declarations are also excluded for now because there 6048 // is no other way to switch these to use dllimport or dllexport. 6049 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6050 6051 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6052 // Allow with a warning for free functions and global variables. 6053 bool JustWarn = false; 6054 if (!OldDecl->isCXXClassMember()) { 6055 auto *VD = dyn_cast<VarDecl>(OldDecl); 6056 if (VD && !VD->getDescribedVarTemplate()) 6057 JustWarn = true; 6058 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6059 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6060 JustWarn = true; 6061 } 6062 6063 // We cannot change a declaration that's been used because IR has already 6064 // been emitted. Dllimported functions will still work though (modulo 6065 // address equality) as they can use the thunk. 6066 if (OldDecl->isUsed()) 6067 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6068 JustWarn = false; 6069 6070 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6071 : diag::err_attribute_dll_redeclaration; 6072 S.Diag(NewDecl->getLocation(), DiagID) 6073 << NewDecl 6074 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6075 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6076 if (!JustWarn) { 6077 NewDecl->setInvalidDecl(); 6078 return; 6079 } 6080 } 6081 6082 // A redeclaration is not allowed to drop a dllimport attribute, the only 6083 // exceptions being inline function definitions (except for function 6084 // templates), local extern declarations, qualified friend declarations or 6085 // special MSVC extension: in the last case, the declaration is treated as if 6086 // it were marked dllexport. 6087 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6088 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6089 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6090 // Ignore static data because out-of-line definitions are diagnosed 6091 // separately. 6092 IsStaticDataMember = VD->isStaticDataMember(); 6093 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6094 VarDecl::DeclarationOnly; 6095 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6096 IsInline = FD->isInlined(); 6097 IsQualifiedFriend = FD->getQualifier() && 6098 FD->getFriendObjectKind() == Decl::FOK_Declared; 6099 } 6100 6101 if (OldImportAttr && !HasNewAttr && 6102 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6103 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6104 if (IsMicrosoft && IsDefinition) { 6105 S.Diag(NewDecl->getLocation(), 6106 diag::warn_redeclaration_without_import_attribute) 6107 << NewDecl; 6108 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6109 NewDecl->dropAttr<DLLImportAttr>(); 6110 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6111 NewImportAttr->getRange(), S.Context, 6112 NewImportAttr->getSpellingListIndex())); 6113 } else { 6114 S.Diag(NewDecl->getLocation(), 6115 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6116 << NewDecl << OldImportAttr; 6117 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6118 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6119 OldDecl->dropAttr<DLLImportAttr>(); 6120 NewDecl->dropAttr<DLLImportAttr>(); 6121 } 6122 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6123 // In MinGW, seeing a function declared inline drops the dllimport 6124 // attribute. 6125 OldDecl->dropAttr<DLLImportAttr>(); 6126 NewDecl->dropAttr<DLLImportAttr>(); 6127 S.Diag(NewDecl->getLocation(), 6128 diag::warn_dllimport_dropped_from_inline_function) 6129 << NewDecl << OldImportAttr; 6130 } 6131 6132 // A specialization of a class template member function is processed here 6133 // since it's a redeclaration. If the parent class is dllexport, the 6134 // specialization inherits that attribute. This doesn't happen automatically 6135 // since the parent class isn't instantiated until later. 6136 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6137 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6138 !NewImportAttr && !NewExportAttr) { 6139 if (const DLLExportAttr *ParentExportAttr = 6140 MD->getParent()->getAttr<DLLExportAttr>()) { 6141 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6142 NewAttr->setInherited(true); 6143 NewDecl->addAttr(NewAttr); 6144 } 6145 } 6146 } 6147 } 6148 6149 /// Given that we are within the definition of the given function, 6150 /// will that definition behave like C99's 'inline', where the 6151 /// definition is discarded except for optimization purposes? 6152 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6153 // Try to avoid calling GetGVALinkageForFunction. 6154 6155 // All cases of this require the 'inline' keyword. 6156 if (!FD->isInlined()) return false; 6157 6158 // This is only possible in C++ with the gnu_inline attribute. 6159 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6160 return false; 6161 6162 // Okay, go ahead and call the relatively-more-expensive function. 6163 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6164 } 6165 6166 /// Determine whether a variable is extern "C" prior to attaching 6167 /// an initializer. We can't just call isExternC() here, because that 6168 /// will also compute and cache whether the declaration is externally 6169 /// visible, which might change when we attach the initializer. 6170 /// 6171 /// This can only be used if the declaration is known to not be a 6172 /// redeclaration of an internal linkage declaration. 6173 /// 6174 /// For instance: 6175 /// 6176 /// auto x = []{}; 6177 /// 6178 /// Attaching the initializer here makes this declaration not externally 6179 /// visible, because its type has internal linkage. 6180 /// 6181 /// FIXME: This is a hack. 6182 template<typename T> 6183 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6184 if (S.getLangOpts().CPlusPlus) { 6185 // In C++, the overloadable attribute negates the effects of extern "C". 6186 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6187 return false; 6188 6189 // So do CUDA's host/device attributes. 6190 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6191 D->template hasAttr<CUDAHostAttr>())) 6192 return false; 6193 } 6194 return D->isExternC(); 6195 } 6196 6197 static bool shouldConsiderLinkage(const VarDecl *VD) { 6198 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6199 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6200 return VD->hasExternalStorage(); 6201 if (DC->isFileContext()) 6202 return true; 6203 if (DC->isRecord()) 6204 return false; 6205 llvm_unreachable("Unexpected context"); 6206 } 6207 6208 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6209 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6210 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6211 isa<OMPDeclareReductionDecl>(DC)) 6212 return true; 6213 if (DC->isRecord()) 6214 return false; 6215 llvm_unreachable("Unexpected context"); 6216 } 6217 6218 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6219 ParsedAttr::Kind Kind) { 6220 // Check decl attributes on the DeclSpec. 6221 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6222 return true; 6223 6224 // Walk the declarator structure, checking decl attributes that were in a type 6225 // position to the decl itself. 6226 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6227 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6228 return true; 6229 } 6230 6231 // Finally, check attributes on the decl itself. 6232 return PD.getAttributes().hasAttribute(Kind); 6233 } 6234 6235 /// Adjust the \c DeclContext for a function or variable that might be a 6236 /// function-local external declaration. 6237 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6238 if (!DC->isFunctionOrMethod()) 6239 return false; 6240 6241 // If this is a local extern function or variable declared within a function 6242 // template, don't add it into the enclosing namespace scope until it is 6243 // instantiated; it might have a dependent type right now. 6244 if (DC->isDependentContext()) 6245 return true; 6246 6247 // C++11 [basic.link]p7: 6248 // When a block scope declaration of an entity with linkage is not found to 6249 // refer to some other declaration, then that entity is a member of the 6250 // innermost enclosing namespace. 6251 // 6252 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6253 // semantically-enclosing namespace, not a lexically-enclosing one. 6254 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6255 DC = DC->getParent(); 6256 return true; 6257 } 6258 6259 /// Returns true if given declaration has external C language linkage. 6260 static bool isDeclExternC(const Decl *D) { 6261 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6262 return FD->isExternC(); 6263 if (const auto *VD = dyn_cast<VarDecl>(D)) 6264 return VD->isExternC(); 6265 6266 llvm_unreachable("Unknown type of decl!"); 6267 } 6268 6269 NamedDecl *Sema::ActOnVariableDeclarator( 6270 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6271 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6272 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6273 QualType R = TInfo->getType(); 6274 DeclarationName Name = GetNameForDeclarator(D).getName(); 6275 6276 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6277 6278 if (D.isDecompositionDeclarator()) { 6279 // Take the name of the first declarator as our name for diagnostic 6280 // purposes. 6281 auto &Decomp = D.getDecompositionDeclarator(); 6282 if (!Decomp.bindings().empty()) { 6283 II = Decomp.bindings()[0].Name; 6284 Name = II; 6285 } 6286 } else if (!II) { 6287 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6288 return nullptr; 6289 } 6290 6291 if (getLangOpts().OpenCL) { 6292 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6293 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6294 // argument. 6295 if (R->isImageType() || R->isPipeType()) { 6296 Diag(D.getIdentifierLoc(), 6297 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6298 << R; 6299 D.setInvalidType(); 6300 return nullptr; 6301 } 6302 6303 // OpenCL v1.2 s6.9.r: 6304 // The event type cannot be used to declare a program scope variable. 6305 // OpenCL v2.0 s6.9.q: 6306 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6307 if (NULL == S->getParent()) { 6308 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6309 Diag(D.getIdentifierLoc(), 6310 diag::err_invalid_type_for_program_scope_var) << R; 6311 D.setInvalidType(); 6312 return nullptr; 6313 } 6314 } 6315 6316 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6317 QualType NR = R; 6318 while (NR->isPointerType()) { 6319 if (NR->isFunctionPointerType()) { 6320 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6321 D.setInvalidType(); 6322 break; 6323 } 6324 NR = NR->getPointeeType(); 6325 } 6326 6327 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6328 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6329 // half array type (unless the cl_khr_fp16 extension is enabled). 6330 if (Context.getBaseElementType(R)->isHalfType()) { 6331 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6332 D.setInvalidType(); 6333 } 6334 } 6335 6336 if (R->isSamplerT()) { 6337 // OpenCL v1.2 s6.9.b p4: 6338 // The sampler type cannot be used with the __local and __global address 6339 // space qualifiers. 6340 if (R.getAddressSpace() == LangAS::opencl_local || 6341 R.getAddressSpace() == LangAS::opencl_global) { 6342 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6343 } 6344 6345 // OpenCL v1.2 s6.12.14.1: 6346 // A global sampler must be declared with either the constant address 6347 // space qualifier or with the const qualifier. 6348 if (DC->isTranslationUnit() && 6349 !(R.getAddressSpace() == LangAS::opencl_constant || 6350 R.isConstQualified())) { 6351 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6352 D.setInvalidType(); 6353 } 6354 } 6355 6356 // OpenCL v1.2 s6.9.r: 6357 // The event type cannot be used with the __local, __constant and __global 6358 // address space qualifiers. 6359 if (R->isEventT()) { 6360 if (R.getAddressSpace() != LangAS::opencl_private) { 6361 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6362 D.setInvalidType(); 6363 } 6364 } 6365 6366 // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not 6367 // supported. OpenCL C does not support thread_local either, and 6368 // also reject all other thread storage class specifiers. 6369 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6370 if (TSC != TSCS_unspecified) { 6371 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6372 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6373 diag::err_opencl_unknown_type_specifier) 6374 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6375 << DeclSpec::getSpecifierName(TSC) << 1; 6376 D.setInvalidType(); 6377 return nullptr; 6378 } 6379 } 6380 6381 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6382 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6383 6384 // dllimport globals without explicit storage class are treated as extern. We 6385 // have to change the storage class this early to get the right DeclContext. 6386 if (SC == SC_None && !DC->isRecord() && 6387 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6388 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6389 SC = SC_Extern; 6390 6391 DeclContext *OriginalDC = DC; 6392 bool IsLocalExternDecl = SC == SC_Extern && 6393 adjustContextForLocalExternDecl(DC); 6394 6395 if (SCSpec == DeclSpec::SCS_mutable) { 6396 // mutable can only appear on non-static class members, so it's always 6397 // an error here 6398 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6399 D.setInvalidType(); 6400 SC = SC_None; 6401 } 6402 6403 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6404 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6405 D.getDeclSpec().getStorageClassSpecLoc())) { 6406 // In C++11, the 'register' storage class specifier is deprecated. 6407 // Suppress the warning in system macros, it's used in macros in some 6408 // popular C system headers, such as in glibc's htonl() macro. 6409 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6410 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6411 : diag::warn_deprecated_register) 6412 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6413 } 6414 6415 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6416 6417 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6418 // C99 6.9p2: The storage-class specifiers auto and register shall not 6419 // appear in the declaration specifiers in an external declaration. 6420 // Global Register+Asm is a GNU extension we support. 6421 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6422 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6423 D.setInvalidType(); 6424 } 6425 } 6426 6427 bool IsMemberSpecialization = false; 6428 bool IsVariableTemplateSpecialization = false; 6429 bool IsPartialSpecialization = false; 6430 bool IsVariableTemplate = false; 6431 VarDecl *NewVD = nullptr; 6432 VarTemplateDecl *NewTemplate = nullptr; 6433 TemplateParameterList *TemplateParams = nullptr; 6434 if (!getLangOpts().CPlusPlus) { 6435 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6436 D.getIdentifierLoc(), II, 6437 R, TInfo, SC); 6438 6439 if (R->getContainedDeducedType()) 6440 ParsingInitForAutoVars.insert(NewVD); 6441 6442 if (D.isInvalidType()) 6443 NewVD->setInvalidDecl(); 6444 } else { 6445 bool Invalid = false; 6446 6447 if (DC->isRecord() && !CurContext->isRecord()) { 6448 // This is an out-of-line definition of a static data member. 6449 switch (SC) { 6450 case SC_None: 6451 break; 6452 case SC_Static: 6453 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6454 diag::err_static_out_of_line) 6455 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6456 break; 6457 case SC_Auto: 6458 case SC_Register: 6459 case SC_Extern: 6460 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6461 // to names of variables declared in a block or to function parameters. 6462 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6463 // of class members 6464 6465 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6466 diag::err_storage_class_for_static_member) 6467 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6468 break; 6469 case SC_PrivateExtern: 6470 llvm_unreachable("C storage class in c++!"); 6471 } 6472 } 6473 6474 if (SC == SC_Static && CurContext->isRecord()) { 6475 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6476 if (RD->isLocalClass()) 6477 Diag(D.getIdentifierLoc(), 6478 diag::err_static_data_member_not_allowed_in_local_class) 6479 << Name << RD->getDeclName(); 6480 6481 // C++98 [class.union]p1: If a union contains a static data member, 6482 // the program is ill-formed. C++11 drops this restriction. 6483 if (RD->isUnion()) 6484 Diag(D.getIdentifierLoc(), 6485 getLangOpts().CPlusPlus11 6486 ? diag::warn_cxx98_compat_static_data_member_in_union 6487 : diag::ext_static_data_member_in_union) << Name; 6488 // We conservatively disallow static data members in anonymous structs. 6489 else if (!RD->getDeclName()) 6490 Diag(D.getIdentifierLoc(), 6491 diag::err_static_data_member_not_allowed_in_anon_struct) 6492 << Name << RD->isUnion(); 6493 } 6494 } 6495 6496 // Match up the template parameter lists with the scope specifier, then 6497 // determine whether we have a template or a template specialization. 6498 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6499 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6500 D.getCXXScopeSpec(), 6501 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6502 ? D.getName().TemplateId 6503 : nullptr, 6504 TemplateParamLists, 6505 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6506 6507 if (TemplateParams) { 6508 if (!TemplateParams->size() && 6509 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6510 // There is an extraneous 'template<>' for this variable. Complain 6511 // about it, but allow the declaration of the variable. 6512 Diag(TemplateParams->getTemplateLoc(), 6513 diag::err_template_variable_noparams) 6514 << II 6515 << SourceRange(TemplateParams->getTemplateLoc(), 6516 TemplateParams->getRAngleLoc()); 6517 TemplateParams = nullptr; 6518 } else { 6519 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6520 // This is an explicit specialization or a partial specialization. 6521 // FIXME: Check that we can declare a specialization here. 6522 IsVariableTemplateSpecialization = true; 6523 IsPartialSpecialization = TemplateParams->size() > 0; 6524 } else { // if (TemplateParams->size() > 0) 6525 // This is a template declaration. 6526 IsVariableTemplate = true; 6527 6528 // Check that we can declare a template here. 6529 if (CheckTemplateDeclScope(S, TemplateParams)) 6530 return nullptr; 6531 6532 // Only C++1y supports variable templates (N3651). 6533 Diag(D.getIdentifierLoc(), 6534 getLangOpts().CPlusPlus14 6535 ? diag::warn_cxx11_compat_variable_template 6536 : diag::ext_variable_template); 6537 } 6538 } 6539 } else { 6540 assert((Invalid || 6541 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6542 "should have a 'template<>' for this decl"); 6543 } 6544 6545 if (IsVariableTemplateSpecialization) { 6546 SourceLocation TemplateKWLoc = 6547 TemplateParamLists.size() > 0 6548 ? TemplateParamLists[0]->getTemplateLoc() 6549 : SourceLocation(); 6550 DeclResult Res = ActOnVarTemplateSpecialization( 6551 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6552 IsPartialSpecialization); 6553 if (Res.isInvalid()) 6554 return nullptr; 6555 NewVD = cast<VarDecl>(Res.get()); 6556 AddToScope = false; 6557 } else if (D.isDecompositionDeclarator()) { 6558 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6559 D.getIdentifierLoc(), R, TInfo, SC, 6560 Bindings); 6561 } else 6562 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6563 D.getIdentifierLoc(), II, R, TInfo, SC); 6564 6565 // If this is supposed to be a variable template, create it as such. 6566 if (IsVariableTemplate) { 6567 NewTemplate = 6568 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6569 TemplateParams, NewVD); 6570 NewVD->setDescribedVarTemplate(NewTemplate); 6571 } 6572 6573 // If this decl has an auto type in need of deduction, make a note of the 6574 // Decl so we can diagnose uses of it in its own initializer. 6575 if (R->getContainedDeducedType()) 6576 ParsingInitForAutoVars.insert(NewVD); 6577 6578 if (D.isInvalidType() || Invalid) { 6579 NewVD->setInvalidDecl(); 6580 if (NewTemplate) 6581 NewTemplate->setInvalidDecl(); 6582 } 6583 6584 SetNestedNameSpecifier(NewVD, D); 6585 6586 // If we have any template parameter lists that don't directly belong to 6587 // the variable (matching the scope specifier), store them. 6588 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6589 if (TemplateParamLists.size() > VDTemplateParamLists) 6590 NewVD->setTemplateParameterListsInfo( 6591 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6592 6593 if (D.getDeclSpec().isConstexprSpecified()) { 6594 NewVD->setConstexpr(true); 6595 // C++1z [dcl.spec.constexpr]p1: 6596 // A static data member declared with the constexpr specifier is 6597 // implicitly an inline variable. 6598 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6599 NewVD->setImplicitlyInline(); 6600 } 6601 } 6602 6603 if (D.getDeclSpec().isInlineSpecified()) { 6604 if (!getLangOpts().CPlusPlus) { 6605 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6606 << 0; 6607 } else if (CurContext->isFunctionOrMethod()) { 6608 // 'inline' is not allowed on block scope variable declaration. 6609 Diag(D.getDeclSpec().getInlineSpecLoc(), 6610 diag::err_inline_declaration_block_scope) << Name 6611 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6612 } else { 6613 Diag(D.getDeclSpec().getInlineSpecLoc(), 6614 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6615 : diag::ext_inline_variable); 6616 NewVD->setInlineSpecified(); 6617 } 6618 } 6619 6620 // Set the lexical context. If the declarator has a C++ scope specifier, the 6621 // lexical context will be different from the semantic context. 6622 NewVD->setLexicalDeclContext(CurContext); 6623 if (NewTemplate) 6624 NewTemplate->setLexicalDeclContext(CurContext); 6625 6626 if (IsLocalExternDecl) { 6627 if (D.isDecompositionDeclarator()) 6628 for (auto *B : Bindings) 6629 B->setLocalExternDecl(); 6630 else 6631 NewVD->setLocalExternDecl(); 6632 } 6633 6634 bool EmitTLSUnsupportedError = false; 6635 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6636 // C++11 [dcl.stc]p4: 6637 // When thread_local is applied to a variable of block scope the 6638 // storage-class-specifier static is implied if it does not appear 6639 // explicitly. 6640 // Core issue: 'static' is not implied if the variable is declared 6641 // 'extern'. 6642 if (NewVD->hasLocalStorage() && 6643 (SCSpec != DeclSpec::SCS_unspecified || 6644 TSCS != DeclSpec::TSCS_thread_local || 6645 !DC->isFunctionOrMethod())) 6646 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6647 diag::err_thread_non_global) 6648 << DeclSpec::getSpecifierName(TSCS); 6649 else if (!Context.getTargetInfo().isTLSSupported()) { 6650 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6651 // Postpone error emission until we've collected attributes required to 6652 // figure out whether it's a host or device variable and whether the 6653 // error should be ignored. 6654 EmitTLSUnsupportedError = true; 6655 // We still need to mark the variable as TLS so it shows up in AST with 6656 // proper storage class for other tools to use even if we're not going 6657 // to emit any code for it. 6658 NewVD->setTSCSpec(TSCS); 6659 } else 6660 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6661 diag::err_thread_unsupported); 6662 } else 6663 NewVD->setTSCSpec(TSCS); 6664 } 6665 6666 // C99 6.7.4p3 6667 // An inline definition of a function with external linkage shall 6668 // not contain a definition of a modifiable object with static or 6669 // thread storage duration... 6670 // We only apply this when the function is required to be defined 6671 // elsewhere, i.e. when the function is not 'extern inline'. Note 6672 // that a local variable with thread storage duration still has to 6673 // be marked 'static'. Also note that it's possible to get these 6674 // semantics in C++ using __attribute__((gnu_inline)). 6675 if (SC == SC_Static && S->getFnParent() != nullptr && 6676 !NewVD->getType().isConstQualified()) { 6677 FunctionDecl *CurFD = getCurFunctionDecl(); 6678 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6679 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6680 diag::warn_static_local_in_extern_inline); 6681 MaybeSuggestAddingStaticToDecl(CurFD); 6682 } 6683 } 6684 6685 if (D.getDeclSpec().isModulePrivateSpecified()) { 6686 if (IsVariableTemplateSpecialization) 6687 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6688 << (IsPartialSpecialization ? 1 : 0) 6689 << FixItHint::CreateRemoval( 6690 D.getDeclSpec().getModulePrivateSpecLoc()); 6691 else if (IsMemberSpecialization) 6692 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6693 << 2 6694 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6695 else if (NewVD->hasLocalStorage()) 6696 Diag(NewVD->getLocation(), diag::err_module_private_local) 6697 << 0 << NewVD->getDeclName() 6698 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6699 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6700 else { 6701 NewVD->setModulePrivate(); 6702 if (NewTemplate) 6703 NewTemplate->setModulePrivate(); 6704 for (auto *B : Bindings) 6705 B->setModulePrivate(); 6706 } 6707 } 6708 6709 // Handle attributes prior to checking for duplicates in MergeVarDecl 6710 ProcessDeclAttributes(S, NewVD, D); 6711 6712 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6713 if (EmitTLSUnsupportedError && 6714 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6715 (getLangOpts().OpenMPIsDevice && 6716 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6717 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6718 diag::err_thread_unsupported); 6719 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6720 // storage [duration]." 6721 if (SC == SC_None && S->getFnParent() != nullptr && 6722 (NewVD->hasAttr<CUDASharedAttr>() || 6723 NewVD->hasAttr<CUDAConstantAttr>())) { 6724 NewVD->setStorageClass(SC_Static); 6725 } 6726 } 6727 6728 // Ensure that dllimport globals without explicit storage class are treated as 6729 // extern. The storage class is set above using parsed attributes. Now we can 6730 // check the VarDecl itself. 6731 assert(!NewVD->hasAttr<DLLImportAttr>() || 6732 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6733 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6734 6735 // In auto-retain/release, infer strong retension for variables of 6736 // retainable type. 6737 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6738 NewVD->setInvalidDecl(); 6739 6740 // Handle GNU asm-label extension (encoded as an attribute). 6741 if (Expr *E = (Expr*)D.getAsmLabel()) { 6742 // The parser guarantees this is a string. 6743 StringLiteral *SE = cast<StringLiteral>(E); 6744 StringRef Label = SE->getString(); 6745 if (S->getFnParent() != nullptr) { 6746 switch (SC) { 6747 case SC_None: 6748 case SC_Auto: 6749 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6750 break; 6751 case SC_Register: 6752 // Local Named register 6753 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6754 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6755 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6756 break; 6757 case SC_Static: 6758 case SC_Extern: 6759 case SC_PrivateExtern: 6760 break; 6761 } 6762 } else if (SC == SC_Register) { 6763 // Global Named register 6764 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6765 const auto &TI = Context.getTargetInfo(); 6766 bool HasSizeMismatch; 6767 6768 if (!TI.isValidGCCRegisterName(Label)) 6769 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6770 else if (!TI.validateGlobalRegisterVariable(Label, 6771 Context.getTypeSize(R), 6772 HasSizeMismatch)) 6773 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6774 else if (HasSizeMismatch) 6775 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6776 } 6777 6778 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6779 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6780 NewVD->setInvalidDecl(true); 6781 } 6782 } 6783 6784 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6785 Context, Label, 0)); 6786 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6787 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6788 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6789 if (I != ExtnameUndeclaredIdentifiers.end()) { 6790 if (isDeclExternC(NewVD)) { 6791 NewVD->addAttr(I->second); 6792 ExtnameUndeclaredIdentifiers.erase(I); 6793 } else 6794 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6795 << /*Variable*/1 << NewVD; 6796 } 6797 } 6798 6799 // Find the shadowed declaration before filtering for scope. 6800 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6801 ? getShadowedDeclaration(NewVD, Previous) 6802 : nullptr; 6803 6804 // Don't consider existing declarations that are in a different 6805 // scope and are out-of-semantic-context declarations (if the new 6806 // declaration has linkage). 6807 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6808 D.getCXXScopeSpec().isNotEmpty() || 6809 IsMemberSpecialization || 6810 IsVariableTemplateSpecialization); 6811 6812 // Check whether the previous declaration is in the same block scope. This 6813 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6814 if (getLangOpts().CPlusPlus && 6815 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6816 NewVD->setPreviousDeclInSameBlockScope( 6817 Previous.isSingleResult() && !Previous.isShadowed() && 6818 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6819 6820 if (!getLangOpts().CPlusPlus) { 6821 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6822 } else { 6823 // If this is an explicit specialization of a static data member, check it. 6824 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6825 CheckMemberSpecialization(NewVD, Previous)) 6826 NewVD->setInvalidDecl(); 6827 6828 // Merge the decl with the existing one if appropriate. 6829 if (!Previous.empty()) { 6830 if (Previous.isSingleResult() && 6831 isa<FieldDecl>(Previous.getFoundDecl()) && 6832 D.getCXXScopeSpec().isSet()) { 6833 // The user tried to define a non-static data member 6834 // out-of-line (C++ [dcl.meaning]p1). 6835 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6836 << D.getCXXScopeSpec().getRange(); 6837 Previous.clear(); 6838 NewVD->setInvalidDecl(); 6839 } 6840 } else if (D.getCXXScopeSpec().isSet()) { 6841 // No previous declaration in the qualifying scope. 6842 Diag(D.getIdentifierLoc(), diag::err_no_member) 6843 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6844 << D.getCXXScopeSpec().getRange(); 6845 NewVD->setInvalidDecl(); 6846 } 6847 6848 if (!IsVariableTemplateSpecialization) 6849 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6850 6851 if (NewTemplate) { 6852 VarTemplateDecl *PrevVarTemplate = 6853 NewVD->getPreviousDecl() 6854 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6855 : nullptr; 6856 6857 // Check the template parameter list of this declaration, possibly 6858 // merging in the template parameter list from the previous variable 6859 // template declaration. 6860 if (CheckTemplateParameterList( 6861 TemplateParams, 6862 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6863 : nullptr, 6864 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6865 DC->isDependentContext()) 6866 ? TPC_ClassTemplateMember 6867 : TPC_VarTemplate)) 6868 NewVD->setInvalidDecl(); 6869 6870 // If we are providing an explicit specialization of a static variable 6871 // template, make a note of that. 6872 if (PrevVarTemplate && 6873 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6874 PrevVarTemplate->setMemberSpecialization(); 6875 } 6876 } 6877 6878 // Diagnose shadowed variables iff this isn't a redeclaration. 6879 if (ShadowedDecl && !D.isRedeclaration()) 6880 CheckShadow(NewVD, ShadowedDecl, Previous); 6881 6882 ProcessPragmaWeak(S, NewVD); 6883 6884 // If this is the first declaration of an extern C variable, update 6885 // the map of such variables. 6886 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6887 isIncompleteDeclExternC(*this, NewVD)) 6888 RegisterLocallyScopedExternCDecl(NewVD, S); 6889 6890 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6891 Decl *ManglingContextDecl; 6892 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6893 NewVD->getDeclContext(), ManglingContextDecl)) { 6894 Context.setManglingNumber( 6895 NewVD, MCtx->getManglingNumber( 6896 NewVD, getMSManglingNumber(getLangOpts(), S))); 6897 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6898 } 6899 } 6900 6901 // Special handling of variable named 'main'. 6902 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6903 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6904 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6905 6906 // C++ [basic.start.main]p3 6907 // A program that declares a variable main at global scope is ill-formed. 6908 if (getLangOpts().CPlusPlus) 6909 Diag(D.getLocStart(), diag::err_main_global_variable); 6910 6911 // In C, and external-linkage variable named main results in undefined 6912 // behavior. 6913 else if (NewVD->hasExternalFormalLinkage()) 6914 Diag(D.getLocStart(), diag::warn_main_redefined); 6915 } 6916 6917 if (D.isRedeclaration() && !Previous.empty()) { 6918 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6919 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6920 D.isFunctionDefinition()); 6921 } 6922 6923 if (NewTemplate) { 6924 if (NewVD->isInvalidDecl()) 6925 NewTemplate->setInvalidDecl(); 6926 ActOnDocumentableDecl(NewTemplate); 6927 return NewTemplate; 6928 } 6929 6930 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6931 CompleteMemberSpecialization(NewVD, Previous); 6932 6933 return NewVD; 6934 } 6935 6936 /// Enum describing the %select options in diag::warn_decl_shadow. 6937 enum ShadowedDeclKind { 6938 SDK_Local, 6939 SDK_Global, 6940 SDK_StaticMember, 6941 SDK_Field, 6942 SDK_Typedef, 6943 SDK_Using 6944 }; 6945 6946 /// Determine what kind of declaration we're shadowing. 6947 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6948 const DeclContext *OldDC) { 6949 if (isa<TypeAliasDecl>(ShadowedDecl)) 6950 return SDK_Using; 6951 else if (isa<TypedefDecl>(ShadowedDecl)) 6952 return SDK_Typedef; 6953 else if (isa<RecordDecl>(OldDC)) 6954 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6955 6956 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6957 } 6958 6959 /// Return the location of the capture if the given lambda captures the given 6960 /// variable \p VD, or an invalid source location otherwise. 6961 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6962 const VarDecl *VD) { 6963 for (const Capture &Capture : LSI->Captures) { 6964 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6965 return Capture.getLocation(); 6966 } 6967 return SourceLocation(); 6968 } 6969 6970 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6971 const LookupResult &R) { 6972 // Only diagnose if we're shadowing an unambiguous field or variable. 6973 if (R.getResultKind() != LookupResult::Found) 6974 return false; 6975 6976 // Return false if warning is ignored. 6977 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6978 } 6979 6980 /// Return the declaration shadowed by the given variable \p D, or null 6981 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6982 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6983 const LookupResult &R) { 6984 if (!shouldWarnIfShadowedDecl(Diags, R)) 6985 return nullptr; 6986 6987 // Don't diagnose declarations at file scope. 6988 if (D->hasGlobalStorage()) 6989 return nullptr; 6990 6991 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6992 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6993 ? ShadowedDecl 6994 : nullptr; 6995 } 6996 6997 /// Return the declaration shadowed by the given typedef \p D, or null 6998 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6999 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7000 const LookupResult &R) { 7001 // Don't warn if typedef declaration is part of a class 7002 if (D->getDeclContext()->isRecord()) 7003 return nullptr; 7004 7005 if (!shouldWarnIfShadowedDecl(Diags, R)) 7006 return nullptr; 7007 7008 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7009 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7010 } 7011 7012 /// Diagnose variable or built-in function shadowing. Implements 7013 /// -Wshadow. 7014 /// 7015 /// This method is called whenever a VarDecl is added to a "useful" 7016 /// scope. 7017 /// 7018 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7019 /// \param R the lookup of the name 7020 /// 7021 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7022 const LookupResult &R) { 7023 DeclContext *NewDC = D->getDeclContext(); 7024 7025 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7026 // Fields are not shadowed by variables in C++ static methods. 7027 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7028 if (MD->isStatic()) 7029 return; 7030 7031 // Fields shadowed by constructor parameters are a special case. Usually 7032 // the constructor initializes the field with the parameter. 7033 if (isa<CXXConstructorDecl>(NewDC)) 7034 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7035 // Remember that this was shadowed so we can either warn about its 7036 // modification or its existence depending on warning settings. 7037 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7038 return; 7039 } 7040 } 7041 7042 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7043 if (shadowedVar->isExternC()) { 7044 // For shadowing external vars, make sure that we point to the global 7045 // declaration, not a locally scoped extern declaration. 7046 for (auto I : shadowedVar->redecls()) 7047 if (I->isFileVarDecl()) { 7048 ShadowedDecl = I; 7049 break; 7050 } 7051 } 7052 7053 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7054 7055 unsigned WarningDiag = diag::warn_decl_shadow; 7056 SourceLocation CaptureLoc; 7057 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7058 isa<CXXMethodDecl>(NewDC)) { 7059 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7060 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7061 if (RD->getLambdaCaptureDefault() == LCD_None) { 7062 // Try to avoid warnings for lambdas with an explicit capture list. 7063 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7064 // Warn only when the lambda captures the shadowed decl explicitly. 7065 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7066 if (CaptureLoc.isInvalid()) 7067 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7068 } else { 7069 // Remember that this was shadowed so we can avoid the warning if the 7070 // shadowed decl isn't captured and the warning settings allow it. 7071 cast<LambdaScopeInfo>(getCurFunction()) 7072 ->ShadowingDecls.push_back( 7073 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7074 return; 7075 } 7076 } 7077 7078 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7079 // A variable can't shadow a local variable in an enclosing scope, if 7080 // they are separated by a non-capturing declaration context. 7081 for (DeclContext *ParentDC = NewDC; 7082 ParentDC && !ParentDC->Equals(OldDC); 7083 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7084 // Only block literals, captured statements, and lambda expressions 7085 // can capture; other scopes don't. 7086 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7087 !isLambdaCallOperator(ParentDC)) { 7088 return; 7089 } 7090 } 7091 } 7092 } 7093 } 7094 7095 // Only warn about certain kinds of shadowing for class members. 7096 if (NewDC && NewDC->isRecord()) { 7097 // In particular, don't warn about shadowing non-class members. 7098 if (!OldDC->isRecord()) 7099 return; 7100 7101 // TODO: should we warn about static data members shadowing 7102 // static data members from base classes? 7103 7104 // TODO: don't diagnose for inaccessible shadowed members. 7105 // This is hard to do perfectly because we might friend the 7106 // shadowing context, but that's just a false negative. 7107 } 7108 7109 7110 DeclarationName Name = R.getLookupName(); 7111 7112 // Emit warning and note. 7113 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7114 return; 7115 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7116 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7117 if (!CaptureLoc.isInvalid()) 7118 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7119 << Name << /*explicitly*/ 1; 7120 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7121 } 7122 7123 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7124 /// when these variables are captured by the lambda. 7125 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7126 for (const auto &Shadow : LSI->ShadowingDecls) { 7127 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7128 // Try to avoid the warning when the shadowed decl isn't captured. 7129 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7130 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7131 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7132 ? diag::warn_decl_shadow_uncaptured_local 7133 : diag::warn_decl_shadow) 7134 << Shadow.VD->getDeclName() 7135 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7136 if (!CaptureLoc.isInvalid()) 7137 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7138 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7139 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7140 } 7141 } 7142 7143 /// Check -Wshadow without the advantage of a previous lookup. 7144 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7145 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7146 return; 7147 7148 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7149 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7150 LookupName(R, S); 7151 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7152 CheckShadow(D, ShadowedDecl, R); 7153 } 7154 7155 /// Check if 'E', which is an expression that is about to be modified, refers 7156 /// to a constructor parameter that shadows a field. 7157 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7158 // Quickly ignore expressions that can't be shadowing ctor parameters. 7159 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7160 return; 7161 E = E->IgnoreParenImpCasts(); 7162 auto *DRE = dyn_cast<DeclRefExpr>(E); 7163 if (!DRE) 7164 return; 7165 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7166 auto I = ShadowingDecls.find(D); 7167 if (I == ShadowingDecls.end()) 7168 return; 7169 const NamedDecl *ShadowedDecl = I->second; 7170 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7171 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7172 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7173 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7174 7175 // Avoid issuing multiple warnings about the same decl. 7176 ShadowingDecls.erase(I); 7177 } 7178 7179 /// Check for conflict between this global or extern "C" declaration and 7180 /// previous global or extern "C" declarations. This is only used in C++. 7181 template<typename T> 7182 static bool checkGlobalOrExternCConflict( 7183 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7184 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7185 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7186 7187 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7188 // The common case: this global doesn't conflict with any extern "C" 7189 // declaration. 7190 return false; 7191 } 7192 7193 if (Prev) { 7194 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7195 // Both the old and new declarations have C language linkage. This is a 7196 // redeclaration. 7197 Previous.clear(); 7198 Previous.addDecl(Prev); 7199 return true; 7200 } 7201 7202 // This is a global, non-extern "C" declaration, and there is a previous 7203 // non-global extern "C" declaration. Diagnose if this is a variable 7204 // declaration. 7205 if (!isa<VarDecl>(ND)) 7206 return false; 7207 } else { 7208 // The declaration is extern "C". Check for any declaration in the 7209 // translation unit which might conflict. 7210 if (IsGlobal) { 7211 // We have already performed the lookup into the translation unit. 7212 IsGlobal = false; 7213 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7214 I != E; ++I) { 7215 if (isa<VarDecl>(*I)) { 7216 Prev = *I; 7217 break; 7218 } 7219 } 7220 } else { 7221 DeclContext::lookup_result R = 7222 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7223 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7224 I != E; ++I) { 7225 if (isa<VarDecl>(*I)) { 7226 Prev = *I; 7227 break; 7228 } 7229 // FIXME: If we have any other entity with this name in global scope, 7230 // the declaration is ill-formed, but that is a defect: it breaks the 7231 // 'stat' hack, for instance. Only variables can have mangled name 7232 // clashes with extern "C" declarations, so only they deserve a 7233 // diagnostic. 7234 } 7235 } 7236 7237 if (!Prev) 7238 return false; 7239 } 7240 7241 // Use the first declaration's location to ensure we point at something which 7242 // is lexically inside an extern "C" linkage-spec. 7243 assert(Prev && "should have found a previous declaration to diagnose"); 7244 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7245 Prev = FD->getFirstDecl(); 7246 else 7247 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7248 7249 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7250 << IsGlobal << ND; 7251 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7252 << IsGlobal; 7253 return false; 7254 } 7255 7256 /// Apply special rules for handling extern "C" declarations. Returns \c true 7257 /// if we have found that this is a redeclaration of some prior entity. 7258 /// 7259 /// Per C++ [dcl.link]p6: 7260 /// Two declarations [for a function or variable] with C language linkage 7261 /// with the same name that appear in different scopes refer to the same 7262 /// [entity]. An entity with C language linkage shall not be declared with 7263 /// the same name as an entity in global scope. 7264 template<typename T> 7265 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7266 LookupResult &Previous) { 7267 if (!S.getLangOpts().CPlusPlus) { 7268 // In C, when declaring a global variable, look for a corresponding 'extern' 7269 // variable declared in function scope. We don't need this in C++, because 7270 // we find local extern decls in the surrounding file-scope DeclContext. 7271 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7272 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7273 Previous.clear(); 7274 Previous.addDecl(Prev); 7275 return true; 7276 } 7277 } 7278 return false; 7279 } 7280 7281 // A declaration in the translation unit can conflict with an extern "C" 7282 // declaration. 7283 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7284 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7285 7286 // An extern "C" declaration can conflict with a declaration in the 7287 // translation unit or can be a redeclaration of an extern "C" declaration 7288 // in another scope. 7289 if (isIncompleteDeclExternC(S,ND)) 7290 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7291 7292 // Neither global nor extern "C": nothing to do. 7293 return false; 7294 } 7295 7296 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7297 // If the decl is already known invalid, don't check it. 7298 if (NewVD->isInvalidDecl()) 7299 return; 7300 7301 QualType T = NewVD->getType(); 7302 7303 // Defer checking an 'auto' type until its initializer is attached. 7304 if (T->isUndeducedType()) 7305 return; 7306 7307 if (NewVD->hasAttrs()) 7308 CheckAlignasUnderalignment(NewVD); 7309 7310 if (T->isObjCObjectType()) { 7311 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7312 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7313 T = Context.getObjCObjectPointerType(T); 7314 NewVD->setType(T); 7315 } 7316 7317 // Emit an error if an address space was applied to decl with local storage. 7318 // This includes arrays of objects with address space qualifiers, but not 7319 // automatic variables that point to other address spaces. 7320 // ISO/IEC TR 18037 S5.1.2 7321 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7322 T.getAddressSpace() != LangAS::Default) { 7323 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7324 NewVD->setInvalidDecl(); 7325 return; 7326 } 7327 7328 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7329 // scope. 7330 if (getLangOpts().OpenCLVersion == 120 && 7331 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7332 NewVD->isStaticLocal()) { 7333 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7334 NewVD->setInvalidDecl(); 7335 return; 7336 } 7337 7338 if (getLangOpts().OpenCL) { 7339 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7340 if (NewVD->hasAttr<BlocksAttr>()) { 7341 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7342 return; 7343 } 7344 7345 if (T->isBlockPointerType()) { 7346 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7347 // can't use 'extern' storage class. 7348 if (!T.isConstQualified()) { 7349 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7350 << 0 /*const*/; 7351 NewVD->setInvalidDecl(); 7352 return; 7353 } 7354 if (NewVD->hasExternalStorage()) { 7355 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7356 NewVD->setInvalidDecl(); 7357 return; 7358 } 7359 } 7360 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7361 // __constant address space. 7362 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7363 // variables inside a function can also be declared in the global 7364 // address space. 7365 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7366 NewVD->hasExternalStorage()) { 7367 if (!T->isSamplerT() && 7368 !(T.getAddressSpace() == LangAS::opencl_constant || 7369 (T.getAddressSpace() == LangAS::opencl_global && 7370 getLangOpts().OpenCLVersion == 200))) { 7371 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7372 if (getLangOpts().OpenCLVersion == 200) 7373 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7374 << Scope << "global or constant"; 7375 else 7376 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7377 << Scope << "constant"; 7378 NewVD->setInvalidDecl(); 7379 return; 7380 } 7381 } else { 7382 if (T.getAddressSpace() == LangAS::opencl_global) { 7383 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7384 << 1 /*is any function*/ << "global"; 7385 NewVD->setInvalidDecl(); 7386 return; 7387 } 7388 if (T.getAddressSpace() == LangAS::opencl_constant || 7389 T.getAddressSpace() == LangAS::opencl_local) { 7390 FunctionDecl *FD = getCurFunctionDecl(); 7391 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7392 // in functions. 7393 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7394 if (T.getAddressSpace() == LangAS::opencl_constant) 7395 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7396 << 0 /*non-kernel only*/ << "constant"; 7397 else 7398 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7399 << 0 /*non-kernel only*/ << "local"; 7400 NewVD->setInvalidDecl(); 7401 return; 7402 } 7403 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7404 // in the outermost scope of a kernel function. 7405 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7406 if (!getCurScope()->isFunctionScope()) { 7407 if (T.getAddressSpace() == LangAS::opencl_constant) 7408 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7409 << "constant"; 7410 else 7411 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7412 << "local"; 7413 NewVD->setInvalidDecl(); 7414 return; 7415 } 7416 } 7417 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7418 // Do not allow other address spaces on automatic variable. 7419 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7420 NewVD->setInvalidDecl(); 7421 return; 7422 } 7423 } 7424 } 7425 7426 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7427 && !NewVD->hasAttr<BlocksAttr>()) { 7428 if (getLangOpts().getGC() != LangOptions::NonGC) 7429 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7430 else { 7431 assert(!getLangOpts().ObjCAutoRefCount); 7432 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7433 } 7434 } 7435 7436 bool isVM = T->isVariablyModifiedType(); 7437 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7438 NewVD->hasAttr<BlocksAttr>()) 7439 setFunctionHasBranchProtectedScope(); 7440 7441 if ((isVM && NewVD->hasLinkage()) || 7442 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7443 bool SizeIsNegative; 7444 llvm::APSInt Oversized; 7445 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7446 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7447 QualType FixedT; 7448 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7449 FixedT = FixedTInfo->getType(); 7450 else if (FixedTInfo) { 7451 // Type and type-as-written are canonically different. We need to fix up 7452 // both types separately. 7453 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7454 Oversized); 7455 } 7456 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7457 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7458 // FIXME: This won't give the correct result for 7459 // int a[10][n]; 7460 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7461 7462 if (NewVD->isFileVarDecl()) 7463 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7464 << SizeRange; 7465 else if (NewVD->isStaticLocal()) 7466 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7467 << SizeRange; 7468 else 7469 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7470 << SizeRange; 7471 NewVD->setInvalidDecl(); 7472 return; 7473 } 7474 7475 if (!FixedTInfo) { 7476 if (NewVD->isFileVarDecl()) 7477 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7478 else 7479 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7480 NewVD->setInvalidDecl(); 7481 return; 7482 } 7483 7484 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7485 NewVD->setType(FixedT); 7486 NewVD->setTypeSourceInfo(FixedTInfo); 7487 } 7488 7489 if (T->isVoidType()) { 7490 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7491 // of objects and functions. 7492 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7493 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7494 << T; 7495 NewVD->setInvalidDecl(); 7496 return; 7497 } 7498 } 7499 7500 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7501 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7502 NewVD->setInvalidDecl(); 7503 return; 7504 } 7505 7506 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7507 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7508 NewVD->setInvalidDecl(); 7509 return; 7510 } 7511 7512 if (NewVD->isConstexpr() && !T->isDependentType() && 7513 RequireLiteralType(NewVD->getLocation(), T, 7514 diag::err_constexpr_var_non_literal)) { 7515 NewVD->setInvalidDecl(); 7516 return; 7517 } 7518 } 7519 7520 /// Perform semantic checking on a newly-created variable 7521 /// declaration. 7522 /// 7523 /// This routine performs all of the type-checking required for a 7524 /// variable declaration once it has been built. It is used both to 7525 /// check variables after they have been parsed and their declarators 7526 /// have been translated into a declaration, and to check variables 7527 /// that have been instantiated from a template. 7528 /// 7529 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7530 /// 7531 /// Returns true if the variable declaration is a redeclaration. 7532 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7533 CheckVariableDeclarationType(NewVD); 7534 7535 // If the decl is already known invalid, don't check it. 7536 if (NewVD->isInvalidDecl()) 7537 return false; 7538 7539 // If we did not find anything by this name, look for a non-visible 7540 // extern "C" declaration with the same name. 7541 if (Previous.empty() && 7542 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7543 Previous.setShadowed(); 7544 7545 if (!Previous.empty()) { 7546 MergeVarDecl(NewVD, Previous); 7547 return true; 7548 } 7549 return false; 7550 } 7551 7552 namespace { 7553 struct FindOverriddenMethod { 7554 Sema *S; 7555 CXXMethodDecl *Method; 7556 7557 /// Member lookup function that determines whether a given C++ 7558 /// method overrides a method in a base class, to be used with 7559 /// CXXRecordDecl::lookupInBases(). 7560 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7561 RecordDecl *BaseRecord = 7562 Specifier->getType()->getAs<RecordType>()->getDecl(); 7563 7564 DeclarationName Name = Method->getDeclName(); 7565 7566 // FIXME: Do we care about other names here too? 7567 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7568 // We really want to find the base class destructor here. 7569 QualType T = S->Context.getTypeDeclType(BaseRecord); 7570 CanQualType CT = S->Context.getCanonicalType(T); 7571 7572 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7573 } 7574 7575 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7576 Path.Decls = Path.Decls.slice(1)) { 7577 NamedDecl *D = Path.Decls.front(); 7578 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7579 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7580 return true; 7581 } 7582 } 7583 7584 return false; 7585 } 7586 }; 7587 7588 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7589 } // end anonymous namespace 7590 7591 /// Report an error regarding overriding, along with any relevant 7592 /// overridden methods. 7593 /// 7594 /// \param DiagID the primary error to report. 7595 /// \param MD the overriding method. 7596 /// \param OEK which overrides to include as notes. 7597 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7598 OverrideErrorKind OEK = OEK_All) { 7599 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7600 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7601 // This check (& the OEK parameter) could be replaced by a predicate, but 7602 // without lambdas that would be overkill. This is still nicer than writing 7603 // out the diag loop 3 times. 7604 if ((OEK == OEK_All) || 7605 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7606 (OEK == OEK_Deleted && O->isDeleted())) 7607 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7608 } 7609 } 7610 7611 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7612 /// and if so, check that it's a valid override and remember it. 7613 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7614 // Look for methods in base classes that this method might override. 7615 CXXBasePaths Paths; 7616 FindOverriddenMethod FOM; 7617 FOM.Method = MD; 7618 FOM.S = this; 7619 bool hasDeletedOverridenMethods = false; 7620 bool hasNonDeletedOverridenMethods = false; 7621 bool AddedAny = false; 7622 if (DC->lookupInBases(FOM, Paths)) { 7623 for (auto *I : Paths.found_decls()) { 7624 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7625 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7626 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7627 !CheckOverridingFunctionAttributes(MD, OldMD) && 7628 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7629 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7630 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7631 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7632 AddedAny = true; 7633 } 7634 } 7635 } 7636 } 7637 7638 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7639 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7640 } 7641 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7642 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7643 } 7644 7645 return AddedAny; 7646 } 7647 7648 namespace { 7649 // Struct for holding all of the extra arguments needed by 7650 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7651 struct ActOnFDArgs { 7652 Scope *S; 7653 Declarator &D; 7654 MultiTemplateParamsArg TemplateParamLists; 7655 bool AddToScope; 7656 }; 7657 } // end anonymous namespace 7658 7659 namespace { 7660 7661 // Callback to only accept typo corrections that have a non-zero edit distance. 7662 // Also only accept corrections that have the same parent decl. 7663 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7664 public: 7665 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7666 CXXRecordDecl *Parent) 7667 : Context(Context), OriginalFD(TypoFD), 7668 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7669 7670 bool ValidateCandidate(const TypoCorrection &candidate) override { 7671 if (candidate.getEditDistance() == 0) 7672 return false; 7673 7674 SmallVector<unsigned, 1> MismatchedParams; 7675 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7676 CDeclEnd = candidate.end(); 7677 CDecl != CDeclEnd; ++CDecl) { 7678 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7679 7680 if (FD && !FD->hasBody() && 7681 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7682 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7683 CXXRecordDecl *Parent = MD->getParent(); 7684 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7685 return true; 7686 } else if (!ExpectedParent) { 7687 return true; 7688 } 7689 } 7690 } 7691 7692 return false; 7693 } 7694 7695 private: 7696 ASTContext &Context; 7697 FunctionDecl *OriginalFD; 7698 CXXRecordDecl *ExpectedParent; 7699 }; 7700 7701 } // end anonymous namespace 7702 7703 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7704 TypoCorrectedFunctionDefinitions.insert(F); 7705 } 7706 7707 /// Generate diagnostics for an invalid function redeclaration. 7708 /// 7709 /// This routine handles generating the diagnostic messages for an invalid 7710 /// function redeclaration, including finding possible similar declarations 7711 /// or performing typo correction if there are no previous declarations with 7712 /// the same name. 7713 /// 7714 /// Returns a NamedDecl iff typo correction was performed and substituting in 7715 /// the new declaration name does not cause new errors. 7716 static NamedDecl *DiagnoseInvalidRedeclaration( 7717 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7718 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7719 DeclarationName Name = NewFD->getDeclName(); 7720 DeclContext *NewDC = NewFD->getDeclContext(); 7721 SmallVector<unsigned, 1> MismatchedParams; 7722 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7723 TypoCorrection Correction; 7724 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7725 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7726 : diag::err_member_decl_does_not_match; 7727 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7728 IsLocalFriend ? Sema::LookupLocalFriendName 7729 : Sema::LookupOrdinaryName, 7730 Sema::ForVisibleRedeclaration); 7731 7732 NewFD->setInvalidDecl(); 7733 if (IsLocalFriend) 7734 SemaRef.LookupName(Prev, S); 7735 else 7736 SemaRef.LookupQualifiedName(Prev, NewDC); 7737 assert(!Prev.isAmbiguous() && 7738 "Cannot have an ambiguity in previous-declaration lookup"); 7739 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7740 if (!Prev.empty()) { 7741 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7742 Func != FuncEnd; ++Func) { 7743 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7744 if (FD && 7745 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7746 // Add 1 to the index so that 0 can mean the mismatch didn't 7747 // involve a parameter 7748 unsigned ParamNum = 7749 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7750 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7751 } 7752 } 7753 // If the qualified name lookup yielded nothing, try typo correction 7754 } else if ((Correction = SemaRef.CorrectTypo( 7755 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7756 &ExtraArgs.D.getCXXScopeSpec(), 7757 llvm::make_unique<DifferentNameValidatorCCC>( 7758 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7759 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7760 // Set up everything for the call to ActOnFunctionDeclarator 7761 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7762 ExtraArgs.D.getIdentifierLoc()); 7763 Previous.clear(); 7764 Previous.setLookupName(Correction.getCorrection()); 7765 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7766 CDeclEnd = Correction.end(); 7767 CDecl != CDeclEnd; ++CDecl) { 7768 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7769 if (FD && !FD->hasBody() && 7770 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7771 Previous.addDecl(FD); 7772 } 7773 } 7774 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7775 7776 NamedDecl *Result; 7777 // Retry building the function declaration with the new previous 7778 // declarations, and with errors suppressed. 7779 { 7780 // Trap errors. 7781 Sema::SFINAETrap Trap(SemaRef); 7782 7783 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7784 // pieces need to verify the typo-corrected C++ declaration and hopefully 7785 // eliminate the need for the parameter pack ExtraArgs. 7786 Result = SemaRef.ActOnFunctionDeclarator( 7787 ExtraArgs.S, ExtraArgs.D, 7788 Correction.getCorrectionDecl()->getDeclContext(), 7789 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7790 ExtraArgs.AddToScope); 7791 7792 if (Trap.hasErrorOccurred()) 7793 Result = nullptr; 7794 } 7795 7796 if (Result) { 7797 // Determine which correction we picked. 7798 Decl *Canonical = Result->getCanonicalDecl(); 7799 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7800 I != E; ++I) 7801 if ((*I)->getCanonicalDecl() == Canonical) 7802 Correction.setCorrectionDecl(*I); 7803 7804 // Let Sema know about the correction. 7805 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7806 SemaRef.diagnoseTypo( 7807 Correction, 7808 SemaRef.PDiag(IsLocalFriend 7809 ? diag::err_no_matching_local_friend_suggest 7810 : diag::err_member_decl_does_not_match_suggest) 7811 << Name << NewDC << IsDefinition); 7812 return Result; 7813 } 7814 7815 // Pretend the typo correction never occurred 7816 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7817 ExtraArgs.D.getIdentifierLoc()); 7818 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7819 Previous.clear(); 7820 Previous.setLookupName(Name); 7821 } 7822 7823 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7824 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7825 7826 bool NewFDisConst = false; 7827 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7828 NewFDisConst = NewMD->isConst(); 7829 7830 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7831 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7832 NearMatch != NearMatchEnd; ++NearMatch) { 7833 FunctionDecl *FD = NearMatch->first; 7834 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7835 bool FDisConst = MD && MD->isConst(); 7836 bool IsMember = MD || !IsLocalFriend; 7837 7838 // FIXME: These notes are poorly worded for the local friend case. 7839 if (unsigned Idx = NearMatch->second) { 7840 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7841 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7842 if (Loc.isInvalid()) Loc = FD->getLocation(); 7843 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7844 : diag::note_local_decl_close_param_match) 7845 << Idx << FDParam->getType() 7846 << NewFD->getParamDecl(Idx - 1)->getType(); 7847 } else if (FDisConst != NewFDisConst) { 7848 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7849 << NewFDisConst << FD->getSourceRange().getEnd(); 7850 } else 7851 SemaRef.Diag(FD->getLocation(), 7852 IsMember ? diag::note_member_def_close_match 7853 : diag::note_local_decl_close_match); 7854 } 7855 return nullptr; 7856 } 7857 7858 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7859 switch (D.getDeclSpec().getStorageClassSpec()) { 7860 default: llvm_unreachable("Unknown storage class!"); 7861 case DeclSpec::SCS_auto: 7862 case DeclSpec::SCS_register: 7863 case DeclSpec::SCS_mutable: 7864 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7865 diag::err_typecheck_sclass_func); 7866 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7867 D.setInvalidType(); 7868 break; 7869 case DeclSpec::SCS_unspecified: break; 7870 case DeclSpec::SCS_extern: 7871 if (D.getDeclSpec().isExternInLinkageSpec()) 7872 return SC_None; 7873 return SC_Extern; 7874 case DeclSpec::SCS_static: { 7875 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7876 // C99 6.7.1p5: 7877 // The declaration of an identifier for a function that has 7878 // block scope shall have no explicit storage-class specifier 7879 // other than extern 7880 // See also (C++ [dcl.stc]p4). 7881 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7882 diag::err_static_block_func); 7883 break; 7884 } else 7885 return SC_Static; 7886 } 7887 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7888 } 7889 7890 // No explicit storage class has already been returned 7891 return SC_None; 7892 } 7893 7894 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7895 DeclContext *DC, QualType &R, 7896 TypeSourceInfo *TInfo, 7897 StorageClass SC, 7898 bool &IsVirtualOkay) { 7899 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7900 DeclarationName Name = NameInfo.getName(); 7901 7902 FunctionDecl *NewFD = nullptr; 7903 bool isInline = D.getDeclSpec().isInlineSpecified(); 7904 7905 if (!SemaRef.getLangOpts().CPlusPlus) { 7906 // Determine whether the function was written with a 7907 // prototype. This true when: 7908 // - there is a prototype in the declarator, or 7909 // - the type R of the function is some kind of typedef or other non- 7910 // attributed reference to a type name (which eventually refers to a 7911 // function type). 7912 bool HasPrototype = 7913 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7914 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7915 7916 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7917 D.getLocStart(), NameInfo, R, 7918 TInfo, SC, isInline, 7919 HasPrototype, false); 7920 if (D.isInvalidType()) 7921 NewFD->setInvalidDecl(); 7922 7923 return NewFD; 7924 } 7925 7926 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7927 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7928 7929 // Check that the return type is not an abstract class type. 7930 // For record types, this is done by the AbstractClassUsageDiagnoser once 7931 // the class has been completely parsed. 7932 if (!DC->isRecord() && 7933 SemaRef.RequireNonAbstractType( 7934 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7935 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7936 D.setInvalidType(); 7937 7938 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7939 // This is a C++ constructor declaration. 7940 assert(DC->isRecord() && 7941 "Constructors can only be declared in a member context"); 7942 7943 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7944 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7945 D.getLocStart(), NameInfo, 7946 R, TInfo, isExplicit, isInline, 7947 /*isImplicitlyDeclared=*/false, 7948 isConstexpr); 7949 7950 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7951 // This is a C++ destructor declaration. 7952 if (DC->isRecord()) { 7953 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7954 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7955 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7956 SemaRef.Context, Record, 7957 D.getLocStart(), 7958 NameInfo, R, TInfo, isInline, 7959 /*isImplicitlyDeclared=*/false); 7960 7961 // If the class is complete, then we now create the implicit exception 7962 // specification. If the class is incomplete or dependent, we can't do 7963 // it yet. 7964 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7965 Record->getDefinition() && !Record->isBeingDefined() && 7966 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7967 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7968 } 7969 7970 IsVirtualOkay = true; 7971 return NewDD; 7972 7973 } else { 7974 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7975 D.setInvalidType(); 7976 7977 // Create a FunctionDecl to satisfy the function definition parsing 7978 // code path. 7979 return FunctionDecl::Create(SemaRef.Context, DC, 7980 D.getLocStart(), 7981 D.getIdentifierLoc(), Name, R, TInfo, 7982 SC, isInline, 7983 /*hasPrototype=*/true, isConstexpr); 7984 } 7985 7986 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7987 if (!DC->isRecord()) { 7988 SemaRef.Diag(D.getIdentifierLoc(), 7989 diag::err_conv_function_not_member); 7990 return nullptr; 7991 } 7992 7993 SemaRef.CheckConversionDeclarator(D, R, SC); 7994 IsVirtualOkay = true; 7995 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7996 D.getLocStart(), NameInfo, 7997 R, TInfo, isInline, isExplicit, 7998 isConstexpr, SourceLocation()); 7999 8000 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8001 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8002 8003 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 8004 isExplicit, NameInfo, R, TInfo, 8005 D.getLocEnd()); 8006 } else if (DC->isRecord()) { 8007 // If the name of the function is the same as the name of the record, 8008 // then this must be an invalid constructor that has a return type. 8009 // (The parser checks for a return type and makes the declarator a 8010 // constructor if it has no return type). 8011 if (Name.getAsIdentifierInfo() && 8012 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8013 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8014 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8015 << SourceRange(D.getIdentifierLoc()); 8016 return nullptr; 8017 } 8018 8019 // This is a C++ method declaration. 8020 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 8021 cast<CXXRecordDecl>(DC), 8022 D.getLocStart(), NameInfo, R, 8023 TInfo, SC, isInline, 8024 isConstexpr, SourceLocation()); 8025 IsVirtualOkay = !Ret->isStatic(); 8026 return Ret; 8027 } else { 8028 bool isFriend = 8029 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8030 if (!isFriend && SemaRef.CurContext->isRecord()) 8031 return nullptr; 8032 8033 // Determine whether the function was written with a 8034 // prototype. This true when: 8035 // - we're in C++ (where every function has a prototype), 8036 return FunctionDecl::Create(SemaRef.Context, DC, 8037 D.getLocStart(), 8038 NameInfo, R, TInfo, SC, isInline, 8039 true/*HasPrototype*/, isConstexpr); 8040 } 8041 } 8042 8043 enum OpenCLParamType { 8044 ValidKernelParam, 8045 PtrPtrKernelParam, 8046 PtrKernelParam, 8047 InvalidAddrSpacePtrKernelParam, 8048 InvalidKernelParam, 8049 RecordKernelParam 8050 }; 8051 8052 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8053 if (PT->isPointerType()) { 8054 QualType PointeeType = PT->getPointeeType(); 8055 if (PointeeType->isPointerType()) 8056 return PtrPtrKernelParam; 8057 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8058 PointeeType.getAddressSpace() == LangAS::opencl_private || 8059 PointeeType.getAddressSpace() == LangAS::Default) 8060 return InvalidAddrSpacePtrKernelParam; 8061 return PtrKernelParam; 8062 } 8063 8064 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 8065 // be used as builtin types. 8066 8067 if (PT->isImageType()) 8068 return PtrKernelParam; 8069 8070 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8071 return InvalidKernelParam; 8072 8073 // OpenCL extension spec v1.2 s9.5: 8074 // This extension adds support for half scalar and vector types as built-in 8075 // types that can be used for arithmetic operations, conversions etc. 8076 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8077 return InvalidKernelParam; 8078 8079 if (PT->isRecordType()) 8080 return RecordKernelParam; 8081 8082 return ValidKernelParam; 8083 } 8084 8085 static void checkIsValidOpenCLKernelParameter( 8086 Sema &S, 8087 Declarator &D, 8088 ParmVarDecl *Param, 8089 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8090 QualType PT = Param->getType(); 8091 8092 // Cache the valid types we encounter to avoid rechecking structs that are 8093 // used again 8094 if (ValidTypes.count(PT.getTypePtr())) 8095 return; 8096 8097 switch (getOpenCLKernelParameterType(S, PT)) { 8098 case PtrPtrKernelParam: 8099 // OpenCL v1.2 s6.9.a: 8100 // A kernel function argument cannot be declared as a 8101 // pointer to a pointer type. 8102 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8103 D.setInvalidType(); 8104 return; 8105 8106 case InvalidAddrSpacePtrKernelParam: 8107 // OpenCL v1.0 s6.5: 8108 // __kernel function arguments declared to be a pointer of a type can point 8109 // to one of the following address spaces only : __global, __local or 8110 // __constant. 8111 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8112 D.setInvalidType(); 8113 return; 8114 8115 // OpenCL v1.2 s6.9.k: 8116 // Arguments to kernel functions in a program cannot be declared with the 8117 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8118 // uintptr_t or a struct and/or union that contain fields declared to be 8119 // one of these built-in scalar types. 8120 8121 case InvalidKernelParam: 8122 // OpenCL v1.2 s6.8 n: 8123 // A kernel function argument cannot be declared 8124 // of event_t type. 8125 // Do not diagnose half type since it is diagnosed as invalid argument 8126 // type for any function elsewhere. 8127 if (!PT->isHalfType()) 8128 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8129 D.setInvalidType(); 8130 return; 8131 8132 case PtrKernelParam: 8133 case ValidKernelParam: 8134 ValidTypes.insert(PT.getTypePtr()); 8135 return; 8136 8137 case RecordKernelParam: 8138 break; 8139 } 8140 8141 // Track nested structs we will inspect 8142 SmallVector<const Decl *, 4> VisitStack; 8143 8144 // Track where we are in the nested structs. Items will migrate from 8145 // VisitStack to HistoryStack as we do the DFS for bad field. 8146 SmallVector<const FieldDecl *, 4> HistoryStack; 8147 HistoryStack.push_back(nullptr); 8148 8149 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8150 VisitStack.push_back(PD); 8151 8152 assert(VisitStack.back() && "First decl null?"); 8153 8154 do { 8155 const Decl *Next = VisitStack.pop_back_val(); 8156 if (!Next) { 8157 assert(!HistoryStack.empty()); 8158 // Found a marker, we have gone up a level 8159 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8160 ValidTypes.insert(Hist->getType().getTypePtr()); 8161 8162 continue; 8163 } 8164 8165 // Adds everything except the original parameter declaration (which is not a 8166 // field itself) to the history stack. 8167 const RecordDecl *RD; 8168 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8169 HistoryStack.push_back(Field); 8170 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8171 } else { 8172 RD = cast<RecordDecl>(Next); 8173 } 8174 8175 // Add a null marker so we know when we've gone back up a level 8176 VisitStack.push_back(nullptr); 8177 8178 for (const auto *FD : RD->fields()) { 8179 QualType QT = FD->getType(); 8180 8181 if (ValidTypes.count(QT.getTypePtr())) 8182 continue; 8183 8184 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8185 if (ParamType == ValidKernelParam) 8186 continue; 8187 8188 if (ParamType == RecordKernelParam) { 8189 VisitStack.push_back(FD); 8190 continue; 8191 } 8192 8193 // OpenCL v1.2 s6.9.p: 8194 // Arguments to kernel functions that are declared to be a struct or union 8195 // do not allow OpenCL objects to be passed as elements of the struct or 8196 // union. 8197 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8198 ParamType == InvalidAddrSpacePtrKernelParam) { 8199 S.Diag(Param->getLocation(), 8200 diag::err_record_with_pointers_kernel_param) 8201 << PT->isUnionType() 8202 << PT; 8203 } else { 8204 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8205 } 8206 8207 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8208 << PD->getDeclName(); 8209 8210 // We have an error, now let's go back up through history and show where 8211 // the offending field came from 8212 for (ArrayRef<const FieldDecl *>::const_iterator 8213 I = HistoryStack.begin() + 1, 8214 E = HistoryStack.end(); 8215 I != E; ++I) { 8216 const FieldDecl *OuterField = *I; 8217 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8218 << OuterField->getType(); 8219 } 8220 8221 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8222 << QT->isPointerType() 8223 << QT; 8224 D.setInvalidType(); 8225 return; 8226 } 8227 } while (!VisitStack.empty()); 8228 } 8229 8230 /// Find the DeclContext in which a tag is implicitly declared if we see an 8231 /// elaborated type specifier in the specified context, and lookup finds 8232 /// nothing. 8233 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8234 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8235 DC = DC->getParent(); 8236 return DC; 8237 } 8238 8239 /// Find the Scope in which a tag is implicitly declared if we see an 8240 /// elaborated type specifier in the specified context, and lookup finds 8241 /// nothing. 8242 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8243 while (S->isClassScope() || 8244 (LangOpts.CPlusPlus && 8245 S->isFunctionPrototypeScope()) || 8246 ((S->getFlags() & Scope::DeclScope) == 0) || 8247 (S->getEntity() && S->getEntity()->isTransparentContext())) 8248 S = S->getParent(); 8249 return S; 8250 } 8251 8252 NamedDecl* 8253 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8254 TypeSourceInfo *TInfo, LookupResult &Previous, 8255 MultiTemplateParamsArg TemplateParamLists, 8256 bool &AddToScope) { 8257 QualType R = TInfo->getType(); 8258 8259 assert(R->isFunctionType()); 8260 8261 // TODO: consider using NameInfo for diagnostic. 8262 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8263 DeclarationName Name = NameInfo.getName(); 8264 StorageClass SC = getFunctionStorageClass(*this, D); 8265 8266 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8267 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8268 diag::err_invalid_thread) 8269 << DeclSpec::getSpecifierName(TSCS); 8270 8271 if (D.isFirstDeclarationOfMember()) 8272 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8273 D.getIdentifierLoc()); 8274 8275 bool isFriend = false; 8276 FunctionTemplateDecl *FunctionTemplate = nullptr; 8277 bool isMemberSpecialization = false; 8278 bool isFunctionTemplateSpecialization = false; 8279 8280 bool isDependentClassScopeExplicitSpecialization = false; 8281 bool HasExplicitTemplateArgs = false; 8282 TemplateArgumentListInfo TemplateArgs; 8283 8284 bool isVirtualOkay = false; 8285 8286 DeclContext *OriginalDC = DC; 8287 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8288 8289 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8290 isVirtualOkay); 8291 if (!NewFD) return nullptr; 8292 8293 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8294 NewFD->setTopLevelDeclInObjCContainer(); 8295 8296 // Set the lexical context. If this is a function-scope declaration, or has a 8297 // C++ scope specifier, or is the object of a friend declaration, the lexical 8298 // context will be different from the semantic context. 8299 NewFD->setLexicalDeclContext(CurContext); 8300 8301 if (IsLocalExternDecl) 8302 NewFD->setLocalExternDecl(); 8303 8304 if (getLangOpts().CPlusPlus) { 8305 bool isInline = D.getDeclSpec().isInlineSpecified(); 8306 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8307 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8308 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8309 isFriend = D.getDeclSpec().isFriendSpecified(); 8310 if (isFriend && !isInline && D.isFunctionDefinition()) { 8311 // C++ [class.friend]p5 8312 // A function can be defined in a friend declaration of a 8313 // class . . . . Such a function is implicitly inline. 8314 NewFD->setImplicitlyInline(); 8315 } 8316 8317 // If this is a method defined in an __interface, and is not a constructor 8318 // or an overloaded operator, then set the pure flag (isVirtual will already 8319 // return true). 8320 if (const CXXRecordDecl *Parent = 8321 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8322 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8323 NewFD->setPure(true); 8324 8325 // C++ [class.union]p2 8326 // A union can have member functions, but not virtual functions. 8327 if (isVirtual && Parent->isUnion()) 8328 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8329 } 8330 8331 SetNestedNameSpecifier(NewFD, D); 8332 isMemberSpecialization = false; 8333 isFunctionTemplateSpecialization = false; 8334 if (D.isInvalidType()) 8335 NewFD->setInvalidDecl(); 8336 8337 // Match up the template parameter lists with the scope specifier, then 8338 // determine whether we have a template or a template specialization. 8339 bool Invalid = false; 8340 if (TemplateParameterList *TemplateParams = 8341 MatchTemplateParametersToScopeSpecifier( 8342 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8343 D.getCXXScopeSpec(), 8344 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8345 ? D.getName().TemplateId 8346 : nullptr, 8347 TemplateParamLists, isFriend, isMemberSpecialization, 8348 Invalid)) { 8349 if (TemplateParams->size() > 0) { 8350 // This is a function template 8351 8352 // Check that we can declare a template here. 8353 if (CheckTemplateDeclScope(S, TemplateParams)) 8354 NewFD->setInvalidDecl(); 8355 8356 // A destructor cannot be a template. 8357 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8358 Diag(NewFD->getLocation(), diag::err_destructor_template); 8359 NewFD->setInvalidDecl(); 8360 } 8361 8362 // If we're adding a template to a dependent context, we may need to 8363 // rebuilding some of the types used within the template parameter list, 8364 // now that we know what the current instantiation is. 8365 if (DC->isDependentContext()) { 8366 ContextRAII SavedContext(*this, DC); 8367 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8368 Invalid = true; 8369 } 8370 8371 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8372 NewFD->getLocation(), 8373 Name, TemplateParams, 8374 NewFD); 8375 FunctionTemplate->setLexicalDeclContext(CurContext); 8376 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8377 8378 // For source fidelity, store the other template param lists. 8379 if (TemplateParamLists.size() > 1) { 8380 NewFD->setTemplateParameterListsInfo(Context, 8381 TemplateParamLists.drop_back(1)); 8382 } 8383 } else { 8384 // This is a function template specialization. 8385 isFunctionTemplateSpecialization = true; 8386 // For source fidelity, store all the template param lists. 8387 if (TemplateParamLists.size() > 0) 8388 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8389 8390 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8391 if (isFriend) { 8392 // We want to remove the "template<>", found here. 8393 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8394 8395 // If we remove the template<> and the name is not a 8396 // template-id, we're actually silently creating a problem: 8397 // the friend declaration will refer to an untemplated decl, 8398 // and clearly the user wants a template specialization. So 8399 // we need to insert '<>' after the name. 8400 SourceLocation InsertLoc; 8401 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8402 InsertLoc = D.getName().getSourceRange().getEnd(); 8403 InsertLoc = getLocForEndOfToken(InsertLoc); 8404 } 8405 8406 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8407 << Name << RemoveRange 8408 << FixItHint::CreateRemoval(RemoveRange) 8409 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8410 } 8411 } 8412 } 8413 else { 8414 // All template param lists were matched against the scope specifier: 8415 // this is NOT (an explicit specialization of) a template. 8416 if (TemplateParamLists.size() > 0) 8417 // For source fidelity, store all the template param lists. 8418 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8419 } 8420 8421 if (Invalid) { 8422 NewFD->setInvalidDecl(); 8423 if (FunctionTemplate) 8424 FunctionTemplate->setInvalidDecl(); 8425 } 8426 8427 // C++ [dcl.fct.spec]p5: 8428 // The virtual specifier shall only be used in declarations of 8429 // nonstatic class member functions that appear within a 8430 // member-specification of a class declaration; see 10.3. 8431 // 8432 if (isVirtual && !NewFD->isInvalidDecl()) { 8433 if (!isVirtualOkay) { 8434 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8435 diag::err_virtual_non_function); 8436 } else if (!CurContext->isRecord()) { 8437 // 'virtual' was specified outside of the class. 8438 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8439 diag::err_virtual_out_of_class) 8440 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8441 } else if (NewFD->getDescribedFunctionTemplate()) { 8442 // C++ [temp.mem]p3: 8443 // A member function template shall not be virtual. 8444 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8445 diag::err_virtual_member_function_template) 8446 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8447 } else { 8448 // Okay: Add virtual to the method. 8449 NewFD->setVirtualAsWritten(true); 8450 } 8451 8452 if (getLangOpts().CPlusPlus14 && 8453 NewFD->getReturnType()->isUndeducedType()) 8454 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8455 } 8456 8457 if (getLangOpts().CPlusPlus14 && 8458 (NewFD->isDependentContext() || 8459 (isFriend && CurContext->isDependentContext())) && 8460 NewFD->getReturnType()->isUndeducedType()) { 8461 // If the function template is referenced directly (for instance, as a 8462 // member of the current instantiation), pretend it has a dependent type. 8463 // This is not really justified by the standard, but is the only sane 8464 // thing to do. 8465 // FIXME: For a friend function, we have not marked the function as being 8466 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8467 const FunctionProtoType *FPT = 8468 NewFD->getType()->castAs<FunctionProtoType>(); 8469 QualType Result = 8470 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8471 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8472 FPT->getExtProtoInfo())); 8473 } 8474 8475 // C++ [dcl.fct.spec]p3: 8476 // The inline specifier shall not appear on a block scope function 8477 // declaration. 8478 if (isInline && !NewFD->isInvalidDecl()) { 8479 if (CurContext->isFunctionOrMethod()) { 8480 // 'inline' is not allowed on block scope function declaration. 8481 Diag(D.getDeclSpec().getInlineSpecLoc(), 8482 diag::err_inline_declaration_block_scope) << Name 8483 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8484 } 8485 } 8486 8487 // C++ [dcl.fct.spec]p6: 8488 // The explicit specifier shall be used only in the declaration of a 8489 // constructor or conversion function within its class definition; 8490 // see 12.3.1 and 12.3.2. 8491 if (isExplicit && !NewFD->isInvalidDecl() && 8492 !isa<CXXDeductionGuideDecl>(NewFD)) { 8493 if (!CurContext->isRecord()) { 8494 // 'explicit' was specified outside of the class. 8495 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8496 diag::err_explicit_out_of_class) 8497 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8498 } else if (!isa<CXXConstructorDecl>(NewFD) && 8499 !isa<CXXConversionDecl>(NewFD)) { 8500 // 'explicit' was specified on a function that wasn't a constructor 8501 // or conversion function. 8502 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8503 diag::err_explicit_non_ctor_or_conv_function) 8504 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8505 } 8506 } 8507 8508 if (isConstexpr) { 8509 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8510 // are implicitly inline. 8511 NewFD->setImplicitlyInline(); 8512 8513 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8514 // be either constructors or to return a literal type. Therefore, 8515 // destructors cannot be declared constexpr. 8516 if (isa<CXXDestructorDecl>(NewFD)) 8517 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8518 } 8519 8520 // If __module_private__ was specified, mark the function accordingly. 8521 if (D.getDeclSpec().isModulePrivateSpecified()) { 8522 if (isFunctionTemplateSpecialization) { 8523 SourceLocation ModulePrivateLoc 8524 = D.getDeclSpec().getModulePrivateSpecLoc(); 8525 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8526 << 0 8527 << FixItHint::CreateRemoval(ModulePrivateLoc); 8528 } else { 8529 NewFD->setModulePrivate(); 8530 if (FunctionTemplate) 8531 FunctionTemplate->setModulePrivate(); 8532 } 8533 } 8534 8535 if (isFriend) { 8536 if (FunctionTemplate) { 8537 FunctionTemplate->setObjectOfFriendDecl(); 8538 FunctionTemplate->setAccess(AS_public); 8539 } 8540 NewFD->setObjectOfFriendDecl(); 8541 NewFD->setAccess(AS_public); 8542 } 8543 8544 // If a function is defined as defaulted or deleted, mark it as such now. 8545 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8546 // definition kind to FDK_Definition. 8547 switch (D.getFunctionDefinitionKind()) { 8548 case FDK_Declaration: 8549 case FDK_Definition: 8550 break; 8551 8552 case FDK_Defaulted: 8553 NewFD->setDefaulted(); 8554 break; 8555 8556 case FDK_Deleted: 8557 NewFD->setDeletedAsWritten(); 8558 break; 8559 } 8560 8561 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8562 D.isFunctionDefinition()) { 8563 // C++ [class.mfct]p2: 8564 // A member function may be defined (8.4) in its class definition, in 8565 // which case it is an inline member function (7.1.2) 8566 NewFD->setImplicitlyInline(); 8567 } 8568 8569 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8570 !CurContext->isRecord()) { 8571 // C++ [class.static]p1: 8572 // A data or function member of a class may be declared static 8573 // in a class definition, in which case it is a static member of 8574 // the class. 8575 8576 // Complain about the 'static' specifier if it's on an out-of-line 8577 // member function definition. 8578 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8579 diag::err_static_out_of_line) 8580 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8581 } 8582 8583 // C++11 [except.spec]p15: 8584 // A deallocation function with no exception-specification is treated 8585 // as if it were specified with noexcept(true). 8586 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8587 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8588 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8589 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8590 NewFD->setType(Context.getFunctionType( 8591 FPT->getReturnType(), FPT->getParamTypes(), 8592 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8593 } 8594 8595 // Filter out previous declarations that don't match the scope. 8596 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8597 D.getCXXScopeSpec().isNotEmpty() || 8598 isMemberSpecialization || 8599 isFunctionTemplateSpecialization); 8600 8601 // Handle GNU asm-label extension (encoded as an attribute). 8602 if (Expr *E = (Expr*) D.getAsmLabel()) { 8603 // The parser guarantees this is a string. 8604 StringLiteral *SE = cast<StringLiteral>(E); 8605 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8606 SE->getString(), 0)); 8607 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8608 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8609 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8610 if (I != ExtnameUndeclaredIdentifiers.end()) { 8611 if (isDeclExternC(NewFD)) { 8612 NewFD->addAttr(I->second); 8613 ExtnameUndeclaredIdentifiers.erase(I); 8614 } else 8615 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8616 << /*Variable*/0 << NewFD; 8617 } 8618 } 8619 8620 // Copy the parameter declarations from the declarator D to the function 8621 // declaration NewFD, if they are available. First scavenge them into Params. 8622 SmallVector<ParmVarDecl*, 16> Params; 8623 unsigned FTIIdx; 8624 if (D.isFunctionDeclarator(FTIIdx)) { 8625 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8626 8627 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8628 // function that takes no arguments, not a function that takes a 8629 // single void argument. 8630 // We let through "const void" here because Sema::GetTypeForDeclarator 8631 // already checks for that case. 8632 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8633 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8634 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8635 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8636 Param->setDeclContext(NewFD); 8637 Params.push_back(Param); 8638 8639 if (Param->isInvalidDecl()) 8640 NewFD->setInvalidDecl(); 8641 } 8642 } 8643 8644 if (!getLangOpts().CPlusPlus) { 8645 // In C, find all the tag declarations from the prototype and move them 8646 // into the function DeclContext. Remove them from the surrounding tag 8647 // injection context of the function, which is typically but not always 8648 // the TU. 8649 DeclContext *PrototypeTagContext = 8650 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8651 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8652 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8653 8654 // We don't want to reparent enumerators. Look at their parent enum 8655 // instead. 8656 if (!TD) { 8657 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8658 TD = cast<EnumDecl>(ECD->getDeclContext()); 8659 } 8660 if (!TD) 8661 continue; 8662 DeclContext *TagDC = TD->getLexicalDeclContext(); 8663 if (!TagDC->containsDecl(TD)) 8664 continue; 8665 TagDC->removeDecl(TD); 8666 TD->setDeclContext(NewFD); 8667 NewFD->addDecl(TD); 8668 8669 // Preserve the lexical DeclContext if it is not the surrounding tag 8670 // injection context of the FD. In this example, the semantic context of 8671 // E will be f and the lexical context will be S, while both the 8672 // semantic and lexical contexts of S will be f: 8673 // void f(struct S { enum E { a } f; } s); 8674 if (TagDC != PrototypeTagContext) 8675 TD->setLexicalDeclContext(TagDC); 8676 } 8677 } 8678 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8679 // When we're declaring a function with a typedef, typeof, etc as in the 8680 // following example, we'll need to synthesize (unnamed) 8681 // parameters for use in the declaration. 8682 // 8683 // @code 8684 // typedef void fn(int); 8685 // fn f; 8686 // @endcode 8687 8688 // Synthesize a parameter for each argument type. 8689 for (const auto &AI : FT->param_types()) { 8690 ParmVarDecl *Param = 8691 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8692 Param->setScopeInfo(0, Params.size()); 8693 Params.push_back(Param); 8694 } 8695 } else { 8696 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8697 "Should not need args for typedef of non-prototype fn"); 8698 } 8699 8700 // Finally, we know we have the right number of parameters, install them. 8701 NewFD->setParams(Params); 8702 8703 if (D.getDeclSpec().isNoreturnSpecified()) 8704 NewFD->addAttr( 8705 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8706 Context, 0)); 8707 8708 // Functions returning a variably modified type violate C99 6.7.5.2p2 8709 // because all functions have linkage. 8710 if (!NewFD->isInvalidDecl() && 8711 NewFD->getReturnType()->isVariablyModifiedType()) { 8712 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8713 NewFD->setInvalidDecl(); 8714 } 8715 8716 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8717 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8718 !NewFD->hasAttr<SectionAttr>()) { 8719 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8720 PragmaClangTextSection.SectionName, 8721 PragmaClangTextSection.PragmaLocation)); 8722 } 8723 8724 // Apply an implicit SectionAttr if #pragma code_seg is active. 8725 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8726 !NewFD->hasAttr<SectionAttr>()) { 8727 NewFD->addAttr( 8728 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8729 CodeSegStack.CurrentValue->getString(), 8730 CodeSegStack.CurrentPragmaLocation)); 8731 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8732 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8733 ASTContext::PSF_Read, 8734 NewFD)) 8735 NewFD->dropAttr<SectionAttr>(); 8736 } 8737 8738 // Apply an implicit CodeSegAttr from class declspec or 8739 // apply an implicit SectionAttr from #pragma code_seg if active. 8740 if (!NewFD->hasAttr<CodeSegAttr>()) { 8741 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 8742 D.isFunctionDefinition())) { 8743 NewFD->addAttr(SAttr); 8744 } 8745 } 8746 8747 // Handle attributes. 8748 ProcessDeclAttributes(S, NewFD, D); 8749 8750 if (getLangOpts().OpenCL) { 8751 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8752 // type declaration will generate a compilation error. 8753 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8754 if (AddressSpace != LangAS::Default) { 8755 Diag(NewFD->getLocation(), 8756 diag::err_opencl_return_value_with_address_space); 8757 NewFD->setInvalidDecl(); 8758 } 8759 } 8760 8761 if (!getLangOpts().CPlusPlus) { 8762 // Perform semantic checking on the function declaration. 8763 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8764 CheckMain(NewFD, D.getDeclSpec()); 8765 8766 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8767 CheckMSVCRTEntryPoint(NewFD); 8768 8769 if (!NewFD->isInvalidDecl()) 8770 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8771 isMemberSpecialization)); 8772 else if (!Previous.empty()) 8773 // Recover gracefully from an invalid redeclaration. 8774 D.setRedeclaration(true); 8775 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8776 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8777 "previous declaration set still overloaded"); 8778 8779 // Diagnose no-prototype function declarations with calling conventions that 8780 // don't support variadic calls. Only do this in C and do it after merging 8781 // possibly prototyped redeclarations. 8782 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8783 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8784 CallingConv CC = FT->getExtInfo().getCC(); 8785 if (!supportsVariadicCall(CC)) { 8786 // Windows system headers sometimes accidentally use stdcall without 8787 // (void) parameters, so we relax this to a warning. 8788 int DiagID = 8789 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8790 Diag(NewFD->getLocation(), DiagID) 8791 << FunctionType::getNameForCallConv(CC); 8792 } 8793 } 8794 } else { 8795 // C++11 [replacement.functions]p3: 8796 // The program's definitions shall not be specified as inline. 8797 // 8798 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8799 // 8800 // Suppress the diagnostic if the function is __attribute__((used)), since 8801 // that forces an external definition to be emitted. 8802 if (D.getDeclSpec().isInlineSpecified() && 8803 NewFD->isReplaceableGlobalAllocationFunction() && 8804 !NewFD->hasAttr<UsedAttr>()) 8805 Diag(D.getDeclSpec().getInlineSpecLoc(), 8806 diag::ext_operator_new_delete_declared_inline) 8807 << NewFD->getDeclName(); 8808 8809 // If the declarator is a template-id, translate the parser's template 8810 // argument list into our AST format. 8811 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8812 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8813 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8814 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8815 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8816 TemplateId->NumArgs); 8817 translateTemplateArguments(TemplateArgsPtr, 8818 TemplateArgs); 8819 8820 HasExplicitTemplateArgs = true; 8821 8822 if (NewFD->isInvalidDecl()) { 8823 HasExplicitTemplateArgs = false; 8824 } else if (FunctionTemplate) { 8825 // Function template with explicit template arguments. 8826 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8827 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8828 8829 HasExplicitTemplateArgs = false; 8830 } else { 8831 assert((isFunctionTemplateSpecialization || 8832 D.getDeclSpec().isFriendSpecified()) && 8833 "should have a 'template<>' for this decl"); 8834 // "friend void foo<>(int);" is an implicit specialization decl. 8835 isFunctionTemplateSpecialization = true; 8836 } 8837 } else if (isFriend && isFunctionTemplateSpecialization) { 8838 // This combination is only possible in a recovery case; the user 8839 // wrote something like: 8840 // template <> friend void foo(int); 8841 // which we're recovering from as if the user had written: 8842 // friend void foo<>(int); 8843 // Go ahead and fake up a template id. 8844 HasExplicitTemplateArgs = true; 8845 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8846 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8847 } 8848 8849 // We do not add HD attributes to specializations here because 8850 // they may have different constexpr-ness compared to their 8851 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8852 // may end up with different effective targets. Instead, a 8853 // specialization inherits its target attributes from its template 8854 // in the CheckFunctionTemplateSpecialization() call below. 8855 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8856 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8857 8858 // If it's a friend (and only if it's a friend), it's possible 8859 // that either the specialized function type or the specialized 8860 // template is dependent, and therefore matching will fail. In 8861 // this case, don't check the specialization yet. 8862 bool InstantiationDependent = false; 8863 if (isFunctionTemplateSpecialization && isFriend && 8864 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8865 TemplateSpecializationType::anyDependentTemplateArguments( 8866 TemplateArgs, 8867 InstantiationDependent))) { 8868 assert(HasExplicitTemplateArgs && 8869 "friend function specialization without template args"); 8870 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8871 Previous)) 8872 NewFD->setInvalidDecl(); 8873 } else if (isFunctionTemplateSpecialization) { 8874 if (CurContext->isDependentContext() && CurContext->isRecord() 8875 && !isFriend) { 8876 isDependentClassScopeExplicitSpecialization = true; 8877 } else if (!NewFD->isInvalidDecl() && 8878 CheckFunctionTemplateSpecialization( 8879 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8880 Previous)) 8881 NewFD->setInvalidDecl(); 8882 8883 // C++ [dcl.stc]p1: 8884 // A storage-class-specifier shall not be specified in an explicit 8885 // specialization (14.7.3) 8886 FunctionTemplateSpecializationInfo *Info = 8887 NewFD->getTemplateSpecializationInfo(); 8888 if (Info && SC != SC_None) { 8889 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8890 Diag(NewFD->getLocation(), 8891 diag::err_explicit_specialization_inconsistent_storage_class) 8892 << SC 8893 << FixItHint::CreateRemoval( 8894 D.getDeclSpec().getStorageClassSpecLoc()); 8895 8896 else 8897 Diag(NewFD->getLocation(), 8898 diag::ext_explicit_specialization_storage_class) 8899 << FixItHint::CreateRemoval( 8900 D.getDeclSpec().getStorageClassSpecLoc()); 8901 } 8902 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8903 if (CheckMemberSpecialization(NewFD, Previous)) 8904 NewFD->setInvalidDecl(); 8905 } 8906 8907 // Perform semantic checking on the function declaration. 8908 if (!isDependentClassScopeExplicitSpecialization) { 8909 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8910 CheckMain(NewFD, D.getDeclSpec()); 8911 8912 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8913 CheckMSVCRTEntryPoint(NewFD); 8914 8915 if (!NewFD->isInvalidDecl()) 8916 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8917 isMemberSpecialization)); 8918 else if (!Previous.empty()) 8919 // Recover gracefully from an invalid redeclaration. 8920 D.setRedeclaration(true); 8921 } 8922 8923 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8924 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8925 "previous declaration set still overloaded"); 8926 8927 NamedDecl *PrincipalDecl = (FunctionTemplate 8928 ? cast<NamedDecl>(FunctionTemplate) 8929 : NewFD); 8930 8931 if (isFriend && NewFD->getPreviousDecl()) { 8932 AccessSpecifier Access = AS_public; 8933 if (!NewFD->isInvalidDecl()) 8934 Access = NewFD->getPreviousDecl()->getAccess(); 8935 8936 NewFD->setAccess(Access); 8937 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8938 } 8939 8940 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8941 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8942 PrincipalDecl->setNonMemberOperator(); 8943 8944 // If we have a function template, check the template parameter 8945 // list. This will check and merge default template arguments. 8946 if (FunctionTemplate) { 8947 FunctionTemplateDecl *PrevTemplate = 8948 FunctionTemplate->getPreviousDecl(); 8949 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8950 PrevTemplate ? PrevTemplate->getTemplateParameters() 8951 : nullptr, 8952 D.getDeclSpec().isFriendSpecified() 8953 ? (D.isFunctionDefinition() 8954 ? TPC_FriendFunctionTemplateDefinition 8955 : TPC_FriendFunctionTemplate) 8956 : (D.getCXXScopeSpec().isSet() && 8957 DC && DC->isRecord() && 8958 DC->isDependentContext()) 8959 ? TPC_ClassTemplateMember 8960 : TPC_FunctionTemplate); 8961 } 8962 8963 if (NewFD->isInvalidDecl()) { 8964 // Ignore all the rest of this. 8965 } else if (!D.isRedeclaration()) { 8966 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8967 AddToScope }; 8968 // Fake up an access specifier if it's supposed to be a class member. 8969 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8970 NewFD->setAccess(AS_public); 8971 8972 // Qualified decls generally require a previous declaration. 8973 if (D.getCXXScopeSpec().isSet()) { 8974 // ...with the major exception of templated-scope or 8975 // dependent-scope friend declarations. 8976 8977 // TODO: we currently also suppress this check in dependent 8978 // contexts because (1) the parameter depth will be off when 8979 // matching friend templates and (2) we might actually be 8980 // selecting a friend based on a dependent factor. But there 8981 // are situations where these conditions don't apply and we 8982 // can actually do this check immediately. 8983 if (isFriend && 8984 (TemplateParamLists.size() || 8985 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8986 CurContext->isDependentContext())) { 8987 // ignore these 8988 } else { 8989 // The user tried to provide an out-of-line definition for a 8990 // function that is a member of a class or namespace, but there 8991 // was no such member function declared (C++ [class.mfct]p2, 8992 // C++ [namespace.memdef]p2). For example: 8993 // 8994 // class X { 8995 // void f() const; 8996 // }; 8997 // 8998 // void X::f() { } // ill-formed 8999 // 9000 // Complain about this problem, and attempt to suggest close 9001 // matches (e.g., those that differ only in cv-qualifiers and 9002 // whether the parameter types are references). 9003 9004 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9005 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9006 AddToScope = ExtraArgs.AddToScope; 9007 return Result; 9008 } 9009 } 9010 9011 // Unqualified local friend declarations are required to resolve 9012 // to something. 9013 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9014 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9015 *this, Previous, NewFD, ExtraArgs, true, S)) { 9016 AddToScope = ExtraArgs.AddToScope; 9017 return Result; 9018 } 9019 } 9020 } else if (!D.isFunctionDefinition() && 9021 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9022 !isFriend && !isFunctionTemplateSpecialization && 9023 !isMemberSpecialization) { 9024 // An out-of-line member function declaration must also be a 9025 // definition (C++ [class.mfct]p2). 9026 // Note that this is not the case for explicit specializations of 9027 // function templates or member functions of class templates, per 9028 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9029 // extension for compatibility with old SWIG code which likes to 9030 // generate them. 9031 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9032 << D.getCXXScopeSpec().getRange(); 9033 } 9034 } 9035 9036 ProcessPragmaWeak(S, NewFD); 9037 checkAttributesAfterMerging(*this, *NewFD); 9038 9039 AddKnownFunctionAttributes(NewFD); 9040 9041 if (NewFD->hasAttr<OverloadableAttr>() && 9042 !NewFD->getType()->getAs<FunctionProtoType>()) { 9043 Diag(NewFD->getLocation(), 9044 diag::err_attribute_overloadable_no_prototype) 9045 << NewFD; 9046 9047 // Turn this into a variadic function with no parameters. 9048 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9049 FunctionProtoType::ExtProtoInfo EPI( 9050 Context.getDefaultCallingConvention(true, false)); 9051 EPI.Variadic = true; 9052 EPI.ExtInfo = FT->getExtInfo(); 9053 9054 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9055 NewFD->setType(R); 9056 } 9057 9058 // If there's a #pragma GCC visibility in scope, and this isn't a class 9059 // member, set the visibility of this function. 9060 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9061 AddPushedVisibilityAttribute(NewFD); 9062 9063 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9064 // marking the function. 9065 AddCFAuditedAttribute(NewFD); 9066 9067 // If this is a function definition, check if we have to apply optnone due to 9068 // a pragma. 9069 if(D.isFunctionDefinition()) 9070 AddRangeBasedOptnone(NewFD); 9071 9072 // If this is the first declaration of an extern C variable, update 9073 // the map of such variables. 9074 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9075 isIncompleteDeclExternC(*this, NewFD)) 9076 RegisterLocallyScopedExternCDecl(NewFD, S); 9077 9078 // Set this FunctionDecl's range up to the right paren. 9079 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9080 9081 if (D.isRedeclaration() && !Previous.empty()) { 9082 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9083 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9084 isMemberSpecialization || 9085 isFunctionTemplateSpecialization, 9086 D.isFunctionDefinition()); 9087 } 9088 9089 if (getLangOpts().CUDA) { 9090 IdentifierInfo *II = NewFD->getIdentifier(); 9091 if (II && 9092 II->isStr(getLangOpts().HIP ? "hipConfigureCall" 9093 : "cudaConfigureCall") && 9094 !NewFD->isInvalidDecl() && 9095 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9096 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9097 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9098 Context.setcudaConfigureCallDecl(NewFD); 9099 } 9100 9101 // Variadic functions, other than a *declaration* of printf, are not allowed 9102 // in device-side CUDA code, unless someone passed 9103 // -fcuda-allow-variadic-functions. 9104 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9105 (NewFD->hasAttr<CUDADeviceAttr>() || 9106 NewFD->hasAttr<CUDAGlobalAttr>()) && 9107 !(II && II->isStr("printf") && NewFD->isExternC() && 9108 !D.isFunctionDefinition())) { 9109 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9110 } 9111 } 9112 9113 MarkUnusedFileScopedDecl(NewFD); 9114 9115 if (getLangOpts().CPlusPlus) { 9116 if (FunctionTemplate) { 9117 if (NewFD->isInvalidDecl()) 9118 FunctionTemplate->setInvalidDecl(); 9119 return FunctionTemplate; 9120 } 9121 9122 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9123 CompleteMemberSpecialization(NewFD, Previous); 9124 } 9125 9126 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9127 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9128 if ((getLangOpts().OpenCLVersion >= 120) 9129 && (SC == SC_Static)) { 9130 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9131 D.setInvalidType(); 9132 } 9133 9134 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9135 if (!NewFD->getReturnType()->isVoidType()) { 9136 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9137 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9138 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9139 : FixItHint()); 9140 D.setInvalidType(); 9141 } 9142 9143 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9144 for (auto Param : NewFD->parameters()) 9145 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9146 } 9147 for (const ParmVarDecl *Param : NewFD->parameters()) { 9148 QualType PT = Param->getType(); 9149 9150 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9151 // types. 9152 if (getLangOpts().OpenCLVersion >= 200) { 9153 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9154 QualType ElemTy = PipeTy->getElementType(); 9155 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9156 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9157 D.setInvalidType(); 9158 } 9159 } 9160 } 9161 } 9162 9163 // Here we have an function template explicit specialization at class scope. 9164 // The actual specialization will be postponed to template instatiation 9165 // time via the ClassScopeFunctionSpecializationDecl node. 9166 if (isDependentClassScopeExplicitSpecialization) { 9167 ClassScopeFunctionSpecializationDecl *NewSpec = 9168 ClassScopeFunctionSpecializationDecl::Create( 9169 Context, CurContext, NewFD->getLocation(), 9170 cast<CXXMethodDecl>(NewFD), 9171 HasExplicitTemplateArgs, TemplateArgs); 9172 CurContext->addDecl(NewSpec); 9173 AddToScope = false; 9174 } 9175 9176 // Diagnose availability attributes. Availability cannot be used on functions 9177 // that are run during load/unload. 9178 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9179 if (NewFD->hasAttr<ConstructorAttr>()) { 9180 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9181 << 1; 9182 NewFD->dropAttr<AvailabilityAttr>(); 9183 } 9184 if (NewFD->hasAttr<DestructorAttr>()) { 9185 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9186 << 2; 9187 NewFD->dropAttr<AvailabilityAttr>(); 9188 } 9189 } 9190 9191 return NewFD; 9192 } 9193 9194 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9195 /// when __declspec(code_seg) "is applied to a class, all member functions of 9196 /// the class and nested classes -- this includes compiler-generated special 9197 /// member functions -- are put in the specified segment." 9198 /// The actual behavior is a little more complicated. The Microsoft compiler 9199 /// won't check outer classes if there is an active value from #pragma code_seg. 9200 /// The CodeSeg is always applied from the direct parent but only from outer 9201 /// classes when the #pragma code_seg stack is empty. See: 9202 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9203 /// available since MS has removed the page. 9204 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9205 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9206 if (!Method) 9207 return nullptr; 9208 const CXXRecordDecl *Parent = Method->getParent(); 9209 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9210 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9211 NewAttr->setImplicit(true); 9212 return NewAttr; 9213 } 9214 9215 // The Microsoft compiler won't check outer classes for the CodeSeg 9216 // when the #pragma code_seg stack is active. 9217 if (S.CodeSegStack.CurrentValue) 9218 return nullptr; 9219 9220 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9221 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9222 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9223 NewAttr->setImplicit(true); 9224 return NewAttr; 9225 } 9226 } 9227 return nullptr; 9228 } 9229 9230 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9231 /// containing class. Otherwise it will return implicit SectionAttr if the 9232 /// function is a definition and there is an active value on CodeSegStack 9233 /// (from the current #pragma code-seg value). 9234 /// 9235 /// \param FD Function being declared. 9236 /// \param IsDefinition Whether it is a definition or just a declarartion. 9237 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9238 /// nullptr if no attribute should be added. 9239 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9240 bool IsDefinition) { 9241 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9242 return A; 9243 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9244 CodeSegStack.CurrentValue) { 9245 return SectionAttr::CreateImplicit(getASTContext(), 9246 SectionAttr::Declspec_allocate, 9247 CodeSegStack.CurrentValue->getString(), 9248 CodeSegStack.CurrentPragmaLocation); 9249 } 9250 return nullptr; 9251 } 9252 /// Checks if the new declaration declared in dependent context must be 9253 /// put in the same redeclaration chain as the specified declaration. 9254 /// 9255 /// \param D Declaration that is checked. 9256 /// \param PrevDecl Previous declaration found with proper lookup method for the 9257 /// same declaration name. 9258 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9259 /// belongs to. 9260 /// 9261 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9262 // Any declarations should be put into redeclaration chains except for 9263 // friend declaration in a dependent context that names a function in 9264 // namespace scope. 9265 // 9266 // This allows to compile code like: 9267 // 9268 // void func(); 9269 // template<typename T> class C1 { friend void func() { } }; 9270 // template<typename T> class C2 { friend void func() { } }; 9271 // 9272 // This code snippet is a valid code unless both templates are instantiated. 9273 return !(D->getLexicalDeclContext()->isDependentContext() && 9274 D->getDeclContext()->isFileContext() && 9275 D->getFriendObjectKind() != Decl::FOK_None); 9276 } 9277 9278 /// Check the target attribute of the function for MultiVersion 9279 /// validity. 9280 /// 9281 /// Returns true if there was an error, false otherwise. 9282 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9283 const auto *TA = FD->getAttr<TargetAttr>(); 9284 assert(TA && "MultiVersion Candidate requires a target attribute"); 9285 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9286 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9287 enum ErrType { Feature = 0, Architecture = 1 }; 9288 9289 if (!ParseInfo.Architecture.empty() && 9290 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9291 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9292 << Architecture << ParseInfo.Architecture; 9293 return true; 9294 } 9295 9296 for (const auto &Feat : ParseInfo.Features) { 9297 auto BareFeat = StringRef{Feat}.substr(1); 9298 if (Feat[0] == '-') { 9299 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9300 << Feature << ("no-" + BareFeat).str(); 9301 return true; 9302 } 9303 9304 if (!TargetInfo.validateCpuSupports(BareFeat) || 9305 !TargetInfo.isValidFeatureName(BareFeat)) { 9306 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9307 << Feature << BareFeat; 9308 return true; 9309 } 9310 } 9311 return false; 9312 } 9313 9314 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9315 const FunctionDecl *NewFD, 9316 bool CausesMV) { 9317 enum DoesntSupport { 9318 FuncTemplates = 0, 9319 VirtFuncs = 1, 9320 DeducedReturn = 2, 9321 Constructors = 3, 9322 Destructors = 4, 9323 DeletedFuncs = 5, 9324 DefaultedFuncs = 6 9325 }; 9326 enum Different { 9327 CallingConv = 0, 9328 ReturnType = 1, 9329 ConstexprSpec = 2, 9330 InlineSpec = 3, 9331 StorageClass = 4, 9332 Linkage = 5 9333 }; 9334 9335 // For now, disallow all other attributes. These should be opt-in, but 9336 // an analysis of all of them is a future FIXME. 9337 if (CausesMV && OldFD && 9338 std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) { 9339 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs); 9340 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9341 return true; 9342 } 9343 9344 if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1) 9345 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs); 9346 9347 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9348 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9349 << FuncTemplates; 9350 9351 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9352 if (NewCXXFD->isVirtual()) 9353 return S.Diag(NewCXXFD->getLocation(), 9354 diag::err_multiversion_doesnt_support) 9355 << VirtFuncs; 9356 9357 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9358 return S.Diag(NewCXXCtor->getLocation(), 9359 diag::err_multiversion_doesnt_support) 9360 << Constructors; 9361 9362 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9363 return S.Diag(NewCXXDtor->getLocation(), 9364 diag::err_multiversion_doesnt_support) 9365 << Destructors; 9366 } 9367 9368 if (NewFD->isDeleted()) 9369 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9370 << DeletedFuncs; 9371 9372 if (NewFD->isDefaulted()) 9373 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9374 << DefaultedFuncs; 9375 9376 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9377 const auto *NewType = cast<FunctionType>(NewQType); 9378 QualType NewReturnType = NewType->getReturnType(); 9379 9380 if (NewReturnType->isUndeducedType()) 9381 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9382 << DeducedReturn; 9383 9384 // Only allow transition to MultiVersion if it hasn't been used. 9385 if (OldFD && CausesMV && OldFD->isUsed(false)) 9386 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9387 9388 // Ensure the return type is identical. 9389 if (OldFD) { 9390 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9391 const auto *OldType = cast<FunctionType>(OldQType); 9392 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9393 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9394 9395 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9396 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9397 << CallingConv; 9398 9399 QualType OldReturnType = OldType->getReturnType(); 9400 9401 if (OldReturnType != NewReturnType) 9402 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9403 << ReturnType; 9404 9405 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9406 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9407 << ConstexprSpec; 9408 9409 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9410 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9411 << InlineSpec; 9412 9413 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9414 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9415 << StorageClass; 9416 9417 if (OldFD->isExternC() != NewFD->isExternC()) 9418 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9419 << Linkage; 9420 9421 if (S.CheckEquivalentExceptionSpec( 9422 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9423 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9424 return true; 9425 } 9426 return false; 9427 } 9428 9429 /// Check the validity of a mulitversion function declaration. 9430 /// Also sets the multiversion'ness' of the function itself. 9431 /// 9432 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9433 /// 9434 /// Returns true if there was an error, false otherwise. 9435 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9436 bool &Redeclaration, NamedDecl *&OldDecl, 9437 bool &MergeTypeWithPrevious, 9438 LookupResult &Previous) { 9439 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9440 if (NewFD->isMain()) { 9441 if (NewTA && NewTA->isDefaultVersion()) { 9442 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9443 NewFD->setInvalidDecl(); 9444 return true; 9445 } 9446 return false; 9447 } 9448 9449 // If there is no matching previous decl, only 'default' can 9450 // cause MultiVersioning. 9451 if (!OldDecl) { 9452 if (NewTA && NewTA->isDefaultVersion()) { 9453 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 9454 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9455 NewFD->setInvalidDecl(); 9456 return true; 9457 } 9458 if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) { 9459 NewFD->setInvalidDecl(); 9460 return true; 9461 } 9462 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9463 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9464 NewFD->setInvalidDecl(); 9465 return true; 9466 } 9467 9468 NewFD->setIsMultiVersion(); 9469 } 9470 return false; 9471 } 9472 9473 if (OldDecl->getDeclContext()->getRedeclContext() != 9474 NewFD->getDeclContext()->getRedeclContext()) 9475 return false; 9476 9477 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9478 // Unresolved 'using' statements (the other way OldDecl can be not a function) 9479 // likely cannot cause a problem here. 9480 if (!OldFD) 9481 return false; 9482 9483 if (!OldFD->isMultiVersion() && !NewTA) 9484 return false; 9485 9486 if (OldFD->isMultiVersion() && !NewTA) { 9487 S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl); 9488 NewFD->setInvalidDecl(); 9489 return true; 9490 } 9491 9492 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9493 // Sort order doesn't matter, it just needs to be consistent. 9494 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end()); 9495 9496 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9497 if (!OldFD->isMultiVersion()) { 9498 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9499 // to change, this is a simple redeclaration. 9500 if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()) 9501 return false; 9502 9503 // Otherwise, this decl causes MultiVersioning. 9504 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9505 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9506 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9507 NewFD->setInvalidDecl(); 9508 return true; 9509 } 9510 9511 if (!OldFD->getType()->getAs<FunctionProtoType>()) { 9512 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9513 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9514 NewFD->setInvalidDecl(); 9515 return true; 9516 } 9517 9518 if (CheckMultiVersionValue(S, NewFD)) { 9519 NewFD->setInvalidDecl(); 9520 return true; 9521 } 9522 9523 if (CheckMultiVersionValue(S, OldFD)) { 9524 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9525 NewFD->setInvalidDecl(); 9526 return true; 9527 } 9528 9529 TargetAttr::ParsedTargetAttr OldParsed = 9530 OldTA->parse(std::less<std::string>()); 9531 9532 if (OldParsed == NewParsed) { 9533 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9534 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9535 NewFD->setInvalidDecl(); 9536 return true; 9537 } 9538 9539 for (const auto *FD : OldFD->redecls()) { 9540 const auto *CurTA = FD->getAttr<TargetAttr>(); 9541 if (!CurTA || CurTA->isInherited()) { 9542 S.Diag(FD->getLocation(), diag::err_target_required_in_redecl); 9543 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9544 NewFD->setInvalidDecl(); 9545 return true; 9546 } 9547 } 9548 9549 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) { 9550 NewFD->setInvalidDecl(); 9551 return true; 9552 } 9553 9554 OldFD->setIsMultiVersion(); 9555 NewFD->setIsMultiVersion(); 9556 Redeclaration = false; 9557 MergeTypeWithPrevious = false; 9558 OldDecl = nullptr; 9559 Previous.clear(); 9560 return false; 9561 } 9562 9563 bool UseMemberUsingDeclRules = 9564 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9565 9566 // Next, check ALL non-overloads to see if this is a redeclaration of a 9567 // previous member of the MultiVersion set. 9568 for (NamedDecl *ND : Previous) { 9569 FunctionDecl *CurFD = ND->getAsFunction(); 9570 if (!CurFD) 9571 continue; 9572 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9573 continue; 9574 9575 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9576 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9577 NewFD->setIsMultiVersion(); 9578 Redeclaration = true; 9579 OldDecl = ND; 9580 return false; 9581 } 9582 9583 TargetAttr::ParsedTargetAttr CurParsed = 9584 CurTA->parse(std::less<std::string>()); 9585 9586 if (CurParsed == NewParsed) { 9587 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9588 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9589 NewFD->setInvalidDecl(); 9590 return true; 9591 } 9592 } 9593 9594 // Else, this is simply a non-redecl case. 9595 if (CheckMultiVersionValue(S, NewFD)) { 9596 NewFD->setInvalidDecl(); 9597 return true; 9598 } 9599 9600 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) { 9601 NewFD->setInvalidDecl(); 9602 return true; 9603 } 9604 9605 NewFD->setIsMultiVersion(); 9606 Redeclaration = false; 9607 MergeTypeWithPrevious = false; 9608 OldDecl = nullptr; 9609 Previous.clear(); 9610 return false; 9611 } 9612 9613 /// Perform semantic checking of a new function declaration. 9614 /// 9615 /// Performs semantic analysis of the new function declaration 9616 /// NewFD. This routine performs all semantic checking that does not 9617 /// require the actual declarator involved in the declaration, and is 9618 /// used both for the declaration of functions as they are parsed 9619 /// (called via ActOnDeclarator) and for the declaration of functions 9620 /// that have been instantiated via C++ template instantiation (called 9621 /// via InstantiateDecl). 9622 /// 9623 /// \param IsMemberSpecialization whether this new function declaration is 9624 /// a member specialization (that replaces any definition provided by the 9625 /// previous declaration). 9626 /// 9627 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9628 /// 9629 /// \returns true if the function declaration is a redeclaration. 9630 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9631 LookupResult &Previous, 9632 bool IsMemberSpecialization) { 9633 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9634 "Variably modified return types are not handled here"); 9635 9636 // Determine whether the type of this function should be merged with 9637 // a previous visible declaration. This never happens for functions in C++, 9638 // and always happens in C if the previous declaration was visible. 9639 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9640 !Previous.isShadowed(); 9641 9642 bool Redeclaration = false; 9643 NamedDecl *OldDecl = nullptr; 9644 bool MayNeedOverloadableChecks = false; 9645 9646 // Merge or overload the declaration with an existing declaration of 9647 // the same name, if appropriate. 9648 if (!Previous.empty()) { 9649 // Determine whether NewFD is an overload of PrevDecl or 9650 // a declaration that requires merging. If it's an overload, 9651 // there's no more work to do here; we'll just add the new 9652 // function to the scope. 9653 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9654 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9655 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9656 Redeclaration = true; 9657 OldDecl = Candidate; 9658 } 9659 } else { 9660 MayNeedOverloadableChecks = true; 9661 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9662 /*NewIsUsingDecl*/ false)) { 9663 case Ovl_Match: 9664 Redeclaration = true; 9665 break; 9666 9667 case Ovl_NonFunction: 9668 Redeclaration = true; 9669 break; 9670 9671 case Ovl_Overload: 9672 Redeclaration = false; 9673 break; 9674 } 9675 } 9676 } 9677 9678 // Check for a previous extern "C" declaration with this name. 9679 if (!Redeclaration && 9680 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9681 if (!Previous.empty()) { 9682 // This is an extern "C" declaration with the same name as a previous 9683 // declaration, and thus redeclares that entity... 9684 Redeclaration = true; 9685 OldDecl = Previous.getFoundDecl(); 9686 MergeTypeWithPrevious = false; 9687 9688 // ... except in the presence of __attribute__((overloadable)). 9689 if (OldDecl->hasAttr<OverloadableAttr>() || 9690 NewFD->hasAttr<OverloadableAttr>()) { 9691 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9692 MayNeedOverloadableChecks = true; 9693 Redeclaration = false; 9694 OldDecl = nullptr; 9695 } 9696 } 9697 } 9698 } 9699 9700 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 9701 MergeTypeWithPrevious, Previous)) 9702 return Redeclaration; 9703 9704 // C++11 [dcl.constexpr]p8: 9705 // A constexpr specifier for a non-static member function that is not 9706 // a constructor declares that member function to be const. 9707 // 9708 // This needs to be delayed until we know whether this is an out-of-line 9709 // definition of a static member function. 9710 // 9711 // This rule is not present in C++1y, so we produce a backwards 9712 // compatibility warning whenever it happens in C++11. 9713 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9714 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9715 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9716 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9717 CXXMethodDecl *OldMD = nullptr; 9718 if (OldDecl) 9719 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9720 if (!OldMD || !OldMD->isStatic()) { 9721 const FunctionProtoType *FPT = 9722 MD->getType()->castAs<FunctionProtoType>(); 9723 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9724 EPI.TypeQuals |= Qualifiers::Const; 9725 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9726 FPT->getParamTypes(), EPI)); 9727 9728 // Warn that we did this, if we're not performing template instantiation. 9729 // In that case, we'll have warned already when the template was defined. 9730 if (!inTemplateInstantiation()) { 9731 SourceLocation AddConstLoc; 9732 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9733 .IgnoreParens().getAs<FunctionTypeLoc>()) 9734 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9735 9736 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9737 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9738 } 9739 } 9740 } 9741 9742 if (Redeclaration) { 9743 // NewFD and OldDecl represent declarations that need to be 9744 // merged. 9745 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9746 NewFD->setInvalidDecl(); 9747 return Redeclaration; 9748 } 9749 9750 Previous.clear(); 9751 Previous.addDecl(OldDecl); 9752 9753 if (FunctionTemplateDecl *OldTemplateDecl = 9754 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9755 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 9756 NewFD->setPreviousDeclaration(OldFD); 9757 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9758 FunctionTemplateDecl *NewTemplateDecl 9759 = NewFD->getDescribedFunctionTemplate(); 9760 assert(NewTemplateDecl && "Template/non-template mismatch"); 9761 if (NewFD->isCXXClassMember()) { 9762 NewFD->setAccess(OldTemplateDecl->getAccess()); 9763 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9764 } 9765 9766 // If this is an explicit specialization of a member that is a function 9767 // template, mark it as a member specialization. 9768 if (IsMemberSpecialization && 9769 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9770 NewTemplateDecl->setMemberSpecialization(); 9771 assert(OldTemplateDecl->isMemberSpecialization()); 9772 // Explicit specializations of a member template do not inherit deleted 9773 // status from the parent member template that they are specializing. 9774 if (OldFD->isDeleted()) { 9775 // FIXME: This assert will not hold in the presence of modules. 9776 assert(OldFD->getCanonicalDecl() == OldFD); 9777 // FIXME: We need an update record for this AST mutation. 9778 OldFD->setDeletedAsWritten(false); 9779 } 9780 } 9781 9782 } else { 9783 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9784 auto *OldFD = cast<FunctionDecl>(OldDecl); 9785 // This needs to happen first so that 'inline' propagates. 9786 NewFD->setPreviousDeclaration(OldFD); 9787 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9788 if (NewFD->isCXXClassMember()) 9789 NewFD->setAccess(OldFD->getAccess()); 9790 } 9791 } 9792 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9793 !NewFD->getAttr<OverloadableAttr>()) { 9794 assert((Previous.empty() || 9795 llvm::any_of(Previous, 9796 [](const NamedDecl *ND) { 9797 return ND->hasAttr<OverloadableAttr>(); 9798 })) && 9799 "Non-redecls shouldn't happen without overloadable present"); 9800 9801 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9802 const auto *FD = dyn_cast<FunctionDecl>(ND); 9803 return FD && !FD->hasAttr<OverloadableAttr>(); 9804 }); 9805 9806 if (OtherUnmarkedIter != Previous.end()) { 9807 Diag(NewFD->getLocation(), 9808 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9809 Diag((*OtherUnmarkedIter)->getLocation(), 9810 diag::note_attribute_overloadable_prev_overload) 9811 << false; 9812 9813 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9814 } 9815 } 9816 9817 // Semantic checking for this function declaration (in isolation). 9818 9819 if (getLangOpts().CPlusPlus) { 9820 // C++-specific checks. 9821 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9822 CheckConstructor(Constructor); 9823 } else if (CXXDestructorDecl *Destructor = 9824 dyn_cast<CXXDestructorDecl>(NewFD)) { 9825 CXXRecordDecl *Record = Destructor->getParent(); 9826 QualType ClassType = Context.getTypeDeclType(Record); 9827 9828 // FIXME: Shouldn't we be able to perform this check even when the class 9829 // type is dependent? Both gcc and edg can handle that. 9830 if (!ClassType->isDependentType()) { 9831 DeclarationName Name 9832 = Context.DeclarationNames.getCXXDestructorName( 9833 Context.getCanonicalType(ClassType)); 9834 if (NewFD->getDeclName() != Name) { 9835 Diag(NewFD->getLocation(), diag::err_destructor_name); 9836 NewFD->setInvalidDecl(); 9837 return Redeclaration; 9838 } 9839 } 9840 } else if (CXXConversionDecl *Conversion 9841 = dyn_cast<CXXConversionDecl>(NewFD)) { 9842 ActOnConversionDeclarator(Conversion); 9843 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9844 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9845 CheckDeductionGuideTemplate(TD); 9846 9847 // A deduction guide is not on the list of entities that can be 9848 // explicitly specialized. 9849 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9850 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9851 << /*explicit specialization*/ 1; 9852 } 9853 9854 // Find any virtual functions that this function overrides. 9855 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9856 if (!Method->isFunctionTemplateSpecialization() && 9857 !Method->getDescribedFunctionTemplate() && 9858 Method->isCanonicalDecl()) { 9859 if (AddOverriddenMethods(Method->getParent(), Method)) { 9860 // If the function was marked as "static", we have a problem. 9861 if (NewFD->getStorageClass() == SC_Static) { 9862 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9863 } 9864 } 9865 } 9866 9867 if (Method->isStatic()) 9868 checkThisInStaticMemberFunctionType(Method); 9869 } 9870 9871 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9872 if (NewFD->isOverloadedOperator() && 9873 CheckOverloadedOperatorDeclaration(NewFD)) { 9874 NewFD->setInvalidDecl(); 9875 return Redeclaration; 9876 } 9877 9878 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9879 if (NewFD->getLiteralIdentifier() && 9880 CheckLiteralOperatorDeclaration(NewFD)) { 9881 NewFD->setInvalidDecl(); 9882 return Redeclaration; 9883 } 9884 9885 // In C++, check default arguments now that we have merged decls. Unless 9886 // the lexical context is the class, because in this case this is done 9887 // during delayed parsing anyway. 9888 if (!CurContext->isRecord()) 9889 CheckCXXDefaultArguments(NewFD); 9890 9891 // If this function declares a builtin function, check the type of this 9892 // declaration against the expected type for the builtin. 9893 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9894 ASTContext::GetBuiltinTypeError Error; 9895 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9896 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9897 // If the type of the builtin differs only in its exception 9898 // specification, that's OK. 9899 // FIXME: If the types do differ in this way, it would be better to 9900 // retain the 'noexcept' form of the type. 9901 if (!T.isNull() && 9902 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9903 NewFD->getType())) 9904 // The type of this function differs from the type of the builtin, 9905 // so forget about the builtin entirely. 9906 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9907 } 9908 9909 // If this function is declared as being extern "C", then check to see if 9910 // the function returns a UDT (class, struct, or union type) that is not C 9911 // compatible, and if it does, warn the user. 9912 // But, issue any diagnostic on the first declaration only. 9913 if (Previous.empty() && NewFD->isExternC()) { 9914 QualType R = NewFD->getReturnType(); 9915 if (R->isIncompleteType() && !R->isVoidType()) 9916 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9917 << NewFD << R; 9918 else if (!R.isPODType(Context) && !R->isVoidType() && 9919 !R->isObjCObjectPointerType()) 9920 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9921 } 9922 9923 // C++1z [dcl.fct]p6: 9924 // [...] whether the function has a non-throwing exception-specification 9925 // [is] part of the function type 9926 // 9927 // This results in an ABI break between C++14 and C++17 for functions whose 9928 // declared type includes an exception-specification in a parameter or 9929 // return type. (Exception specifications on the function itself are OK in 9930 // most cases, and exception specifications are not permitted in most other 9931 // contexts where they could make it into a mangling.) 9932 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 9933 auto HasNoexcept = [&](QualType T) -> bool { 9934 // Strip off declarator chunks that could be between us and a function 9935 // type. We don't need to look far, exception specifications are very 9936 // restricted prior to C++17. 9937 if (auto *RT = T->getAs<ReferenceType>()) 9938 T = RT->getPointeeType(); 9939 else if (T->isAnyPointerType()) 9940 T = T->getPointeeType(); 9941 else if (auto *MPT = T->getAs<MemberPointerType>()) 9942 T = MPT->getPointeeType(); 9943 if (auto *FPT = T->getAs<FunctionProtoType>()) 9944 if (FPT->isNothrow()) 9945 return true; 9946 return false; 9947 }; 9948 9949 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9950 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9951 for (QualType T : FPT->param_types()) 9952 AnyNoexcept |= HasNoexcept(T); 9953 if (AnyNoexcept) 9954 Diag(NewFD->getLocation(), 9955 diag::warn_cxx17_compat_exception_spec_in_signature) 9956 << NewFD; 9957 } 9958 9959 if (!Redeclaration && LangOpts.CUDA) 9960 checkCUDATargetOverload(NewFD, Previous); 9961 } 9962 return Redeclaration; 9963 } 9964 9965 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9966 // C++11 [basic.start.main]p3: 9967 // A program that [...] declares main to be inline, static or 9968 // constexpr is ill-formed. 9969 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9970 // appear in a declaration of main. 9971 // static main is not an error under C99, but we should warn about it. 9972 // We accept _Noreturn main as an extension. 9973 if (FD->getStorageClass() == SC_Static) 9974 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9975 ? diag::err_static_main : diag::warn_static_main) 9976 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9977 if (FD->isInlineSpecified()) 9978 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9979 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9980 if (DS.isNoreturnSpecified()) { 9981 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9982 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9983 Diag(NoreturnLoc, diag::ext_noreturn_main); 9984 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9985 << FixItHint::CreateRemoval(NoreturnRange); 9986 } 9987 if (FD->isConstexpr()) { 9988 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9989 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9990 FD->setConstexpr(false); 9991 } 9992 9993 if (getLangOpts().OpenCL) { 9994 Diag(FD->getLocation(), diag::err_opencl_no_main) 9995 << FD->hasAttr<OpenCLKernelAttr>(); 9996 FD->setInvalidDecl(); 9997 return; 9998 } 9999 10000 QualType T = FD->getType(); 10001 assert(T->isFunctionType() && "function decl is not of function type"); 10002 const FunctionType* FT = T->castAs<FunctionType>(); 10003 10004 // Set default calling convention for main() 10005 if (FT->getCallConv() != CC_C) { 10006 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10007 FD->setType(QualType(FT, 0)); 10008 T = Context.getCanonicalType(FD->getType()); 10009 } 10010 10011 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10012 // In C with GNU extensions we allow main() to have non-integer return 10013 // type, but we should warn about the extension, and we disable the 10014 // implicit-return-zero rule. 10015 10016 // GCC in C mode accepts qualified 'int'. 10017 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10018 FD->setHasImplicitReturnZero(true); 10019 else { 10020 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10021 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10022 if (RTRange.isValid()) 10023 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10024 << FixItHint::CreateReplacement(RTRange, "int"); 10025 } 10026 } else { 10027 // In C and C++, main magically returns 0 if you fall off the end; 10028 // set the flag which tells us that. 10029 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10030 10031 // All the standards say that main() should return 'int'. 10032 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10033 FD->setHasImplicitReturnZero(true); 10034 else { 10035 // Otherwise, this is just a flat-out error. 10036 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10037 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10038 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10039 : FixItHint()); 10040 FD->setInvalidDecl(true); 10041 } 10042 } 10043 10044 // Treat protoless main() as nullary. 10045 if (isa<FunctionNoProtoType>(FT)) return; 10046 10047 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10048 unsigned nparams = FTP->getNumParams(); 10049 assert(FD->getNumParams() == nparams); 10050 10051 bool HasExtraParameters = (nparams > 3); 10052 10053 if (FTP->isVariadic()) { 10054 Diag(FD->getLocation(), diag::ext_variadic_main); 10055 // FIXME: if we had information about the location of the ellipsis, we 10056 // could add a FixIt hint to remove it as a parameter. 10057 } 10058 10059 // Darwin passes an undocumented fourth argument of type char**. If 10060 // other platforms start sprouting these, the logic below will start 10061 // getting shifty. 10062 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10063 HasExtraParameters = false; 10064 10065 if (HasExtraParameters) { 10066 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10067 FD->setInvalidDecl(true); 10068 nparams = 3; 10069 } 10070 10071 // FIXME: a lot of the following diagnostics would be improved 10072 // if we had some location information about types. 10073 10074 QualType CharPP = 10075 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10076 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10077 10078 for (unsigned i = 0; i < nparams; ++i) { 10079 QualType AT = FTP->getParamType(i); 10080 10081 bool mismatch = true; 10082 10083 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10084 mismatch = false; 10085 else if (Expected[i] == CharPP) { 10086 // As an extension, the following forms are okay: 10087 // char const ** 10088 // char const * const * 10089 // char * const * 10090 10091 QualifierCollector qs; 10092 const PointerType* PT; 10093 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10094 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10095 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10096 Context.CharTy)) { 10097 qs.removeConst(); 10098 mismatch = !qs.empty(); 10099 } 10100 } 10101 10102 if (mismatch) { 10103 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10104 // TODO: suggest replacing given type with expected type 10105 FD->setInvalidDecl(true); 10106 } 10107 } 10108 10109 if (nparams == 1 && !FD->isInvalidDecl()) { 10110 Diag(FD->getLocation(), diag::warn_main_one_arg); 10111 } 10112 10113 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10114 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10115 FD->setInvalidDecl(); 10116 } 10117 } 10118 10119 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10120 QualType T = FD->getType(); 10121 assert(T->isFunctionType() && "function decl is not of function type"); 10122 const FunctionType *FT = T->castAs<FunctionType>(); 10123 10124 // Set an implicit return of 'zero' if the function can return some integral, 10125 // enumeration, pointer or nullptr type. 10126 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10127 FT->getReturnType()->isAnyPointerType() || 10128 FT->getReturnType()->isNullPtrType()) 10129 // DllMain is exempt because a return value of zero means it failed. 10130 if (FD->getName() != "DllMain") 10131 FD->setHasImplicitReturnZero(true); 10132 10133 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10134 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10135 FD->setInvalidDecl(); 10136 } 10137 } 10138 10139 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10140 // FIXME: Need strict checking. In C89, we need to check for 10141 // any assignment, increment, decrement, function-calls, or 10142 // commas outside of a sizeof. In C99, it's the same list, 10143 // except that the aforementioned are allowed in unevaluated 10144 // expressions. Everything else falls under the 10145 // "may accept other forms of constant expressions" exception. 10146 // (We never end up here for C++, so the constant expression 10147 // rules there don't matter.) 10148 const Expr *Culprit; 10149 if (Init->isConstantInitializer(Context, false, &Culprit)) 10150 return false; 10151 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10152 << Culprit->getSourceRange(); 10153 return true; 10154 } 10155 10156 namespace { 10157 // Visits an initialization expression to see if OrigDecl is evaluated in 10158 // its own initialization and throws a warning if it does. 10159 class SelfReferenceChecker 10160 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10161 Sema &S; 10162 Decl *OrigDecl; 10163 bool isRecordType; 10164 bool isPODType; 10165 bool isReferenceType; 10166 10167 bool isInitList; 10168 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10169 10170 public: 10171 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10172 10173 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10174 S(S), OrigDecl(OrigDecl) { 10175 isPODType = false; 10176 isRecordType = false; 10177 isReferenceType = false; 10178 isInitList = false; 10179 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10180 isPODType = VD->getType().isPODType(S.Context); 10181 isRecordType = VD->getType()->isRecordType(); 10182 isReferenceType = VD->getType()->isReferenceType(); 10183 } 10184 } 10185 10186 // For most expressions, just call the visitor. For initializer lists, 10187 // track the index of the field being initialized since fields are 10188 // initialized in order allowing use of previously initialized fields. 10189 void CheckExpr(Expr *E) { 10190 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10191 if (!InitList) { 10192 Visit(E); 10193 return; 10194 } 10195 10196 // Track and increment the index here. 10197 isInitList = true; 10198 InitFieldIndex.push_back(0); 10199 for (auto Child : InitList->children()) { 10200 CheckExpr(cast<Expr>(Child)); 10201 ++InitFieldIndex.back(); 10202 } 10203 InitFieldIndex.pop_back(); 10204 } 10205 10206 // Returns true if MemberExpr is checked and no further checking is needed. 10207 // Returns false if additional checking is required. 10208 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10209 llvm::SmallVector<FieldDecl*, 4> Fields; 10210 Expr *Base = E; 10211 bool ReferenceField = false; 10212 10213 // Get the field memebers used. 10214 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10215 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10216 if (!FD) 10217 return false; 10218 Fields.push_back(FD); 10219 if (FD->getType()->isReferenceType()) 10220 ReferenceField = true; 10221 Base = ME->getBase()->IgnoreParenImpCasts(); 10222 } 10223 10224 // Keep checking only if the base Decl is the same. 10225 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10226 if (!DRE || DRE->getDecl() != OrigDecl) 10227 return false; 10228 10229 // A reference field can be bound to an unininitialized field. 10230 if (CheckReference && !ReferenceField) 10231 return true; 10232 10233 // Convert FieldDecls to their index number. 10234 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10235 for (const FieldDecl *I : llvm::reverse(Fields)) 10236 UsedFieldIndex.push_back(I->getFieldIndex()); 10237 10238 // See if a warning is needed by checking the first difference in index 10239 // numbers. If field being used has index less than the field being 10240 // initialized, then the use is safe. 10241 for (auto UsedIter = UsedFieldIndex.begin(), 10242 UsedEnd = UsedFieldIndex.end(), 10243 OrigIter = InitFieldIndex.begin(), 10244 OrigEnd = InitFieldIndex.end(); 10245 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10246 if (*UsedIter < *OrigIter) 10247 return true; 10248 if (*UsedIter > *OrigIter) 10249 break; 10250 } 10251 10252 // TODO: Add a different warning which will print the field names. 10253 HandleDeclRefExpr(DRE); 10254 return true; 10255 } 10256 10257 // For most expressions, the cast is directly above the DeclRefExpr. 10258 // For conditional operators, the cast can be outside the conditional 10259 // operator if both expressions are DeclRefExpr's. 10260 void HandleValue(Expr *E) { 10261 E = E->IgnoreParens(); 10262 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10263 HandleDeclRefExpr(DRE); 10264 return; 10265 } 10266 10267 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10268 Visit(CO->getCond()); 10269 HandleValue(CO->getTrueExpr()); 10270 HandleValue(CO->getFalseExpr()); 10271 return; 10272 } 10273 10274 if (BinaryConditionalOperator *BCO = 10275 dyn_cast<BinaryConditionalOperator>(E)) { 10276 Visit(BCO->getCond()); 10277 HandleValue(BCO->getFalseExpr()); 10278 return; 10279 } 10280 10281 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10282 HandleValue(OVE->getSourceExpr()); 10283 return; 10284 } 10285 10286 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10287 if (BO->getOpcode() == BO_Comma) { 10288 Visit(BO->getLHS()); 10289 HandleValue(BO->getRHS()); 10290 return; 10291 } 10292 } 10293 10294 if (isa<MemberExpr>(E)) { 10295 if (isInitList) { 10296 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10297 false /*CheckReference*/)) 10298 return; 10299 } 10300 10301 Expr *Base = E->IgnoreParenImpCasts(); 10302 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10303 // Check for static member variables and don't warn on them. 10304 if (!isa<FieldDecl>(ME->getMemberDecl())) 10305 return; 10306 Base = ME->getBase()->IgnoreParenImpCasts(); 10307 } 10308 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10309 HandleDeclRefExpr(DRE); 10310 return; 10311 } 10312 10313 Visit(E); 10314 } 10315 10316 // Reference types not handled in HandleValue are handled here since all 10317 // uses of references are bad, not just r-value uses. 10318 void VisitDeclRefExpr(DeclRefExpr *E) { 10319 if (isReferenceType) 10320 HandleDeclRefExpr(E); 10321 } 10322 10323 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10324 if (E->getCastKind() == CK_LValueToRValue) { 10325 HandleValue(E->getSubExpr()); 10326 return; 10327 } 10328 10329 Inherited::VisitImplicitCastExpr(E); 10330 } 10331 10332 void VisitMemberExpr(MemberExpr *E) { 10333 if (isInitList) { 10334 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10335 return; 10336 } 10337 10338 // Don't warn on arrays since they can be treated as pointers. 10339 if (E->getType()->canDecayToPointerType()) return; 10340 10341 // Warn when a non-static method call is followed by non-static member 10342 // field accesses, which is followed by a DeclRefExpr. 10343 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10344 bool Warn = (MD && !MD->isStatic()); 10345 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10346 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10347 if (!isa<FieldDecl>(ME->getMemberDecl())) 10348 Warn = false; 10349 Base = ME->getBase()->IgnoreParenImpCasts(); 10350 } 10351 10352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10353 if (Warn) 10354 HandleDeclRefExpr(DRE); 10355 return; 10356 } 10357 10358 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10359 // Visit that expression. 10360 Visit(Base); 10361 } 10362 10363 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10364 Expr *Callee = E->getCallee(); 10365 10366 if (isa<UnresolvedLookupExpr>(Callee)) 10367 return Inherited::VisitCXXOperatorCallExpr(E); 10368 10369 Visit(Callee); 10370 for (auto Arg: E->arguments()) 10371 HandleValue(Arg->IgnoreParenImpCasts()); 10372 } 10373 10374 void VisitUnaryOperator(UnaryOperator *E) { 10375 // For POD record types, addresses of its own members are well-defined. 10376 if (E->getOpcode() == UO_AddrOf && isRecordType && 10377 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10378 if (!isPODType) 10379 HandleValue(E->getSubExpr()); 10380 return; 10381 } 10382 10383 if (E->isIncrementDecrementOp()) { 10384 HandleValue(E->getSubExpr()); 10385 return; 10386 } 10387 10388 Inherited::VisitUnaryOperator(E); 10389 } 10390 10391 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10392 10393 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10394 if (E->getConstructor()->isCopyConstructor()) { 10395 Expr *ArgExpr = E->getArg(0); 10396 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10397 if (ILE->getNumInits() == 1) 10398 ArgExpr = ILE->getInit(0); 10399 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10400 if (ICE->getCastKind() == CK_NoOp) 10401 ArgExpr = ICE->getSubExpr(); 10402 HandleValue(ArgExpr); 10403 return; 10404 } 10405 Inherited::VisitCXXConstructExpr(E); 10406 } 10407 10408 void VisitCallExpr(CallExpr *E) { 10409 // Treat std::move as a use. 10410 if (E->isCallToStdMove()) { 10411 HandleValue(E->getArg(0)); 10412 return; 10413 } 10414 10415 Inherited::VisitCallExpr(E); 10416 } 10417 10418 void VisitBinaryOperator(BinaryOperator *E) { 10419 if (E->isCompoundAssignmentOp()) { 10420 HandleValue(E->getLHS()); 10421 Visit(E->getRHS()); 10422 return; 10423 } 10424 10425 Inherited::VisitBinaryOperator(E); 10426 } 10427 10428 // A custom visitor for BinaryConditionalOperator is needed because the 10429 // regular visitor would check the condition and true expression separately 10430 // but both point to the same place giving duplicate diagnostics. 10431 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10432 Visit(E->getCond()); 10433 Visit(E->getFalseExpr()); 10434 } 10435 10436 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10437 Decl* ReferenceDecl = DRE->getDecl(); 10438 if (OrigDecl != ReferenceDecl) return; 10439 unsigned diag; 10440 if (isReferenceType) { 10441 diag = diag::warn_uninit_self_reference_in_reference_init; 10442 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10443 diag = diag::warn_static_self_reference_in_init; 10444 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10445 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10446 DRE->getDecl()->getType()->isRecordType()) { 10447 diag = diag::warn_uninit_self_reference_in_init; 10448 } else { 10449 // Local variables will be handled by the CFG analysis. 10450 return; 10451 } 10452 10453 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10454 S.PDiag(diag) 10455 << DRE->getDecl() 10456 << OrigDecl->getLocation() 10457 << DRE->getSourceRange()); 10458 } 10459 }; 10460 10461 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10462 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10463 bool DirectInit) { 10464 // Parameters arguments are occassionially constructed with itself, 10465 // for instance, in recursive functions. Skip them. 10466 if (isa<ParmVarDecl>(OrigDecl)) 10467 return; 10468 10469 E = E->IgnoreParens(); 10470 10471 // Skip checking T a = a where T is not a record or reference type. 10472 // Doing so is a way to silence uninitialized warnings. 10473 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10474 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10475 if (ICE->getCastKind() == CK_LValueToRValue) 10476 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10477 if (DRE->getDecl() == OrigDecl) 10478 return; 10479 10480 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10481 } 10482 } // end anonymous namespace 10483 10484 namespace { 10485 // Simple wrapper to add the name of a variable or (if no variable is 10486 // available) a DeclarationName into a diagnostic. 10487 struct VarDeclOrName { 10488 VarDecl *VDecl; 10489 DeclarationName Name; 10490 10491 friend const Sema::SemaDiagnosticBuilder & 10492 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10493 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10494 } 10495 }; 10496 } // end anonymous namespace 10497 10498 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10499 DeclarationName Name, QualType Type, 10500 TypeSourceInfo *TSI, 10501 SourceRange Range, bool DirectInit, 10502 Expr *Init) { 10503 bool IsInitCapture = !VDecl; 10504 assert((!VDecl || !VDecl->isInitCapture()) && 10505 "init captures are expected to be deduced prior to initialization"); 10506 10507 VarDeclOrName VN{VDecl, Name}; 10508 10509 DeducedType *Deduced = Type->getContainedDeducedType(); 10510 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10511 10512 // C++11 [dcl.spec.auto]p3 10513 if (!Init) { 10514 assert(VDecl && "no init for init capture deduction?"); 10515 10516 // Except for class argument deduction, and then for an initializing 10517 // declaration only, i.e. no static at class scope or extern. 10518 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10519 VDecl->hasExternalStorage() || 10520 VDecl->isStaticDataMember()) { 10521 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10522 << VDecl->getDeclName() << Type; 10523 return QualType(); 10524 } 10525 } 10526 10527 ArrayRef<Expr*> DeduceInits; 10528 if (Init) 10529 DeduceInits = Init; 10530 10531 if (DirectInit) { 10532 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10533 DeduceInits = PL->exprs(); 10534 } 10535 10536 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10537 assert(VDecl && "non-auto type for init capture deduction?"); 10538 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10539 InitializationKind Kind = InitializationKind::CreateForInit( 10540 VDecl->getLocation(), DirectInit, Init); 10541 // FIXME: Initialization should not be taking a mutable list of inits. 10542 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10543 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10544 InitsCopy); 10545 } 10546 10547 if (DirectInit) { 10548 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10549 DeduceInits = IL->inits(); 10550 } 10551 10552 // Deduction only works if we have exactly one source expression. 10553 if (DeduceInits.empty()) { 10554 // It isn't possible to write this directly, but it is possible to 10555 // end up in this situation with "auto x(some_pack...);" 10556 Diag(Init->getLocStart(), IsInitCapture 10557 ? diag::err_init_capture_no_expression 10558 : diag::err_auto_var_init_no_expression) 10559 << VN << Type << Range; 10560 return QualType(); 10561 } 10562 10563 if (DeduceInits.size() > 1) { 10564 Diag(DeduceInits[1]->getLocStart(), 10565 IsInitCapture ? diag::err_init_capture_multiple_expressions 10566 : diag::err_auto_var_init_multiple_expressions) 10567 << VN << Type << Range; 10568 return QualType(); 10569 } 10570 10571 Expr *DeduceInit = DeduceInits[0]; 10572 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10573 Diag(Init->getLocStart(), IsInitCapture 10574 ? diag::err_init_capture_paren_braces 10575 : diag::err_auto_var_init_paren_braces) 10576 << isa<InitListExpr>(Init) << VN << Type << Range; 10577 return QualType(); 10578 } 10579 10580 // Expressions default to 'id' when we're in a debugger. 10581 bool DefaultedAnyToId = false; 10582 if (getLangOpts().DebuggerCastResultToId && 10583 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10584 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10585 if (Result.isInvalid()) { 10586 return QualType(); 10587 } 10588 Init = Result.get(); 10589 DefaultedAnyToId = true; 10590 } 10591 10592 // C++ [dcl.decomp]p1: 10593 // If the assignment-expression [...] has array type A and no ref-qualifier 10594 // is present, e has type cv A 10595 if (VDecl && isa<DecompositionDecl>(VDecl) && 10596 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10597 DeduceInit->getType()->isConstantArrayType()) 10598 return Context.getQualifiedType(DeduceInit->getType(), 10599 Type.getQualifiers()); 10600 10601 QualType DeducedType; 10602 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10603 if (!IsInitCapture) 10604 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10605 else if (isa<InitListExpr>(Init)) 10606 Diag(Range.getBegin(), 10607 diag::err_init_capture_deduction_failure_from_init_list) 10608 << VN 10609 << (DeduceInit->getType().isNull() ? TSI->getType() 10610 : DeduceInit->getType()) 10611 << DeduceInit->getSourceRange(); 10612 else 10613 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10614 << VN << TSI->getType() 10615 << (DeduceInit->getType().isNull() ? TSI->getType() 10616 : DeduceInit->getType()) 10617 << DeduceInit->getSourceRange(); 10618 } 10619 10620 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10621 // 'id' instead of a specific object type prevents most of our usual 10622 // checks. 10623 // We only want to warn outside of template instantiations, though: 10624 // inside a template, the 'id' could have come from a parameter. 10625 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10626 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10627 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10628 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10629 } 10630 10631 return DeducedType; 10632 } 10633 10634 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10635 Expr *Init) { 10636 QualType DeducedType = deduceVarTypeFromInitializer( 10637 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10638 VDecl->getSourceRange(), DirectInit, Init); 10639 if (DeducedType.isNull()) { 10640 VDecl->setInvalidDecl(); 10641 return true; 10642 } 10643 10644 VDecl->setType(DeducedType); 10645 assert(VDecl->isLinkageValid()); 10646 10647 // In ARC, infer lifetime. 10648 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10649 VDecl->setInvalidDecl(); 10650 10651 // If this is a redeclaration, check that the type we just deduced matches 10652 // the previously declared type. 10653 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10654 // We never need to merge the type, because we cannot form an incomplete 10655 // array of auto, nor deduce such a type. 10656 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10657 } 10658 10659 // Check the deduced type is valid for a variable declaration. 10660 CheckVariableDeclarationType(VDecl); 10661 return VDecl->isInvalidDecl(); 10662 } 10663 10664 /// AddInitializerToDecl - Adds the initializer Init to the 10665 /// declaration dcl. If DirectInit is true, this is C++ direct 10666 /// initialization rather than copy initialization. 10667 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10668 // If there is no declaration, there was an error parsing it. Just ignore 10669 // the initializer. 10670 if (!RealDecl || RealDecl->isInvalidDecl()) { 10671 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10672 return; 10673 } 10674 10675 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10676 // Pure-specifiers are handled in ActOnPureSpecifier. 10677 Diag(Method->getLocation(), diag::err_member_function_initialization) 10678 << Method->getDeclName() << Init->getSourceRange(); 10679 Method->setInvalidDecl(); 10680 return; 10681 } 10682 10683 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10684 if (!VDecl) { 10685 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10686 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10687 RealDecl->setInvalidDecl(); 10688 return; 10689 } 10690 10691 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10692 if (VDecl->getType()->isUndeducedType()) { 10693 // Attempt typo correction early so that the type of the init expression can 10694 // be deduced based on the chosen correction if the original init contains a 10695 // TypoExpr. 10696 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10697 if (!Res.isUsable()) { 10698 RealDecl->setInvalidDecl(); 10699 return; 10700 } 10701 Init = Res.get(); 10702 10703 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10704 return; 10705 } 10706 10707 // dllimport cannot be used on variable definitions. 10708 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10709 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10710 VDecl->setInvalidDecl(); 10711 return; 10712 } 10713 10714 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10715 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10716 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10717 VDecl->setInvalidDecl(); 10718 return; 10719 } 10720 10721 if (!VDecl->getType()->isDependentType()) { 10722 // A definition must end up with a complete type, which means it must be 10723 // complete with the restriction that an array type might be completed by 10724 // the initializer; note that later code assumes this restriction. 10725 QualType BaseDeclType = VDecl->getType(); 10726 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10727 BaseDeclType = Array->getElementType(); 10728 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10729 diag::err_typecheck_decl_incomplete_type)) { 10730 RealDecl->setInvalidDecl(); 10731 return; 10732 } 10733 10734 // The variable can not have an abstract class type. 10735 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10736 diag::err_abstract_type_in_decl, 10737 AbstractVariableType)) 10738 VDecl->setInvalidDecl(); 10739 } 10740 10741 // If adding the initializer will turn this declaration into a definition, 10742 // and we already have a definition for this variable, diagnose or otherwise 10743 // handle the situation. 10744 VarDecl *Def; 10745 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10746 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10747 !VDecl->isThisDeclarationADemotedDefinition() && 10748 checkVarDeclRedefinition(Def, VDecl)) 10749 return; 10750 10751 if (getLangOpts().CPlusPlus) { 10752 // C++ [class.static.data]p4 10753 // If a static data member is of const integral or const 10754 // enumeration type, its declaration in the class definition can 10755 // specify a constant-initializer which shall be an integral 10756 // constant expression (5.19). In that case, the member can appear 10757 // in integral constant expressions. The member shall still be 10758 // defined in a namespace scope if it is used in the program and the 10759 // namespace scope definition shall not contain an initializer. 10760 // 10761 // We already performed a redefinition check above, but for static 10762 // data members we also need to check whether there was an in-class 10763 // declaration with an initializer. 10764 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10765 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10766 << VDecl->getDeclName(); 10767 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10768 diag::note_previous_initializer) 10769 << 0; 10770 return; 10771 } 10772 10773 if (VDecl->hasLocalStorage()) 10774 setFunctionHasBranchProtectedScope(); 10775 10776 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10777 VDecl->setInvalidDecl(); 10778 return; 10779 } 10780 } 10781 10782 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10783 // a kernel function cannot be initialized." 10784 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10785 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10786 VDecl->setInvalidDecl(); 10787 return; 10788 } 10789 10790 // Get the decls type and save a reference for later, since 10791 // CheckInitializerTypes may change it. 10792 QualType DclT = VDecl->getType(), SavT = DclT; 10793 10794 // Expressions default to 'id' when we're in a debugger 10795 // and we are assigning it to a variable of Objective-C pointer type. 10796 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10797 Init->getType() == Context.UnknownAnyTy) { 10798 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10799 if (Result.isInvalid()) { 10800 VDecl->setInvalidDecl(); 10801 return; 10802 } 10803 Init = Result.get(); 10804 } 10805 10806 // Perform the initialization. 10807 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10808 if (!VDecl->isInvalidDecl()) { 10809 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10810 InitializationKind Kind = InitializationKind::CreateForInit( 10811 VDecl->getLocation(), DirectInit, Init); 10812 10813 MultiExprArg Args = Init; 10814 if (CXXDirectInit) 10815 Args = MultiExprArg(CXXDirectInit->getExprs(), 10816 CXXDirectInit->getNumExprs()); 10817 10818 // Try to correct any TypoExprs in the initialization arguments. 10819 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10820 ExprResult Res = CorrectDelayedTyposInExpr( 10821 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10822 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10823 return Init.Failed() ? ExprError() : E; 10824 }); 10825 if (Res.isInvalid()) { 10826 VDecl->setInvalidDecl(); 10827 } else if (Res.get() != Args[Idx]) { 10828 Args[Idx] = Res.get(); 10829 } 10830 } 10831 if (VDecl->isInvalidDecl()) 10832 return; 10833 10834 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10835 /*TopLevelOfInitList=*/false, 10836 /*TreatUnavailableAsInvalid=*/false); 10837 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10838 if (Result.isInvalid()) { 10839 VDecl->setInvalidDecl(); 10840 return; 10841 } 10842 10843 Init = Result.getAs<Expr>(); 10844 } 10845 10846 // Check for self-references within variable initializers. 10847 // Variables declared within a function/method body (except for references) 10848 // are handled by a dataflow analysis. 10849 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10850 VDecl->getType()->isReferenceType()) { 10851 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10852 } 10853 10854 // If the type changed, it means we had an incomplete type that was 10855 // completed by the initializer. For example: 10856 // int ary[] = { 1, 3, 5 }; 10857 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10858 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10859 VDecl->setType(DclT); 10860 10861 if (!VDecl->isInvalidDecl()) { 10862 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10863 10864 if (VDecl->hasAttr<BlocksAttr>()) 10865 checkRetainCycles(VDecl, Init); 10866 10867 // It is safe to assign a weak reference into a strong variable. 10868 // Although this code can still have problems: 10869 // id x = self.weakProp; 10870 // id y = self.weakProp; 10871 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10872 // paths through the function. This should be revisited if 10873 // -Wrepeated-use-of-weak is made flow-sensitive. 10874 if (FunctionScopeInfo *FSI = getCurFunction()) 10875 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10876 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10877 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10878 Init->getLocStart())) 10879 FSI->markSafeWeakUse(Init); 10880 } 10881 10882 // The initialization is usually a full-expression. 10883 // 10884 // FIXME: If this is a braced initialization of an aggregate, it is not 10885 // an expression, and each individual field initializer is a separate 10886 // full-expression. For instance, in: 10887 // 10888 // struct Temp { ~Temp(); }; 10889 // struct S { S(Temp); }; 10890 // struct T { S a, b; } t = { Temp(), Temp() } 10891 // 10892 // we should destroy the first Temp before constructing the second. 10893 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10894 false, 10895 VDecl->isConstexpr()); 10896 if (Result.isInvalid()) { 10897 VDecl->setInvalidDecl(); 10898 return; 10899 } 10900 Init = Result.get(); 10901 10902 // Attach the initializer to the decl. 10903 VDecl->setInit(Init); 10904 10905 if (VDecl->isLocalVarDecl()) { 10906 // Don't check the initializer if the declaration is malformed. 10907 if (VDecl->isInvalidDecl()) { 10908 // do nothing 10909 10910 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10911 // This is true even in OpenCL C++. 10912 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10913 CheckForConstantInitializer(Init, DclT); 10914 10915 // Otherwise, C++ does not restrict the initializer. 10916 } else if (getLangOpts().CPlusPlus) { 10917 // do nothing 10918 10919 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10920 // static storage duration shall be constant expressions or string literals. 10921 } else if (VDecl->getStorageClass() == SC_Static) { 10922 CheckForConstantInitializer(Init, DclT); 10923 10924 // C89 is stricter than C99 for aggregate initializers. 10925 // C89 6.5.7p3: All the expressions [...] in an initializer list 10926 // for an object that has aggregate or union type shall be 10927 // constant expressions. 10928 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10929 isa<InitListExpr>(Init)) { 10930 const Expr *Culprit; 10931 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10932 Diag(Culprit->getExprLoc(), 10933 diag::ext_aggregate_init_not_constant) 10934 << Culprit->getSourceRange(); 10935 } 10936 } 10937 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10938 VDecl->getLexicalDeclContext()->isRecord()) { 10939 // This is an in-class initialization for a static data member, e.g., 10940 // 10941 // struct S { 10942 // static const int value = 17; 10943 // }; 10944 10945 // C++ [class.mem]p4: 10946 // A member-declarator can contain a constant-initializer only 10947 // if it declares a static member (9.4) of const integral or 10948 // const enumeration type, see 9.4.2. 10949 // 10950 // C++11 [class.static.data]p3: 10951 // If a non-volatile non-inline const static data member is of integral 10952 // or enumeration type, its declaration in the class definition can 10953 // specify a brace-or-equal-initializer in which every initializer-clause 10954 // that is an assignment-expression is a constant expression. A static 10955 // data member of literal type can be declared in the class definition 10956 // with the constexpr specifier; if so, its declaration shall specify a 10957 // brace-or-equal-initializer in which every initializer-clause that is 10958 // an assignment-expression is a constant expression. 10959 10960 // Do nothing on dependent types. 10961 if (DclT->isDependentType()) { 10962 10963 // Allow any 'static constexpr' members, whether or not they are of literal 10964 // type. We separately check that every constexpr variable is of literal 10965 // type. 10966 } else if (VDecl->isConstexpr()) { 10967 10968 // Require constness. 10969 } else if (!DclT.isConstQualified()) { 10970 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10971 << Init->getSourceRange(); 10972 VDecl->setInvalidDecl(); 10973 10974 // We allow integer constant expressions in all cases. 10975 } else if (DclT->isIntegralOrEnumerationType()) { 10976 // Check whether the expression is a constant expression. 10977 SourceLocation Loc; 10978 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10979 // In C++11, a non-constexpr const static data member with an 10980 // in-class initializer cannot be volatile. 10981 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10982 else if (Init->isValueDependent()) 10983 ; // Nothing to check. 10984 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10985 ; // Ok, it's an ICE! 10986 else if (Init->isEvaluatable(Context)) { 10987 // If we can constant fold the initializer through heroics, accept it, 10988 // but report this as a use of an extension for -pedantic. 10989 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10990 << Init->getSourceRange(); 10991 } else { 10992 // Otherwise, this is some crazy unknown case. Report the issue at the 10993 // location provided by the isIntegerConstantExpr failed check. 10994 Diag(Loc, diag::err_in_class_initializer_non_constant) 10995 << Init->getSourceRange(); 10996 VDecl->setInvalidDecl(); 10997 } 10998 10999 // We allow foldable floating-point constants as an extension. 11000 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 11001 // In C++98, this is a GNU extension. In C++11, it is not, but we support 11002 // it anyway and provide a fixit to add the 'constexpr'. 11003 if (getLangOpts().CPlusPlus11) { 11004 Diag(VDecl->getLocation(), 11005 diag::ext_in_class_initializer_float_type_cxx11) 11006 << DclT << Init->getSourceRange(); 11007 Diag(VDecl->getLocStart(), 11008 diag::note_in_class_initializer_float_type_cxx11) 11009 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 11010 } else { 11011 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 11012 << DclT << Init->getSourceRange(); 11013 11014 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 11015 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 11016 << Init->getSourceRange(); 11017 VDecl->setInvalidDecl(); 11018 } 11019 } 11020 11021 // Suggest adding 'constexpr' in C++11 for literal types. 11022 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 11023 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 11024 << DclT << Init->getSourceRange() 11025 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 11026 VDecl->setConstexpr(true); 11027 11028 } else { 11029 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 11030 << DclT << Init->getSourceRange(); 11031 VDecl->setInvalidDecl(); 11032 } 11033 } else if (VDecl->isFileVarDecl()) { 11034 // In C, extern is typically used to avoid tentative definitions when 11035 // declaring variables in headers, but adding an intializer makes it a 11036 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 11037 // In C++, extern is often used to give implictly static const variables 11038 // external linkage, so don't warn in that case. If selectany is present, 11039 // this might be header code intended for C and C++ inclusion, so apply the 11040 // C++ rules. 11041 if (VDecl->getStorageClass() == SC_Extern && 11042 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 11043 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 11044 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 11045 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 11046 Diag(VDecl->getLocation(), diag::warn_extern_init); 11047 11048 // C99 6.7.8p4. All file scoped initializers need to be constant. 11049 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 11050 CheckForConstantInitializer(Init, DclT); 11051 } 11052 11053 // We will represent direct-initialization similarly to copy-initialization: 11054 // int x(1); -as-> int x = 1; 11055 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 11056 // 11057 // Clients that want to distinguish between the two forms, can check for 11058 // direct initializer using VarDecl::getInitStyle(). 11059 // A major benefit is that clients that don't particularly care about which 11060 // exactly form was it (like the CodeGen) can handle both cases without 11061 // special case code. 11062 11063 // C++ 8.5p11: 11064 // The form of initialization (using parentheses or '=') is generally 11065 // insignificant, but does matter when the entity being initialized has a 11066 // class type. 11067 if (CXXDirectInit) { 11068 assert(DirectInit && "Call-style initializer must be direct init."); 11069 VDecl->setInitStyle(VarDecl::CallInit); 11070 } else if (DirectInit) { 11071 // This must be list-initialization. No other way is direct-initialization. 11072 VDecl->setInitStyle(VarDecl::ListInit); 11073 } 11074 11075 CheckCompleteVariableDeclaration(VDecl); 11076 } 11077 11078 /// ActOnInitializerError - Given that there was an error parsing an 11079 /// initializer for the given declaration, try to return to some form 11080 /// of sanity. 11081 void Sema::ActOnInitializerError(Decl *D) { 11082 // Our main concern here is re-establishing invariants like "a 11083 // variable's type is either dependent or complete". 11084 if (!D || D->isInvalidDecl()) return; 11085 11086 VarDecl *VD = dyn_cast<VarDecl>(D); 11087 if (!VD) return; 11088 11089 // Bindings are not usable if we can't make sense of the initializer. 11090 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11091 for (auto *BD : DD->bindings()) 11092 BD->setInvalidDecl(); 11093 11094 // Auto types are meaningless if we can't make sense of the initializer. 11095 if (ParsingInitForAutoVars.count(D)) { 11096 D->setInvalidDecl(); 11097 return; 11098 } 11099 11100 QualType Ty = VD->getType(); 11101 if (Ty->isDependentType()) return; 11102 11103 // Require a complete type. 11104 if (RequireCompleteType(VD->getLocation(), 11105 Context.getBaseElementType(Ty), 11106 diag::err_typecheck_decl_incomplete_type)) { 11107 VD->setInvalidDecl(); 11108 return; 11109 } 11110 11111 // Require a non-abstract type. 11112 if (RequireNonAbstractType(VD->getLocation(), Ty, 11113 diag::err_abstract_type_in_decl, 11114 AbstractVariableType)) { 11115 VD->setInvalidDecl(); 11116 return; 11117 } 11118 11119 // Don't bother complaining about constructors or destructors, 11120 // though. 11121 } 11122 11123 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11124 // If there is no declaration, there was an error parsing it. Just ignore it. 11125 if (!RealDecl) 11126 return; 11127 11128 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11129 QualType Type = Var->getType(); 11130 11131 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11132 if (isa<DecompositionDecl>(RealDecl)) { 11133 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11134 Var->setInvalidDecl(); 11135 return; 11136 } 11137 11138 if (Type->isUndeducedType() && 11139 DeduceVariableDeclarationType(Var, false, nullptr)) 11140 return; 11141 11142 // C++11 [class.static.data]p3: A static data member can be declared with 11143 // the constexpr specifier; if so, its declaration shall specify 11144 // a brace-or-equal-initializer. 11145 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11146 // the definition of a variable [...] or the declaration of a static data 11147 // member. 11148 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11149 !Var->isThisDeclarationADemotedDefinition()) { 11150 if (Var->isStaticDataMember()) { 11151 // C++1z removes the relevant rule; the in-class declaration is always 11152 // a definition there. 11153 if (!getLangOpts().CPlusPlus17) { 11154 Diag(Var->getLocation(), 11155 diag::err_constexpr_static_mem_var_requires_init) 11156 << Var->getDeclName(); 11157 Var->setInvalidDecl(); 11158 return; 11159 } 11160 } else { 11161 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11162 Var->setInvalidDecl(); 11163 return; 11164 } 11165 } 11166 11167 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11168 // be initialized. 11169 if (!Var->isInvalidDecl() && 11170 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11171 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11172 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11173 Var->setInvalidDecl(); 11174 return; 11175 } 11176 11177 switch (Var->isThisDeclarationADefinition()) { 11178 case VarDecl::Definition: 11179 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11180 break; 11181 11182 // We have an out-of-line definition of a static data member 11183 // that has an in-class initializer, so we type-check this like 11184 // a declaration. 11185 // 11186 LLVM_FALLTHROUGH; 11187 11188 case VarDecl::DeclarationOnly: 11189 // It's only a declaration. 11190 11191 // Block scope. C99 6.7p7: If an identifier for an object is 11192 // declared with no linkage (C99 6.2.2p6), the type for the 11193 // object shall be complete. 11194 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11195 !Var->hasLinkage() && !Var->isInvalidDecl() && 11196 RequireCompleteType(Var->getLocation(), Type, 11197 diag::err_typecheck_decl_incomplete_type)) 11198 Var->setInvalidDecl(); 11199 11200 // Make sure that the type is not abstract. 11201 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11202 RequireNonAbstractType(Var->getLocation(), Type, 11203 diag::err_abstract_type_in_decl, 11204 AbstractVariableType)) 11205 Var->setInvalidDecl(); 11206 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11207 Var->getStorageClass() == SC_PrivateExtern) { 11208 Diag(Var->getLocation(), diag::warn_private_extern); 11209 Diag(Var->getLocation(), diag::note_private_extern); 11210 } 11211 11212 return; 11213 11214 case VarDecl::TentativeDefinition: 11215 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11216 // object that has file scope without an initializer, and without a 11217 // storage-class specifier or with the storage-class specifier "static", 11218 // constitutes a tentative definition. Note: A tentative definition with 11219 // external linkage is valid (C99 6.2.2p5). 11220 if (!Var->isInvalidDecl()) { 11221 if (const IncompleteArrayType *ArrayT 11222 = Context.getAsIncompleteArrayType(Type)) { 11223 if (RequireCompleteType(Var->getLocation(), 11224 ArrayT->getElementType(), 11225 diag::err_illegal_decl_array_incomplete_type)) 11226 Var->setInvalidDecl(); 11227 } else if (Var->getStorageClass() == SC_Static) { 11228 // C99 6.9.2p3: If the declaration of an identifier for an object is 11229 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11230 // declared type shall not be an incomplete type. 11231 // NOTE: code such as the following 11232 // static struct s; 11233 // struct s { int a; }; 11234 // is accepted by gcc. Hence here we issue a warning instead of 11235 // an error and we do not invalidate the static declaration. 11236 // NOTE: to avoid multiple warnings, only check the first declaration. 11237 if (Var->isFirstDecl()) 11238 RequireCompleteType(Var->getLocation(), Type, 11239 diag::ext_typecheck_decl_incomplete_type); 11240 } 11241 } 11242 11243 // Record the tentative definition; we're done. 11244 if (!Var->isInvalidDecl()) 11245 TentativeDefinitions.push_back(Var); 11246 return; 11247 } 11248 11249 // Provide a specific diagnostic for uninitialized variable 11250 // definitions with incomplete array type. 11251 if (Type->isIncompleteArrayType()) { 11252 Diag(Var->getLocation(), 11253 diag::err_typecheck_incomplete_array_needs_initializer); 11254 Var->setInvalidDecl(); 11255 return; 11256 } 11257 11258 // Provide a specific diagnostic for uninitialized variable 11259 // definitions with reference type. 11260 if (Type->isReferenceType()) { 11261 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11262 << Var->getDeclName() 11263 << SourceRange(Var->getLocation(), Var->getLocation()); 11264 Var->setInvalidDecl(); 11265 return; 11266 } 11267 11268 // Do not attempt to type-check the default initializer for a 11269 // variable with dependent type. 11270 if (Type->isDependentType()) 11271 return; 11272 11273 if (Var->isInvalidDecl()) 11274 return; 11275 11276 if (!Var->hasAttr<AliasAttr>()) { 11277 if (RequireCompleteType(Var->getLocation(), 11278 Context.getBaseElementType(Type), 11279 diag::err_typecheck_decl_incomplete_type)) { 11280 Var->setInvalidDecl(); 11281 return; 11282 } 11283 } else { 11284 return; 11285 } 11286 11287 // The variable can not have an abstract class type. 11288 if (RequireNonAbstractType(Var->getLocation(), Type, 11289 diag::err_abstract_type_in_decl, 11290 AbstractVariableType)) { 11291 Var->setInvalidDecl(); 11292 return; 11293 } 11294 11295 // Check for jumps past the implicit initializer. C++0x 11296 // clarifies that this applies to a "variable with automatic 11297 // storage duration", not a "local variable". 11298 // C++11 [stmt.dcl]p3 11299 // A program that jumps from a point where a variable with automatic 11300 // storage duration is not in scope to a point where it is in scope is 11301 // ill-formed unless the variable has scalar type, class type with a 11302 // trivial default constructor and a trivial destructor, a cv-qualified 11303 // version of one of these types, or an array of one of the preceding 11304 // types and is declared without an initializer. 11305 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11306 if (const RecordType *Record 11307 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11308 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11309 // Mark the function (if we're in one) for further checking even if the 11310 // looser rules of C++11 do not require such checks, so that we can 11311 // diagnose incompatibilities with C++98. 11312 if (!CXXRecord->isPOD()) 11313 setFunctionHasBranchProtectedScope(); 11314 } 11315 } 11316 11317 // C++03 [dcl.init]p9: 11318 // If no initializer is specified for an object, and the 11319 // object is of (possibly cv-qualified) non-POD class type (or 11320 // array thereof), the object shall be default-initialized; if 11321 // the object is of const-qualified type, the underlying class 11322 // type shall have a user-declared default 11323 // constructor. Otherwise, if no initializer is specified for 11324 // a non- static object, the object and its subobjects, if 11325 // any, have an indeterminate initial value); if the object 11326 // or any of its subobjects are of const-qualified type, the 11327 // program is ill-formed. 11328 // C++0x [dcl.init]p11: 11329 // If no initializer is specified for an object, the object is 11330 // default-initialized; [...]. 11331 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11332 InitializationKind Kind 11333 = InitializationKind::CreateDefault(Var->getLocation()); 11334 11335 InitializationSequence InitSeq(*this, Entity, Kind, None); 11336 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11337 if (Init.isInvalid()) 11338 Var->setInvalidDecl(); 11339 else if (Init.get()) { 11340 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11341 // This is important for template substitution. 11342 Var->setInitStyle(VarDecl::CallInit); 11343 } 11344 11345 CheckCompleteVariableDeclaration(Var); 11346 } 11347 } 11348 11349 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11350 // If there is no declaration, there was an error parsing it. Ignore it. 11351 if (!D) 11352 return; 11353 11354 VarDecl *VD = dyn_cast<VarDecl>(D); 11355 if (!VD) { 11356 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11357 D->setInvalidDecl(); 11358 return; 11359 } 11360 11361 VD->setCXXForRangeDecl(true); 11362 11363 // for-range-declaration cannot be given a storage class specifier. 11364 int Error = -1; 11365 switch (VD->getStorageClass()) { 11366 case SC_None: 11367 break; 11368 case SC_Extern: 11369 Error = 0; 11370 break; 11371 case SC_Static: 11372 Error = 1; 11373 break; 11374 case SC_PrivateExtern: 11375 Error = 2; 11376 break; 11377 case SC_Auto: 11378 Error = 3; 11379 break; 11380 case SC_Register: 11381 Error = 4; 11382 break; 11383 } 11384 if (Error != -1) { 11385 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11386 << VD->getDeclName() << Error; 11387 D->setInvalidDecl(); 11388 } 11389 } 11390 11391 StmtResult 11392 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11393 IdentifierInfo *Ident, 11394 ParsedAttributes &Attrs, 11395 SourceLocation AttrEnd) { 11396 // C++1y [stmt.iter]p1: 11397 // A range-based for statement of the form 11398 // for ( for-range-identifier : for-range-initializer ) statement 11399 // is equivalent to 11400 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11401 DeclSpec DS(Attrs.getPool().getFactory()); 11402 11403 const char *PrevSpec; 11404 unsigned DiagID; 11405 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11406 getPrintingPolicy()); 11407 11408 Declarator D(DS, DeclaratorContext::ForContext); 11409 D.SetIdentifier(Ident, IdentLoc); 11410 D.takeAttributes(Attrs, AttrEnd); 11411 11412 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11413 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 11414 IdentLoc); 11415 Decl *Var = ActOnDeclarator(S, D); 11416 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11417 FinalizeDeclaration(Var); 11418 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11419 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11420 } 11421 11422 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11423 if (var->isInvalidDecl()) return; 11424 11425 if (getLangOpts().OpenCL) { 11426 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11427 // initialiser 11428 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11429 !var->hasInit()) { 11430 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11431 << 1 /*Init*/; 11432 var->setInvalidDecl(); 11433 return; 11434 } 11435 } 11436 11437 // In Objective-C, don't allow jumps past the implicit initialization of a 11438 // local retaining variable. 11439 if (getLangOpts().ObjC1 && 11440 var->hasLocalStorage()) { 11441 switch (var->getType().getObjCLifetime()) { 11442 case Qualifiers::OCL_None: 11443 case Qualifiers::OCL_ExplicitNone: 11444 case Qualifiers::OCL_Autoreleasing: 11445 break; 11446 11447 case Qualifiers::OCL_Weak: 11448 case Qualifiers::OCL_Strong: 11449 setFunctionHasBranchProtectedScope(); 11450 break; 11451 } 11452 } 11453 11454 if (var->hasLocalStorage() && 11455 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11456 setFunctionHasBranchProtectedScope(); 11457 11458 // Warn about externally-visible variables being defined without a 11459 // prior declaration. We only want to do this for global 11460 // declarations, but we also specifically need to avoid doing it for 11461 // class members because the linkage of an anonymous class can 11462 // change if it's later given a typedef name. 11463 if (var->isThisDeclarationADefinition() && 11464 var->getDeclContext()->getRedeclContext()->isFileContext() && 11465 var->isExternallyVisible() && var->hasLinkage() && 11466 !var->isInline() && !var->getDescribedVarTemplate() && 11467 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11468 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11469 var->getLocation())) { 11470 // Find a previous declaration that's not a definition. 11471 VarDecl *prev = var->getPreviousDecl(); 11472 while (prev && prev->isThisDeclarationADefinition()) 11473 prev = prev->getPreviousDecl(); 11474 11475 if (!prev) 11476 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11477 } 11478 11479 // Cache the result of checking for constant initialization. 11480 Optional<bool> CacheHasConstInit; 11481 const Expr *CacheCulprit; 11482 auto checkConstInit = [&]() mutable { 11483 if (!CacheHasConstInit) 11484 CacheHasConstInit = var->getInit()->isConstantInitializer( 11485 Context, var->getType()->isReferenceType(), &CacheCulprit); 11486 return *CacheHasConstInit; 11487 }; 11488 11489 if (var->getTLSKind() == VarDecl::TLS_Static) { 11490 if (var->getType().isDestructedType()) { 11491 // GNU C++98 edits for __thread, [basic.start.term]p3: 11492 // The type of an object with thread storage duration shall not 11493 // have a non-trivial destructor. 11494 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11495 if (getLangOpts().CPlusPlus11) 11496 Diag(var->getLocation(), diag::note_use_thread_local); 11497 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11498 if (!checkConstInit()) { 11499 // GNU C++98 edits for __thread, [basic.start.init]p4: 11500 // An object of thread storage duration shall not require dynamic 11501 // initialization. 11502 // FIXME: Need strict checking here. 11503 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11504 << CacheCulprit->getSourceRange(); 11505 if (getLangOpts().CPlusPlus11) 11506 Diag(var->getLocation(), diag::note_use_thread_local); 11507 } 11508 } 11509 } 11510 11511 // Apply section attributes and pragmas to global variables. 11512 bool GlobalStorage = var->hasGlobalStorage(); 11513 if (GlobalStorage && var->isThisDeclarationADefinition() && 11514 !inTemplateInstantiation()) { 11515 PragmaStack<StringLiteral *> *Stack = nullptr; 11516 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11517 if (var->getType().isConstQualified()) 11518 Stack = &ConstSegStack; 11519 else if (!var->getInit()) { 11520 Stack = &BSSSegStack; 11521 SectionFlags |= ASTContext::PSF_Write; 11522 } else { 11523 Stack = &DataSegStack; 11524 SectionFlags |= ASTContext::PSF_Write; 11525 } 11526 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11527 var->addAttr(SectionAttr::CreateImplicit( 11528 Context, SectionAttr::Declspec_allocate, 11529 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11530 } 11531 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11532 if (UnifySection(SA->getName(), SectionFlags, var)) 11533 var->dropAttr<SectionAttr>(); 11534 11535 // Apply the init_seg attribute if this has an initializer. If the 11536 // initializer turns out to not be dynamic, we'll end up ignoring this 11537 // attribute. 11538 if (CurInitSeg && var->getInit()) 11539 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11540 CurInitSegLoc)); 11541 } 11542 11543 // All the following checks are C++ only. 11544 if (!getLangOpts().CPlusPlus) { 11545 // If this variable must be emitted, add it as an initializer for the 11546 // current module. 11547 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11548 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11549 return; 11550 } 11551 11552 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11553 CheckCompleteDecompositionDeclaration(DD); 11554 11555 QualType type = var->getType(); 11556 if (type->isDependentType()) return; 11557 11558 // __block variables might require us to capture a copy-initializer. 11559 if (var->hasAttr<BlocksAttr>()) { 11560 // It's currently invalid to ever have a __block variable with an 11561 // array type; should we diagnose that here? 11562 11563 // Regardless, we don't want to ignore array nesting when 11564 // constructing this copy. 11565 if (type->isStructureOrClassType()) { 11566 EnterExpressionEvaluationContext scope( 11567 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11568 SourceLocation poi = var->getLocation(); 11569 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11570 ExprResult result 11571 = PerformMoveOrCopyInitialization( 11572 InitializedEntity::InitializeBlock(poi, type, false), 11573 var, var->getType(), varRef, /*AllowNRVO=*/true); 11574 if (!result.isInvalid()) { 11575 result = MaybeCreateExprWithCleanups(result); 11576 Expr *init = result.getAs<Expr>(); 11577 Context.setBlockVarCopyInits(var, init); 11578 } 11579 } 11580 } 11581 11582 Expr *Init = var->getInit(); 11583 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11584 QualType baseType = Context.getBaseElementType(type); 11585 11586 if (Init && !Init->isValueDependent()) { 11587 if (var->isConstexpr()) { 11588 SmallVector<PartialDiagnosticAt, 8> Notes; 11589 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11590 SourceLocation DiagLoc = var->getLocation(); 11591 // If the note doesn't add any useful information other than a source 11592 // location, fold it into the primary diagnostic. 11593 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11594 diag::note_invalid_subexpr_in_const_expr) { 11595 DiagLoc = Notes[0].first; 11596 Notes.clear(); 11597 } 11598 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11599 << var << Init->getSourceRange(); 11600 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11601 Diag(Notes[I].first, Notes[I].second); 11602 } 11603 } else if (var->isUsableInConstantExpressions(Context)) { 11604 // Check whether the initializer of a const variable of integral or 11605 // enumeration type is an ICE now, since we can't tell whether it was 11606 // initialized by a constant expression if we check later. 11607 var->checkInitIsICE(); 11608 } 11609 11610 // Don't emit further diagnostics about constexpr globals since they 11611 // were just diagnosed. 11612 if (!var->isConstexpr() && GlobalStorage && 11613 var->hasAttr<RequireConstantInitAttr>()) { 11614 // FIXME: Need strict checking in C++03 here. 11615 bool DiagErr = getLangOpts().CPlusPlus11 11616 ? !var->checkInitIsICE() : !checkConstInit(); 11617 if (DiagErr) { 11618 auto attr = var->getAttr<RequireConstantInitAttr>(); 11619 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11620 << Init->getSourceRange(); 11621 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11622 << attr->getRange(); 11623 if (getLangOpts().CPlusPlus11) { 11624 APValue Value; 11625 SmallVector<PartialDiagnosticAt, 8> Notes; 11626 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11627 for (auto &it : Notes) 11628 Diag(it.first, it.second); 11629 } else { 11630 Diag(CacheCulprit->getExprLoc(), 11631 diag::note_invalid_subexpr_in_const_expr) 11632 << CacheCulprit->getSourceRange(); 11633 } 11634 } 11635 } 11636 else if (!var->isConstexpr() && IsGlobal && 11637 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11638 var->getLocation())) { 11639 // Warn about globals which don't have a constant initializer. Don't 11640 // warn about globals with a non-trivial destructor because we already 11641 // warned about them. 11642 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11643 if (!(RD && !RD->hasTrivialDestructor())) { 11644 if (!checkConstInit()) 11645 Diag(var->getLocation(), diag::warn_global_constructor) 11646 << Init->getSourceRange(); 11647 } 11648 } 11649 } 11650 11651 // Require the destructor. 11652 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11653 FinalizeVarWithDestructor(var, recordType); 11654 11655 // If this variable must be emitted, add it as an initializer for the current 11656 // module. 11657 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11658 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11659 } 11660 11661 /// Determines if a variable's alignment is dependent. 11662 static bool hasDependentAlignment(VarDecl *VD) { 11663 if (VD->getType()->isDependentType()) 11664 return true; 11665 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11666 if (I->isAlignmentDependent()) 11667 return true; 11668 return false; 11669 } 11670 11671 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11672 /// any semantic actions necessary after any initializer has been attached. 11673 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11674 // Note that we are no longer parsing the initializer for this declaration. 11675 ParsingInitForAutoVars.erase(ThisDecl); 11676 11677 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11678 if (!VD) 11679 return; 11680 11681 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11682 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11683 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11684 if (PragmaClangBSSSection.Valid) 11685 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11686 PragmaClangBSSSection.SectionName, 11687 PragmaClangBSSSection.PragmaLocation)); 11688 if (PragmaClangDataSection.Valid) 11689 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11690 PragmaClangDataSection.SectionName, 11691 PragmaClangDataSection.PragmaLocation)); 11692 if (PragmaClangRodataSection.Valid) 11693 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11694 PragmaClangRodataSection.SectionName, 11695 PragmaClangRodataSection.PragmaLocation)); 11696 } 11697 11698 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11699 for (auto *BD : DD->bindings()) { 11700 FinalizeDeclaration(BD); 11701 } 11702 } 11703 11704 checkAttributesAfterMerging(*this, *VD); 11705 11706 // Perform TLS alignment check here after attributes attached to the variable 11707 // which may affect the alignment have been processed. Only perform the check 11708 // if the target has a maximum TLS alignment (zero means no constraints). 11709 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11710 // Protect the check so that it's not performed on dependent types and 11711 // dependent alignments (we can't determine the alignment in that case). 11712 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11713 !VD->isInvalidDecl()) { 11714 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11715 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11716 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11717 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11718 << (unsigned)MaxAlignChars.getQuantity(); 11719 } 11720 } 11721 } 11722 11723 if (VD->isStaticLocal()) { 11724 if (FunctionDecl *FD = 11725 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11726 // Static locals inherit dll attributes from their function. 11727 if (Attr *A = getDLLAttr(FD)) { 11728 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11729 NewAttr->setInherited(true); 11730 VD->addAttr(NewAttr); 11731 } 11732 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11733 // function, only __shared__ variables may be declared with 11734 // static storage class. 11735 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11736 CUDADiagIfDeviceCode(VD->getLocation(), 11737 diag::err_device_static_local_var) 11738 << CurrentCUDATarget()) 11739 VD->setInvalidDecl(); 11740 } 11741 } 11742 11743 // Perform check for initializers of device-side global variables. 11744 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11745 // 7.5). We must also apply the same checks to all __shared__ 11746 // variables whether they are local or not. CUDA also allows 11747 // constant initializers for __constant__ and __device__ variables. 11748 if (getLangOpts().CUDA) 11749 checkAllowedCUDAInitializer(VD); 11750 11751 // Grab the dllimport or dllexport attribute off of the VarDecl. 11752 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11753 11754 // Imported static data members cannot be defined out-of-line. 11755 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11756 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11757 VD->isThisDeclarationADefinition()) { 11758 // We allow definitions of dllimport class template static data members 11759 // with a warning. 11760 CXXRecordDecl *Context = 11761 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11762 bool IsClassTemplateMember = 11763 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11764 Context->getDescribedClassTemplate(); 11765 11766 Diag(VD->getLocation(), 11767 IsClassTemplateMember 11768 ? diag::warn_attribute_dllimport_static_field_definition 11769 : diag::err_attribute_dllimport_static_field_definition); 11770 Diag(IA->getLocation(), diag::note_attribute); 11771 if (!IsClassTemplateMember) 11772 VD->setInvalidDecl(); 11773 } 11774 } 11775 11776 // dllimport/dllexport variables cannot be thread local, their TLS index 11777 // isn't exported with the variable. 11778 if (DLLAttr && VD->getTLSKind()) { 11779 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11780 if (F && getDLLAttr(F)) { 11781 assert(VD->isStaticLocal()); 11782 // But if this is a static local in a dlimport/dllexport function, the 11783 // function will never be inlined, which means the var would never be 11784 // imported, so having it marked import/export is safe. 11785 } else { 11786 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11787 << DLLAttr; 11788 VD->setInvalidDecl(); 11789 } 11790 } 11791 11792 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11793 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11794 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11795 VD->dropAttr<UsedAttr>(); 11796 } 11797 } 11798 11799 const DeclContext *DC = VD->getDeclContext(); 11800 // If there's a #pragma GCC visibility in scope, and this isn't a class 11801 // member, set the visibility of this variable. 11802 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11803 AddPushedVisibilityAttribute(VD); 11804 11805 // FIXME: Warn on unused var template partial specializations. 11806 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11807 MarkUnusedFileScopedDecl(VD); 11808 11809 // Now we have parsed the initializer and can update the table of magic 11810 // tag values. 11811 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11812 !VD->getType()->isIntegralOrEnumerationType()) 11813 return; 11814 11815 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11816 const Expr *MagicValueExpr = VD->getInit(); 11817 if (!MagicValueExpr) { 11818 continue; 11819 } 11820 llvm::APSInt MagicValueInt; 11821 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11822 Diag(I->getRange().getBegin(), 11823 diag::err_type_tag_for_datatype_not_ice) 11824 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11825 continue; 11826 } 11827 if (MagicValueInt.getActiveBits() > 64) { 11828 Diag(I->getRange().getBegin(), 11829 diag::err_type_tag_for_datatype_too_large) 11830 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11831 continue; 11832 } 11833 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11834 RegisterTypeTagForDatatype(I->getArgumentKind(), 11835 MagicValue, 11836 I->getMatchingCType(), 11837 I->getLayoutCompatible(), 11838 I->getMustBeNull()); 11839 } 11840 } 11841 11842 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11843 auto *VD = dyn_cast<VarDecl>(DD); 11844 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11845 } 11846 11847 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11848 ArrayRef<Decl *> Group) { 11849 SmallVector<Decl*, 8> Decls; 11850 11851 if (DS.isTypeSpecOwned()) 11852 Decls.push_back(DS.getRepAsDecl()); 11853 11854 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11855 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11856 bool DiagnosedMultipleDecomps = false; 11857 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11858 bool DiagnosedNonDeducedAuto = false; 11859 11860 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11861 if (Decl *D = Group[i]) { 11862 // For declarators, there are some additional syntactic-ish checks we need 11863 // to perform. 11864 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11865 if (!FirstDeclaratorInGroup) 11866 FirstDeclaratorInGroup = DD; 11867 if (!FirstDecompDeclaratorInGroup) 11868 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11869 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11870 !hasDeducedAuto(DD)) 11871 FirstNonDeducedAutoInGroup = DD; 11872 11873 if (FirstDeclaratorInGroup != DD) { 11874 // A decomposition declaration cannot be combined with any other 11875 // declaration in the same group. 11876 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11877 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11878 diag::err_decomp_decl_not_alone) 11879 << FirstDeclaratorInGroup->getSourceRange() 11880 << DD->getSourceRange(); 11881 DiagnosedMultipleDecomps = true; 11882 } 11883 11884 // A declarator that uses 'auto' in any way other than to declare a 11885 // variable with a deduced type cannot be combined with any other 11886 // declarator in the same group. 11887 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11888 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11889 diag::err_auto_non_deduced_not_alone) 11890 << FirstNonDeducedAutoInGroup->getType() 11891 ->hasAutoForTrailingReturnType() 11892 << FirstDeclaratorInGroup->getSourceRange() 11893 << DD->getSourceRange(); 11894 DiagnosedNonDeducedAuto = true; 11895 } 11896 } 11897 } 11898 11899 Decls.push_back(D); 11900 } 11901 } 11902 11903 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11904 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11905 handleTagNumbering(Tag, S); 11906 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11907 getLangOpts().CPlusPlus) 11908 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11909 } 11910 } 11911 11912 return BuildDeclaratorGroup(Decls); 11913 } 11914 11915 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11916 /// group, performing any necessary semantic checking. 11917 Sema::DeclGroupPtrTy 11918 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11919 // C++14 [dcl.spec.auto]p7: (DR1347) 11920 // If the type that replaces the placeholder type is not the same in each 11921 // deduction, the program is ill-formed. 11922 if (Group.size() > 1) { 11923 QualType Deduced; 11924 VarDecl *DeducedDecl = nullptr; 11925 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11926 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11927 if (!D || D->isInvalidDecl()) 11928 break; 11929 DeducedType *DT = D->getType()->getContainedDeducedType(); 11930 if (!DT || DT->getDeducedType().isNull()) 11931 continue; 11932 if (Deduced.isNull()) { 11933 Deduced = DT->getDeducedType(); 11934 DeducedDecl = D; 11935 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11936 auto *AT = dyn_cast<AutoType>(DT); 11937 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11938 diag::err_auto_different_deductions) 11939 << (AT ? (unsigned)AT->getKeyword() : 3) 11940 << Deduced << DeducedDecl->getDeclName() 11941 << DT->getDeducedType() << D->getDeclName() 11942 << DeducedDecl->getInit()->getSourceRange() 11943 << D->getInit()->getSourceRange(); 11944 D->setInvalidDecl(); 11945 break; 11946 } 11947 } 11948 } 11949 11950 ActOnDocumentableDecls(Group); 11951 11952 return DeclGroupPtrTy::make( 11953 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11954 } 11955 11956 void Sema::ActOnDocumentableDecl(Decl *D) { 11957 ActOnDocumentableDecls(D); 11958 } 11959 11960 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11961 // Don't parse the comment if Doxygen diagnostics are ignored. 11962 if (Group.empty() || !Group[0]) 11963 return; 11964 11965 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11966 Group[0]->getLocation()) && 11967 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11968 Group[0]->getLocation())) 11969 return; 11970 11971 if (Group.size() >= 2) { 11972 // This is a decl group. Normally it will contain only declarations 11973 // produced from declarator list. But in case we have any definitions or 11974 // additional declaration references: 11975 // 'typedef struct S {} S;' 11976 // 'typedef struct S *S;' 11977 // 'struct S *pS;' 11978 // FinalizeDeclaratorGroup adds these as separate declarations. 11979 Decl *MaybeTagDecl = Group[0]; 11980 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11981 Group = Group.slice(1); 11982 } 11983 } 11984 11985 // See if there are any new comments that are not attached to a decl. 11986 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11987 if (!Comments.empty() && 11988 !Comments.back()->isAttached()) { 11989 // There is at least one comment that not attached to a decl. 11990 // Maybe it should be attached to one of these decls? 11991 // 11992 // Note that this way we pick up not only comments that precede the 11993 // declaration, but also comments that *follow* the declaration -- thanks to 11994 // the lookahead in the lexer: we've consumed the semicolon and looked 11995 // ahead through comments. 11996 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11997 Context.getCommentForDecl(Group[i], &PP); 11998 } 11999 } 12000 12001 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 12002 /// to introduce parameters into function prototype scope. 12003 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 12004 const DeclSpec &DS = D.getDeclSpec(); 12005 12006 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 12007 12008 // C++03 [dcl.stc]p2 also permits 'auto'. 12009 StorageClass SC = SC_None; 12010 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 12011 SC = SC_Register; 12012 // In C++11, the 'register' storage class specifier is deprecated. 12013 // In C++17, it is not allowed, but we tolerate it as an extension. 12014 if (getLangOpts().CPlusPlus11) { 12015 Diag(DS.getStorageClassSpecLoc(), 12016 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 12017 : diag::warn_deprecated_register) 12018 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 12019 } 12020 } else if (getLangOpts().CPlusPlus && 12021 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 12022 SC = SC_Auto; 12023 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 12024 Diag(DS.getStorageClassSpecLoc(), 12025 diag::err_invalid_storage_class_in_func_decl); 12026 D.getMutableDeclSpec().ClearStorageClassSpecs(); 12027 } 12028 12029 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12030 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12031 << DeclSpec::getSpecifierName(TSCS); 12032 if (DS.isInlineSpecified()) 12033 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12034 << getLangOpts().CPlusPlus17; 12035 if (DS.isConstexprSpecified()) 12036 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12037 << 0; 12038 12039 DiagnoseFunctionSpecifiers(DS); 12040 12041 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12042 QualType parmDeclType = TInfo->getType(); 12043 12044 if (getLangOpts().CPlusPlus) { 12045 // Check that there are no default arguments inside the type of this 12046 // parameter. 12047 CheckExtraCXXDefaultArguments(D); 12048 12049 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12050 if (D.getCXXScopeSpec().isSet()) { 12051 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12052 << D.getCXXScopeSpec().getRange(); 12053 D.getCXXScopeSpec().clear(); 12054 } 12055 } 12056 12057 // Ensure we have a valid name 12058 IdentifierInfo *II = nullptr; 12059 if (D.hasName()) { 12060 II = D.getIdentifier(); 12061 if (!II) { 12062 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12063 << GetNameForDeclarator(D).getName(); 12064 D.setInvalidType(true); 12065 } 12066 } 12067 12068 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12069 if (II) { 12070 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12071 ForVisibleRedeclaration); 12072 LookupName(R, S); 12073 if (R.isSingleResult()) { 12074 NamedDecl *PrevDecl = R.getFoundDecl(); 12075 if (PrevDecl->isTemplateParameter()) { 12076 // Maybe we will complain about the shadowed template parameter. 12077 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12078 // Just pretend that we didn't see the previous declaration. 12079 PrevDecl = nullptr; 12080 } else if (S->isDeclScope(PrevDecl)) { 12081 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12082 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12083 12084 // Recover by removing the name 12085 II = nullptr; 12086 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12087 D.setInvalidType(true); 12088 } 12089 } 12090 } 12091 12092 // Temporarily put parameter variables in the translation unit, not 12093 // the enclosing context. This prevents them from accidentally 12094 // looking like class members in C++. 12095 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 12096 D.getLocStart(), 12097 D.getIdentifierLoc(), II, 12098 parmDeclType, TInfo, 12099 SC); 12100 12101 if (D.isInvalidType()) 12102 New->setInvalidDecl(); 12103 12104 assert(S->isFunctionPrototypeScope()); 12105 assert(S->getFunctionPrototypeDepth() >= 1); 12106 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12107 S->getNextFunctionPrototypeIndex()); 12108 12109 // Add the parameter declaration into this scope. 12110 S->AddDecl(New); 12111 if (II) 12112 IdResolver.AddDecl(New); 12113 12114 ProcessDeclAttributes(S, New, D); 12115 12116 if (D.getDeclSpec().isModulePrivateSpecified()) 12117 Diag(New->getLocation(), diag::err_module_private_local) 12118 << 1 << New->getDeclName() 12119 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12120 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12121 12122 if (New->hasAttr<BlocksAttr>()) { 12123 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12124 } 12125 return New; 12126 } 12127 12128 /// Synthesizes a variable for a parameter arising from a 12129 /// typedef. 12130 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12131 SourceLocation Loc, 12132 QualType T) { 12133 /* FIXME: setting StartLoc == Loc. 12134 Would it be worth to modify callers so as to provide proper source 12135 location for the unnamed parameters, embedding the parameter's type? */ 12136 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12137 T, Context.getTrivialTypeSourceInfo(T, Loc), 12138 SC_None, nullptr); 12139 Param->setImplicit(); 12140 return Param; 12141 } 12142 12143 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12144 // Don't diagnose unused-parameter errors in template instantiations; we 12145 // will already have done so in the template itself. 12146 if (inTemplateInstantiation()) 12147 return; 12148 12149 for (const ParmVarDecl *Parameter : Parameters) { 12150 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12151 !Parameter->hasAttr<UnusedAttr>()) { 12152 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12153 << Parameter->getDeclName(); 12154 } 12155 } 12156 } 12157 12158 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12159 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12160 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12161 return; 12162 12163 // Warn if the return value is pass-by-value and larger than the specified 12164 // threshold. 12165 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12166 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12167 if (Size > LangOpts.NumLargeByValueCopy) 12168 Diag(D->getLocation(), diag::warn_return_value_size) 12169 << D->getDeclName() << Size; 12170 } 12171 12172 // Warn if any parameter is pass-by-value and larger than the specified 12173 // threshold. 12174 for (const ParmVarDecl *Parameter : Parameters) { 12175 QualType T = Parameter->getType(); 12176 if (T->isDependentType() || !T.isPODType(Context)) 12177 continue; 12178 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12179 if (Size > LangOpts.NumLargeByValueCopy) 12180 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12181 << Parameter->getDeclName() << Size; 12182 } 12183 } 12184 12185 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12186 SourceLocation NameLoc, IdentifierInfo *Name, 12187 QualType T, TypeSourceInfo *TSInfo, 12188 StorageClass SC) { 12189 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12190 if (getLangOpts().ObjCAutoRefCount && 12191 T.getObjCLifetime() == Qualifiers::OCL_None && 12192 T->isObjCLifetimeType()) { 12193 12194 Qualifiers::ObjCLifetime lifetime; 12195 12196 // Special cases for arrays: 12197 // - if it's const, use __unsafe_unretained 12198 // - otherwise, it's an error 12199 if (T->isArrayType()) { 12200 if (!T.isConstQualified()) { 12201 DelayedDiagnostics.add( 12202 sema::DelayedDiagnostic::makeForbiddenType( 12203 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12204 } 12205 lifetime = Qualifiers::OCL_ExplicitNone; 12206 } else { 12207 lifetime = T->getObjCARCImplicitLifetime(); 12208 } 12209 T = Context.getLifetimeQualifiedType(T, lifetime); 12210 } 12211 12212 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12213 Context.getAdjustedParameterType(T), 12214 TSInfo, SC, nullptr); 12215 12216 // Parameters can not be abstract class types. 12217 // For record types, this is done by the AbstractClassUsageDiagnoser once 12218 // the class has been completely parsed. 12219 if (!CurContext->isRecord() && 12220 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12221 AbstractParamType)) 12222 New->setInvalidDecl(); 12223 12224 // Parameter declarators cannot be interface types. All ObjC objects are 12225 // passed by reference. 12226 if (T->isObjCObjectType()) { 12227 SourceLocation TypeEndLoc = 12228 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 12229 Diag(NameLoc, 12230 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12231 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12232 T = Context.getObjCObjectPointerType(T); 12233 New->setType(T); 12234 } 12235 12236 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12237 // duration shall not be qualified by an address-space qualifier." 12238 // Since all parameters have automatic store duration, they can not have 12239 // an address space. 12240 if (T.getAddressSpace() != LangAS::Default && 12241 // OpenCL allows function arguments declared to be an array of a type 12242 // to be qualified with an address space. 12243 !(getLangOpts().OpenCL && 12244 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12245 Diag(NameLoc, diag::err_arg_with_address_space); 12246 New->setInvalidDecl(); 12247 } 12248 12249 return New; 12250 } 12251 12252 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12253 SourceLocation LocAfterDecls) { 12254 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12255 12256 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12257 // for a K&R function. 12258 if (!FTI.hasPrototype) { 12259 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12260 --i; 12261 if (FTI.Params[i].Param == nullptr) { 12262 SmallString<256> Code; 12263 llvm::raw_svector_ostream(Code) 12264 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12265 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12266 << FTI.Params[i].Ident 12267 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12268 12269 // Implicitly declare the argument as type 'int' for lack of a better 12270 // type. 12271 AttributeFactory attrs; 12272 DeclSpec DS(attrs); 12273 const char* PrevSpec; // unused 12274 unsigned DiagID; // unused 12275 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12276 DiagID, Context.getPrintingPolicy()); 12277 // Use the identifier location for the type source range. 12278 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12279 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12280 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12281 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12282 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12283 } 12284 } 12285 } 12286 } 12287 12288 Decl * 12289 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12290 MultiTemplateParamsArg TemplateParameterLists, 12291 SkipBodyInfo *SkipBody) { 12292 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12293 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12294 Scope *ParentScope = FnBodyScope->getParent(); 12295 12296 D.setFunctionDefinitionKind(FDK_Definition); 12297 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12298 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12299 } 12300 12301 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12302 Consumer.HandleInlineFunctionDefinition(D); 12303 } 12304 12305 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12306 const FunctionDecl*& PossibleZeroParamPrototype) { 12307 // Don't warn about invalid declarations. 12308 if (FD->isInvalidDecl()) 12309 return false; 12310 12311 // Or declarations that aren't global. 12312 if (!FD->isGlobal()) 12313 return false; 12314 12315 // Don't warn about C++ member functions. 12316 if (isa<CXXMethodDecl>(FD)) 12317 return false; 12318 12319 // Don't warn about 'main'. 12320 if (FD->isMain()) 12321 return false; 12322 12323 // Don't warn about inline functions. 12324 if (FD->isInlined()) 12325 return false; 12326 12327 // Don't warn about function templates. 12328 if (FD->getDescribedFunctionTemplate()) 12329 return false; 12330 12331 // Don't warn about function template specializations. 12332 if (FD->isFunctionTemplateSpecialization()) 12333 return false; 12334 12335 // Don't warn for OpenCL kernels. 12336 if (FD->hasAttr<OpenCLKernelAttr>()) 12337 return false; 12338 12339 // Don't warn on explicitly deleted functions. 12340 if (FD->isDeleted()) 12341 return false; 12342 12343 bool MissingPrototype = true; 12344 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12345 Prev; Prev = Prev->getPreviousDecl()) { 12346 // Ignore any declarations that occur in function or method 12347 // scope, because they aren't visible from the header. 12348 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12349 continue; 12350 12351 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12352 if (FD->getNumParams() == 0) 12353 PossibleZeroParamPrototype = Prev; 12354 break; 12355 } 12356 12357 return MissingPrototype; 12358 } 12359 12360 void 12361 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12362 const FunctionDecl *EffectiveDefinition, 12363 SkipBodyInfo *SkipBody) { 12364 const FunctionDecl *Definition = EffectiveDefinition; 12365 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12366 // If this is a friend function defined in a class template, it does not 12367 // have a body until it is used, nevertheless it is a definition, see 12368 // [temp.inst]p2: 12369 // 12370 // ... for the purpose of determining whether an instantiated redeclaration 12371 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12372 // corresponds to a definition in the template is considered to be a 12373 // definition. 12374 // 12375 // The following code must produce redefinition error: 12376 // 12377 // template<typename T> struct C20 { friend void func_20() {} }; 12378 // C20<int> c20i; 12379 // void func_20() {} 12380 // 12381 for (auto I : FD->redecls()) { 12382 if (I != FD && !I->isInvalidDecl() && 12383 I->getFriendObjectKind() != Decl::FOK_None) { 12384 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12385 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12386 // A merged copy of the same function, instantiated as a member of 12387 // the same class, is OK. 12388 if (declaresSameEntity(OrigFD, Original) && 12389 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12390 cast<Decl>(FD->getLexicalDeclContext()))) 12391 continue; 12392 } 12393 12394 if (Original->isThisDeclarationADefinition()) { 12395 Definition = I; 12396 break; 12397 } 12398 } 12399 } 12400 } 12401 } 12402 if (!Definition) 12403 return; 12404 12405 if (canRedefineFunction(Definition, getLangOpts())) 12406 return; 12407 12408 // Don't emit an error when this is redefinition of a typo-corrected 12409 // definition. 12410 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12411 return; 12412 12413 // If we don't have a visible definition of the function, and it's inline or 12414 // a template, skip the new definition. 12415 if (SkipBody && !hasVisibleDefinition(Definition) && 12416 (Definition->getFormalLinkage() == InternalLinkage || 12417 Definition->isInlined() || 12418 Definition->getDescribedFunctionTemplate() || 12419 Definition->getNumTemplateParameterLists())) { 12420 SkipBody->ShouldSkip = true; 12421 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12422 makeMergedDefinitionVisible(TD); 12423 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12424 return; 12425 } 12426 12427 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12428 Definition->getStorageClass() == SC_Extern) 12429 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12430 << FD->getDeclName() << getLangOpts().CPlusPlus; 12431 else 12432 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12433 12434 Diag(Definition->getLocation(), diag::note_previous_definition); 12435 FD->setInvalidDecl(); 12436 } 12437 12438 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12439 Sema &S) { 12440 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12441 12442 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12443 LSI->CallOperator = CallOperator; 12444 LSI->Lambda = LambdaClass; 12445 LSI->ReturnType = CallOperator->getReturnType(); 12446 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12447 12448 if (LCD == LCD_None) 12449 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12450 else if (LCD == LCD_ByCopy) 12451 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12452 else if (LCD == LCD_ByRef) 12453 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12454 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12455 12456 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12457 LSI->Mutable = !CallOperator->isConst(); 12458 12459 // Add the captures to the LSI so they can be noted as already 12460 // captured within tryCaptureVar. 12461 auto I = LambdaClass->field_begin(); 12462 for (const auto &C : LambdaClass->captures()) { 12463 if (C.capturesVariable()) { 12464 VarDecl *VD = C.getCapturedVar(); 12465 if (VD->isInitCapture()) 12466 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12467 QualType CaptureType = VD->getType(); 12468 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12469 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12470 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12471 /*EllipsisLoc*/C.isPackExpansion() 12472 ? C.getEllipsisLoc() : SourceLocation(), 12473 CaptureType, /*Expr*/ nullptr); 12474 12475 } else if (C.capturesThis()) { 12476 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12477 /*Expr*/ nullptr, 12478 C.getCaptureKind() == LCK_StarThis); 12479 } else { 12480 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12481 } 12482 ++I; 12483 } 12484 } 12485 12486 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12487 SkipBodyInfo *SkipBody) { 12488 if (!D) { 12489 // Parsing the function declaration failed in some way. Push on a fake scope 12490 // anyway so we can try to parse the function body. 12491 PushFunctionScope(); 12492 return D; 12493 } 12494 12495 FunctionDecl *FD = nullptr; 12496 12497 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12498 FD = FunTmpl->getTemplatedDecl(); 12499 else 12500 FD = cast<FunctionDecl>(D); 12501 12502 // Check for defining attributes before the check for redefinition. 12503 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12504 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12505 FD->dropAttr<AliasAttr>(); 12506 FD->setInvalidDecl(); 12507 } 12508 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12509 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12510 FD->dropAttr<IFuncAttr>(); 12511 FD->setInvalidDecl(); 12512 } 12513 12514 // See if this is a redefinition. If 'will have body' is already set, then 12515 // these checks were already performed when it was set. 12516 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12517 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12518 12519 // If we're skipping the body, we're done. Don't enter the scope. 12520 if (SkipBody && SkipBody->ShouldSkip) 12521 return D; 12522 } 12523 12524 // Mark this function as "will have a body eventually". This lets users to 12525 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12526 // this function. 12527 FD->setWillHaveBody(); 12528 12529 // If we are instantiating a generic lambda call operator, push 12530 // a LambdaScopeInfo onto the function stack. But use the information 12531 // that's already been calculated (ActOnLambdaExpr) to prime the current 12532 // LambdaScopeInfo. 12533 // When the template operator is being specialized, the LambdaScopeInfo, 12534 // has to be properly restored so that tryCaptureVariable doesn't try 12535 // and capture any new variables. In addition when calculating potential 12536 // captures during transformation of nested lambdas, it is necessary to 12537 // have the LSI properly restored. 12538 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12539 assert(inTemplateInstantiation() && 12540 "There should be an active template instantiation on the stack " 12541 "when instantiating a generic lambda!"); 12542 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12543 } else { 12544 // Enter a new function scope 12545 PushFunctionScope(); 12546 } 12547 12548 // Builtin functions cannot be defined. 12549 if (unsigned BuiltinID = FD->getBuiltinID()) { 12550 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12551 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12552 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12553 FD->setInvalidDecl(); 12554 } 12555 } 12556 12557 // The return type of a function definition must be complete 12558 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12559 QualType ResultType = FD->getReturnType(); 12560 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12561 !FD->isInvalidDecl() && 12562 RequireCompleteType(FD->getLocation(), ResultType, 12563 diag::err_func_def_incomplete_result)) 12564 FD->setInvalidDecl(); 12565 12566 if (FnBodyScope) 12567 PushDeclContext(FnBodyScope, FD); 12568 12569 // Check the validity of our function parameters 12570 CheckParmsForFunctionDef(FD->parameters(), 12571 /*CheckParameterNames=*/true); 12572 12573 // Add non-parameter declarations already in the function to the current 12574 // scope. 12575 if (FnBodyScope) { 12576 for (Decl *NPD : FD->decls()) { 12577 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12578 if (!NonParmDecl) 12579 continue; 12580 assert(!isa<ParmVarDecl>(NonParmDecl) && 12581 "parameters should not be in newly created FD yet"); 12582 12583 // If the decl has a name, make it accessible in the current scope. 12584 if (NonParmDecl->getDeclName()) 12585 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12586 12587 // Similarly, dive into enums and fish their constants out, making them 12588 // accessible in this scope. 12589 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12590 for (auto *EI : ED->enumerators()) 12591 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12592 } 12593 } 12594 } 12595 12596 // Introduce our parameters into the function scope 12597 for (auto Param : FD->parameters()) { 12598 Param->setOwningFunction(FD); 12599 12600 // If this has an identifier, add it to the scope stack. 12601 if (Param->getIdentifier() && FnBodyScope) { 12602 CheckShadow(FnBodyScope, Param); 12603 12604 PushOnScopeChains(Param, FnBodyScope); 12605 } 12606 } 12607 12608 // Ensure that the function's exception specification is instantiated. 12609 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12610 ResolveExceptionSpec(D->getLocation(), FPT); 12611 12612 // dllimport cannot be applied to non-inline function definitions. 12613 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12614 !FD->isTemplateInstantiation()) { 12615 assert(!FD->hasAttr<DLLExportAttr>()); 12616 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12617 FD->setInvalidDecl(); 12618 return D; 12619 } 12620 // We want to attach documentation to original Decl (which might be 12621 // a function template). 12622 ActOnDocumentableDecl(D); 12623 if (getCurLexicalContext()->isObjCContainer() && 12624 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12625 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12626 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12627 12628 return D; 12629 } 12630 12631 /// Given the set of return statements within a function body, 12632 /// compute the variables that are subject to the named return value 12633 /// optimization. 12634 /// 12635 /// Each of the variables that is subject to the named return value 12636 /// optimization will be marked as NRVO variables in the AST, and any 12637 /// return statement that has a marked NRVO variable as its NRVO candidate can 12638 /// use the named return value optimization. 12639 /// 12640 /// This function applies a very simplistic algorithm for NRVO: if every return 12641 /// statement in the scope of a variable has the same NRVO candidate, that 12642 /// candidate is an NRVO variable. 12643 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12644 ReturnStmt **Returns = Scope->Returns.data(); 12645 12646 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12647 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12648 if (!NRVOCandidate->isNRVOVariable()) 12649 Returns[I]->setNRVOCandidate(nullptr); 12650 } 12651 } 12652 } 12653 12654 bool Sema::canDelayFunctionBody(const Declarator &D) { 12655 // We can't delay parsing the body of a constexpr function template (yet). 12656 if (D.getDeclSpec().isConstexprSpecified()) 12657 return false; 12658 12659 // We can't delay parsing the body of a function template with a deduced 12660 // return type (yet). 12661 if (D.getDeclSpec().hasAutoTypeSpec()) { 12662 // If the placeholder introduces a non-deduced trailing return type, 12663 // we can still delay parsing it. 12664 if (D.getNumTypeObjects()) { 12665 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12666 if (Outer.Kind == DeclaratorChunk::Function && 12667 Outer.Fun.hasTrailingReturnType()) { 12668 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12669 return Ty.isNull() || !Ty->isUndeducedType(); 12670 } 12671 } 12672 return false; 12673 } 12674 12675 return true; 12676 } 12677 12678 bool Sema::canSkipFunctionBody(Decl *D) { 12679 // We cannot skip the body of a function (or function template) which is 12680 // constexpr, since we may need to evaluate its body in order to parse the 12681 // rest of the file. 12682 // We cannot skip the body of a function with an undeduced return type, 12683 // because any callers of that function need to know the type. 12684 if (const FunctionDecl *FD = D->getAsFunction()) { 12685 if (FD->isConstexpr()) 12686 return false; 12687 // We can't simply call Type::isUndeducedType here, because inside template 12688 // auto can be deduced to a dependent type, which is not considered 12689 // "undeduced". 12690 if (FD->getReturnType()->getContainedDeducedType()) 12691 return false; 12692 } 12693 return Consumer.shouldSkipFunctionBody(D); 12694 } 12695 12696 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12697 if (!Decl) 12698 return nullptr; 12699 if (FunctionDecl *FD = Decl->getAsFunction()) 12700 FD->setHasSkippedBody(); 12701 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 12702 MD->setHasSkippedBody(); 12703 return Decl; 12704 } 12705 12706 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12707 return ActOnFinishFunctionBody(D, BodyArg, false); 12708 } 12709 12710 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12711 bool IsInstantiation) { 12712 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12713 12714 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12715 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12716 12717 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12718 CheckCompletedCoroutineBody(FD, Body); 12719 12720 if (FD) { 12721 FD->setBody(Body); 12722 FD->setWillHaveBody(false); 12723 12724 if (getLangOpts().CPlusPlus14) { 12725 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12726 FD->getReturnType()->isUndeducedType()) { 12727 // If the function has a deduced result type but contains no 'return' 12728 // statements, the result type as written must be exactly 'auto', and 12729 // the deduced result type is 'void'. 12730 if (!FD->getReturnType()->getAs<AutoType>()) { 12731 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12732 << FD->getReturnType(); 12733 FD->setInvalidDecl(); 12734 } else { 12735 // Substitute 'void' for the 'auto' in the type. 12736 TypeLoc ResultType = getReturnTypeLoc(FD); 12737 Context.adjustDeducedFunctionResultType( 12738 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12739 } 12740 } 12741 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12742 // In C++11, we don't use 'auto' deduction rules for lambda call 12743 // operators because we don't support return type deduction. 12744 auto *LSI = getCurLambda(); 12745 if (LSI->HasImplicitReturnType) { 12746 deduceClosureReturnType(*LSI); 12747 12748 // C++11 [expr.prim.lambda]p4: 12749 // [...] if there are no return statements in the compound-statement 12750 // [the deduced type is] the type void 12751 QualType RetType = 12752 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12753 12754 // Update the return type to the deduced type. 12755 const FunctionProtoType *Proto = 12756 FD->getType()->getAs<FunctionProtoType>(); 12757 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12758 Proto->getExtProtoInfo())); 12759 } 12760 } 12761 12762 // If the function implicitly returns zero (like 'main') or is naked, 12763 // don't complain about missing return statements. 12764 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12765 WP.disableCheckFallThrough(); 12766 12767 // MSVC permits the use of pure specifier (=0) on function definition, 12768 // defined at class scope, warn about this non-standard construct. 12769 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12770 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12771 12772 if (!FD->isInvalidDecl()) { 12773 // Don't diagnose unused parameters of defaulted or deleted functions. 12774 if (!FD->isDeleted() && !FD->isDefaulted()) 12775 DiagnoseUnusedParameters(FD->parameters()); 12776 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12777 FD->getReturnType(), FD); 12778 12779 // If this is a structor, we need a vtable. 12780 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12781 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12782 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12783 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12784 12785 // Try to apply the named return value optimization. We have to check 12786 // if we can do this here because lambdas keep return statements around 12787 // to deduce an implicit return type. 12788 if (FD->getReturnType()->isRecordType() && 12789 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 12790 computeNRVO(Body, getCurFunction()); 12791 } 12792 12793 // GNU warning -Wmissing-prototypes: 12794 // Warn if a global function is defined without a previous 12795 // prototype declaration. This warning is issued even if the 12796 // definition itself provides a prototype. The aim is to detect 12797 // global functions that fail to be declared in header files. 12798 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12799 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12800 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12801 12802 if (PossibleZeroParamPrototype) { 12803 // We found a declaration that is not a prototype, 12804 // but that could be a zero-parameter prototype 12805 if (TypeSourceInfo *TI = 12806 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12807 TypeLoc TL = TI->getTypeLoc(); 12808 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12809 Diag(PossibleZeroParamPrototype->getLocation(), 12810 diag::note_declaration_not_a_prototype) 12811 << PossibleZeroParamPrototype 12812 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12813 } 12814 } 12815 12816 // GNU warning -Wstrict-prototypes 12817 // Warn if K&R function is defined without a previous declaration. 12818 // This warning is issued only if the definition itself does not provide 12819 // a prototype. Only K&R definitions do not provide a prototype. 12820 // An empty list in a function declarator that is part of a definition 12821 // of that function specifies that the function has no parameters 12822 // (C99 6.7.5.3p14) 12823 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12824 !LangOpts.CPlusPlus) { 12825 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12826 TypeLoc TL = TI->getTypeLoc(); 12827 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12828 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12829 } 12830 } 12831 12832 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12833 const CXXMethodDecl *KeyFunction; 12834 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12835 MD->isVirtual() && 12836 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12837 MD == KeyFunction->getCanonicalDecl()) { 12838 // Update the key-function state if necessary for this ABI. 12839 if (FD->isInlined() && 12840 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12841 Context.setNonKeyFunction(MD); 12842 12843 // If the newly-chosen key function is already defined, then we 12844 // need to mark the vtable as used retroactively. 12845 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12846 const FunctionDecl *Definition; 12847 if (KeyFunction && KeyFunction->isDefined(Definition)) 12848 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12849 } else { 12850 // We just defined they key function; mark the vtable as used. 12851 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12852 } 12853 } 12854 } 12855 12856 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12857 "Function parsing confused"); 12858 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12859 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12860 MD->setBody(Body); 12861 if (!MD->isInvalidDecl()) { 12862 DiagnoseUnusedParameters(MD->parameters()); 12863 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12864 MD->getReturnType(), MD); 12865 12866 if (Body) 12867 computeNRVO(Body, getCurFunction()); 12868 } 12869 if (getCurFunction()->ObjCShouldCallSuper) { 12870 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12871 << MD->getSelector().getAsString(); 12872 getCurFunction()->ObjCShouldCallSuper = false; 12873 } 12874 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12875 const ObjCMethodDecl *InitMethod = nullptr; 12876 bool isDesignated = 12877 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12878 assert(isDesignated && InitMethod); 12879 (void)isDesignated; 12880 12881 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12882 auto IFace = MD->getClassInterface(); 12883 if (!IFace) 12884 return false; 12885 auto SuperD = IFace->getSuperClass(); 12886 if (!SuperD) 12887 return false; 12888 return SuperD->getIdentifier() == 12889 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12890 }; 12891 // Don't issue this warning for unavailable inits or direct subclasses 12892 // of NSObject. 12893 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12894 Diag(MD->getLocation(), 12895 diag::warn_objc_designated_init_missing_super_call); 12896 Diag(InitMethod->getLocation(), 12897 diag::note_objc_designated_init_marked_here); 12898 } 12899 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12900 } 12901 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12902 // Don't issue this warning for unavaialable inits. 12903 if (!MD->isUnavailable()) 12904 Diag(MD->getLocation(), 12905 diag::warn_objc_secondary_init_missing_init_call); 12906 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12907 } 12908 } else { 12909 // Parsing the function declaration failed in some way. Pop the fake scope 12910 // we pushed on. 12911 PopFunctionScopeInfo(ActivePolicy, dcl); 12912 return nullptr; 12913 } 12914 12915 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12916 DiagnoseUnguardedAvailabilityViolations(dcl); 12917 12918 assert(!getCurFunction()->ObjCShouldCallSuper && 12919 "This should only be set for ObjC methods, which should have been " 12920 "handled in the block above."); 12921 12922 // Verify and clean out per-function state. 12923 if (Body && (!FD || !FD->isDefaulted())) { 12924 // C++ constructors that have function-try-blocks can't have return 12925 // statements in the handlers of that block. (C++ [except.handle]p14) 12926 // Verify this. 12927 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12928 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12929 12930 // Verify that gotos and switch cases don't jump into scopes illegally. 12931 if (getCurFunction()->NeedsScopeChecking() && 12932 !PP.isCodeCompletionEnabled()) 12933 DiagnoseInvalidJumps(Body); 12934 12935 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12936 if (!Destructor->getParent()->isDependentType()) 12937 CheckDestructor(Destructor); 12938 12939 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12940 Destructor->getParent()); 12941 } 12942 12943 // If any errors have occurred, clear out any temporaries that may have 12944 // been leftover. This ensures that these temporaries won't be picked up for 12945 // deletion in some later function. 12946 if (getDiagnostics().hasErrorOccurred() || 12947 getDiagnostics().getSuppressAllDiagnostics()) { 12948 DiscardCleanupsInEvaluationContext(); 12949 } 12950 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12951 !isa<FunctionTemplateDecl>(dcl)) { 12952 // Since the body is valid, issue any analysis-based warnings that are 12953 // enabled. 12954 ActivePolicy = &WP; 12955 } 12956 12957 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12958 (!CheckConstexprFunctionDecl(FD) || 12959 !CheckConstexprFunctionBody(FD, Body))) 12960 FD->setInvalidDecl(); 12961 12962 if (FD && FD->hasAttr<NakedAttr>()) { 12963 for (const Stmt *S : Body->children()) { 12964 // Allow local register variables without initializer as they don't 12965 // require prologue. 12966 bool RegisterVariables = false; 12967 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12968 for (const auto *Decl : DS->decls()) { 12969 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12970 RegisterVariables = 12971 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12972 if (!RegisterVariables) 12973 break; 12974 } 12975 } 12976 } 12977 if (RegisterVariables) 12978 continue; 12979 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12980 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12981 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12982 FD->setInvalidDecl(); 12983 break; 12984 } 12985 } 12986 } 12987 12988 assert(ExprCleanupObjects.size() == 12989 ExprEvalContexts.back().NumCleanupObjects && 12990 "Leftover temporaries in function"); 12991 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12992 assert(MaybeODRUseExprs.empty() && 12993 "Leftover expressions for odr-use checking"); 12994 } 12995 12996 if (!IsInstantiation) 12997 PopDeclContext(); 12998 12999 PopFunctionScopeInfo(ActivePolicy, dcl); 13000 // If any errors have occurred, clear out any temporaries that may have 13001 // been leftover. This ensures that these temporaries won't be picked up for 13002 // deletion in some later function. 13003 if (getDiagnostics().hasErrorOccurred()) { 13004 DiscardCleanupsInEvaluationContext(); 13005 } 13006 13007 return dcl; 13008 } 13009 13010 /// When we finish delayed parsing of an attribute, we must attach it to the 13011 /// relevant Decl. 13012 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 13013 ParsedAttributes &Attrs) { 13014 // Always attach attributes to the underlying decl. 13015 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 13016 D = TD->getTemplatedDecl(); 13017 ProcessDeclAttributeList(S, D, Attrs); 13018 13019 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 13020 if (Method->isStatic()) 13021 checkThisInStaticMemberFunctionAttributes(Method); 13022 } 13023 13024 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 13025 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 13026 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 13027 IdentifierInfo &II, Scope *S) { 13028 // Find the scope in which the identifier is injected and the corresponding 13029 // DeclContext. 13030 // FIXME: C89 does not say what happens if there is no enclosing block scope. 13031 // In that case, we inject the declaration into the translation unit scope 13032 // instead. 13033 Scope *BlockScope = S; 13034 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 13035 BlockScope = BlockScope->getParent(); 13036 13037 Scope *ContextScope = BlockScope; 13038 while (!ContextScope->getEntity()) 13039 ContextScope = ContextScope->getParent(); 13040 ContextRAII SavedContext(*this, ContextScope->getEntity()); 13041 13042 // Before we produce a declaration for an implicitly defined 13043 // function, see whether there was a locally-scoped declaration of 13044 // this name as a function or variable. If so, use that 13045 // (non-visible) declaration, and complain about it. 13046 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 13047 if (ExternCPrev) { 13048 // We still need to inject the function into the enclosing block scope so 13049 // that later (non-call) uses can see it. 13050 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13051 13052 // C89 footnote 38: 13053 // If in fact it is not defined as having type "function returning int", 13054 // the behavior is undefined. 13055 if (!isa<FunctionDecl>(ExternCPrev) || 13056 !Context.typesAreCompatible( 13057 cast<FunctionDecl>(ExternCPrev)->getType(), 13058 Context.getFunctionNoProtoType(Context.IntTy))) { 13059 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13060 << ExternCPrev << !getLangOpts().C99; 13061 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13062 return ExternCPrev; 13063 } 13064 } 13065 13066 // Extension in C99. Legal in C90, but warn about it. 13067 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13068 unsigned diag_id; 13069 if (II.getName().startswith("__builtin_")) 13070 diag_id = diag::warn_builtin_unknown; 13071 else if (getLangOpts().C99 || getLangOpts().OpenCL) 13072 diag_id = diag::ext_implicit_function_decl; 13073 else 13074 diag_id = diag::warn_implicit_function_decl; 13075 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL; 13076 13077 // If we found a prior declaration of this function, don't bother building 13078 // another one. We've already pushed that one into scope, so there's nothing 13079 // more to do. 13080 if (ExternCPrev) 13081 return ExternCPrev; 13082 13083 // Because typo correction is expensive, only do it if the implicit 13084 // function declaration is going to be treated as an error. 13085 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13086 TypoCorrection Corrected; 13087 if (S && 13088 (Corrected = CorrectTypo( 13089 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 13090 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 13091 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13092 /*ErrorRecovery*/false); 13093 } 13094 13095 // Set a Declarator for the implicit definition: int foo(); 13096 const char *Dummy; 13097 AttributeFactory attrFactory; 13098 DeclSpec DS(attrFactory); 13099 unsigned DiagID; 13100 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13101 Context.getPrintingPolicy()); 13102 (void)Error; // Silence warning. 13103 assert(!Error && "Error setting up implicit decl!"); 13104 SourceLocation NoLoc; 13105 Declarator D(DS, DeclaratorContext::BlockContext); 13106 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13107 /*IsAmbiguous=*/false, 13108 /*LParenLoc=*/NoLoc, 13109 /*Params=*/nullptr, 13110 /*NumParams=*/0, 13111 /*EllipsisLoc=*/NoLoc, 13112 /*RParenLoc=*/NoLoc, 13113 /*TypeQuals=*/0, 13114 /*RefQualifierIsLvalueRef=*/true, 13115 /*RefQualifierLoc=*/NoLoc, 13116 /*ConstQualifierLoc=*/NoLoc, 13117 /*VolatileQualifierLoc=*/NoLoc, 13118 /*RestrictQualifierLoc=*/NoLoc, 13119 /*MutableLoc=*/NoLoc, EST_None, 13120 /*ESpecRange=*/SourceRange(), 13121 /*Exceptions=*/nullptr, 13122 /*ExceptionRanges=*/nullptr, 13123 /*NumExceptions=*/0, 13124 /*NoexceptExpr=*/nullptr, 13125 /*ExceptionSpecTokens=*/nullptr, 13126 /*DeclsInPrototype=*/None, Loc, 13127 Loc, D), 13128 std::move(DS.getAttributes()), SourceLocation()); 13129 D.SetIdentifier(&II, Loc); 13130 13131 // Insert this function into the enclosing block scope. 13132 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13133 FD->setImplicit(); 13134 13135 AddKnownFunctionAttributes(FD); 13136 13137 return FD; 13138 } 13139 13140 /// Adds any function attributes that we know a priori based on 13141 /// the declaration of this function. 13142 /// 13143 /// These attributes can apply both to implicitly-declared builtins 13144 /// (like __builtin___printf_chk) or to library-declared functions 13145 /// like NSLog or printf. 13146 /// 13147 /// We need to check for duplicate attributes both here and where user-written 13148 /// attributes are applied to declarations. 13149 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13150 if (FD->isInvalidDecl()) 13151 return; 13152 13153 // If this is a built-in function, map its builtin attributes to 13154 // actual attributes. 13155 if (unsigned BuiltinID = FD->getBuiltinID()) { 13156 // Handle printf-formatting attributes. 13157 unsigned FormatIdx; 13158 bool HasVAListArg; 13159 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13160 if (!FD->hasAttr<FormatAttr>()) { 13161 const char *fmt = "printf"; 13162 unsigned int NumParams = FD->getNumParams(); 13163 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13164 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13165 fmt = "NSString"; 13166 FD->addAttr(FormatAttr::CreateImplicit(Context, 13167 &Context.Idents.get(fmt), 13168 FormatIdx+1, 13169 HasVAListArg ? 0 : FormatIdx+2, 13170 FD->getLocation())); 13171 } 13172 } 13173 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13174 HasVAListArg)) { 13175 if (!FD->hasAttr<FormatAttr>()) 13176 FD->addAttr(FormatAttr::CreateImplicit(Context, 13177 &Context.Idents.get("scanf"), 13178 FormatIdx+1, 13179 HasVAListArg ? 0 : FormatIdx+2, 13180 FD->getLocation())); 13181 } 13182 13183 // Mark const if we don't care about errno and that is the only thing 13184 // preventing the function from being const. This allows IRgen to use LLVM 13185 // intrinsics for such functions. 13186 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13187 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13188 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13189 13190 // We make "fma" on some platforms const because we know it does not set 13191 // errno in those environments even though it could set errno based on the 13192 // C standard. 13193 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13194 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13195 !FD->hasAttr<ConstAttr>()) { 13196 switch (BuiltinID) { 13197 case Builtin::BI__builtin_fma: 13198 case Builtin::BI__builtin_fmaf: 13199 case Builtin::BI__builtin_fmal: 13200 case Builtin::BIfma: 13201 case Builtin::BIfmaf: 13202 case Builtin::BIfmal: 13203 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13204 break; 13205 default: 13206 break; 13207 } 13208 } 13209 13210 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13211 !FD->hasAttr<ReturnsTwiceAttr>()) 13212 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13213 FD->getLocation())); 13214 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13215 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13216 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13217 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13218 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13219 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13220 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13221 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13222 // Add the appropriate attribute, depending on the CUDA compilation mode 13223 // and which target the builtin belongs to. For example, during host 13224 // compilation, aux builtins are __device__, while the rest are __host__. 13225 if (getLangOpts().CUDAIsDevice != 13226 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13227 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13228 else 13229 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13230 } 13231 } 13232 13233 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13234 // throw, add an implicit nothrow attribute to any extern "C" function we come 13235 // across. 13236 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13237 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13238 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13239 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13240 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13241 } 13242 13243 IdentifierInfo *Name = FD->getIdentifier(); 13244 if (!Name) 13245 return; 13246 if ((!getLangOpts().CPlusPlus && 13247 FD->getDeclContext()->isTranslationUnit()) || 13248 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13249 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13250 LinkageSpecDecl::lang_c)) { 13251 // Okay: this could be a libc/libm/Objective-C function we know 13252 // about. 13253 } else 13254 return; 13255 13256 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13257 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13258 // target-specific builtins, perhaps? 13259 if (!FD->hasAttr<FormatAttr>()) 13260 FD->addAttr(FormatAttr::CreateImplicit(Context, 13261 &Context.Idents.get("printf"), 2, 13262 Name->isStr("vasprintf") ? 0 : 3, 13263 FD->getLocation())); 13264 } 13265 13266 if (Name->isStr("__CFStringMakeConstantString")) { 13267 // We already have a __builtin___CFStringMakeConstantString, 13268 // but builds that use -fno-constant-cfstrings don't go through that. 13269 if (!FD->hasAttr<FormatArgAttr>()) 13270 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13271 FD->getLocation())); 13272 } 13273 } 13274 13275 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13276 TypeSourceInfo *TInfo) { 13277 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13278 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13279 13280 if (!TInfo) { 13281 assert(D.isInvalidType() && "no declarator info for valid type"); 13282 TInfo = Context.getTrivialTypeSourceInfo(T); 13283 } 13284 13285 // Scope manipulation handled by caller. 13286 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 13287 D.getLocStart(), 13288 D.getIdentifierLoc(), 13289 D.getIdentifier(), 13290 TInfo); 13291 13292 // Bail out immediately if we have an invalid declaration. 13293 if (D.isInvalidType()) { 13294 NewTD->setInvalidDecl(); 13295 return NewTD; 13296 } 13297 13298 if (D.getDeclSpec().isModulePrivateSpecified()) { 13299 if (CurContext->isFunctionOrMethod()) 13300 Diag(NewTD->getLocation(), diag::err_module_private_local) 13301 << 2 << NewTD->getDeclName() 13302 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13303 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13304 else 13305 NewTD->setModulePrivate(); 13306 } 13307 13308 // C++ [dcl.typedef]p8: 13309 // If the typedef declaration defines an unnamed class (or 13310 // enum), the first typedef-name declared by the declaration 13311 // to be that class type (or enum type) is used to denote the 13312 // class type (or enum type) for linkage purposes only. 13313 // We need to check whether the type was declared in the declaration. 13314 switch (D.getDeclSpec().getTypeSpecType()) { 13315 case TST_enum: 13316 case TST_struct: 13317 case TST_interface: 13318 case TST_union: 13319 case TST_class: { 13320 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13321 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13322 break; 13323 } 13324 13325 default: 13326 break; 13327 } 13328 13329 return NewTD; 13330 } 13331 13332 /// Check that this is a valid underlying type for an enum declaration. 13333 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13334 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13335 QualType T = TI->getType(); 13336 13337 if (T->isDependentType()) 13338 return false; 13339 13340 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13341 if (BT->isInteger()) 13342 return false; 13343 13344 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13345 return true; 13346 } 13347 13348 /// Check whether this is a valid redeclaration of a previous enumeration. 13349 /// \return true if the redeclaration was invalid. 13350 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13351 QualType EnumUnderlyingTy, bool IsFixed, 13352 const EnumDecl *Prev) { 13353 if (IsScoped != Prev->isScoped()) { 13354 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13355 << Prev->isScoped(); 13356 Diag(Prev->getLocation(), diag::note_previous_declaration); 13357 return true; 13358 } 13359 13360 if (IsFixed && Prev->isFixed()) { 13361 if (!EnumUnderlyingTy->isDependentType() && 13362 !Prev->getIntegerType()->isDependentType() && 13363 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13364 Prev->getIntegerType())) { 13365 // TODO: Highlight the underlying type of the redeclaration. 13366 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13367 << EnumUnderlyingTy << Prev->getIntegerType(); 13368 Diag(Prev->getLocation(), diag::note_previous_declaration) 13369 << Prev->getIntegerTypeRange(); 13370 return true; 13371 } 13372 } else if (IsFixed != Prev->isFixed()) { 13373 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13374 << Prev->isFixed(); 13375 Diag(Prev->getLocation(), diag::note_previous_declaration); 13376 return true; 13377 } 13378 13379 return false; 13380 } 13381 13382 /// Get diagnostic %select index for tag kind for 13383 /// redeclaration diagnostic message. 13384 /// WARNING: Indexes apply to particular diagnostics only! 13385 /// 13386 /// \returns diagnostic %select index. 13387 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13388 switch (Tag) { 13389 case TTK_Struct: return 0; 13390 case TTK_Interface: return 1; 13391 case TTK_Class: return 2; 13392 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13393 } 13394 } 13395 13396 /// Determine if tag kind is a class-key compatible with 13397 /// class for redeclaration (class, struct, or __interface). 13398 /// 13399 /// \returns true iff the tag kind is compatible. 13400 static bool isClassCompatTagKind(TagTypeKind Tag) 13401 { 13402 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13403 } 13404 13405 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13406 TagTypeKind TTK) { 13407 if (isa<TypedefDecl>(PrevDecl)) 13408 return NTK_Typedef; 13409 else if (isa<TypeAliasDecl>(PrevDecl)) 13410 return NTK_TypeAlias; 13411 else if (isa<ClassTemplateDecl>(PrevDecl)) 13412 return NTK_Template; 13413 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13414 return NTK_TypeAliasTemplate; 13415 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13416 return NTK_TemplateTemplateArgument; 13417 switch (TTK) { 13418 case TTK_Struct: 13419 case TTK_Interface: 13420 case TTK_Class: 13421 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13422 case TTK_Union: 13423 return NTK_NonUnion; 13424 case TTK_Enum: 13425 return NTK_NonEnum; 13426 } 13427 llvm_unreachable("invalid TTK"); 13428 } 13429 13430 /// Determine whether a tag with a given kind is acceptable 13431 /// as a redeclaration of the given tag declaration. 13432 /// 13433 /// \returns true if the new tag kind is acceptable, false otherwise. 13434 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13435 TagTypeKind NewTag, bool isDefinition, 13436 SourceLocation NewTagLoc, 13437 const IdentifierInfo *Name) { 13438 // C++ [dcl.type.elab]p3: 13439 // The class-key or enum keyword present in the 13440 // elaborated-type-specifier shall agree in kind with the 13441 // declaration to which the name in the elaborated-type-specifier 13442 // refers. This rule also applies to the form of 13443 // elaborated-type-specifier that declares a class-name or 13444 // friend class since it can be construed as referring to the 13445 // definition of the class. Thus, in any 13446 // elaborated-type-specifier, the enum keyword shall be used to 13447 // refer to an enumeration (7.2), the union class-key shall be 13448 // used to refer to a union (clause 9), and either the class or 13449 // struct class-key shall be used to refer to a class (clause 9) 13450 // declared using the class or struct class-key. 13451 TagTypeKind OldTag = Previous->getTagKind(); 13452 if (!isDefinition || !isClassCompatTagKind(NewTag)) 13453 if (OldTag == NewTag) 13454 return true; 13455 13456 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13457 // Warn about the struct/class tag mismatch. 13458 bool isTemplate = false; 13459 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13460 isTemplate = Record->getDescribedClassTemplate(); 13461 13462 if (inTemplateInstantiation()) { 13463 // In a template instantiation, do not offer fix-its for tag mismatches 13464 // since they usually mess up the template instead of fixing the problem. 13465 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13466 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13467 << getRedeclDiagFromTagKind(OldTag); 13468 return true; 13469 } 13470 13471 if (isDefinition) { 13472 // On definitions, check previous tags and issue a fix-it for each 13473 // one that doesn't match the current tag. 13474 if (Previous->getDefinition()) { 13475 // Don't suggest fix-its for redefinitions. 13476 return true; 13477 } 13478 13479 bool previousMismatch = false; 13480 for (auto I : Previous->redecls()) { 13481 if (I->getTagKind() != NewTag) { 13482 if (!previousMismatch) { 13483 previousMismatch = true; 13484 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13485 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13486 << getRedeclDiagFromTagKind(I->getTagKind()); 13487 } 13488 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13489 << getRedeclDiagFromTagKind(NewTag) 13490 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13491 TypeWithKeyword::getTagTypeKindName(NewTag)); 13492 } 13493 } 13494 return true; 13495 } 13496 13497 // Check for a previous definition. If current tag and definition 13498 // are same type, do nothing. If no definition, but disagree with 13499 // with previous tag type, give a warning, but no fix-it. 13500 const TagDecl *Redecl = Previous->getDefinition() ? 13501 Previous->getDefinition() : Previous; 13502 if (Redecl->getTagKind() == NewTag) { 13503 return true; 13504 } 13505 13506 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13507 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13508 << getRedeclDiagFromTagKind(OldTag); 13509 Diag(Redecl->getLocation(), diag::note_previous_use); 13510 13511 // If there is a previous definition, suggest a fix-it. 13512 if (Previous->getDefinition()) { 13513 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13514 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13515 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13516 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13517 } 13518 13519 return true; 13520 } 13521 return false; 13522 } 13523 13524 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13525 /// from an outer enclosing namespace or file scope inside a friend declaration. 13526 /// This should provide the commented out code in the following snippet: 13527 /// namespace N { 13528 /// struct X; 13529 /// namespace M { 13530 /// struct Y { friend struct /*N::*/ X; }; 13531 /// } 13532 /// } 13533 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13534 SourceLocation NameLoc) { 13535 // While the decl is in a namespace, do repeated lookup of that name and see 13536 // if we get the same namespace back. If we do not, continue until 13537 // translation unit scope, at which point we have a fully qualified NNS. 13538 SmallVector<IdentifierInfo *, 4> Namespaces; 13539 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13540 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13541 // This tag should be declared in a namespace, which can only be enclosed by 13542 // other namespaces. Bail if there's an anonymous namespace in the chain. 13543 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13544 if (!Namespace || Namespace->isAnonymousNamespace()) 13545 return FixItHint(); 13546 IdentifierInfo *II = Namespace->getIdentifier(); 13547 Namespaces.push_back(II); 13548 NamedDecl *Lookup = SemaRef.LookupSingleName( 13549 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13550 if (Lookup == Namespace) 13551 break; 13552 } 13553 13554 // Once we have all the namespaces, reverse them to go outermost first, and 13555 // build an NNS. 13556 SmallString<64> Insertion; 13557 llvm::raw_svector_ostream OS(Insertion); 13558 if (DC->isTranslationUnit()) 13559 OS << "::"; 13560 std::reverse(Namespaces.begin(), Namespaces.end()); 13561 for (auto *II : Namespaces) 13562 OS << II->getName() << "::"; 13563 return FixItHint::CreateInsertion(NameLoc, Insertion); 13564 } 13565 13566 /// Determine whether a tag originally declared in context \p OldDC can 13567 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 13568 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13569 /// using-declaration). 13570 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13571 DeclContext *NewDC) { 13572 OldDC = OldDC->getRedeclContext(); 13573 NewDC = NewDC->getRedeclContext(); 13574 13575 if (OldDC->Equals(NewDC)) 13576 return true; 13577 13578 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13579 // encloses the other). 13580 if (S.getLangOpts().MSVCCompat && 13581 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13582 return true; 13583 13584 return false; 13585 } 13586 13587 /// This is invoked when we see 'struct foo' or 'struct {'. In the 13588 /// former case, Name will be non-null. In the later case, Name will be null. 13589 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13590 /// reference/declaration/definition of a tag. 13591 /// 13592 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13593 /// trailing-type-specifier) other than one in an alias-declaration. 13594 /// 13595 /// \param SkipBody If non-null, will be set to indicate if the caller should 13596 /// skip the definition of this tag and treat it as if it were a declaration. 13597 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13598 SourceLocation KWLoc, CXXScopeSpec &SS, 13599 IdentifierInfo *Name, SourceLocation NameLoc, 13600 const ParsedAttributesView &Attrs, AccessSpecifier AS, 13601 SourceLocation ModulePrivateLoc, 13602 MultiTemplateParamsArg TemplateParameterLists, 13603 bool &OwnedDecl, bool &IsDependent, 13604 SourceLocation ScopedEnumKWLoc, 13605 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 13606 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13607 SkipBodyInfo *SkipBody) { 13608 // If this is not a definition, it must have a name. 13609 IdentifierInfo *OrigName = Name; 13610 assert((Name != nullptr || TUK == TUK_Definition) && 13611 "Nameless record must be a definition!"); 13612 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13613 13614 OwnedDecl = false; 13615 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13616 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13617 13618 // FIXME: Check member specializations more carefully. 13619 bool isMemberSpecialization = false; 13620 bool Invalid = false; 13621 13622 // We only need to do this matching if we have template parameters 13623 // or a scope specifier, which also conveniently avoids this work 13624 // for non-C++ cases. 13625 if (TemplateParameterLists.size() > 0 || 13626 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13627 if (TemplateParameterList *TemplateParams = 13628 MatchTemplateParametersToScopeSpecifier( 13629 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13630 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13631 if (Kind == TTK_Enum) { 13632 Diag(KWLoc, diag::err_enum_template); 13633 return nullptr; 13634 } 13635 13636 if (TemplateParams->size() > 0) { 13637 // This is a declaration or definition of a class template (which may 13638 // be a member of another template). 13639 13640 if (Invalid) 13641 return nullptr; 13642 13643 OwnedDecl = false; 13644 DeclResult Result = CheckClassTemplate( 13645 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 13646 AS, ModulePrivateLoc, 13647 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 13648 TemplateParameterLists.data(), SkipBody); 13649 return Result.get(); 13650 } else { 13651 // The "template<>" header is extraneous. 13652 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13653 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13654 isMemberSpecialization = true; 13655 } 13656 } 13657 } 13658 13659 // Figure out the underlying type if this a enum declaration. We need to do 13660 // this early, because it's needed to detect if this is an incompatible 13661 // redeclaration. 13662 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13663 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 13664 13665 if (Kind == TTK_Enum) { 13666 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 13667 // No underlying type explicitly specified, or we failed to parse the 13668 // type, default to int. 13669 EnumUnderlying = Context.IntTy.getTypePtr(); 13670 } else if (UnderlyingType.get()) { 13671 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13672 // integral type; any cv-qualification is ignored. 13673 TypeSourceInfo *TI = nullptr; 13674 GetTypeFromParser(UnderlyingType.get(), &TI); 13675 EnumUnderlying = TI; 13676 13677 if (CheckEnumUnderlyingType(TI)) 13678 // Recover by falling back to int. 13679 EnumUnderlying = Context.IntTy.getTypePtr(); 13680 13681 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13682 UPPC_FixedUnderlyingType)) 13683 EnumUnderlying = Context.IntTy.getTypePtr(); 13684 13685 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13686 // For MSVC ABI compatibility, unfixed enums must use an underlying type 13687 // of 'int'. However, if this is an unfixed forward declaration, don't set 13688 // the underlying type unless the user enables -fms-compatibility. This 13689 // makes unfixed forward declared enums incomplete and is more conforming. 13690 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 13691 EnumUnderlying = Context.IntTy.getTypePtr(); 13692 } 13693 } 13694 13695 DeclContext *SearchDC = CurContext; 13696 DeclContext *DC = CurContext; 13697 bool isStdBadAlloc = false; 13698 bool isStdAlignValT = false; 13699 13700 RedeclarationKind Redecl = forRedeclarationInCurContext(); 13701 if (TUK == TUK_Friend || TUK == TUK_Reference) 13702 Redecl = NotForRedeclaration; 13703 13704 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13705 /// implemented asks for structural equivalence checking, the returned decl 13706 /// here is passed back to the parser, allowing the tag body to be parsed. 13707 auto createTagFromNewDecl = [&]() -> TagDecl * { 13708 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13709 // If there is an identifier, use the location of the identifier as the 13710 // location of the decl, otherwise use the location of the struct/union 13711 // keyword. 13712 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13713 TagDecl *New = nullptr; 13714 13715 if (Kind == TTK_Enum) { 13716 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13717 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 13718 // If this is an undefined enum, bail. 13719 if (TUK != TUK_Definition && !Invalid) 13720 return nullptr; 13721 if (EnumUnderlying) { 13722 EnumDecl *ED = cast<EnumDecl>(New); 13723 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13724 ED->setIntegerTypeSourceInfo(TI); 13725 else 13726 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13727 ED->setPromotionType(ED->getIntegerType()); 13728 } 13729 } else { // struct/union 13730 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13731 nullptr); 13732 } 13733 13734 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13735 // Add alignment attributes if necessary; these attributes are checked 13736 // when the ASTContext lays out the structure. 13737 // 13738 // It is important for implementing the correct semantics that this 13739 // happen here (in ActOnTag). The #pragma pack stack is 13740 // maintained as a result of parser callbacks which can occur at 13741 // many points during the parsing of a struct declaration (because 13742 // the #pragma tokens are effectively skipped over during the 13743 // parsing of the struct). 13744 if (TUK == TUK_Definition) { 13745 AddAlignmentAttributesForRecord(RD); 13746 AddMsStructLayoutForRecord(RD); 13747 } 13748 } 13749 New->setLexicalDeclContext(CurContext); 13750 return New; 13751 }; 13752 13753 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13754 if (Name && SS.isNotEmpty()) { 13755 // We have a nested-name tag ('struct foo::bar'). 13756 13757 // Check for invalid 'foo::'. 13758 if (SS.isInvalid()) { 13759 Name = nullptr; 13760 goto CreateNewDecl; 13761 } 13762 13763 // If this is a friend or a reference to a class in a dependent 13764 // context, don't try to make a decl for it. 13765 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13766 DC = computeDeclContext(SS, false); 13767 if (!DC) { 13768 IsDependent = true; 13769 return nullptr; 13770 } 13771 } else { 13772 DC = computeDeclContext(SS, true); 13773 if (!DC) { 13774 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13775 << SS.getRange(); 13776 return nullptr; 13777 } 13778 } 13779 13780 if (RequireCompleteDeclContext(SS, DC)) 13781 return nullptr; 13782 13783 SearchDC = DC; 13784 // Look-up name inside 'foo::'. 13785 LookupQualifiedName(Previous, DC); 13786 13787 if (Previous.isAmbiguous()) 13788 return nullptr; 13789 13790 if (Previous.empty()) { 13791 // Name lookup did not find anything. However, if the 13792 // nested-name-specifier refers to the current instantiation, 13793 // and that current instantiation has any dependent base 13794 // classes, we might find something at instantiation time: treat 13795 // this as a dependent elaborated-type-specifier. 13796 // But this only makes any sense for reference-like lookups. 13797 if (Previous.wasNotFoundInCurrentInstantiation() && 13798 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13799 IsDependent = true; 13800 return nullptr; 13801 } 13802 13803 // A tag 'foo::bar' must already exist. 13804 Diag(NameLoc, diag::err_not_tag_in_scope) 13805 << Kind << Name << DC << SS.getRange(); 13806 Name = nullptr; 13807 Invalid = true; 13808 goto CreateNewDecl; 13809 } 13810 } else if (Name) { 13811 // C++14 [class.mem]p14: 13812 // If T is the name of a class, then each of the following shall have a 13813 // name different from T: 13814 // -- every member of class T that is itself a type 13815 if (TUK != TUK_Reference && TUK != TUK_Friend && 13816 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13817 return nullptr; 13818 13819 // If this is a named struct, check to see if there was a previous forward 13820 // declaration or definition. 13821 // FIXME: We're looking into outer scopes here, even when we 13822 // shouldn't be. Doing so can result in ambiguities that we 13823 // shouldn't be diagnosing. 13824 LookupName(Previous, S); 13825 13826 // When declaring or defining a tag, ignore ambiguities introduced 13827 // by types using'ed into this scope. 13828 if (Previous.isAmbiguous() && 13829 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13830 LookupResult::Filter F = Previous.makeFilter(); 13831 while (F.hasNext()) { 13832 NamedDecl *ND = F.next(); 13833 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13834 SearchDC->getRedeclContext())) 13835 F.erase(); 13836 } 13837 F.done(); 13838 } 13839 13840 // C++11 [namespace.memdef]p3: 13841 // If the name in a friend declaration is neither qualified nor 13842 // a template-id and the declaration is a function or an 13843 // elaborated-type-specifier, the lookup to determine whether 13844 // the entity has been previously declared shall not consider 13845 // any scopes outside the innermost enclosing namespace. 13846 // 13847 // MSVC doesn't implement the above rule for types, so a friend tag 13848 // declaration may be a redeclaration of a type declared in an enclosing 13849 // scope. They do implement this rule for friend functions. 13850 // 13851 // Does it matter that this should be by scope instead of by 13852 // semantic context? 13853 if (!Previous.empty() && TUK == TUK_Friend) { 13854 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13855 LookupResult::Filter F = Previous.makeFilter(); 13856 bool FriendSawTagOutsideEnclosingNamespace = false; 13857 while (F.hasNext()) { 13858 NamedDecl *ND = F.next(); 13859 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13860 if (DC->isFileContext() && 13861 !EnclosingNS->Encloses(ND->getDeclContext())) { 13862 if (getLangOpts().MSVCCompat) 13863 FriendSawTagOutsideEnclosingNamespace = true; 13864 else 13865 F.erase(); 13866 } 13867 } 13868 F.done(); 13869 13870 // Diagnose this MSVC extension in the easy case where lookup would have 13871 // unambiguously found something outside the enclosing namespace. 13872 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13873 NamedDecl *ND = Previous.getFoundDecl(); 13874 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13875 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13876 } 13877 } 13878 13879 // Note: there used to be some attempt at recovery here. 13880 if (Previous.isAmbiguous()) 13881 return nullptr; 13882 13883 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13884 // FIXME: This makes sure that we ignore the contexts associated 13885 // with C structs, unions, and enums when looking for a matching 13886 // tag declaration or definition. See the similar lookup tweak 13887 // in Sema::LookupName; is there a better way to deal with this? 13888 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13889 SearchDC = SearchDC->getParent(); 13890 } 13891 } 13892 13893 if (Previous.isSingleResult() && 13894 Previous.getFoundDecl()->isTemplateParameter()) { 13895 // Maybe we will complain about the shadowed template parameter. 13896 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13897 // Just pretend that we didn't see the previous declaration. 13898 Previous.clear(); 13899 } 13900 13901 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13902 DC->Equals(getStdNamespace())) { 13903 if (Name->isStr("bad_alloc")) { 13904 // This is a declaration of or a reference to "std::bad_alloc". 13905 isStdBadAlloc = true; 13906 13907 // If std::bad_alloc has been implicitly declared (but made invisible to 13908 // name lookup), fill in this implicit declaration as the previous 13909 // declaration, so that the declarations get chained appropriately. 13910 if (Previous.empty() && StdBadAlloc) 13911 Previous.addDecl(getStdBadAlloc()); 13912 } else if (Name->isStr("align_val_t")) { 13913 isStdAlignValT = true; 13914 if (Previous.empty() && StdAlignValT) 13915 Previous.addDecl(getStdAlignValT()); 13916 } 13917 } 13918 13919 // If we didn't find a previous declaration, and this is a reference 13920 // (or friend reference), move to the correct scope. In C++, we 13921 // also need to do a redeclaration lookup there, just in case 13922 // there's a shadow friend decl. 13923 if (Name && Previous.empty() && 13924 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13925 if (Invalid) goto CreateNewDecl; 13926 assert(SS.isEmpty()); 13927 13928 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13929 // C++ [basic.scope.pdecl]p5: 13930 // -- for an elaborated-type-specifier of the form 13931 // 13932 // class-key identifier 13933 // 13934 // if the elaborated-type-specifier is used in the 13935 // decl-specifier-seq or parameter-declaration-clause of a 13936 // function defined in namespace scope, the identifier is 13937 // declared as a class-name in the namespace that contains 13938 // the declaration; otherwise, except as a friend 13939 // declaration, the identifier is declared in the smallest 13940 // non-class, non-function-prototype scope that contains the 13941 // declaration. 13942 // 13943 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13944 // C structs and unions. 13945 // 13946 // It is an error in C++ to declare (rather than define) an enum 13947 // type, including via an elaborated type specifier. We'll 13948 // diagnose that later; for now, declare the enum in the same 13949 // scope as we would have picked for any other tag type. 13950 // 13951 // GNU C also supports this behavior as part of its incomplete 13952 // enum types extension, while GNU C++ does not. 13953 // 13954 // Find the context where we'll be declaring the tag. 13955 // FIXME: We would like to maintain the current DeclContext as the 13956 // lexical context, 13957 SearchDC = getTagInjectionContext(SearchDC); 13958 13959 // Find the scope where we'll be declaring the tag. 13960 S = getTagInjectionScope(S, getLangOpts()); 13961 } else { 13962 assert(TUK == TUK_Friend); 13963 // C++ [namespace.memdef]p3: 13964 // If a friend declaration in a non-local class first declares a 13965 // class or function, the friend class or function is a member of 13966 // the innermost enclosing namespace. 13967 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13968 } 13969 13970 // In C++, we need to do a redeclaration lookup to properly 13971 // diagnose some problems. 13972 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13973 // hidden declaration so that we don't get ambiguity errors when using a 13974 // type declared by an elaborated-type-specifier. In C that is not correct 13975 // and we should instead merge compatible types found by lookup. 13976 if (getLangOpts().CPlusPlus) { 13977 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13978 LookupQualifiedName(Previous, SearchDC); 13979 } else { 13980 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13981 LookupName(Previous, S); 13982 } 13983 } 13984 13985 // If we have a known previous declaration to use, then use it. 13986 if (Previous.empty() && SkipBody && SkipBody->Previous) 13987 Previous.addDecl(SkipBody->Previous); 13988 13989 if (!Previous.empty()) { 13990 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13991 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13992 13993 // It's okay to have a tag decl in the same scope as a typedef 13994 // which hides a tag decl in the same scope. Finding this 13995 // insanity with a redeclaration lookup can only actually happen 13996 // in C++. 13997 // 13998 // This is also okay for elaborated-type-specifiers, which is 13999 // technically forbidden by the current standard but which is 14000 // okay according to the likely resolution of an open issue; 14001 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 14002 if (getLangOpts().CPlusPlus) { 14003 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14004 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 14005 TagDecl *Tag = TT->getDecl(); 14006 if (Tag->getDeclName() == Name && 14007 Tag->getDeclContext()->getRedeclContext() 14008 ->Equals(TD->getDeclContext()->getRedeclContext())) { 14009 PrevDecl = Tag; 14010 Previous.clear(); 14011 Previous.addDecl(Tag); 14012 Previous.resolveKind(); 14013 } 14014 } 14015 } 14016 } 14017 14018 // If this is a redeclaration of a using shadow declaration, it must 14019 // declare a tag in the same context. In MSVC mode, we allow a 14020 // redefinition if either context is within the other. 14021 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 14022 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 14023 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 14024 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 14025 !(OldTag && isAcceptableTagRedeclContext( 14026 *this, OldTag->getDeclContext(), SearchDC))) { 14027 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 14028 Diag(Shadow->getTargetDecl()->getLocation(), 14029 diag::note_using_decl_target); 14030 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 14031 << 0; 14032 // Recover by ignoring the old declaration. 14033 Previous.clear(); 14034 goto CreateNewDecl; 14035 } 14036 } 14037 14038 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 14039 // If this is a use of a previous tag, or if the tag is already declared 14040 // in the same scope (so that the definition/declaration completes or 14041 // rementions the tag), reuse the decl. 14042 if (TUK == TUK_Reference || TUK == TUK_Friend || 14043 isDeclInScope(DirectPrevDecl, SearchDC, S, 14044 SS.isNotEmpty() || isMemberSpecialization)) { 14045 // Make sure that this wasn't declared as an enum and now used as a 14046 // struct or something similar. 14047 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14048 TUK == TUK_Definition, KWLoc, 14049 Name)) { 14050 bool SafeToContinue 14051 = (PrevTagDecl->getTagKind() != TTK_Enum && 14052 Kind != TTK_Enum); 14053 if (SafeToContinue) 14054 Diag(KWLoc, diag::err_use_with_wrong_tag) 14055 << Name 14056 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14057 PrevTagDecl->getKindName()); 14058 else 14059 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14060 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14061 14062 if (SafeToContinue) 14063 Kind = PrevTagDecl->getTagKind(); 14064 else { 14065 // Recover by making this an anonymous redefinition. 14066 Name = nullptr; 14067 Previous.clear(); 14068 Invalid = true; 14069 } 14070 } 14071 14072 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14073 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14074 14075 // If this is an elaborated-type-specifier for a scoped enumeration, 14076 // the 'class' keyword is not necessary and not permitted. 14077 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14078 if (ScopedEnum) 14079 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14080 << PrevEnum->isScoped() 14081 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14082 return PrevTagDecl; 14083 } 14084 14085 QualType EnumUnderlyingTy; 14086 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14087 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14088 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14089 EnumUnderlyingTy = QualType(T, 0); 14090 14091 // All conflicts with previous declarations are recovered by 14092 // returning the previous declaration, unless this is a definition, 14093 // in which case we want the caller to bail out. 14094 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14095 ScopedEnum, EnumUnderlyingTy, 14096 IsFixed, PrevEnum)) 14097 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14098 } 14099 14100 // C++11 [class.mem]p1: 14101 // A member shall not be declared twice in the member-specification, 14102 // except that a nested class or member class template can be declared 14103 // and then later defined. 14104 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14105 S->isDeclScope(PrevDecl)) { 14106 Diag(NameLoc, diag::ext_member_redeclared); 14107 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14108 } 14109 14110 if (!Invalid) { 14111 // If this is a use, just return the declaration we found, unless 14112 // we have attributes. 14113 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14114 if (!Attrs.empty()) { 14115 // FIXME: Diagnose these attributes. For now, we create a new 14116 // declaration to hold them. 14117 } else if (TUK == TUK_Reference && 14118 (PrevTagDecl->getFriendObjectKind() == 14119 Decl::FOK_Undeclared || 14120 PrevDecl->getOwningModule() != getCurrentModule()) && 14121 SS.isEmpty()) { 14122 // This declaration is a reference to an existing entity, but 14123 // has different visibility from that entity: it either makes 14124 // a friend visible or it makes a type visible in a new module. 14125 // In either case, create a new declaration. We only do this if 14126 // the declaration would have meant the same thing if no prior 14127 // declaration were found, that is, if it was found in the same 14128 // scope where we would have injected a declaration. 14129 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14130 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14131 return PrevTagDecl; 14132 // This is in the injected scope, create a new declaration in 14133 // that scope. 14134 S = getTagInjectionScope(S, getLangOpts()); 14135 } else { 14136 return PrevTagDecl; 14137 } 14138 } 14139 14140 // Diagnose attempts to redefine a tag. 14141 if (TUK == TUK_Definition) { 14142 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14143 // If we're defining a specialization and the previous definition 14144 // is from an implicit instantiation, don't emit an error 14145 // here; we'll catch this in the general case below. 14146 bool IsExplicitSpecializationAfterInstantiation = false; 14147 if (isMemberSpecialization) { 14148 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14149 IsExplicitSpecializationAfterInstantiation = 14150 RD->getTemplateSpecializationKind() != 14151 TSK_ExplicitSpecialization; 14152 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14153 IsExplicitSpecializationAfterInstantiation = 14154 ED->getTemplateSpecializationKind() != 14155 TSK_ExplicitSpecialization; 14156 } 14157 14158 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14159 // not keep more that one definition around (merge them). However, 14160 // ensure the decl passes the structural compatibility check in 14161 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14162 NamedDecl *Hidden = nullptr; 14163 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14164 // There is a definition of this tag, but it is not visible. We 14165 // explicitly make use of C++'s one definition rule here, and 14166 // assume that this definition is identical to the hidden one 14167 // we already have. Make the existing definition visible and 14168 // use it in place of this one. 14169 if (!getLangOpts().CPlusPlus) { 14170 // Postpone making the old definition visible until after we 14171 // complete parsing the new one and do the structural 14172 // comparison. 14173 SkipBody->CheckSameAsPrevious = true; 14174 SkipBody->New = createTagFromNewDecl(); 14175 SkipBody->Previous = Hidden; 14176 } else { 14177 SkipBody->ShouldSkip = true; 14178 makeMergedDefinitionVisible(Hidden); 14179 } 14180 return Def; 14181 } else if (!IsExplicitSpecializationAfterInstantiation) { 14182 // A redeclaration in function prototype scope in C isn't 14183 // visible elsewhere, so merely issue a warning. 14184 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14185 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14186 else 14187 Diag(NameLoc, diag::err_redefinition) << Name; 14188 notePreviousDefinition(Def, 14189 NameLoc.isValid() ? NameLoc : KWLoc); 14190 // If this is a redefinition, recover by making this 14191 // struct be anonymous, which will make any later 14192 // references get the previous definition. 14193 Name = nullptr; 14194 Previous.clear(); 14195 Invalid = true; 14196 } 14197 } else { 14198 // If the type is currently being defined, complain 14199 // about a nested redefinition. 14200 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14201 if (TD->isBeingDefined()) { 14202 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14203 Diag(PrevTagDecl->getLocation(), 14204 diag::note_previous_definition); 14205 Name = nullptr; 14206 Previous.clear(); 14207 Invalid = true; 14208 } 14209 } 14210 14211 // Okay, this is definition of a previously declared or referenced 14212 // tag. We're going to create a new Decl for it. 14213 } 14214 14215 // Okay, we're going to make a redeclaration. If this is some kind 14216 // of reference, make sure we build the redeclaration in the same DC 14217 // as the original, and ignore the current access specifier. 14218 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14219 SearchDC = PrevTagDecl->getDeclContext(); 14220 AS = AS_none; 14221 } 14222 } 14223 // If we get here we have (another) forward declaration or we 14224 // have a definition. Just create a new decl. 14225 14226 } else { 14227 // If we get here, this is a definition of a new tag type in a nested 14228 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14229 // new decl/type. We set PrevDecl to NULL so that the entities 14230 // have distinct types. 14231 Previous.clear(); 14232 } 14233 // If we get here, we're going to create a new Decl. If PrevDecl 14234 // is non-NULL, it's a definition of the tag declared by 14235 // PrevDecl. If it's NULL, we have a new definition. 14236 14237 // Otherwise, PrevDecl is not a tag, but was found with tag 14238 // lookup. This is only actually possible in C++, where a few 14239 // things like templates still live in the tag namespace. 14240 } else { 14241 // Use a better diagnostic if an elaborated-type-specifier 14242 // found the wrong kind of type on the first 14243 // (non-redeclaration) lookup. 14244 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14245 !Previous.isForRedeclaration()) { 14246 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14247 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14248 << Kind; 14249 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14250 Invalid = true; 14251 14252 // Otherwise, only diagnose if the declaration is in scope. 14253 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14254 SS.isNotEmpty() || isMemberSpecialization)) { 14255 // do nothing 14256 14257 // Diagnose implicit declarations introduced by elaborated types. 14258 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14259 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14260 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14261 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14262 Invalid = true; 14263 14264 // Otherwise it's a declaration. Call out a particularly common 14265 // case here. 14266 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14267 unsigned Kind = 0; 14268 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14269 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14270 << Name << Kind << TND->getUnderlyingType(); 14271 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14272 Invalid = true; 14273 14274 // Otherwise, diagnose. 14275 } else { 14276 // The tag name clashes with something else in the target scope, 14277 // issue an error and recover by making this tag be anonymous. 14278 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14279 notePreviousDefinition(PrevDecl, NameLoc); 14280 Name = nullptr; 14281 Invalid = true; 14282 } 14283 14284 // The existing declaration isn't relevant to us; we're in a 14285 // new scope, so clear out the previous declaration. 14286 Previous.clear(); 14287 } 14288 } 14289 14290 CreateNewDecl: 14291 14292 TagDecl *PrevDecl = nullptr; 14293 if (Previous.isSingleResult()) 14294 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14295 14296 // If there is an identifier, use the location of the identifier as the 14297 // location of the decl, otherwise use the location of the struct/union 14298 // keyword. 14299 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14300 14301 // Otherwise, create a new declaration. If there is a previous 14302 // declaration of the same entity, the two will be linked via 14303 // PrevDecl. 14304 TagDecl *New; 14305 14306 if (Kind == TTK_Enum) { 14307 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14308 // enum X { A, B, C } D; D should chain to X. 14309 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14310 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14311 ScopedEnumUsesClassTag, IsFixed); 14312 14313 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14314 StdAlignValT = cast<EnumDecl>(New); 14315 14316 // If this is an undefined enum, warn. 14317 if (TUK != TUK_Definition && !Invalid) { 14318 TagDecl *Def; 14319 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 14320 cast<EnumDecl>(New)->isFixed()) { 14321 // C++0x: 7.2p2: opaque-enum-declaration. 14322 // Conflicts are diagnosed above. Do nothing. 14323 } 14324 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14325 Diag(Loc, diag::ext_forward_ref_enum_def) 14326 << New; 14327 Diag(Def->getLocation(), diag::note_previous_definition); 14328 } else { 14329 unsigned DiagID = diag::ext_forward_ref_enum; 14330 if (getLangOpts().MSVCCompat) 14331 DiagID = diag::ext_ms_forward_ref_enum; 14332 else if (getLangOpts().CPlusPlus) 14333 DiagID = diag::err_forward_ref_enum; 14334 Diag(Loc, DiagID); 14335 } 14336 } 14337 14338 if (EnumUnderlying) { 14339 EnumDecl *ED = cast<EnumDecl>(New); 14340 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14341 ED->setIntegerTypeSourceInfo(TI); 14342 else 14343 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14344 ED->setPromotionType(ED->getIntegerType()); 14345 assert(ED->isComplete() && "enum with type should be complete"); 14346 } 14347 } else { 14348 // struct/union/class 14349 14350 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14351 // struct X { int A; } D; D should chain to X. 14352 if (getLangOpts().CPlusPlus) { 14353 // FIXME: Look for a way to use RecordDecl for simple structs. 14354 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14355 cast_or_null<CXXRecordDecl>(PrevDecl)); 14356 14357 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14358 StdBadAlloc = cast<CXXRecordDecl>(New); 14359 } else 14360 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14361 cast_or_null<RecordDecl>(PrevDecl)); 14362 } 14363 14364 // C++11 [dcl.type]p3: 14365 // A type-specifier-seq shall not define a class or enumeration [...]. 14366 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14367 TUK == TUK_Definition) { 14368 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14369 << Context.getTagDeclType(New); 14370 Invalid = true; 14371 } 14372 14373 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14374 DC->getDeclKind() == Decl::Enum) { 14375 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14376 << Context.getTagDeclType(New); 14377 Invalid = true; 14378 } 14379 14380 // Maybe add qualifier info. 14381 if (SS.isNotEmpty()) { 14382 if (SS.isSet()) { 14383 // If this is either a declaration or a definition, check the 14384 // nested-name-specifier against the current context. 14385 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14386 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14387 isMemberSpecialization)) 14388 Invalid = true; 14389 14390 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14391 if (TemplateParameterLists.size() > 0) { 14392 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14393 } 14394 } 14395 else 14396 Invalid = true; 14397 } 14398 14399 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14400 // Add alignment attributes if necessary; these attributes are checked when 14401 // the ASTContext lays out the structure. 14402 // 14403 // It is important for implementing the correct semantics that this 14404 // happen here (in ActOnTag). The #pragma pack stack is 14405 // maintained as a result of parser callbacks which can occur at 14406 // many points during the parsing of a struct declaration (because 14407 // the #pragma tokens are effectively skipped over during the 14408 // parsing of the struct). 14409 if (TUK == TUK_Definition) { 14410 AddAlignmentAttributesForRecord(RD); 14411 AddMsStructLayoutForRecord(RD); 14412 } 14413 } 14414 14415 if (ModulePrivateLoc.isValid()) { 14416 if (isMemberSpecialization) 14417 Diag(New->getLocation(), diag::err_module_private_specialization) 14418 << 2 14419 << FixItHint::CreateRemoval(ModulePrivateLoc); 14420 // __module_private__ does not apply to local classes. However, we only 14421 // diagnose this as an error when the declaration specifiers are 14422 // freestanding. Here, we just ignore the __module_private__. 14423 else if (!SearchDC->isFunctionOrMethod()) 14424 New->setModulePrivate(); 14425 } 14426 14427 // If this is a specialization of a member class (of a class template), 14428 // check the specialization. 14429 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14430 Invalid = true; 14431 14432 // If we're declaring or defining a tag in function prototype scope in C, 14433 // note that this type can only be used within the function and add it to 14434 // the list of decls to inject into the function definition scope. 14435 if ((Name || Kind == TTK_Enum) && 14436 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14437 if (getLangOpts().CPlusPlus) { 14438 // C++ [dcl.fct]p6: 14439 // Types shall not be defined in return or parameter types. 14440 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14441 Diag(Loc, diag::err_type_defined_in_param_type) 14442 << Name; 14443 Invalid = true; 14444 } 14445 } else if (!PrevDecl) { 14446 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14447 } 14448 } 14449 14450 if (Invalid) 14451 New->setInvalidDecl(); 14452 14453 // Set the lexical context. If the tag has a C++ scope specifier, the 14454 // lexical context will be different from the semantic context. 14455 New->setLexicalDeclContext(CurContext); 14456 14457 // Mark this as a friend decl if applicable. 14458 // In Microsoft mode, a friend declaration also acts as a forward 14459 // declaration so we always pass true to setObjectOfFriendDecl to make 14460 // the tag name visible. 14461 if (TUK == TUK_Friend) 14462 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14463 14464 // Set the access specifier. 14465 if (!Invalid && SearchDC->isRecord()) 14466 SetMemberAccessSpecifier(New, PrevDecl, AS); 14467 14468 if (PrevDecl) 14469 CheckRedeclarationModuleOwnership(New, PrevDecl); 14470 14471 if (TUK == TUK_Definition) 14472 New->startDefinition(); 14473 14474 ProcessDeclAttributeList(S, New, Attrs); 14475 AddPragmaAttributes(S, New); 14476 14477 // If this has an identifier, add it to the scope stack. 14478 if (TUK == TUK_Friend) { 14479 // We might be replacing an existing declaration in the lookup tables; 14480 // if so, borrow its access specifier. 14481 if (PrevDecl) 14482 New->setAccess(PrevDecl->getAccess()); 14483 14484 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14485 DC->makeDeclVisibleInContext(New); 14486 if (Name) // can be null along some error paths 14487 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14488 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14489 } else if (Name) { 14490 S = getNonFieldDeclScope(S); 14491 PushOnScopeChains(New, S, true); 14492 } else { 14493 CurContext->addDecl(New); 14494 } 14495 14496 // If this is the C FILE type, notify the AST context. 14497 if (IdentifierInfo *II = New->getIdentifier()) 14498 if (!New->isInvalidDecl() && 14499 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14500 II->isStr("FILE")) 14501 Context.setFILEDecl(New); 14502 14503 if (PrevDecl) 14504 mergeDeclAttributes(New, PrevDecl); 14505 14506 // If there's a #pragma GCC visibility in scope, set the visibility of this 14507 // record. 14508 AddPushedVisibilityAttribute(New); 14509 14510 if (isMemberSpecialization && !New->isInvalidDecl()) 14511 CompleteMemberSpecialization(New, Previous); 14512 14513 OwnedDecl = true; 14514 // In C++, don't return an invalid declaration. We can't recover well from 14515 // the cases where we make the type anonymous. 14516 if (Invalid && getLangOpts().CPlusPlus) { 14517 if (New->isBeingDefined()) 14518 if (auto RD = dyn_cast<RecordDecl>(New)) 14519 RD->completeDefinition(); 14520 return nullptr; 14521 } else { 14522 return New; 14523 } 14524 } 14525 14526 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14527 AdjustDeclIfTemplate(TagD); 14528 TagDecl *Tag = cast<TagDecl>(TagD); 14529 14530 // Enter the tag context. 14531 PushDeclContext(S, Tag); 14532 14533 ActOnDocumentableDecl(TagD); 14534 14535 // If there's a #pragma GCC visibility in scope, set the visibility of this 14536 // record. 14537 AddPushedVisibilityAttribute(Tag); 14538 } 14539 14540 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14541 SkipBodyInfo &SkipBody) { 14542 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14543 return false; 14544 14545 // Make the previous decl visible. 14546 makeMergedDefinitionVisible(SkipBody.Previous); 14547 return true; 14548 } 14549 14550 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14551 assert(isa<ObjCContainerDecl>(IDecl) && 14552 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14553 DeclContext *OCD = cast<DeclContext>(IDecl); 14554 assert(getContainingDC(OCD) == CurContext && 14555 "The next DeclContext should be lexically contained in the current one."); 14556 CurContext = OCD; 14557 return IDecl; 14558 } 14559 14560 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14561 SourceLocation FinalLoc, 14562 bool IsFinalSpelledSealed, 14563 SourceLocation LBraceLoc) { 14564 AdjustDeclIfTemplate(TagD); 14565 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14566 14567 FieldCollector->StartClass(); 14568 14569 if (!Record->getIdentifier()) 14570 return; 14571 14572 if (FinalLoc.isValid()) 14573 Record->addAttr(new (Context) 14574 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14575 14576 // C++ [class]p2: 14577 // [...] The class-name is also inserted into the scope of the 14578 // class itself; this is known as the injected-class-name. For 14579 // purposes of access checking, the injected-class-name is treated 14580 // as if it were a public member name. 14581 CXXRecordDecl *InjectedClassName 14582 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14583 Record->getLocStart(), Record->getLocation(), 14584 Record->getIdentifier(), 14585 /*PrevDecl=*/nullptr, 14586 /*DelayTypeCreation=*/true); 14587 Context.getTypeDeclType(InjectedClassName, Record); 14588 InjectedClassName->setImplicit(); 14589 InjectedClassName->setAccess(AS_public); 14590 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14591 InjectedClassName->setDescribedClassTemplate(Template); 14592 PushOnScopeChains(InjectedClassName, S); 14593 assert(InjectedClassName->isInjectedClassName() && 14594 "Broken injected-class-name"); 14595 } 14596 14597 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14598 SourceRange BraceRange) { 14599 AdjustDeclIfTemplate(TagD); 14600 TagDecl *Tag = cast<TagDecl>(TagD); 14601 Tag->setBraceRange(BraceRange); 14602 14603 // Make sure we "complete" the definition even it is invalid. 14604 if (Tag->isBeingDefined()) { 14605 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14606 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14607 RD->completeDefinition(); 14608 } 14609 14610 if (isa<CXXRecordDecl>(Tag)) { 14611 FieldCollector->FinishClass(); 14612 } 14613 14614 // Exit this scope of this tag's definition. 14615 PopDeclContext(); 14616 14617 if (getCurLexicalContext()->isObjCContainer() && 14618 Tag->getDeclContext()->isFileContext()) 14619 Tag->setTopLevelDeclInObjCContainer(); 14620 14621 // Notify the consumer that we've defined a tag. 14622 if (!Tag->isInvalidDecl()) 14623 Consumer.HandleTagDeclDefinition(Tag); 14624 } 14625 14626 void Sema::ActOnObjCContainerFinishDefinition() { 14627 // Exit this scope of this interface definition. 14628 PopDeclContext(); 14629 } 14630 14631 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14632 assert(DC == CurContext && "Mismatch of container contexts"); 14633 OriginalLexicalContext = DC; 14634 ActOnObjCContainerFinishDefinition(); 14635 } 14636 14637 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14638 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14639 OriginalLexicalContext = nullptr; 14640 } 14641 14642 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14643 AdjustDeclIfTemplate(TagD); 14644 TagDecl *Tag = cast<TagDecl>(TagD); 14645 Tag->setInvalidDecl(); 14646 14647 // Make sure we "complete" the definition even it is invalid. 14648 if (Tag->isBeingDefined()) { 14649 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14650 RD->completeDefinition(); 14651 } 14652 14653 // We're undoing ActOnTagStartDefinition here, not 14654 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14655 // the FieldCollector. 14656 14657 PopDeclContext(); 14658 } 14659 14660 // Note that FieldName may be null for anonymous bitfields. 14661 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14662 IdentifierInfo *FieldName, 14663 QualType FieldTy, bool IsMsStruct, 14664 Expr *BitWidth, bool *ZeroWidth) { 14665 // Default to true; that shouldn't confuse checks for emptiness 14666 if (ZeroWidth) 14667 *ZeroWidth = true; 14668 14669 // C99 6.7.2.1p4 - verify the field type. 14670 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14671 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14672 // Handle incomplete types with specific error. 14673 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14674 return ExprError(); 14675 if (FieldName) 14676 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14677 << FieldName << FieldTy << BitWidth->getSourceRange(); 14678 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14679 << FieldTy << BitWidth->getSourceRange(); 14680 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14681 UPPC_BitFieldWidth)) 14682 return ExprError(); 14683 14684 // If the bit-width is type- or value-dependent, don't try to check 14685 // it now. 14686 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14687 return BitWidth; 14688 14689 llvm::APSInt Value; 14690 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14691 if (ICE.isInvalid()) 14692 return ICE; 14693 BitWidth = ICE.get(); 14694 14695 if (Value != 0 && ZeroWidth) 14696 *ZeroWidth = false; 14697 14698 // Zero-width bitfield is ok for anonymous field. 14699 if (Value == 0 && FieldName) 14700 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14701 14702 if (Value.isSigned() && Value.isNegative()) { 14703 if (FieldName) 14704 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14705 << FieldName << Value.toString(10); 14706 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14707 << Value.toString(10); 14708 } 14709 14710 if (!FieldTy->isDependentType()) { 14711 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14712 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14713 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14714 14715 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14716 // ABI. 14717 bool CStdConstraintViolation = 14718 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14719 bool MSBitfieldViolation = 14720 Value.ugt(TypeStorageSize) && 14721 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14722 if (CStdConstraintViolation || MSBitfieldViolation) { 14723 unsigned DiagWidth = 14724 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14725 if (FieldName) 14726 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14727 << FieldName << (unsigned)Value.getZExtValue() 14728 << !CStdConstraintViolation << DiagWidth; 14729 14730 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14731 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14732 << DiagWidth; 14733 } 14734 14735 // Warn on types where the user might conceivably expect to get all 14736 // specified bits as value bits: that's all integral types other than 14737 // 'bool'. 14738 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14739 if (FieldName) 14740 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14741 << FieldName << (unsigned)Value.getZExtValue() 14742 << (unsigned)TypeWidth; 14743 else 14744 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14745 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14746 } 14747 } 14748 14749 return BitWidth; 14750 } 14751 14752 /// ActOnField - Each field of a C struct/union is passed into this in order 14753 /// to create a FieldDecl object for it. 14754 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14755 Declarator &D, Expr *BitfieldWidth) { 14756 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14757 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14758 /*InitStyle=*/ICIS_NoInit, AS_public); 14759 return Res; 14760 } 14761 14762 /// HandleField - Analyze a field of a C struct or a C++ data member. 14763 /// 14764 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14765 SourceLocation DeclStart, 14766 Declarator &D, Expr *BitWidth, 14767 InClassInitStyle InitStyle, 14768 AccessSpecifier AS) { 14769 if (D.isDecompositionDeclarator()) { 14770 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14771 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14772 << Decomp.getSourceRange(); 14773 return nullptr; 14774 } 14775 14776 IdentifierInfo *II = D.getIdentifier(); 14777 SourceLocation Loc = DeclStart; 14778 if (II) Loc = D.getIdentifierLoc(); 14779 14780 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14781 QualType T = TInfo->getType(); 14782 if (getLangOpts().CPlusPlus) { 14783 CheckExtraCXXDefaultArguments(D); 14784 14785 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14786 UPPC_DataMemberType)) { 14787 D.setInvalidType(); 14788 T = Context.IntTy; 14789 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14790 } 14791 } 14792 14793 // TR 18037 does not allow fields to be declared with address spaces. 14794 if (T.getQualifiers().hasAddressSpace() || 14795 T->isDependentAddressSpaceType() || 14796 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 14797 Diag(Loc, diag::err_field_with_address_space); 14798 D.setInvalidType(); 14799 } 14800 14801 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14802 // used as structure or union field: image, sampler, event or block types. 14803 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14804 T->isSamplerT() || T->isBlockPointerType())) { 14805 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14806 D.setInvalidType(); 14807 } 14808 14809 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14810 14811 if (D.getDeclSpec().isInlineSpecified()) 14812 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14813 << getLangOpts().CPlusPlus17; 14814 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14815 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14816 diag::err_invalid_thread) 14817 << DeclSpec::getSpecifierName(TSCS); 14818 14819 // Check to see if this name was declared as a member previously 14820 NamedDecl *PrevDecl = nullptr; 14821 LookupResult Previous(*this, II, Loc, LookupMemberName, 14822 ForVisibleRedeclaration); 14823 LookupName(Previous, S); 14824 switch (Previous.getResultKind()) { 14825 case LookupResult::Found: 14826 case LookupResult::FoundUnresolvedValue: 14827 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14828 break; 14829 14830 case LookupResult::FoundOverloaded: 14831 PrevDecl = Previous.getRepresentativeDecl(); 14832 break; 14833 14834 case LookupResult::NotFound: 14835 case LookupResult::NotFoundInCurrentInstantiation: 14836 case LookupResult::Ambiguous: 14837 break; 14838 } 14839 Previous.suppressDiagnostics(); 14840 14841 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14842 // Maybe we will complain about the shadowed template parameter. 14843 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14844 // Just pretend that we didn't see the previous declaration. 14845 PrevDecl = nullptr; 14846 } 14847 14848 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14849 PrevDecl = nullptr; 14850 14851 bool Mutable 14852 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14853 SourceLocation TSSL = D.getLocStart(); 14854 FieldDecl *NewFD 14855 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14856 TSSL, AS, PrevDecl, &D); 14857 14858 if (NewFD->isInvalidDecl()) 14859 Record->setInvalidDecl(); 14860 14861 if (D.getDeclSpec().isModulePrivateSpecified()) 14862 NewFD->setModulePrivate(); 14863 14864 if (NewFD->isInvalidDecl() && PrevDecl) { 14865 // Don't introduce NewFD into scope; there's already something 14866 // with the same name in the same scope. 14867 } else if (II) { 14868 PushOnScopeChains(NewFD, S); 14869 } else 14870 Record->addDecl(NewFD); 14871 14872 return NewFD; 14873 } 14874 14875 /// Build a new FieldDecl and check its well-formedness. 14876 /// 14877 /// This routine builds a new FieldDecl given the fields name, type, 14878 /// record, etc. \p PrevDecl should refer to any previous declaration 14879 /// with the same name and in the same scope as the field to be 14880 /// created. 14881 /// 14882 /// \returns a new FieldDecl. 14883 /// 14884 /// \todo The Declarator argument is a hack. It will be removed once 14885 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14886 TypeSourceInfo *TInfo, 14887 RecordDecl *Record, SourceLocation Loc, 14888 bool Mutable, Expr *BitWidth, 14889 InClassInitStyle InitStyle, 14890 SourceLocation TSSL, 14891 AccessSpecifier AS, NamedDecl *PrevDecl, 14892 Declarator *D) { 14893 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14894 bool InvalidDecl = false; 14895 if (D) InvalidDecl = D->isInvalidType(); 14896 14897 // If we receive a broken type, recover by assuming 'int' and 14898 // marking this declaration as invalid. 14899 if (T.isNull()) { 14900 InvalidDecl = true; 14901 T = Context.IntTy; 14902 } 14903 14904 QualType EltTy = Context.getBaseElementType(T); 14905 if (!EltTy->isDependentType()) { 14906 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14907 // Fields of incomplete type force their record to be invalid. 14908 Record->setInvalidDecl(); 14909 InvalidDecl = true; 14910 } else { 14911 NamedDecl *Def; 14912 EltTy->isIncompleteType(&Def); 14913 if (Def && Def->isInvalidDecl()) { 14914 Record->setInvalidDecl(); 14915 InvalidDecl = true; 14916 } 14917 } 14918 } 14919 14920 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14921 if (BitWidth && getLangOpts().OpenCL) { 14922 Diag(Loc, diag::err_opencl_bitfields); 14923 InvalidDecl = true; 14924 } 14925 14926 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 14927 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 14928 T.hasQualifiers()) { 14929 InvalidDecl = true; 14930 Diag(Loc, diag::err_anon_bitfield_qualifiers); 14931 } 14932 14933 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14934 // than a variably modified type. 14935 if (!InvalidDecl && T->isVariablyModifiedType()) { 14936 bool SizeIsNegative; 14937 llvm::APSInt Oversized; 14938 14939 TypeSourceInfo *FixedTInfo = 14940 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14941 SizeIsNegative, 14942 Oversized); 14943 if (FixedTInfo) { 14944 Diag(Loc, diag::warn_illegal_constant_array_size); 14945 TInfo = FixedTInfo; 14946 T = FixedTInfo->getType(); 14947 } else { 14948 if (SizeIsNegative) 14949 Diag(Loc, diag::err_typecheck_negative_array_size); 14950 else if (Oversized.getBoolValue()) 14951 Diag(Loc, diag::err_array_too_large) 14952 << Oversized.toString(10); 14953 else 14954 Diag(Loc, diag::err_typecheck_field_variable_size); 14955 InvalidDecl = true; 14956 } 14957 } 14958 14959 // Fields can not have abstract class types 14960 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14961 diag::err_abstract_type_in_decl, 14962 AbstractFieldType)) 14963 InvalidDecl = true; 14964 14965 bool ZeroWidth = false; 14966 if (InvalidDecl) 14967 BitWidth = nullptr; 14968 // If this is declared as a bit-field, check the bit-field. 14969 if (BitWidth) { 14970 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14971 &ZeroWidth).get(); 14972 if (!BitWidth) { 14973 InvalidDecl = true; 14974 BitWidth = nullptr; 14975 ZeroWidth = false; 14976 } 14977 } 14978 14979 // Check that 'mutable' is consistent with the type of the declaration. 14980 if (!InvalidDecl && Mutable) { 14981 unsigned DiagID = 0; 14982 if (T->isReferenceType()) 14983 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14984 : diag::err_mutable_reference; 14985 else if (T.isConstQualified()) 14986 DiagID = diag::err_mutable_const; 14987 14988 if (DiagID) { 14989 SourceLocation ErrLoc = Loc; 14990 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14991 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14992 Diag(ErrLoc, DiagID); 14993 if (DiagID != diag::ext_mutable_reference) { 14994 Mutable = false; 14995 InvalidDecl = true; 14996 } 14997 } 14998 } 14999 15000 // C++11 [class.union]p8 (DR1460): 15001 // At most one variant member of a union may have a 15002 // brace-or-equal-initializer. 15003 if (InitStyle != ICIS_NoInit) 15004 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 15005 15006 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 15007 BitWidth, Mutable, InitStyle); 15008 if (InvalidDecl) 15009 NewFD->setInvalidDecl(); 15010 15011 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 15012 Diag(Loc, diag::err_duplicate_member) << II; 15013 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15014 NewFD->setInvalidDecl(); 15015 } 15016 15017 if (!InvalidDecl && getLangOpts().CPlusPlus) { 15018 if (Record->isUnion()) { 15019 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15020 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15021 if (RDecl->getDefinition()) { 15022 // C++ [class.union]p1: An object of a class with a non-trivial 15023 // constructor, a non-trivial copy constructor, a non-trivial 15024 // destructor, or a non-trivial copy assignment operator 15025 // cannot be a member of a union, nor can an array of such 15026 // objects. 15027 if (CheckNontrivialField(NewFD)) 15028 NewFD->setInvalidDecl(); 15029 } 15030 } 15031 15032 // C++ [class.union]p1: If a union contains a member of reference type, 15033 // the program is ill-formed, except when compiling with MSVC extensions 15034 // enabled. 15035 if (EltTy->isReferenceType()) { 15036 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15037 diag::ext_union_member_of_reference_type : 15038 diag::err_union_member_of_reference_type) 15039 << NewFD->getDeclName() << EltTy; 15040 if (!getLangOpts().MicrosoftExt) 15041 NewFD->setInvalidDecl(); 15042 } 15043 } 15044 } 15045 15046 // FIXME: We need to pass in the attributes given an AST 15047 // representation, not a parser representation. 15048 if (D) { 15049 // FIXME: The current scope is almost... but not entirely... correct here. 15050 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15051 15052 if (NewFD->hasAttrs()) 15053 CheckAlignasUnderalignment(NewFD); 15054 } 15055 15056 // In auto-retain/release, infer strong retension for fields of 15057 // retainable type. 15058 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15059 NewFD->setInvalidDecl(); 15060 15061 if (T.isObjCGCWeak()) 15062 Diag(Loc, diag::warn_attribute_weak_on_field); 15063 15064 NewFD->setAccess(AS); 15065 return NewFD; 15066 } 15067 15068 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15069 assert(FD); 15070 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15071 15072 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15073 return false; 15074 15075 QualType EltTy = Context.getBaseElementType(FD->getType()); 15076 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15077 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15078 if (RDecl->getDefinition()) { 15079 // We check for copy constructors before constructors 15080 // because otherwise we'll never get complaints about 15081 // copy constructors. 15082 15083 CXXSpecialMember member = CXXInvalid; 15084 // We're required to check for any non-trivial constructors. Since the 15085 // implicit default constructor is suppressed if there are any 15086 // user-declared constructors, we just need to check that there is a 15087 // trivial default constructor and a trivial copy constructor. (We don't 15088 // worry about move constructors here, since this is a C++98 check.) 15089 if (RDecl->hasNonTrivialCopyConstructor()) 15090 member = CXXCopyConstructor; 15091 else if (!RDecl->hasTrivialDefaultConstructor()) 15092 member = CXXDefaultConstructor; 15093 else if (RDecl->hasNonTrivialCopyAssignment()) 15094 member = CXXCopyAssignment; 15095 else if (RDecl->hasNonTrivialDestructor()) 15096 member = CXXDestructor; 15097 15098 if (member != CXXInvalid) { 15099 if (!getLangOpts().CPlusPlus11 && 15100 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15101 // Objective-C++ ARC: it is an error to have a non-trivial field of 15102 // a union. However, system headers in Objective-C programs 15103 // occasionally have Objective-C lifetime objects within unions, 15104 // and rather than cause the program to fail, we make those 15105 // members unavailable. 15106 SourceLocation Loc = FD->getLocation(); 15107 if (getSourceManager().isInSystemHeader(Loc)) { 15108 if (!FD->hasAttr<UnavailableAttr>()) 15109 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15110 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15111 return false; 15112 } 15113 } 15114 15115 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15116 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15117 diag::err_illegal_union_or_anon_struct_member) 15118 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15119 DiagnoseNontrivial(RDecl, member); 15120 return !getLangOpts().CPlusPlus11; 15121 } 15122 } 15123 } 15124 15125 return false; 15126 } 15127 15128 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15129 /// AST enum value. 15130 static ObjCIvarDecl::AccessControl 15131 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15132 switch (ivarVisibility) { 15133 default: llvm_unreachable("Unknown visitibility kind"); 15134 case tok::objc_private: return ObjCIvarDecl::Private; 15135 case tok::objc_public: return ObjCIvarDecl::Public; 15136 case tok::objc_protected: return ObjCIvarDecl::Protected; 15137 case tok::objc_package: return ObjCIvarDecl::Package; 15138 } 15139 } 15140 15141 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15142 /// in order to create an IvarDecl object for it. 15143 Decl *Sema::ActOnIvar(Scope *S, 15144 SourceLocation DeclStart, 15145 Declarator &D, Expr *BitfieldWidth, 15146 tok::ObjCKeywordKind Visibility) { 15147 15148 IdentifierInfo *II = D.getIdentifier(); 15149 Expr *BitWidth = (Expr*)BitfieldWidth; 15150 SourceLocation Loc = DeclStart; 15151 if (II) Loc = D.getIdentifierLoc(); 15152 15153 // FIXME: Unnamed fields can be handled in various different ways, for 15154 // example, unnamed unions inject all members into the struct namespace! 15155 15156 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15157 QualType T = TInfo->getType(); 15158 15159 if (BitWidth) { 15160 // 6.7.2.1p3, 6.7.2.1p4 15161 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15162 if (!BitWidth) 15163 D.setInvalidType(); 15164 } else { 15165 // Not a bitfield. 15166 15167 // validate II. 15168 15169 } 15170 if (T->isReferenceType()) { 15171 Diag(Loc, diag::err_ivar_reference_type); 15172 D.setInvalidType(); 15173 } 15174 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15175 // than a variably modified type. 15176 else if (T->isVariablyModifiedType()) { 15177 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15178 D.setInvalidType(); 15179 } 15180 15181 // Get the visibility (access control) for this ivar. 15182 ObjCIvarDecl::AccessControl ac = 15183 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15184 : ObjCIvarDecl::None; 15185 // Must set ivar's DeclContext to its enclosing interface. 15186 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15187 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15188 return nullptr; 15189 ObjCContainerDecl *EnclosingContext; 15190 if (ObjCImplementationDecl *IMPDecl = 15191 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15192 if (LangOpts.ObjCRuntime.isFragile()) { 15193 // Case of ivar declared in an implementation. Context is that of its class. 15194 EnclosingContext = IMPDecl->getClassInterface(); 15195 assert(EnclosingContext && "Implementation has no class interface!"); 15196 } 15197 else 15198 EnclosingContext = EnclosingDecl; 15199 } else { 15200 if (ObjCCategoryDecl *CDecl = 15201 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15202 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15203 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15204 return nullptr; 15205 } 15206 } 15207 EnclosingContext = EnclosingDecl; 15208 } 15209 15210 // Construct the decl. 15211 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15212 DeclStart, Loc, II, T, 15213 TInfo, ac, (Expr *)BitfieldWidth); 15214 15215 if (II) { 15216 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15217 ForVisibleRedeclaration); 15218 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15219 && !isa<TagDecl>(PrevDecl)) { 15220 Diag(Loc, diag::err_duplicate_member) << II; 15221 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15222 NewID->setInvalidDecl(); 15223 } 15224 } 15225 15226 // Process attributes attached to the ivar. 15227 ProcessDeclAttributes(S, NewID, D); 15228 15229 if (D.isInvalidType()) 15230 NewID->setInvalidDecl(); 15231 15232 // In ARC, infer 'retaining' for ivars of retainable type. 15233 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15234 NewID->setInvalidDecl(); 15235 15236 if (D.getDeclSpec().isModulePrivateSpecified()) 15237 NewID->setModulePrivate(); 15238 15239 if (II) { 15240 // FIXME: When interfaces are DeclContexts, we'll need to add 15241 // these to the interface. 15242 S->AddDecl(NewID); 15243 IdResolver.AddDecl(NewID); 15244 } 15245 15246 if (LangOpts.ObjCRuntime.isNonFragile() && 15247 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15248 Diag(Loc, diag::warn_ivars_in_interface); 15249 15250 return NewID; 15251 } 15252 15253 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15254 /// class and class extensions. For every class \@interface and class 15255 /// extension \@interface, if the last ivar is a bitfield of any type, 15256 /// then add an implicit `char :0` ivar to the end of that interface. 15257 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15258 SmallVectorImpl<Decl *> &AllIvarDecls) { 15259 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15260 return; 15261 15262 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15263 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15264 15265 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15266 return; 15267 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15268 if (!ID) { 15269 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15270 if (!CD->IsClassExtension()) 15271 return; 15272 } 15273 // No need to add this to end of @implementation. 15274 else 15275 return; 15276 } 15277 // All conditions are met. Add a new bitfield to the tail end of ivars. 15278 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15279 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15280 15281 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15282 DeclLoc, DeclLoc, nullptr, 15283 Context.CharTy, 15284 Context.getTrivialTypeSourceInfo(Context.CharTy, 15285 DeclLoc), 15286 ObjCIvarDecl::Private, BW, 15287 true); 15288 AllIvarDecls.push_back(Ivar); 15289 } 15290 15291 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15292 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15293 SourceLocation RBrac, 15294 const ParsedAttributesView &Attrs) { 15295 assert(EnclosingDecl && "missing record or interface decl"); 15296 15297 // If this is an Objective-C @implementation or category and we have 15298 // new fields here we should reset the layout of the interface since 15299 // it will now change. 15300 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15301 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15302 switch (DC->getKind()) { 15303 default: break; 15304 case Decl::ObjCCategory: 15305 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15306 break; 15307 case Decl::ObjCImplementation: 15308 Context. 15309 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15310 break; 15311 } 15312 } 15313 15314 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15315 15316 // Start counting up the number of named members; make sure to include 15317 // members of anonymous structs and unions in the total. 15318 unsigned NumNamedMembers = 0; 15319 if (Record) { 15320 for (const auto *I : Record->decls()) { 15321 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15322 if (IFD->getDeclName()) 15323 ++NumNamedMembers; 15324 } 15325 } 15326 15327 // Verify that all the fields are okay. 15328 SmallVector<FieldDecl*, 32> RecFields; 15329 15330 bool ObjCFieldLifetimeErrReported = false; 15331 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15332 i != end; ++i) { 15333 FieldDecl *FD = cast<FieldDecl>(*i); 15334 15335 // Get the type for the field. 15336 const Type *FDTy = FD->getType().getTypePtr(); 15337 15338 if (!FD->isAnonymousStructOrUnion()) { 15339 // Remember all fields written by the user. 15340 RecFields.push_back(FD); 15341 } 15342 15343 // If the field is already invalid for some reason, don't emit more 15344 // diagnostics about it. 15345 if (FD->isInvalidDecl()) { 15346 EnclosingDecl->setInvalidDecl(); 15347 continue; 15348 } 15349 15350 // C99 6.7.2.1p2: 15351 // A structure or union shall not contain a member with 15352 // incomplete or function type (hence, a structure shall not 15353 // contain an instance of itself, but may contain a pointer to 15354 // an instance of itself), except that the last member of a 15355 // structure with more than one named member may have incomplete 15356 // array type; such a structure (and any union containing, 15357 // possibly recursively, a member that is such a structure) 15358 // shall not be a member of a structure or an element of an 15359 // array. 15360 bool IsLastField = (i + 1 == Fields.end()); 15361 if (FDTy->isFunctionType()) { 15362 // Field declared as a function. 15363 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15364 << FD->getDeclName(); 15365 FD->setInvalidDecl(); 15366 EnclosingDecl->setInvalidDecl(); 15367 continue; 15368 } else if (FDTy->isIncompleteArrayType() && 15369 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15370 if (Record) { 15371 // Flexible array member. 15372 // Microsoft and g++ is more permissive regarding flexible array. 15373 // It will accept flexible array in union and also 15374 // as the sole element of a struct/class. 15375 unsigned DiagID = 0; 15376 if (!Record->isUnion() && !IsLastField) { 15377 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15378 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15379 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15380 FD->setInvalidDecl(); 15381 EnclosingDecl->setInvalidDecl(); 15382 continue; 15383 } else if (Record->isUnion()) 15384 DiagID = getLangOpts().MicrosoftExt 15385 ? diag::ext_flexible_array_union_ms 15386 : getLangOpts().CPlusPlus 15387 ? diag::ext_flexible_array_union_gnu 15388 : diag::err_flexible_array_union; 15389 else if (NumNamedMembers < 1) 15390 DiagID = getLangOpts().MicrosoftExt 15391 ? diag::ext_flexible_array_empty_aggregate_ms 15392 : getLangOpts().CPlusPlus 15393 ? diag::ext_flexible_array_empty_aggregate_gnu 15394 : diag::err_flexible_array_empty_aggregate; 15395 15396 if (DiagID) 15397 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15398 << Record->getTagKind(); 15399 // While the layout of types that contain virtual bases is not specified 15400 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15401 // virtual bases after the derived members. This would make a flexible 15402 // array member declared at the end of an object not adjacent to the end 15403 // of the type. 15404 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 15405 if (RD->getNumVBases() != 0) 15406 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15407 << FD->getDeclName() << Record->getTagKind(); 15408 if (!getLangOpts().C99) 15409 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15410 << FD->getDeclName() << Record->getTagKind(); 15411 15412 // If the element type has a non-trivial destructor, we would not 15413 // implicitly destroy the elements, so disallow it for now. 15414 // 15415 // FIXME: GCC allows this. We should probably either implicitly delete 15416 // the destructor of the containing class, or just allow this. 15417 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15418 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15419 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15420 << FD->getDeclName() << FD->getType(); 15421 FD->setInvalidDecl(); 15422 EnclosingDecl->setInvalidDecl(); 15423 continue; 15424 } 15425 // Okay, we have a legal flexible array member at the end of the struct. 15426 Record->setHasFlexibleArrayMember(true); 15427 } else { 15428 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15429 // unless they are followed by another ivar. That check is done 15430 // elsewhere, after synthesized ivars are known. 15431 } 15432 } else if (!FDTy->isDependentType() && 15433 RequireCompleteType(FD->getLocation(), FD->getType(), 15434 diag::err_field_incomplete)) { 15435 // Incomplete type 15436 FD->setInvalidDecl(); 15437 EnclosingDecl->setInvalidDecl(); 15438 continue; 15439 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15440 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15441 // A type which contains a flexible array member is considered to be a 15442 // flexible array member. 15443 Record->setHasFlexibleArrayMember(true); 15444 if (!Record->isUnion()) { 15445 // If this is a struct/class and this is not the last element, reject 15446 // it. Note that GCC supports variable sized arrays in the middle of 15447 // structures. 15448 if (!IsLastField) 15449 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15450 << FD->getDeclName() << FD->getType(); 15451 else { 15452 // We support flexible arrays at the end of structs in 15453 // other structs as an extension. 15454 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15455 << FD->getDeclName(); 15456 } 15457 } 15458 } 15459 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15460 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15461 diag::err_abstract_type_in_decl, 15462 AbstractIvarType)) { 15463 // Ivars can not have abstract class types 15464 FD->setInvalidDecl(); 15465 } 15466 if (Record && FDTTy->getDecl()->hasObjectMember()) 15467 Record->setHasObjectMember(true); 15468 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15469 Record->setHasVolatileMember(true); 15470 } else if (FDTy->isObjCObjectType()) { 15471 /// A field cannot be an Objective-c object 15472 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15473 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15474 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15475 FD->setType(T); 15476 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15477 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { 15478 // It's an error in ARC or Weak if a field has lifetime. 15479 // We don't want to report this in a system header, though, 15480 // so we just make the field unavailable. 15481 // FIXME: that's really not sufficient; we need to make the type 15482 // itself invalid to, say, initialize or copy. 15483 QualType T = FD->getType(); 15484 if (T.hasNonTrivialObjCLifetime()) { 15485 SourceLocation loc = FD->getLocation(); 15486 if (getSourceManager().isInSystemHeader(loc)) { 15487 if (!FD->hasAttr<UnavailableAttr>()) { 15488 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15489 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15490 } 15491 } else { 15492 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15493 << T->isBlockPointerType() << Record->getTagKind(); 15494 } 15495 ObjCFieldLifetimeErrReported = true; 15496 } 15497 } else if (getLangOpts().ObjC1 && 15498 getLangOpts().getGC() != LangOptions::NonGC && 15499 Record && !Record->hasObjectMember()) { 15500 if (FD->getType()->isObjCObjectPointerType() || 15501 FD->getType().isObjCGCStrong()) 15502 Record->setHasObjectMember(true); 15503 else if (Context.getAsArrayType(FD->getType())) { 15504 QualType BaseType = Context.getBaseElementType(FD->getType()); 15505 if (BaseType->isRecordType() && 15506 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15507 Record->setHasObjectMember(true); 15508 else if (BaseType->isObjCObjectPointerType() || 15509 BaseType.isObjCGCStrong()) 15510 Record->setHasObjectMember(true); 15511 } 15512 } 15513 15514 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 15515 QualType FT = FD->getType(); 15516 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 15517 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 15518 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 15519 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 15520 Record->setNonTrivialToPrimitiveCopy(true); 15521 if (FT.isDestructedType()) { 15522 Record->setNonTrivialToPrimitiveDestroy(true); 15523 Record->setParamDestroyedInCallee(true); 15524 } 15525 15526 if (const auto *RT = FT->getAs<RecordType>()) { 15527 if (RT->getDecl()->getArgPassingRestrictions() == 15528 RecordDecl::APK_CanNeverPassInRegs) 15529 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15530 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 15531 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15532 } 15533 15534 if (Record && FD->getType().isVolatileQualified()) 15535 Record->setHasVolatileMember(true); 15536 // Keep track of the number of named members. 15537 if (FD->getIdentifier()) 15538 ++NumNamedMembers; 15539 } 15540 15541 // Okay, we successfully defined 'Record'. 15542 if (Record) { 15543 bool Completed = false; 15544 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15545 if (!CXXRecord->isInvalidDecl()) { 15546 // Set access bits correctly on the directly-declared conversions. 15547 for (CXXRecordDecl::conversion_iterator 15548 I = CXXRecord->conversion_begin(), 15549 E = CXXRecord->conversion_end(); I != E; ++I) 15550 I.setAccess((*I)->getAccess()); 15551 } 15552 15553 if (!CXXRecord->isDependentType()) { 15554 if (CXXRecord->hasUserDeclaredDestructor()) { 15555 // Adjust user-defined destructor exception spec. 15556 if (getLangOpts().CPlusPlus11) 15557 AdjustDestructorExceptionSpec(CXXRecord, 15558 CXXRecord->getDestructor()); 15559 } 15560 15561 // Add any implicitly-declared members to this class. 15562 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15563 15564 if (!CXXRecord->isInvalidDecl()) { 15565 // If we have virtual base classes, we may end up finding multiple 15566 // final overriders for a given virtual function. Check for this 15567 // problem now. 15568 if (CXXRecord->getNumVBases()) { 15569 CXXFinalOverriderMap FinalOverriders; 15570 CXXRecord->getFinalOverriders(FinalOverriders); 15571 15572 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15573 MEnd = FinalOverriders.end(); 15574 M != MEnd; ++M) { 15575 for (OverridingMethods::iterator SO = M->second.begin(), 15576 SOEnd = M->second.end(); 15577 SO != SOEnd; ++SO) { 15578 assert(SO->second.size() > 0 && 15579 "Virtual function without overriding functions?"); 15580 if (SO->second.size() == 1) 15581 continue; 15582 15583 // C++ [class.virtual]p2: 15584 // In a derived class, if a virtual member function of a base 15585 // class subobject has more than one final overrider the 15586 // program is ill-formed. 15587 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15588 << (const NamedDecl *)M->first << Record; 15589 Diag(M->first->getLocation(), 15590 diag::note_overridden_virtual_function); 15591 for (OverridingMethods::overriding_iterator 15592 OM = SO->second.begin(), 15593 OMEnd = SO->second.end(); 15594 OM != OMEnd; ++OM) 15595 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15596 << (const NamedDecl *)M->first << OM->Method->getParent(); 15597 15598 Record->setInvalidDecl(); 15599 } 15600 } 15601 CXXRecord->completeDefinition(&FinalOverriders); 15602 Completed = true; 15603 } 15604 } 15605 } 15606 } 15607 15608 if (!Completed) 15609 Record->completeDefinition(); 15610 15611 // Handle attributes before checking the layout. 15612 ProcessDeclAttributeList(S, Record, Attrs); 15613 15614 // We may have deferred checking for a deleted destructor. Check now. 15615 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15616 auto *Dtor = CXXRecord->getDestructor(); 15617 if (Dtor && Dtor->isImplicit() && 15618 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 15619 CXXRecord->setImplicitDestructorIsDeleted(); 15620 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15621 } 15622 } 15623 15624 if (Record->hasAttrs()) { 15625 CheckAlignasUnderalignment(Record); 15626 15627 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15628 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15629 IA->getRange(), IA->getBestCase(), 15630 IA->getSemanticSpelling()); 15631 } 15632 15633 // Check if the structure/union declaration is a type that can have zero 15634 // size in C. For C this is a language extension, for C++ it may cause 15635 // compatibility problems. 15636 bool CheckForZeroSize; 15637 if (!getLangOpts().CPlusPlus) { 15638 CheckForZeroSize = true; 15639 } else { 15640 // For C++ filter out types that cannot be referenced in C code. 15641 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15642 CheckForZeroSize = 15643 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15644 !CXXRecord->isDependentType() && 15645 CXXRecord->isCLike(); 15646 } 15647 if (CheckForZeroSize) { 15648 bool ZeroSize = true; 15649 bool IsEmpty = true; 15650 unsigned NonBitFields = 0; 15651 for (RecordDecl::field_iterator I = Record->field_begin(), 15652 E = Record->field_end(); 15653 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15654 IsEmpty = false; 15655 if (I->isUnnamedBitfield()) { 15656 if (!I->isZeroLengthBitField(Context)) 15657 ZeroSize = false; 15658 } else { 15659 ++NonBitFields; 15660 QualType FieldType = I->getType(); 15661 if (FieldType->isIncompleteType() || 15662 !Context.getTypeSizeInChars(FieldType).isZero()) 15663 ZeroSize = false; 15664 } 15665 } 15666 15667 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15668 // allowed in C++, but warn if its declaration is inside 15669 // extern "C" block. 15670 if (ZeroSize) { 15671 Diag(RecLoc, getLangOpts().CPlusPlus ? 15672 diag::warn_zero_size_struct_union_in_extern_c : 15673 diag::warn_zero_size_struct_union_compat) 15674 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15675 } 15676 15677 // Structs without named members are extension in C (C99 6.7.2.1p7), 15678 // but are accepted by GCC. 15679 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15680 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15681 diag::ext_no_named_members_in_struct_union) 15682 << Record->isUnion(); 15683 } 15684 } 15685 } else { 15686 ObjCIvarDecl **ClsFields = 15687 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15688 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15689 ID->setEndOfDefinitionLoc(RBrac); 15690 // Add ivar's to class's DeclContext. 15691 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15692 ClsFields[i]->setLexicalDeclContext(ID); 15693 ID->addDecl(ClsFields[i]); 15694 } 15695 // Must enforce the rule that ivars in the base classes may not be 15696 // duplicates. 15697 if (ID->getSuperClass()) 15698 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15699 } else if (ObjCImplementationDecl *IMPDecl = 15700 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15701 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15702 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15703 // Ivar declared in @implementation never belongs to the implementation. 15704 // Only it is in implementation's lexical context. 15705 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15706 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15707 IMPDecl->setIvarLBraceLoc(LBrac); 15708 IMPDecl->setIvarRBraceLoc(RBrac); 15709 } else if (ObjCCategoryDecl *CDecl = 15710 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15711 // case of ivars in class extension; all other cases have been 15712 // reported as errors elsewhere. 15713 // FIXME. Class extension does not have a LocEnd field. 15714 // CDecl->setLocEnd(RBrac); 15715 // Add ivar's to class extension's DeclContext. 15716 // Diagnose redeclaration of private ivars. 15717 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15718 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15719 if (IDecl) { 15720 if (const ObjCIvarDecl *ClsIvar = 15721 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15722 Diag(ClsFields[i]->getLocation(), 15723 diag::err_duplicate_ivar_declaration); 15724 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15725 continue; 15726 } 15727 for (const auto *Ext : IDecl->known_extensions()) { 15728 if (const ObjCIvarDecl *ClsExtIvar 15729 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15730 Diag(ClsFields[i]->getLocation(), 15731 diag::err_duplicate_ivar_declaration); 15732 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15733 continue; 15734 } 15735 } 15736 } 15737 ClsFields[i]->setLexicalDeclContext(CDecl); 15738 CDecl->addDecl(ClsFields[i]); 15739 } 15740 CDecl->setIvarLBraceLoc(LBrac); 15741 CDecl->setIvarRBraceLoc(RBrac); 15742 } 15743 } 15744 } 15745 15746 /// Determine whether the given integral value is representable within 15747 /// the given type T. 15748 static bool isRepresentableIntegerValue(ASTContext &Context, 15749 llvm::APSInt &Value, 15750 QualType T) { 15751 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 15752 "Integral type required!"); 15753 unsigned BitWidth = Context.getIntWidth(T); 15754 15755 if (Value.isUnsigned() || Value.isNonNegative()) { 15756 if (T->isSignedIntegerOrEnumerationType()) 15757 --BitWidth; 15758 return Value.getActiveBits() <= BitWidth; 15759 } 15760 return Value.getMinSignedBits() <= BitWidth; 15761 } 15762 15763 // Given an integral type, return the next larger integral type 15764 // (or a NULL type of no such type exists). 15765 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15766 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15767 // enum checking below. 15768 assert((T->isIntegralType(Context) || 15769 T->isEnumeralType()) && "Integral type required!"); 15770 const unsigned NumTypes = 4; 15771 QualType SignedIntegralTypes[NumTypes] = { 15772 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15773 }; 15774 QualType UnsignedIntegralTypes[NumTypes] = { 15775 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15776 Context.UnsignedLongLongTy 15777 }; 15778 15779 unsigned BitWidth = Context.getTypeSize(T); 15780 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15781 : UnsignedIntegralTypes; 15782 for (unsigned I = 0; I != NumTypes; ++I) 15783 if (Context.getTypeSize(Types[I]) > BitWidth) 15784 return Types[I]; 15785 15786 return QualType(); 15787 } 15788 15789 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15790 EnumConstantDecl *LastEnumConst, 15791 SourceLocation IdLoc, 15792 IdentifierInfo *Id, 15793 Expr *Val) { 15794 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15795 llvm::APSInt EnumVal(IntWidth); 15796 QualType EltTy; 15797 15798 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15799 Val = nullptr; 15800 15801 if (Val) 15802 Val = DefaultLvalueConversion(Val).get(); 15803 15804 if (Val) { 15805 if (Enum->isDependentType() || Val->isTypeDependent()) 15806 EltTy = Context.DependentTy; 15807 else { 15808 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15809 !getLangOpts().MSVCCompat) { 15810 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15811 // constant-expression in the enumerator-definition shall be a converted 15812 // constant expression of the underlying type. 15813 EltTy = Enum->getIntegerType(); 15814 ExprResult Converted = 15815 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15816 CCEK_Enumerator); 15817 if (Converted.isInvalid()) 15818 Val = nullptr; 15819 else 15820 Val = Converted.get(); 15821 } else if (!Val->isValueDependent() && 15822 !(Val = VerifyIntegerConstantExpression(Val, 15823 &EnumVal).get())) { 15824 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15825 } else { 15826 if (Enum->isComplete()) { 15827 EltTy = Enum->getIntegerType(); 15828 15829 // In Obj-C and Microsoft mode, require the enumeration value to be 15830 // representable in the underlying type of the enumeration. In C++11, 15831 // we perform a non-narrowing conversion as part of converted constant 15832 // expression checking. 15833 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15834 if (getLangOpts().MSVCCompat) { 15835 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15836 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15837 } else 15838 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15839 } else 15840 Val = ImpCastExprToType(Val, EltTy, 15841 EltTy->isBooleanType() ? 15842 CK_IntegralToBoolean : CK_IntegralCast) 15843 .get(); 15844 } else if (getLangOpts().CPlusPlus) { 15845 // C++11 [dcl.enum]p5: 15846 // If the underlying type is not fixed, the type of each enumerator 15847 // is the type of its initializing value: 15848 // - If an initializer is specified for an enumerator, the 15849 // initializing value has the same type as the expression. 15850 EltTy = Val->getType(); 15851 } else { 15852 // C99 6.7.2.2p2: 15853 // The expression that defines the value of an enumeration constant 15854 // shall be an integer constant expression that has a value 15855 // representable as an int. 15856 15857 // Complain if the value is not representable in an int. 15858 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15859 Diag(IdLoc, diag::ext_enum_value_not_int) 15860 << EnumVal.toString(10) << Val->getSourceRange() 15861 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15862 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15863 // Force the type of the expression to 'int'. 15864 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15865 } 15866 EltTy = Val->getType(); 15867 } 15868 } 15869 } 15870 } 15871 15872 if (!Val) { 15873 if (Enum->isDependentType()) 15874 EltTy = Context.DependentTy; 15875 else if (!LastEnumConst) { 15876 // C++0x [dcl.enum]p5: 15877 // If the underlying type is not fixed, the type of each enumerator 15878 // is the type of its initializing value: 15879 // - If no initializer is specified for the first enumerator, the 15880 // initializing value has an unspecified integral type. 15881 // 15882 // GCC uses 'int' for its unspecified integral type, as does 15883 // C99 6.7.2.2p3. 15884 if (Enum->isFixed()) { 15885 EltTy = Enum->getIntegerType(); 15886 } 15887 else { 15888 EltTy = Context.IntTy; 15889 } 15890 } else { 15891 // Assign the last value + 1. 15892 EnumVal = LastEnumConst->getInitVal(); 15893 ++EnumVal; 15894 EltTy = LastEnumConst->getType(); 15895 15896 // Check for overflow on increment. 15897 if (EnumVal < LastEnumConst->getInitVal()) { 15898 // C++0x [dcl.enum]p5: 15899 // If the underlying type is not fixed, the type of each enumerator 15900 // is the type of its initializing value: 15901 // 15902 // - Otherwise the type of the initializing value is the same as 15903 // the type of the initializing value of the preceding enumerator 15904 // unless the incremented value is not representable in that type, 15905 // in which case the type is an unspecified integral type 15906 // sufficient to contain the incremented value. If no such type 15907 // exists, the program is ill-formed. 15908 QualType T = getNextLargerIntegralType(Context, EltTy); 15909 if (T.isNull() || Enum->isFixed()) { 15910 // There is no integral type larger enough to represent this 15911 // value. Complain, then allow the value to wrap around. 15912 EnumVal = LastEnumConst->getInitVal(); 15913 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15914 ++EnumVal; 15915 if (Enum->isFixed()) 15916 // When the underlying type is fixed, this is ill-formed. 15917 Diag(IdLoc, diag::err_enumerator_wrapped) 15918 << EnumVal.toString(10) 15919 << EltTy; 15920 else 15921 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15922 << EnumVal.toString(10); 15923 } else { 15924 EltTy = T; 15925 } 15926 15927 // Retrieve the last enumerator's value, extent that type to the 15928 // type that is supposed to be large enough to represent the incremented 15929 // value, then increment. 15930 EnumVal = LastEnumConst->getInitVal(); 15931 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15932 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15933 ++EnumVal; 15934 15935 // If we're not in C++, diagnose the overflow of enumerator values, 15936 // which in C99 means that the enumerator value is not representable in 15937 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15938 // permits enumerator values that are representable in some larger 15939 // integral type. 15940 if (!getLangOpts().CPlusPlus && !T.isNull()) 15941 Diag(IdLoc, diag::warn_enum_value_overflow); 15942 } else if (!getLangOpts().CPlusPlus && 15943 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15944 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15945 Diag(IdLoc, diag::ext_enum_value_not_int) 15946 << EnumVal.toString(10) << 1; 15947 } 15948 } 15949 } 15950 15951 if (!EltTy->isDependentType()) { 15952 // Make the enumerator value match the signedness and size of the 15953 // enumerator's type. 15954 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15955 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15956 } 15957 15958 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15959 Val, EnumVal); 15960 } 15961 15962 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15963 SourceLocation IILoc) { 15964 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15965 !getLangOpts().CPlusPlus) 15966 return SkipBodyInfo(); 15967 15968 // We have an anonymous enum definition. Look up the first enumerator to 15969 // determine if we should merge the definition with an existing one and 15970 // skip the body. 15971 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15972 forRedeclarationInCurContext()); 15973 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15974 if (!PrevECD) 15975 return SkipBodyInfo(); 15976 15977 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15978 NamedDecl *Hidden; 15979 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15980 SkipBodyInfo Skip; 15981 Skip.Previous = Hidden; 15982 return Skip; 15983 } 15984 15985 return SkipBodyInfo(); 15986 } 15987 15988 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15989 SourceLocation IdLoc, IdentifierInfo *Id, 15990 const ParsedAttributesView &Attrs, 15991 SourceLocation EqualLoc, Expr *Val) { 15992 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15993 EnumConstantDecl *LastEnumConst = 15994 cast_or_null<EnumConstantDecl>(lastEnumConst); 15995 15996 // The scope passed in may not be a decl scope. Zip up the scope tree until 15997 // we find one that is. 15998 S = getNonFieldDeclScope(S); 15999 16000 // Verify that there isn't already something declared with this name in this 16001 // scope. 16002 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 16003 ForVisibleRedeclaration); 16004 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16005 // Maybe we will complain about the shadowed template parameter. 16006 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 16007 // Just pretend that we didn't see the previous declaration. 16008 PrevDecl = nullptr; 16009 } 16010 16011 // C++ [class.mem]p15: 16012 // If T is the name of a class, then each of the following shall have a name 16013 // different from T: 16014 // - every enumerator of every member of class T that is an unscoped 16015 // enumerated type 16016 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 16017 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 16018 DeclarationNameInfo(Id, IdLoc)); 16019 16020 EnumConstantDecl *New = 16021 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 16022 if (!New) 16023 return nullptr; 16024 16025 if (PrevDecl) { 16026 // When in C++, we may get a TagDecl with the same name; in this case the 16027 // enum constant will 'hide' the tag. 16028 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 16029 "Received TagDecl when not in C++!"); 16030 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 16031 if (isa<EnumConstantDecl>(PrevDecl)) 16032 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 16033 else 16034 Diag(IdLoc, diag::err_redefinition) << Id; 16035 notePreviousDefinition(PrevDecl, IdLoc); 16036 return nullptr; 16037 } 16038 } 16039 16040 // Process attributes. 16041 ProcessDeclAttributeList(S, New, Attrs); 16042 AddPragmaAttributes(S, New); 16043 16044 // Register this decl in the current scope stack. 16045 New->setAccess(TheEnumDecl->getAccess()); 16046 PushOnScopeChains(New, S); 16047 16048 ActOnDocumentableDecl(New); 16049 16050 return New; 16051 } 16052 16053 // Returns true when the enum initial expression does not trigger the 16054 // duplicate enum warning. A few common cases are exempted as follows: 16055 // Element2 = Element1 16056 // Element2 = Element1 + 1 16057 // Element2 = Element1 - 1 16058 // Where Element2 and Element1 are from the same enum. 16059 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16060 Expr *InitExpr = ECD->getInitExpr(); 16061 if (!InitExpr) 16062 return true; 16063 InitExpr = InitExpr->IgnoreImpCasts(); 16064 16065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16066 if (!BO->isAdditiveOp()) 16067 return true; 16068 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16069 if (!IL) 16070 return true; 16071 if (IL->getValue() != 1) 16072 return true; 16073 16074 InitExpr = BO->getLHS(); 16075 } 16076 16077 // This checks if the elements are from the same enum. 16078 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16079 if (!DRE) 16080 return true; 16081 16082 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16083 if (!EnumConstant) 16084 return true; 16085 16086 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16087 Enum) 16088 return true; 16089 16090 return false; 16091 } 16092 16093 // Emits a warning when an element is implicitly set a value that 16094 // a previous element has already been set to. 16095 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16096 EnumDecl *Enum, QualType EnumType) { 16097 // Avoid anonymous enums 16098 if (!Enum->getIdentifier()) 16099 return; 16100 16101 // Only check for small enums. 16102 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16103 return; 16104 16105 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16106 return; 16107 16108 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16109 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16110 16111 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16112 typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap; 16113 16114 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16115 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16116 llvm::APSInt Val = D->getInitVal(); 16117 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16118 }; 16119 16120 DuplicatesVector DupVector; 16121 ValueToVectorMap EnumMap; 16122 16123 // Populate the EnumMap with all values represented by enum constants without 16124 // an initializer. 16125 for (auto *Element : Elements) { 16126 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16127 16128 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16129 // this constant. Skip this enum since it may be ill-formed. 16130 if (!ECD) { 16131 return; 16132 } 16133 16134 // Constants with initalizers are handled in the next loop. 16135 if (ECD->getInitExpr()) 16136 continue; 16137 16138 // Duplicate values are handled in the next loop. 16139 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16140 } 16141 16142 if (EnumMap.size() == 0) 16143 return; 16144 16145 // Create vectors for any values that has duplicates. 16146 for (auto *Element : Elements) { 16147 // The last loop returned if any constant was null. 16148 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16149 if (!ValidDuplicateEnum(ECD, Enum)) 16150 continue; 16151 16152 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16153 if (Iter == EnumMap.end()) 16154 continue; 16155 16156 DeclOrVector& Entry = Iter->second; 16157 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16158 // Ensure constants are different. 16159 if (D == ECD) 16160 continue; 16161 16162 // Create new vector and push values onto it. 16163 auto Vec = llvm::make_unique<ECDVector>(); 16164 Vec->push_back(D); 16165 Vec->push_back(ECD); 16166 16167 // Update entry to point to the duplicates vector. 16168 Entry = Vec.get(); 16169 16170 // Store the vector somewhere we can consult later for quick emission of 16171 // diagnostics. 16172 DupVector.emplace_back(std::move(Vec)); 16173 continue; 16174 } 16175 16176 ECDVector *Vec = Entry.get<ECDVector*>(); 16177 // Make sure constants are not added more than once. 16178 if (*Vec->begin() == ECD) 16179 continue; 16180 16181 Vec->push_back(ECD); 16182 } 16183 16184 // Emit diagnostics. 16185 for (const auto &Vec : DupVector) { 16186 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16187 16188 // Emit warning for one enum constant. 16189 auto *FirstECD = Vec->front(); 16190 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16191 << FirstECD << FirstECD->getInitVal().toString(10) 16192 << FirstECD->getSourceRange(); 16193 16194 // Emit one note for each of the remaining enum constants with 16195 // the same value. 16196 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16197 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16198 << ECD << ECD->getInitVal().toString(10) 16199 << ECD->getSourceRange(); 16200 } 16201 } 16202 16203 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16204 bool AllowMask) const { 16205 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16206 assert(ED->isCompleteDefinition() && "expected enum definition"); 16207 16208 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16209 llvm::APInt &FlagBits = R.first->second; 16210 16211 if (R.second) { 16212 for (auto *E : ED->enumerators()) { 16213 const auto &EVal = E->getInitVal(); 16214 // Only single-bit enumerators introduce new flag values. 16215 if (EVal.isPowerOf2()) 16216 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16217 } 16218 } 16219 16220 // A value is in a flag enum if either its bits are a subset of the enum's 16221 // flag bits (the first condition) or we are allowing masks and the same is 16222 // true of its complement (the second condition). When masks are allowed, we 16223 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16224 // 16225 // While it's true that any value could be used as a mask, the assumption is 16226 // that a mask will have all of the insignificant bits set. Anything else is 16227 // likely a logic error. 16228 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16229 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16230 } 16231 16232 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16233 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 16234 const ParsedAttributesView &Attrs) { 16235 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16236 QualType EnumType = Context.getTypeDeclType(Enum); 16237 16238 ProcessDeclAttributeList(S, Enum, Attrs); 16239 16240 if (Enum->isDependentType()) { 16241 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16242 EnumConstantDecl *ECD = 16243 cast_or_null<EnumConstantDecl>(Elements[i]); 16244 if (!ECD) continue; 16245 16246 ECD->setType(EnumType); 16247 } 16248 16249 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16250 return; 16251 } 16252 16253 // TODO: If the result value doesn't fit in an int, it must be a long or long 16254 // long value. ISO C does not support this, but GCC does as an extension, 16255 // emit a warning. 16256 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16257 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16258 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16259 16260 // Verify that all the values are okay, compute the size of the values, and 16261 // reverse the list. 16262 unsigned NumNegativeBits = 0; 16263 unsigned NumPositiveBits = 0; 16264 16265 // Keep track of whether all elements have type int. 16266 bool AllElementsInt = true; 16267 16268 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16269 EnumConstantDecl *ECD = 16270 cast_or_null<EnumConstantDecl>(Elements[i]); 16271 if (!ECD) continue; // Already issued a diagnostic. 16272 16273 const llvm::APSInt &InitVal = ECD->getInitVal(); 16274 16275 // Keep track of the size of positive and negative values. 16276 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16277 NumPositiveBits = std::max(NumPositiveBits, 16278 (unsigned)InitVal.getActiveBits()); 16279 else 16280 NumNegativeBits = std::max(NumNegativeBits, 16281 (unsigned)InitVal.getMinSignedBits()); 16282 16283 // Keep track of whether every enum element has type int (very commmon). 16284 if (AllElementsInt) 16285 AllElementsInt = ECD->getType() == Context.IntTy; 16286 } 16287 16288 // Figure out the type that should be used for this enum. 16289 QualType BestType; 16290 unsigned BestWidth; 16291 16292 // C++0x N3000 [conv.prom]p3: 16293 // An rvalue of an unscoped enumeration type whose underlying 16294 // type is not fixed can be converted to an rvalue of the first 16295 // of the following types that can represent all the values of 16296 // the enumeration: int, unsigned int, long int, unsigned long 16297 // int, long long int, or unsigned long long int. 16298 // C99 6.4.4.3p2: 16299 // An identifier declared as an enumeration constant has type int. 16300 // The C99 rule is modified by a gcc extension 16301 QualType BestPromotionType; 16302 16303 bool Packed = Enum->hasAttr<PackedAttr>(); 16304 // -fshort-enums is the equivalent to specifying the packed attribute on all 16305 // enum definitions. 16306 if (LangOpts.ShortEnums) 16307 Packed = true; 16308 16309 // If the enum already has a type because it is fixed or dictated by the 16310 // target, promote that type instead of analyzing the enumerators. 16311 if (Enum->isComplete()) { 16312 BestType = Enum->getIntegerType(); 16313 if (BestType->isPromotableIntegerType()) 16314 BestPromotionType = Context.getPromotedIntegerType(BestType); 16315 else 16316 BestPromotionType = BestType; 16317 16318 BestWidth = Context.getIntWidth(BestType); 16319 } 16320 else if (NumNegativeBits) { 16321 // If there is a negative value, figure out the smallest integer type (of 16322 // int/long/longlong) that fits. 16323 // If it's packed, check also if it fits a char or a short. 16324 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16325 BestType = Context.SignedCharTy; 16326 BestWidth = CharWidth; 16327 } else if (Packed && NumNegativeBits <= ShortWidth && 16328 NumPositiveBits < ShortWidth) { 16329 BestType = Context.ShortTy; 16330 BestWidth = ShortWidth; 16331 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16332 BestType = Context.IntTy; 16333 BestWidth = IntWidth; 16334 } else { 16335 BestWidth = Context.getTargetInfo().getLongWidth(); 16336 16337 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16338 BestType = Context.LongTy; 16339 } else { 16340 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16341 16342 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16343 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16344 BestType = Context.LongLongTy; 16345 } 16346 } 16347 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16348 } else { 16349 // If there is no negative value, figure out the smallest type that fits 16350 // all of the enumerator values. 16351 // If it's packed, check also if it fits a char or a short. 16352 if (Packed && NumPositiveBits <= CharWidth) { 16353 BestType = Context.UnsignedCharTy; 16354 BestPromotionType = Context.IntTy; 16355 BestWidth = CharWidth; 16356 } else if (Packed && NumPositiveBits <= ShortWidth) { 16357 BestType = Context.UnsignedShortTy; 16358 BestPromotionType = Context.IntTy; 16359 BestWidth = ShortWidth; 16360 } else if (NumPositiveBits <= IntWidth) { 16361 BestType = Context.UnsignedIntTy; 16362 BestWidth = IntWidth; 16363 BestPromotionType 16364 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16365 ? Context.UnsignedIntTy : Context.IntTy; 16366 } else if (NumPositiveBits <= 16367 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16368 BestType = Context.UnsignedLongTy; 16369 BestPromotionType 16370 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16371 ? Context.UnsignedLongTy : Context.LongTy; 16372 } else { 16373 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16374 assert(NumPositiveBits <= BestWidth && 16375 "How could an initializer get larger than ULL?"); 16376 BestType = Context.UnsignedLongLongTy; 16377 BestPromotionType 16378 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16379 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16380 } 16381 } 16382 16383 // Loop over all of the enumerator constants, changing their types to match 16384 // the type of the enum if needed. 16385 for (auto *D : Elements) { 16386 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16387 if (!ECD) continue; // Already issued a diagnostic. 16388 16389 // Standard C says the enumerators have int type, but we allow, as an 16390 // extension, the enumerators to be larger than int size. If each 16391 // enumerator value fits in an int, type it as an int, otherwise type it the 16392 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16393 // that X has type 'int', not 'unsigned'. 16394 16395 // Determine whether the value fits into an int. 16396 llvm::APSInt InitVal = ECD->getInitVal(); 16397 16398 // If it fits into an integer type, force it. Otherwise force it to match 16399 // the enum decl type. 16400 QualType NewTy; 16401 unsigned NewWidth; 16402 bool NewSign; 16403 if (!getLangOpts().CPlusPlus && 16404 !Enum->isFixed() && 16405 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16406 NewTy = Context.IntTy; 16407 NewWidth = IntWidth; 16408 NewSign = true; 16409 } else if (ECD->getType() == BestType) { 16410 // Already the right type! 16411 if (getLangOpts().CPlusPlus) 16412 // C++ [dcl.enum]p4: Following the closing brace of an 16413 // enum-specifier, each enumerator has the type of its 16414 // enumeration. 16415 ECD->setType(EnumType); 16416 continue; 16417 } else { 16418 NewTy = BestType; 16419 NewWidth = BestWidth; 16420 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16421 } 16422 16423 // Adjust the APSInt value. 16424 InitVal = InitVal.extOrTrunc(NewWidth); 16425 InitVal.setIsSigned(NewSign); 16426 ECD->setInitVal(InitVal); 16427 16428 // Adjust the Expr initializer and type. 16429 if (ECD->getInitExpr() && 16430 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16431 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16432 CK_IntegralCast, 16433 ECD->getInitExpr(), 16434 /*base paths*/ nullptr, 16435 VK_RValue)); 16436 if (getLangOpts().CPlusPlus) 16437 // C++ [dcl.enum]p4: Following the closing brace of an 16438 // enum-specifier, each enumerator has the type of its 16439 // enumeration. 16440 ECD->setType(EnumType); 16441 else 16442 ECD->setType(NewTy); 16443 } 16444 16445 Enum->completeDefinition(BestType, BestPromotionType, 16446 NumPositiveBits, NumNegativeBits); 16447 16448 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16449 16450 if (Enum->isClosedFlag()) { 16451 for (Decl *D : Elements) { 16452 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16453 if (!ECD) continue; // Already issued a diagnostic. 16454 16455 llvm::APSInt InitVal = ECD->getInitVal(); 16456 if (InitVal != 0 && !InitVal.isPowerOf2() && 16457 !IsValueInFlagEnum(Enum, InitVal, true)) 16458 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16459 << ECD << Enum; 16460 } 16461 } 16462 16463 // Now that the enum type is defined, ensure it's not been underaligned. 16464 if (Enum->hasAttrs()) 16465 CheckAlignasUnderalignment(Enum); 16466 } 16467 16468 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16469 SourceLocation StartLoc, 16470 SourceLocation EndLoc) { 16471 StringLiteral *AsmString = cast<StringLiteral>(expr); 16472 16473 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16474 AsmString, StartLoc, 16475 EndLoc); 16476 CurContext->addDecl(New); 16477 return New; 16478 } 16479 16480 static void checkModuleImportContext(Sema &S, Module *M, 16481 SourceLocation ImportLoc, DeclContext *DC, 16482 bool FromInclude = false) { 16483 SourceLocation ExternCLoc; 16484 16485 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16486 switch (LSD->getLanguage()) { 16487 case LinkageSpecDecl::lang_c: 16488 if (ExternCLoc.isInvalid()) 16489 ExternCLoc = LSD->getLocStart(); 16490 break; 16491 case LinkageSpecDecl::lang_cxx: 16492 break; 16493 } 16494 DC = LSD->getParent(); 16495 } 16496 16497 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 16498 DC = DC->getParent(); 16499 16500 if (!isa<TranslationUnitDecl>(DC)) { 16501 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16502 ? diag::ext_module_import_not_at_top_level_noop 16503 : diag::err_module_import_not_at_top_level_fatal) 16504 << M->getFullModuleName() << DC; 16505 S.Diag(cast<Decl>(DC)->getLocStart(), 16506 diag::note_module_import_not_at_top_level) << DC; 16507 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16508 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16509 << M->getFullModuleName(); 16510 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16511 } 16512 } 16513 16514 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16515 SourceLocation ModuleLoc, 16516 ModuleDeclKind MDK, 16517 ModuleIdPath Path) { 16518 assert(getLangOpts().ModulesTS && 16519 "should only have module decl in modules TS"); 16520 16521 // A module implementation unit requires that we are not compiling a module 16522 // of any kind. A module interface unit requires that we are not compiling a 16523 // module map. 16524 switch (getLangOpts().getCompilingModule()) { 16525 case LangOptions::CMK_None: 16526 // It's OK to compile a module interface as a normal translation unit. 16527 break; 16528 16529 case LangOptions::CMK_ModuleInterface: 16530 if (MDK != ModuleDeclKind::Implementation) 16531 break; 16532 16533 // We were asked to compile a module interface unit but this is a module 16534 // implementation unit. That indicates the 'export' is missing. 16535 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16536 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16537 MDK = ModuleDeclKind::Interface; 16538 break; 16539 16540 case LangOptions::CMK_ModuleMap: 16541 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16542 return nullptr; 16543 } 16544 16545 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16546 16547 // FIXME: Most of this work should be done by the preprocessor rather than 16548 // here, in order to support macro import. 16549 16550 // Only one module-declaration is permitted per source file. 16551 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16552 Diag(ModuleLoc, diag::err_module_redeclaration); 16553 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16554 diag::note_prev_module_declaration); 16555 return nullptr; 16556 } 16557 16558 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16559 // modules, the dots here are just another character that can appear in a 16560 // module name. 16561 std::string ModuleName; 16562 for (auto &Piece : Path) { 16563 if (!ModuleName.empty()) 16564 ModuleName += "."; 16565 ModuleName += Piece.first->getName(); 16566 } 16567 16568 // If a module name was explicitly specified on the command line, it must be 16569 // correct. 16570 if (!getLangOpts().CurrentModule.empty() && 16571 getLangOpts().CurrentModule != ModuleName) { 16572 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16573 << SourceRange(Path.front().second, Path.back().second) 16574 << getLangOpts().CurrentModule; 16575 return nullptr; 16576 } 16577 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16578 16579 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16580 Module *Mod; 16581 16582 switch (MDK) { 16583 case ModuleDeclKind::Interface: { 16584 // We can't have parsed or imported a definition of this module or parsed a 16585 // module map defining it already. 16586 if (auto *M = Map.findModule(ModuleName)) { 16587 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16588 if (M->DefinitionLoc.isValid()) 16589 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16590 else if (const auto *FE = M->getASTFile()) 16591 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16592 << FE->getName(); 16593 Mod = M; 16594 break; 16595 } 16596 16597 // Create a Module for the module that we're defining. 16598 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16599 ModuleScopes.front().Module); 16600 assert(Mod && "module creation should not fail"); 16601 break; 16602 } 16603 16604 case ModuleDeclKind::Partition: 16605 // FIXME: Check we are in a submodule of the named module. 16606 return nullptr; 16607 16608 case ModuleDeclKind::Implementation: 16609 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16610 PP.getIdentifierInfo(ModuleName), Path[0].second); 16611 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16612 /*IsIncludeDirective=*/false); 16613 if (!Mod) { 16614 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 16615 // Create an empty module interface unit for error recovery. 16616 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16617 ModuleScopes.front().Module); 16618 } 16619 break; 16620 } 16621 16622 // Switch from the global module to the named module. 16623 ModuleScopes.back().Module = Mod; 16624 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 16625 VisibleModules.setVisible(Mod, ModuleLoc); 16626 16627 // From now on, we have an owning module for all declarations we see. 16628 // However, those declarations are module-private unless explicitly 16629 // exported. 16630 auto *TU = Context.getTranslationUnitDecl(); 16631 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16632 TU->setLocalOwningModule(Mod); 16633 16634 // FIXME: Create a ModuleDecl. 16635 return nullptr; 16636 } 16637 16638 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16639 SourceLocation ImportLoc, 16640 ModuleIdPath Path) { 16641 Module *Mod = 16642 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16643 /*IsIncludeDirective=*/false); 16644 if (!Mod) 16645 return true; 16646 16647 VisibleModules.setVisible(Mod, ImportLoc); 16648 16649 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16650 16651 // FIXME: we should support importing a submodule within a different submodule 16652 // of the same top-level module. Until we do, make it an error rather than 16653 // silently ignoring the import. 16654 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16655 // warn on a redundant import of the current module? 16656 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16657 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16658 Diag(ImportLoc, getLangOpts().isCompilingModule() 16659 ? diag::err_module_self_import 16660 : diag::err_module_import_in_implementation) 16661 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16662 16663 SmallVector<SourceLocation, 2> IdentifierLocs; 16664 Module *ModCheck = Mod; 16665 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16666 // If we've run out of module parents, just drop the remaining identifiers. 16667 // We need the length to be consistent. 16668 if (!ModCheck) 16669 break; 16670 ModCheck = ModCheck->Parent; 16671 16672 IdentifierLocs.push_back(Path[I].second); 16673 } 16674 16675 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 16676 Mod, IdentifierLocs); 16677 if (!ModuleScopes.empty()) 16678 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16679 CurContext->addDecl(Import); 16680 16681 // Re-export the module if needed. 16682 if (Import->isExported() && 16683 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) 16684 getCurrentModule()->Exports.emplace_back(Mod, false); 16685 16686 return Import; 16687 } 16688 16689 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16690 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16691 BuildModuleInclude(DirectiveLoc, Mod); 16692 } 16693 16694 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16695 // Determine whether we're in the #include buffer for a module. The #includes 16696 // in that buffer do not qualify as module imports; they're just an 16697 // implementation detail of us building the module. 16698 // 16699 // FIXME: Should we even get ActOnModuleInclude calls for those? 16700 bool IsInModuleIncludes = 16701 TUKind == TU_Module && 16702 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16703 16704 bool ShouldAddImport = !IsInModuleIncludes; 16705 16706 // If this module import was due to an inclusion directive, create an 16707 // implicit import declaration to capture it in the AST. 16708 if (ShouldAddImport) { 16709 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16710 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16711 DirectiveLoc, Mod, 16712 DirectiveLoc); 16713 if (!ModuleScopes.empty()) 16714 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16715 TU->addDecl(ImportD); 16716 Consumer.HandleImplicitImportDecl(ImportD); 16717 } 16718 16719 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16720 VisibleModules.setVisible(Mod, DirectiveLoc); 16721 } 16722 16723 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16724 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16725 16726 ModuleScopes.push_back({}); 16727 ModuleScopes.back().Module = Mod; 16728 if (getLangOpts().ModulesLocalVisibility) 16729 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16730 16731 VisibleModules.setVisible(Mod, DirectiveLoc); 16732 16733 // The enclosing context is now part of this module. 16734 // FIXME: Consider creating a child DeclContext to hold the entities 16735 // lexically within the module. 16736 if (getLangOpts().trackLocalOwningModule()) { 16737 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16738 cast<Decl>(DC)->setModuleOwnershipKind( 16739 getLangOpts().ModulesLocalVisibility 16740 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16741 : Decl::ModuleOwnershipKind::Visible); 16742 cast<Decl>(DC)->setLocalOwningModule(Mod); 16743 } 16744 } 16745 } 16746 16747 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16748 if (getLangOpts().ModulesLocalVisibility) { 16749 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16750 // Leaving a module hides namespace names, so our visible namespace cache 16751 // is now out of date. 16752 VisibleNamespaceCache.clear(); 16753 } 16754 16755 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16756 "left the wrong module scope"); 16757 ModuleScopes.pop_back(); 16758 16759 // We got to the end of processing a local module. Create an 16760 // ImportDecl as we would for an imported module. 16761 FileID File = getSourceManager().getFileID(EomLoc); 16762 SourceLocation DirectiveLoc; 16763 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16764 // We reached the end of a #included module header. Use the #include loc. 16765 assert(File != getSourceManager().getMainFileID() && 16766 "end of submodule in main source file"); 16767 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16768 } else { 16769 // We reached an EOM pragma. Use the pragma location. 16770 DirectiveLoc = EomLoc; 16771 } 16772 BuildModuleInclude(DirectiveLoc, Mod); 16773 16774 // Any further declarations are in whatever module we returned to. 16775 if (getLangOpts().trackLocalOwningModule()) { 16776 // The parser guarantees that this is the same context that we entered 16777 // the module within. 16778 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16779 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16780 if (!getCurrentModule()) 16781 cast<Decl>(DC)->setModuleOwnershipKind( 16782 Decl::ModuleOwnershipKind::Unowned); 16783 } 16784 } 16785 } 16786 16787 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16788 Module *Mod) { 16789 // Bail if we're not allowed to implicitly import a module here. 16790 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16791 VisibleModules.isVisible(Mod)) 16792 return; 16793 16794 // Create the implicit import declaration. 16795 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16796 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16797 Loc, Mod, Loc); 16798 TU->addDecl(ImportD); 16799 Consumer.HandleImplicitImportDecl(ImportD); 16800 16801 // Make the module visible. 16802 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16803 VisibleModules.setVisible(Mod, Loc); 16804 } 16805 16806 /// We have parsed the start of an export declaration, including the '{' 16807 /// (if present). 16808 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16809 SourceLocation LBraceLoc) { 16810 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16811 16812 // C++ Modules TS draft: 16813 // An export-declaration shall appear in the purview of a module other than 16814 // the global module. 16815 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 16816 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16817 16818 // An export-declaration [...] shall not contain more than one 16819 // export keyword. 16820 // 16821 // The intent here is that an export-declaration cannot appear within another 16822 // export-declaration. 16823 if (D->isExported()) 16824 Diag(ExportLoc, diag::err_export_within_export); 16825 16826 CurContext->addDecl(D); 16827 PushDeclContext(S, D); 16828 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16829 return D; 16830 } 16831 16832 /// Complete the definition of an export declaration. 16833 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16834 auto *ED = cast<ExportDecl>(D); 16835 if (RBraceLoc.isValid()) 16836 ED->setRBraceLoc(RBraceLoc); 16837 16838 // FIXME: Diagnose export of internal-linkage declaration (including 16839 // anonymous namespace). 16840 16841 PopDeclContext(); 16842 return D; 16843 } 16844 16845 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16846 IdentifierInfo* AliasName, 16847 SourceLocation PragmaLoc, 16848 SourceLocation NameLoc, 16849 SourceLocation AliasNameLoc) { 16850 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16851 LookupOrdinaryName); 16852 AsmLabelAttr *Attr = 16853 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16854 16855 // If a declaration that: 16856 // 1) declares a function or a variable 16857 // 2) has external linkage 16858 // already exists, add a label attribute to it. 16859 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16860 if (isDeclExternC(PrevDecl)) 16861 PrevDecl->addAttr(Attr); 16862 else 16863 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16864 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16865 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16866 } else 16867 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16868 } 16869 16870 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16871 SourceLocation PragmaLoc, 16872 SourceLocation NameLoc) { 16873 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16874 16875 if (PrevDecl) { 16876 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16877 } else { 16878 (void)WeakUndeclaredIdentifiers.insert( 16879 std::pair<IdentifierInfo*,WeakInfo> 16880 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16881 } 16882 } 16883 16884 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16885 IdentifierInfo* AliasName, 16886 SourceLocation PragmaLoc, 16887 SourceLocation NameLoc, 16888 SourceLocation AliasNameLoc) { 16889 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16890 LookupOrdinaryName); 16891 WeakInfo W = WeakInfo(Name, NameLoc); 16892 16893 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16894 if (!PrevDecl->hasAttr<AliasAttr>()) 16895 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16896 DeclApplyPragmaWeak(TUScope, ND, W); 16897 } else { 16898 (void)WeakUndeclaredIdentifiers.insert( 16899 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16900 } 16901 } 16902 16903 Decl *Sema::getObjCDeclContext() const { 16904 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16905 } 16906