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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2456 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2457 AttrSpellingListIndex, 2458 IA->getSemanticSpelling()); 2459 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2460 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2461 &S.Context.Idents.get(AA->getSpelling()), 2462 AttrSpellingListIndex); 2463 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2464 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2465 isa<CUDAGlobalAttr>(Attr))) { 2466 // CUDA target attributes are part of function signature for 2467 // overloading purposes and must not be merged. 2468 return false; 2469 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2470 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2471 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2472 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2473 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2474 NewAttr = S.mergeInternalLinkageAttr( 2475 D, InternalLinkageA->getRange(), 2476 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2477 AttrSpellingListIndex); 2478 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2479 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2480 &S.Context.Idents.get(CommonA->getSpelling()), 2481 AttrSpellingListIndex); 2482 else if (isa<AlignedAttr>(Attr)) 2483 // AlignedAttrs are handled separately, because we need to handle all 2484 // such attributes on a declaration at the same time. 2485 NewAttr = nullptr; 2486 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2487 (AMK == Sema::AMK_Override || 2488 AMK == Sema::AMK_ProtocolImplementation)) 2489 NewAttr = nullptr; 2490 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2491 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2492 UA->getGuid()); 2493 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2494 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2495 2496 if (NewAttr) { 2497 NewAttr->setInherited(true); 2498 D->addAttr(NewAttr); 2499 if (isa<MSInheritanceAttr>(NewAttr)) 2500 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2501 return true; 2502 } 2503 2504 return false; 2505 } 2506 2507 static const NamedDecl *getDefinition(const Decl *D) { 2508 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2509 return TD->getDefinition(); 2510 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2511 const VarDecl *Def = VD->getDefinition(); 2512 if (Def) 2513 return Def; 2514 return VD->getActingDefinition(); 2515 } 2516 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2517 return FD->getDefinition(); 2518 return nullptr; 2519 } 2520 2521 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2522 for (const auto *Attribute : D->attrs()) 2523 if (Attribute->getKind() == Kind) 2524 return true; 2525 return false; 2526 } 2527 2528 /// checkNewAttributesAfterDef - If we already have a definition, check that 2529 /// there are no new attributes in this declaration. 2530 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2531 if (!New->hasAttrs()) 2532 return; 2533 2534 const NamedDecl *Def = getDefinition(Old); 2535 if (!Def || Def == New) 2536 return; 2537 2538 AttrVec &NewAttributes = New->getAttrs(); 2539 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2540 const Attr *NewAttribute = NewAttributes[I]; 2541 2542 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2543 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2544 Sema::SkipBodyInfo SkipBody; 2545 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2546 2547 // If we're skipping this definition, drop the "alias" attribute. 2548 if (SkipBody.ShouldSkip) { 2549 NewAttributes.erase(NewAttributes.begin() + I); 2550 --E; 2551 continue; 2552 } 2553 } else { 2554 VarDecl *VD = cast<VarDecl>(New); 2555 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2556 VarDecl::TentativeDefinition 2557 ? diag::err_alias_after_tentative 2558 : diag::err_redefinition; 2559 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2560 if (Diag == diag::err_redefinition) 2561 S.notePreviousDefinition(Def, VD->getLocation()); 2562 else 2563 S.Diag(Def->getLocation(), diag::note_previous_definition); 2564 VD->setInvalidDecl(); 2565 } 2566 ++I; 2567 continue; 2568 } 2569 2570 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2571 // Tentative definitions are only interesting for the alias check above. 2572 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2573 ++I; 2574 continue; 2575 } 2576 } 2577 2578 if (hasAttribute(Def, NewAttribute->getKind())) { 2579 ++I; 2580 continue; // regular attr merging will take care of validating this. 2581 } 2582 2583 if (isa<C11NoReturnAttr>(NewAttribute)) { 2584 // C's _Noreturn is allowed to be added to a function after it is defined. 2585 ++I; 2586 continue; 2587 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2588 if (AA->isAlignas()) { 2589 // C++11 [dcl.align]p6: 2590 // if any declaration of an entity has an alignment-specifier, 2591 // every defining declaration of that entity shall specify an 2592 // equivalent alignment. 2593 // C11 6.7.5/7: 2594 // If the definition of an object does not have an alignment 2595 // specifier, any other declaration of that object shall also 2596 // have no alignment specifier. 2597 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2598 << AA; 2599 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2600 << AA; 2601 NewAttributes.erase(NewAttributes.begin() + I); 2602 --E; 2603 continue; 2604 } 2605 } 2606 2607 S.Diag(NewAttribute->getLocation(), 2608 diag::warn_attribute_precede_definition); 2609 S.Diag(Def->getLocation(), diag::note_previous_definition); 2610 NewAttributes.erase(NewAttributes.begin() + I); 2611 --E; 2612 } 2613 } 2614 2615 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2616 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2617 AvailabilityMergeKind AMK) { 2618 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2619 UsedAttr *NewAttr = OldAttr->clone(Context); 2620 NewAttr->setInherited(true); 2621 New->addAttr(NewAttr); 2622 } 2623 2624 if (!Old->hasAttrs() && !New->hasAttrs()) 2625 return; 2626 2627 // Attributes declared post-definition are currently ignored. 2628 checkNewAttributesAfterDef(*this, New, Old); 2629 2630 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2631 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2632 if (OldA->getLabel() != NewA->getLabel()) { 2633 // This redeclaration changes __asm__ label. 2634 Diag(New->getLocation(), diag::err_different_asm_label); 2635 Diag(OldA->getLocation(), diag::note_previous_declaration); 2636 } 2637 } else if (Old->isUsed()) { 2638 // This redeclaration adds an __asm__ label to a declaration that has 2639 // already been ODR-used. 2640 Diag(New->getLocation(), diag::err_late_asm_label_name) 2641 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2642 } 2643 } 2644 2645 // Re-declaration cannot add abi_tag's. 2646 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2647 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2648 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2649 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2650 NewTag) == OldAbiTagAttr->tags_end()) { 2651 Diag(NewAbiTagAttr->getLocation(), 2652 diag::err_new_abi_tag_on_redeclaration) 2653 << NewTag; 2654 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2655 } 2656 } 2657 } else { 2658 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2659 Diag(Old->getLocation(), diag::note_previous_declaration); 2660 } 2661 } 2662 2663 // This redeclaration adds a section attribute. 2664 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2665 if (auto *VD = dyn_cast<VarDecl>(New)) { 2666 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2667 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2668 Diag(Old->getLocation(), diag::note_previous_declaration); 2669 } 2670 } 2671 } 2672 2673 if (!Old->hasAttrs()) 2674 return; 2675 2676 bool foundAny = New->hasAttrs(); 2677 2678 // Ensure that any moving of objects within the allocated map is done before 2679 // we process them. 2680 if (!foundAny) New->setAttrs(AttrVec()); 2681 2682 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2683 // Ignore deprecated/unavailable/availability attributes if requested. 2684 AvailabilityMergeKind LocalAMK = AMK_None; 2685 if (isa<DeprecatedAttr>(I) || 2686 isa<UnavailableAttr>(I) || 2687 isa<AvailabilityAttr>(I)) { 2688 switch (AMK) { 2689 case AMK_None: 2690 continue; 2691 2692 case AMK_Redeclaration: 2693 case AMK_Override: 2694 case AMK_ProtocolImplementation: 2695 LocalAMK = AMK; 2696 break; 2697 } 2698 } 2699 2700 // Already handled. 2701 if (isa<UsedAttr>(I)) 2702 continue; 2703 2704 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2705 foundAny = true; 2706 } 2707 2708 if (mergeAlignedAttrs(*this, New, Old)) 2709 foundAny = true; 2710 2711 if (!foundAny) New->dropAttrs(); 2712 } 2713 2714 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2715 /// to the new one. 2716 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2717 const ParmVarDecl *oldDecl, 2718 Sema &S) { 2719 // C++11 [dcl.attr.depend]p2: 2720 // The first declaration of a function shall specify the 2721 // carries_dependency attribute for its declarator-id if any declaration 2722 // of the function specifies the carries_dependency attribute. 2723 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2724 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2725 S.Diag(CDA->getLocation(), 2726 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2727 // Find the first declaration of the parameter. 2728 // FIXME: Should we build redeclaration chains for function parameters? 2729 const FunctionDecl *FirstFD = 2730 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2731 const ParmVarDecl *FirstVD = 2732 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2733 S.Diag(FirstVD->getLocation(), 2734 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2735 } 2736 2737 if (!oldDecl->hasAttrs()) 2738 return; 2739 2740 bool foundAny = newDecl->hasAttrs(); 2741 2742 // Ensure that any moving of objects within the allocated map is 2743 // done before we process them. 2744 if (!foundAny) newDecl->setAttrs(AttrVec()); 2745 2746 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2747 if (!DeclHasAttr(newDecl, I)) { 2748 InheritableAttr *newAttr = 2749 cast<InheritableParamAttr>(I->clone(S.Context)); 2750 newAttr->setInherited(true); 2751 newDecl->addAttr(newAttr); 2752 foundAny = true; 2753 } 2754 } 2755 2756 if (!foundAny) newDecl->dropAttrs(); 2757 } 2758 2759 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2760 const ParmVarDecl *OldParam, 2761 Sema &S) { 2762 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2763 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2764 if (*Oldnullability != *Newnullability) { 2765 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2766 << DiagNullabilityKind( 2767 *Newnullability, 2768 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2769 != 0)) 2770 << DiagNullabilityKind( 2771 *Oldnullability, 2772 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2773 != 0)); 2774 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2775 } 2776 } else { 2777 QualType NewT = NewParam->getType(); 2778 NewT = S.Context.getAttributedType( 2779 AttributedType::getNullabilityAttrKind(*Oldnullability), 2780 NewT, NewT); 2781 NewParam->setType(NewT); 2782 } 2783 } 2784 } 2785 2786 namespace { 2787 2788 /// Used in MergeFunctionDecl to keep track of function parameters in 2789 /// C. 2790 struct GNUCompatibleParamWarning { 2791 ParmVarDecl *OldParm; 2792 ParmVarDecl *NewParm; 2793 QualType PromotedType; 2794 }; 2795 2796 } // end anonymous namespace 2797 2798 /// getSpecialMember - get the special member enum for a method. 2799 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2800 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2801 if (Ctor->isDefaultConstructor()) 2802 return Sema::CXXDefaultConstructor; 2803 2804 if (Ctor->isCopyConstructor()) 2805 return Sema::CXXCopyConstructor; 2806 2807 if (Ctor->isMoveConstructor()) 2808 return Sema::CXXMoveConstructor; 2809 } else if (isa<CXXDestructorDecl>(MD)) { 2810 return Sema::CXXDestructor; 2811 } else if (MD->isCopyAssignmentOperator()) { 2812 return Sema::CXXCopyAssignment; 2813 } else if (MD->isMoveAssignmentOperator()) { 2814 return Sema::CXXMoveAssignment; 2815 } 2816 2817 return Sema::CXXInvalid; 2818 } 2819 2820 // Determine whether the previous declaration was a definition, implicit 2821 // declaration, or a declaration. 2822 template <typename T> 2823 static std::pair<diag::kind, SourceLocation> 2824 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2825 diag::kind PrevDiag; 2826 SourceLocation OldLocation = Old->getLocation(); 2827 if (Old->isThisDeclarationADefinition()) 2828 PrevDiag = diag::note_previous_definition; 2829 else if (Old->isImplicit()) { 2830 PrevDiag = diag::note_previous_implicit_declaration; 2831 if (OldLocation.isInvalid()) 2832 OldLocation = New->getLocation(); 2833 } else 2834 PrevDiag = diag::note_previous_declaration; 2835 return std::make_pair(PrevDiag, OldLocation); 2836 } 2837 2838 /// canRedefineFunction - checks if a function can be redefined. Currently, 2839 /// only extern inline functions can be redefined, and even then only in 2840 /// GNU89 mode. 2841 static bool canRedefineFunction(const FunctionDecl *FD, 2842 const LangOptions& LangOpts) { 2843 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2844 !LangOpts.CPlusPlus && 2845 FD->isInlineSpecified() && 2846 FD->getStorageClass() == SC_Extern); 2847 } 2848 2849 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2850 const AttributedType *AT = T->getAs<AttributedType>(); 2851 while (AT && !AT->isCallingConv()) 2852 AT = AT->getModifiedType()->getAs<AttributedType>(); 2853 return AT; 2854 } 2855 2856 template <typename T> 2857 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2858 const DeclContext *DC = Old->getDeclContext(); 2859 if (DC->isRecord()) 2860 return false; 2861 2862 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2863 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2864 return true; 2865 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2866 return true; 2867 return false; 2868 } 2869 2870 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2871 static bool isExternC(VarTemplateDecl *) { return false; } 2872 2873 /// \brief Check whether a redeclaration of an entity introduced by a 2874 /// using-declaration is valid, given that we know it's not an overload 2875 /// (nor a hidden tag declaration). 2876 template<typename ExpectedDecl> 2877 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2878 ExpectedDecl *New) { 2879 // C++11 [basic.scope.declarative]p4: 2880 // Given a set of declarations in a single declarative region, each of 2881 // which specifies the same unqualified name, 2882 // -- they shall all refer to the same entity, or all refer to functions 2883 // and function templates; or 2884 // -- exactly one declaration shall declare a class name or enumeration 2885 // name that is not a typedef name and the other declarations shall all 2886 // refer to the same variable or enumerator, or all refer to functions 2887 // and function templates; in this case the class name or enumeration 2888 // name is hidden (3.3.10). 2889 2890 // C++11 [namespace.udecl]p14: 2891 // If a function declaration in namespace scope or block scope has the 2892 // same name and the same parameter-type-list as a function introduced 2893 // by a using-declaration, and the declarations do not declare the same 2894 // function, the program is ill-formed. 2895 2896 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2897 if (Old && 2898 !Old->getDeclContext()->getRedeclContext()->Equals( 2899 New->getDeclContext()->getRedeclContext()) && 2900 !(isExternC(Old) && isExternC(New))) 2901 Old = nullptr; 2902 2903 if (!Old) { 2904 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2905 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2906 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2907 return true; 2908 } 2909 return false; 2910 } 2911 2912 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2913 const FunctionDecl *B) { 2914 assert(A->getNumParams() == B->getNumParams()); 2915 2916 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2917 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2918 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2919 if (AttrA == AttrB) 2920 return true; 2921 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2922 }; 2923 2924 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2925 } 2926 2927 /// If necessary, adjust the semantic declaration context for a qualified 2928 /// declaration to name the correct inline namespace within the qualifier. 2929 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2930 DeclaratorDecl *OldD) { 2931 // The only case where we need to update the DeclContext is when 2932 // redeclaration lookup for a qualified name finds a declaration 2933 // in an inline namespace within the context named by the qualifier: 2934 // 2935 // inline namespace N { int f(); } 2936 // int ::f(); // Sema DC needs adjusting from :: to N::. 2937 // 2938 // For unqualified declarations, the semantic context *can* change 2939 // along the redeclaration chain (for local extern declarations, 2940 // extern "C" declarations, and friend declarations in particular). 2941 if (!NewD->getQualifier()) 2942 return; 2943 2944 // NewD is probably already in the right context. 2945 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2946 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2947 if (NamedDC->Equals(SemaDC)) 2948 return; 2949 2950 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2951 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2952 "unexpected context for redeclaration"); 2953 2954 auto *LexDC = NewD->getLexicalDeclContext(); 2955 auto FixSemaDC = [=](NamedDecl *D) { 2956 if (!D) 2957 return; 2958 D->setDeclContext(SemaDC); 2959 D->setLexicalDeclContext(LexDC); 2960 }; 2961 2962 FixSemaDC(NewD); 2963 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 2964 FixSemaDC(FD->getDescribedFunctionTemplate()); 2965 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 2966 FixSemaDC(VD->getDescribedVarTemplate()); 2967 } 2968 2969 /// MergeFunctionDecl - We just parsed a function 'New' from 2970 /// declarator D which has the same name and scope as a previous 2971 /// declaration 'Old'. Figure out how to resolve this situation, 2972 /// merging decls or emitting diagnostics as appropriate. 2973 /// 2974 /// In C++, New and Old must be declarations that are not 2975 /// overloaded. Use IsOverload to determine whether New and Old are 2976 /// overloaded, and to select the Old declaration that New should be 2977 /// merged with. 2978 /// 2979 /// Returns true if there was an error, false otherwise. 2980 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2981 Scope *S, bool MergeTypeWithOld) { 2982 // Verify the old decl was also a function. 2983 FunctionDecl *Old = OldD->getAsFunction(); 2984 if (!Old) { 2985 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2986 if (New->getFriendObjectKind()) { 2987 Diag(New->getLocation(), diag::err_using_decl_friend); 2988 Diag(Shadow->getTargetDecl()->getLocation(), 2989 diag::note_using_decl_target); 2990 Diag(Shadow->getUsingDecl()->getLocation(), 2991 diag::note_using_decl) << 0; 2992 return true; 2993 } 2994 2995 // Check whether the two declarations might declare the same function. 2996 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2997 return true; 2998 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2999 } else { 3000 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3001 << New->getDeclName(); 3002 notePreviousDefinition(OldD, New->getLocation()); 3003 return true; 3004 } 3005 } 3006 3007 // If the old declaration is invalid, just give up here. 3008 if (Old->isInvalidDecl()) 3009 return true; 3010 3011 // Disallow redeclaration of some builtins. 3012 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3013 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3014 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3015 << Old << Old->getType(); 3016 return true; 3017 } 3018 3019 diag::kind PrevDiag; 3020 SourceLocation OldLocation; 3021 std::tie(PrevDiag, OldLocation) = 3022 getNoteDiagForInvalidRedeclaration(Old, New); 3023 3024 // Don't complain about this if we're in GNU89 mode and the old function 3025 // is an extern inline function. 3026 // Don't complain about specializations. They are not supposed to have 3027 // storage classes. 3028 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3029 New->getStorageClass() == SC_Static && 3030 Old->hasExternalFormalLinkage() && 3031 !New->getTemplateSpecializationInfo() && 3032 !canRedefineFunction(Old, getLangOpts())) { 3033 if (getLangOpts().MicrosoftExt) { 3034 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3035 Diag(OldLocation, PrevDiag); 3036 } else { 3037 Diag(New->getLocation(), diag::err_static_non_static) << New; 3038 Diag(OldLocation, PrevDiag); 3039 return true; 3040 } 3041 } 3042 3043 if (New->hasAttr<InternalLinkageAttr>() && 3044 !Old->hasAttr<InternalLinkageAttr>()) { 3045 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3046 << New->getDeclName(); 3047 notePreviousDefinition(Old, New->getLocation()); 3048 New->dropAttr<InternalLinkageAttr>(); 3049 } 3050 3051 if (CheckRedeclarationModuleOwnership(New, Old)) 3052 return true; 3053 3054 if (!getLangOpts().CPlusPlus) { 3055 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3056 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3057 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3058 << New << OldOvl; 3059 3060 // Try our best to find a decl that actually has the overloadable 3061 // attribute for the note. In most cases (e.g. programs with only one 3062 // broken declaration/definition), this won't matter. 3063 // 3064 // FIXME: We could do this if we juggled some extra state in 3065 // OverloadableAttr, rather than just removing it. 3066 const Decl *DiagOld = Old; 3067 if (OldOvl) { 3068 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3069 const auto *A = D->getAttr<OverloadableAttr>(); 3070 return A && !A->isImplicit(); 3071 }); 3072 // If we've implicitly added *all* of the overloadable attrs to this 3073 // chain, emitting a "previous redecl" note is pointless. 3074 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3075 } 3076 3077 if (DiagOld) 3078 Diag(DiagOld->getLocation(), 3079 diag::note_attribute_overloadable_prev_overload) 3080 << OldOvl; 3081 3082 if (OldOvl) 3083 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3084 else 3085 New->dropAttr<OverloadableAttr>(); 3086 } 3087 } 3088 3089 // If a function is first declared with a calling convention, but is later 3090 // declared or defined without one, all following decls assume the calling 3091 // convention of the first. 3092 // 3093 // It's OK if a function is first declared without a calling convention, 3094 // but is later declared or defined with the default calling convention. 3095 // 3096 // To test if either decl has an explicit calling convention, we look for 3097 // AttributedType sugar nodes on the type as written. If they are missing or 3098 // were canonicalized away, we assume the calling convention was implicit. 3099 // 3100 // Note also that we DO NOT return at this point, because we still have 3101 // other tests to run. 3102 QualType OldQType = Context.getCanonicalType(Old->getType()); 3103 QualType NewQType = Context.getCanonicalType(New->getType()); 3104 const FunctionType *OldType = cast<FunctionType>(OldQType); 3105 const FunctionType *NewType = cast<FunctionType>(NewQType); 3106 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3107 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3108 bool RequiresAdjustment = false; 3109 3110 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3111 FunctionDecl *First = Old->getFirstDecl(); 3112 const FunctionType *FT = 3113 First->getType().getCanonicalType()->castAs<FunctionType>(); 3114 FunctionType::ExtInfo FI = FT->getExtInfo(); 3115 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3116 if (!NewCCExplicit) { 3117 // Inherit the CC from the previous declaration if it was specified 3118 // there but not here. 3119 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3120 RequiresAdjustment = true; 3121 } else { 3122 // Calling conventions aren't compatible, so complain. 3123 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3124 Diag(New->getLocation(), diag::err_cconv_change) 3125 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3126 << !FirstCCExplicit 3127 << (!FirstCCExplicit ? "" : 3128 FunctionType::getNameForCallConv(FI.getCC())); 3129 3130 // Put the note on the first decl, since it is the one that matters. 3131 Diag(First->getLocation(), diag::note_previous_declaration); 3132 return true; 3133 } 3134 } 3135 3136 // FIXME: diagnose the other way around? 3137 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3138 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3139 RequiresAdjustment = true; 3140 } 3141 3142 // Merge regparm attribute. 3143 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3144 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3145 if (NewTypeInfo.getHasRegParm()) { 3146 Diag(New->getLocation(), diag::err_regparm_mismatch) 3147 << NewType->getRegParmType() 3148 << OldType->getRegParmType(); 3149 Diag(OldLocation, diag::note_previous_declaration); 3150 return true; 3151 } 3152 3153 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3154 RequiresAdjustment = true; 3155 } 3156 3157 // Merge ns_returns_retained attribute. 3158 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3159 if (NewTypeInfo.getProducesResult()) { 3160 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3161 << "'ns_returns_retained'"; 3162 Diag(OldLocation, diag::note_previous_declaration); 3163 return true; 3164 } 3165 3166 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3167 RequiresAdjustment = true; 3168 } 3169 3170 if (OldTypeInfo.getNoCallerSavedRegs() != 3171 NewTypeInfo.getNoCallerSavedRegs()) { 3172 if (NewTypeInfo.getNoCallerSavedRegs()) { 3173 AnyX86NoCallerSavedRegistersAttr *Attr = 3174 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3175 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3176 Diag(OldLocation, diag::note_previous_declaration); 3177 return true; 3178 } 3179 3180 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3181 RequiresAdjustment = true; 3182 } 3183 3184 if (RequiresAdjustment) { 3185 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3186 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3187 New->setType(QualType(AdjustedType, 0)); 3188 NewQType = Context.getCanonicalType(New->getType()); 3189 NewType = cast<FunctionType>(NewQType); 3190 } 3191 3192 // If this redeclaration makes the function inline, we may need to add it to 3193 // UndefinedButUsed. 3194 if (!Old->isInlined() && New->isInlined() && 3195 !New->hasAttr<GNUInlineAttr>() && 3196 !getLangOpts().GNUInline && 3197 Old->isUsed(false) && 3198 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3199 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3200 SourceLocation())); 3201 3202 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3203 // about it. 3204 if (New->hasAttr<GNUInlineAttr>() && 3205 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3206 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3207 } 3208 3209 // If pass_object_size params don't match up perfectly, this isn't a valid 3210 // redeclaration. 3211 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3212 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3213 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3214 << New->getDeclName(); 3215 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3216 return true; 3217 } 3218 3219 if (getLangOpts().CPlusPlus) { 3220 // C++1z [over.load]p2 3221 // Certain function declarations cannot be overloaded: 3222 // -- Function declarations that differ only in the return type, 3223 // the exception specification, or both cannot be overloaded. 3224 3225 // Check the exception specifications match. This may recompute the type of 3226 // both Old and New if it resolved exception specifications, so grab the 3227 // types again after this. Because this updates the type, we do this before 3228 // any of the other checks below, which may update the "de facto" NewQType 3229 // but do not necessarily update the type of New. 3230 if (CheckEquivalentExceptionSpec(Old, New)) 3231 return true; 3232 OldQType = Context.getCanonicalType(Old->getType()); 3233 NewQType = Context.getCanonicalType(New->getType()); 3234 3235 // Go back to the type source info to compare the declared return types, 3236 // per C++1y [dcl.type.auto]p13: 3237 // Redeclarations or specializations of a function or function template 3238 // with a declared return type that uses a placeholder type shall also 3239 // use that placeholder, not a deduced type. 3240 QualType OldDeclaredReturnType = 3241 (Old->getTypeSourceInfo() 3242 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3243 : OldType)->getReturnType(); 3244 QualType NewDeclaredReturnType = 3245 (New->getTypeSourceInfo() 3246 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3247 : NewType)->getReturnType(); 3248 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3249 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3250 New->isLocalExternDecl())) { 3251 QualType ResQT; 3252 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3253 OldDeclaredReturnType->isObjCObjectPointerType()) 3254 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3255 if (ResQT.isNull()) { 3256 if (New->isCXXClassMember() && New->isOutOfLine()) 3257 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3258 << New << New->getReturnTypeSourceRange(); 3259 else 3260 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3261 << New->getReturnTypeSourceRange(); 3262 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3263 << Old->getReturnTypeSourceRange(); 3264 return true; 3265 } 3266 else 3267 NewQType = ResQT; 3268 } 3269 3270 QualType OldReturnType = OldType->getReturnType(); 3271 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3272 if (OldReturnType != NewReturnType) { 3273 // If this function has a deduced return type and has already been 3274 // defined, copy the deduced value from the old declaration. 3275 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3276 if (OldAT && OldAT->isDeduced()) { 3277 New->setType( 3278 SubstAutoType(New->getType(), 3279 OldAT->isDependentType() ? Context.DependentTy 3280 : OldAT->getDeducedType())); 3281 NewQType = Context.getCanonicalType( 3282 SubstAutoType(NewQType, 3283 OldAT->isDependentType() ? Context.DependentTy 3284 : OldAT->getDeducedType())); 3285 } 3286 } 3287 3288 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3289 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3290 if (OldMethod && NewMethod) { 3291 // Preserve triviality. 3292 NewMethod->setTrivial(OldMethod->isTrivial()); 3293 3294 // MSVC allows explicit template specialization at class scope: 3295 // 2 CXXMethodDecls referring to the same function will be injected. 3296 // We don't want a redeclaration error. 3297 bool IsClassScopeExplicitSpecialization = 3298 OldMethod->isFunctionTemplateSpecialization() && 3299 NewMethod->isFunctionTemplateSpecialization(); 3300 bool isFriend = NewMethod->getFriendObjectKind(); 3301 3302 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3303 !IsClassScopeExplicitSpecialization) { 3304 // -- Member function declarations with the same name and the 3305 // same parameter types cannot be overloaded if any of them 3306 // is a static member function declaration. 3307 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3308 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3309 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3310 return true; 3311 } 3312 3313 // C++ [class.mem]p1: 3314 // [...] A member shall not be declared twice in the 3315 // member-specification, except that a nested class or member 3316 // class template can be declared and then later defined. 3317 if (!inTemplateInstantiation()) { 3318 unsigned NewDiag; 3319 if (isa<CXXConstructorDecl>(OldMethod)) 3320 NewDiag = diag::err_constructor_redeclared; 3321 else if (isa<CXXDestructorDecl>(NewMethod)) 3322 NewDiag = diag::err_destructor_redeclared; 3323 else if (isa<CXXConversionDecl>(NewMethod)) 3324 NewDiag = diag::err_conv_function_redeclared; 3325 else 3326 NewDiag = diag::err_member_redeclared; 3327 3328 Diag(New->getLocation(), NewDiag); 3329 } else { 3330 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3331 << New << New->getType(); 3332 } 3333 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3334 return true; 3335 3336 // Complain if this is an explicit declaration of a special 3337 // member that was initially declared implicitly. 3338 // 3339 // As an exception, it's okay to befriend such methods in order 3340 // to permit the implicit constructor/destructor/operator calls. 3341 } else if (OldMethod->isImplicit()) { 3342 if (isFriend) { 3343 NewMethod->setImplicit(); 3344 } else { 3345 Diag(NewMethod->getLocation(), 3346 diag::err_definition_of_implicitly_declared_member) 3347 << New << getSpecialMember(OldMethod); 3348 return true; 3349 } 3350 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3351 Diag(NewMethod->getLocation(), 3352 diag::err_definition_of_explicitly_defaulted_member) 3353 << getSpecialMember(OldMethod); 3354 return true; 3355 } 3356 } 3357 3358 // C++11 [dcl.attr.noreturn]p1: 3359 // The first declaration of a function shall specify the noreturn 3360 // attribute if any declaration of that function specifies the noreturn 3361 // attribute. 3362 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3363 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3364 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3365 Diag(Old->getFirstDecl()->getLocation(), 3366 diag::note_noreturn_missing_first_decl); 3367 } 3368 3369 // C++11 [dcl.attr.depend]p2: 3370 // The first declaration of a function shall specify the 3371 // carries_dependency attribute for its declarator-id if any declaration 3372 // of the function specifies the carries_dependency attribute. 3373 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3374 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3375 Diag(CDA->getLocation(), 3376 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3377 Diag(Old->getFirstDecl()->getLocation(), 3378 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3379 } 3380 3381 // (C++98 8.3.5p3): 3382 // All declarations for a function shall agree exactly in both the 3383 // return type and the parameter-type-list. 3384 // We also want to respect all the extended bits except noreturn. 3385 3386 // noreturn should now match unless the old type info didn't have it. 3387 QualType OldQTypeForComparison = OldQType; 3388 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3389 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3390 const FunctionType *OldTypeForComparison 3391 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3392 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3393 assert(OldQTypeForComparison.isCanonical()); 3394 } 3395 3396 if (haveIncompatibleLanguageLinkages(Old, New)) { 3397 // As a special case, retain the language linkage from previous 3398 // declarations of a friend function as an extension. 3399 // 3400 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3401 // and is useful because there's otherwise no way to specify language 3402 // linkage within class scope. 3403 // 3404 // Check cautiously as the friend object kind isn't yet complete. 3405 if (New->getFriendObjectKind() != Decl::FOK_None) { 3406 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3407 Diag(OldLocation, PrevDiag); 3408 } else { 3409 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3410 Diag(OldLocation, PrevDiag); 3411 return true; 3412 } 3413 } 3414 3415 if (OldQTypeForComparison == NewQType) 3416 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3417 3418 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3419 New->isLocalExternDecl()) { 3420 // It's OK if we couldn't merge types for a local function declaraton 3421 // if either the old or new type is dependent. We'll merge the types 3422 // when we instantiate the function. 3423 return false; 3424 } 3425 3426 // Fall through for conflicting redeclarations and redefinitions. 3427 } 3428 3429 // C: Function types need to be compatible, not identical. This handles 3430 // duplicate function decls like "void f(int); void f(enum X);" properly. 3431 if (!getLangOpts().CPlusPlus && 3432 Context.typesAreCompatible(OldQType, NewQType)) { 3433 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3434 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3435 const FunctionProtoType *OldProto = nullptr; 3436 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3437 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3438 // The old declaration provided a function prototype, but the 3439 // new declaration does not. Merge in the prototype. 3440 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3441 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3442 NewQType = 3443 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3444 OldProto->getExtProtoInfo()); 3445 New->setType(NewQType); 3446 New->setHasInheritedPrototype(); 3447 3448 // Synthesize parameters with the same types. 3449 SmallVector<ParmVarDecl*, 16> Params; 3450 for (const auto &ParamType : OldProto->param_types()) { 3451 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3452 SourceLocation(), nullptr, 3453 ParamType, /*TInfo=*/nullptr, 3454 SC_None, nullptr); 3455 Param->setScopeInfo(0, Params.size()); 3456 Param->setImplicit(); 3457 Params.push_back(Param); 3458 } 3459 3460 New->setParams(Params); 3461 } 3462 3463 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3464 } 3465 3466 // GNU C permits a K&R definition to follow a prototype declaration 3467 // if the declared types of the parameters in the K&R definition 3468 // match the types in the prototype declaration, even when the 3469 // promoted types of the parameters from the K&R definition differ 3470 // from the types in the prototype. GCC then keeps the types from 3471 // the prototype. 3472 // 3473 // If a variadic prototype is followed by a non-variadic K&R definition, 3474 // the K&R definition becomes variadic. This is sort of an edge case, but 3475 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3476 // C99 6.9.1p8. 3477 if (!getLangOpts().CPlusPlus && 3478 Old->hasPrototype() && !New->hasPrototype() && 3479 New->getType()->getAs<FunctionProtoType>() && 3480 Old->getNumParams() == New->getNumParams()) { 3481 SmallVector<QualType, 16> ArgTypes; 3482 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3483 const FunctionProtoType *OldProto 3484 = Old->getType()->getAs<FunctionProtoType>(); 3485 const FunctionProtoType *NewProto 3486 = New->getType()->getAs<FunctionProtoType>(); 3487 3488 // Determine whether this is the GNU C extension. 3489 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3490 NewProto->getReturnType()); 3491 bool LooseCompatible = !MergedReturn.isNull(); 3492 for (unsigned Idx = 0, End = Old->getNumParams(); 3493 LooseCompatible && Idx != End; ++Idx) { 3494 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3495 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3496 if (Context.typesAreCompatible(OldParm->getType(), 3497 NewProto->getParamType(Idx))) { 3498 ArgTypes.push_back(NewParm->getType()); 3499 } else if (Context.typesAreCompatible(OldParm->getType(), 3500 NewParm->getType(), 3501 /*CompareUnqualified=*/true)) { 3502 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3503 NewProto->getParamType(Idx) }; 3504 Warnings.push_back(Warn); 3505 ArgTypes.push_back(NewParm->getType()); 3506 } else 3507 LooseCompatible = false; 3508 } 3509 3510 if (LooseCompatible) { 3511 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3512 Diag(Warnings[Warn].NewParm->getLocation(), 3513 diag::ext_param_promoted_not_compatible_with_prototype) 3514 << Warnings[Warn].PromotedType 3515 << Warnings[Warn].OldParm->getType(); 3516 if (Warnings[Warn].OldParm->getLocation().isValid()) 3517 Diag(Warnings[Warn].OldParm->getLocation(), 3518 diag::note_previous_declaration); 3519 } 3520 3521 if (MergeTypeWithOld) 3522 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3523 OldProto->getExtProtoInfo())); 3524 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3525 } 3526 3527 // Fall through to diagnose conflicting types. 3528 } 3529 3530 // A function that has already been declared has been redeclared or 3531 // defined with a different type; show an appropriate diagnostic. 3532 3533 // If the previous declaration was an implicitly-generated builtin 3534 // declaration, then at the very least we should use a specialized note. 3535 unsigned BuiltinID; 3536 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3537 // If it's actually a library-defined builtin function like 'malloc' 3538 // or 'printf', just warn about the incompatible redeclaration. 3539 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3540 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3541 Diag(OldLocation, diag::note_previous_builtin_declaration) 3542 << Old << Old->getType(); 3543 3544 // If this is a global redeclaration, just forget hereafter 3545 // about the "builtin-ness" of the function. 3546 // 3547 // Doing this for local extern declarations is problematic. If 3548 // the builtin declaration remains visible, a second invalid 3549 // local declaration will produce a hard error; if it doesn't 3550 // remain visible, a single bogus local redeclaration (which is 3551 // actually only a warning) could break all the downstream code. 3552 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3553 New->getIdentifier()->revertBuiltin(); 3554 3555 return false; 3556 } 3557 3558 PrevDiag = diag::note_previous_builtin_declaration; 3559 } 3560 3561 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3562 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3563 return true; 3564 } 3565 3566 /// \brief Completes the merge of two function declarations that are 3567 /// known to be compatible. 3568 /// 3569 /// This routine handles the merging of attributes and other 3570 /// properties of function declarations from the old declaration to 3571 /// the new declaration, once we know that New is in fact a 3572 /// redeclaration of Old. 3573 /// 3574 /// \returns false 3575 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3576 Scope *S, bool MergeTypeWithOld) { 3577 // Merge the attributes 3578 mergeDeclAttributes(New, Old); 3579 3580 // Merge "pure" flag. 3581 if (Old->isPure()) 3582 New->setPure(); 3583 3584 // Merge "used" flag. 3585 if (Old->getMostRecentDecl()->isUsed(false)) 3586 New->setIsUsed(); 3587 3588 // Merge attributes from the parameters. These can mismatch with K&R 3589 // declarations. 3590 if (New->getNumParams() == Old->getNumParams()) 3591 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3592 ParmVarDecl *NewParam = New->getParamDecl(i); 3593 ParmVarDecl *OldParam = Old->getParamDecl(i); 3594 mergeParamDeclAttributes(NewParam, OldParam, *this); 3595 mergeParamDeclTypes(NewParam, OldParam, *this); 3596 } 3597 3598 if (getLangOpts().CPlusPlus) 3599 return MergeCXXFunctionDecl(New, Old, S); 3600 3601 // Merge the function types so the we get the composite types for the return 3602 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3603 // was visible. 3604 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3605 if (!Merged.isNull() && MergeTypeWithOld) 3606 New->setType(Merged); 3607 3608 return false; 3609 } 3610 3611 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3612 ObjCMethodDecl *oldMethod) { 3613 // Merge the attributes, including deprecated/unavailable 3614 AvailabilityMergeKind MergeKind = 3615 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3616 ? AMK_ProtocolImplementation 3617 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3618 : AMK_Override; 3619 3620 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3621 3622 // Merge attributes from the parameters. 3623 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3624 oe = oldMethod->param_end(); 3625 for (ObjCMethodDecl::param_iterator 3626 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3627 ni != ne && oi != oe; ++ni, ++oi) 3628 mergeParamDeclAttributes(*ni, *oi, *this); 3629 3630 CheckObjCMethodOverride(newMethod, oldMethod); 3631 } 3632 3633 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3634 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3635 3636 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3637 ? diag::err_redefinition_different_type 3638 : diag::err_redeclaration_different_type) 3639 << New->getDeclName() << New->getType() << Old->getType(); 3640 3641 diag::kind PrevDiag; 3642 SourceLocation OldLocation; 3643 std::tie(PrevDiag, OldLocation) 3644 = getNoteDiagForInvalidRedeclaration(Old, New); 3645 S.Diag(OldLocation, PrevDiag); 3646 New->setInvalidDecl(); 3647 } 3648 3649 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3650 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3651 /// emitting diagnostics as appropriate. 3652 /// 3653 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3654 /// to here in AddInitializerToDecl. We can't check them before the initializer 3655 /// is attached. 3656 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3657 bool MergeTypeWithOld) { 3658 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3659 return; 3660 3661 QualType MergedT; 3662 if (getLangOpts().CPlusPlus) { 3663 if (New->getType()->isUndeducedType()) { 3664 // We don't know what the new type is until the initializer is attached. 3665 return; 3666 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3667 // These could still be something that needs exception specs checked. 3668 return MergeVarDeclExceptionSpecs(New, Old); 3669 } 3670 // C++ [basic.link]p10: 3671 // [...] the types specified by all declarations referring to a given 3672 // object or function shall be identical, except that declarations for an 3673 // array object can specify array types that differ by the presence or 3674 // absence of a major array bound (8.3.4). 3675 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3676 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3677 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3678 3679 // We are merging a variable declaration New into Old. If it has an array 3680 // bound, and that bound differs from Old's bound, we should diagnose the 3681 // mismatch. 3682 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3683 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3684 PrevVD = PrevVD->getPreviousDecl()) { 3685 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3686 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3687 continue; 3688 3689 if (!Context.hasSameType(NewArray, PrevVDTy)) 3690 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3691 } 3692 } 3693 3694 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3695 if (Context.hasSameType(OldArray->getElementType(), 3696 NewArray->getElementType())) 3697 MergedT = New->getType(); 3698 } 3699 // FIXME: Check visibility. New is hidden but has a complete type. If New 3700 // has no array bound, it should not inherit one from Old, if Old is not 3701 // visible. 3702 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3703 if (Context.hasSameType(OldArray->getElementType(), 3704 NewArray->getElementType())) 3705 MergedT = Old->getType(); 3706 } 3707 } 3708 else if (New->getType()->isObjCObjectPointerType() && 3709 Old->getType()->isObjCObjectPointerType()) { 3710 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3711 Old->getType()); 3712 } 3713 } else { 3714 // C 6.2.7p2: 3715 // All declarations that refer to the same object or function shall have 3716 // compatible type. 3717 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3718 } 3719 if (MergedT.isNull()) { 3720 // It's OK if we couldn't merge types if either type is dependent, for a 3721 // block-scope variable. In other cases (static data members of class 3722 // templates, variable templates, ...), we require the types to be 3723 // equivalent. 3724 // FIXME: The C++ standard doesn't say anything about this. 3725 if ((New->getType()->isDependentType() || 3726 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3727 // If the old type was dependent, we can't merge with it, so the new type 3728 // becomes dependent for now. We'll reproduce the original type when we 3729 // instantiate the TypeSourceInfo for the variable. 3730 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3731 New->setType(Context.DependentTy); 3732 return; 3733 } 3734 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3735 } 3736 3737 // Don't actually update the type on the new declaration if the old 3738 // declaration was an extern declaration in a different scope. 3739 if (MergeTypeWithOld) 3740 New->setType(MergedT); 3741 } 3742 3743 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3744 LookupResult &Previous) { 3745 // C11 6.2.7p4: 3746 // For an identifier with internal or external linkage declared 3747 // in a scope in which a prior declaration of that identifier is 3748 // visible, if the prior declaration specifies internal or 3749 // external linkage, the type of the identifier at the later 3750 // declaration becomes the composite type. 3751 // 3752 // If the variable isn't visible, we do not merge with its type. 3753 if (Previous.isShadowed()) 3754 return false; 3755 3756 if (S.getLangOpts().CPlusPlus) { 3757 // C++11 [dcl.array]p3: 3758 // If there is a preceding declaration of the entity in the same 3759 // scope in which the bound was specified, an omitted array bound 3760 // is taken to be the same as in that earlier declaration. 3761 return NewVD->isPreviousDeclInSameBlockScope() || 3762 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3763 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3764 } else { 3765 // If the old declaration was function-local, don't merge with its 3766 // type unless we're in the same function. 3767 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3768 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3769 } 3770 } 3771 3772 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3773 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3774 /// situation, merging decls or emitting diagnostics as appropriate. 3775 /// 3776 /// Tentative definition rules (C99 6.9.2p2) are checked by 3777 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3778 /// definitions here, since the initializer hasn't been attached. 3779 /// 3780 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3781 // If the new decl is already invalid, don't do any other checking. 3782 if (New->isInvalidDecl()) 3783 return; 3784 3785 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3786 return; 3787 3788 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3789 3790 // Verify the old decl was also a variable or variable template. 3791 VarDecl *Old = nullptr; 3792 VarTemplateDecl *OldTemplate = nullptr; 3793 if (Previous.isSingleResult()) { 3794 if (NewTemplate) { 3795 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3796 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3797 3798 if (auto *Shadow = 3799 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3800 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3801 return New->setInvalidDecl(); 3802 } else { 3803 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3804 3805 if (auto *Shadow = 3806 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3807 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3808 return New->setInvalidDecl(); 3809 } 3810 } 3811 if (!Old) { 3812 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3813 << New->getDeclName(); 3814 notePreviousDefinition(Previous.getRepresentativeDecl(), 3815 New->getLocation()); 3816 return New->setInvalidDecl(); 3817 } 3818 3819 // Ensure the template parameters are compatible. 3820 if (NewTemplate && 3821 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3822 OldTemplate->getTemplateParameters(), 3823 /*Complain=*/true, TPL_TemplateMatch)) 3824 return New->setInvalidDecl(); 3825 3826 // C++ [class.mem]p1: 3827 // A member shall not be declared twice in the member-specification [...] 3828 // 3829 // Here, we need only consider static data members. 3830 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3831 Diag(New->getLocation(), diag::err_duplicate_member) 3832 << New->getIdentifier(); 3833 Diag(Old->getLocation(), diag::note_previous_declaration); 3834 New->setInvalidDecl(); 3835 } 3836 3837 mergeDeclAttributes(New, Old); 3838 // Warn if an already-declared variable is made a weak_import in a subsequent 3839 // declaration 3840 if (New->hasAttr<WeakImportAttr>() && 3841 Old->getStorageClass() == SC_None && 3842 !Old->hasAttr<WeakImportAttr>()) { 3843 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3844 notePreviousDefinition(Old, New->getLocation()); 3845 // Remove weak_import attribute on new declaration. 3846 New->dropAttr<WeakImportAttr>(); 3847 } 3848 3849 if (New->hasAttr<InternalLinkageAttr>() && 3850 !Old->hasAttr<InternalLinkageAttr>()) { 3851 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3852 << New->getDeclName(); 3853 notePreviousDefinition(Old, New->getLocation()); 3854 New->dropAttr<InternalLinkageAttr>(); 3855 } 3856 3857 // Merge the types. 3858 VarDecl *MostRecent = Old->getMostRecentDecl(); 3859 if (MostRecent != Old) { 3860 MergeVarDeclTypes(New, MostRecent, 3861 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3862 if (New->isInvalidDecl()) 3863 return; 3864 } 3865 3866 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3867 if (New->isInvalidDecl()) 3868 return; 3869 3870 diag::kind PrevDiag; 3871 SourceLocation OldLocation; 3872 std::tie(PrevDiag, OldLocation) = 3873 getNoteDiagForInvalidRedeclaration(Old, New); 3874 3875 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3876 if (New->getStorageClass() == SC_Static && 3877 !New->isStaticDataMember() && 3878 Old->hasExternalFormalLinkage()) { 3879 if (getLangOpts().MicrosoftExt) { 3880 Diag(New->getLocation(), diag::ext_static_non_static) 3881 << New->getDeclName(); 3882 Diag(OldLocation, PrevDiag); 3883 } else { 3884 Diag(New->getLocation(), diag::err_static_non_static) 3885 << New->getDeclName(); 3886 Diag(OldLocation, PrevDiag); 3887 return New->setInvalidDecl(); 3888 } 3889 } 3890 // C99 6.2.2p4: 3891 // For an identifier declared with the storage-class specifier 3892 // extern in a scope in which a prior declaration of that 3893 // identifier is visible,23) if the prior declaration specifies 3894 // internal or external linkage, the linkage of the identifier at 3895 // the later declaration is the same as the linkage specified at 3896 // the prior declaration. If no prior declaration is visible, or 3897 // if the prior declaration specifies no linkage, then the 3898 // identifier has external linkage. 3899 if (New->hasExternalStorage() && Old->hasLinkage()) 3900 /* Okay */; 3901 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3902 !New->isStaticDataMember() && 3903 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3904 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3905 Diag(OldLocation, PrevDiag); 3906 return New->setInvalidDecl(); 3907 } 3908 3909 // Check if extern is followed by non-extern and vice-versa. 3910 if (New->hasExternalStorage() && 3911 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3912 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3913 Diag(OldLocation, PrevDiag); 3914 return New->setInvalidDecl(); 3915 } 3916 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3917 !New->hasExternalStorage()) { 3918 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3919 Diag(OldLocation, PrevDiag); 3920 return New->setInvalidDecl(); 3921 } 3922 3923 if (CheckRedeclarationModuleOwnership(New, Old)) 3924 return; 3925 3926 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3927 3928 // FIXME: The test for external storage here seems wrong? We still 3929 // need to check for mismatches. 3930 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3931 // Don't complain about out-of-line definitions of static members. 3932 !(Old->getLexicalDeclContext()->isRecord() && 3933 !New->getLexicalDeclContext()->isRecord())) { 3934 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3935 Diag(OldLocation, PrevDiag); 3936 return New->setInvalidDecl(); 3937 } 3938 3939 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3940 if (VarDecl *Def = Old->getDefinition()) { 3941 // C++1z [dcl.fcn.spec]p4: 3942 // If the definition of a variable appears in a translation unit before 3943 // its first declaration as inline, the program is ill-formed. 3944 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3945 Diag(Def->getLocation(), diag::note_previous_definition); 3946 } 3947 } 3948 3949 // If this redeclaration makes the variable inline, we may need to add it to 3950 // UndefinedButUsed. 3951 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3952 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3953 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3954 SourceLocation())); 3955 3956 if (New->getTLSKind() != Old->getTLSKind()) { 3957 if (!Old->getTLSKind()) { 3958 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3959 Diag(OldLocation, PrevDiag); 3960 } else if (!New->getTLSKind()) { 3961 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3962 Diag(OldLocation, PrevDiag); 3963 } else { 3964 // Do not allow redeclaration to change the variable between requiring 3965 // static and dynamic initialization. 3966 // FIXME: GCC allows this, but uses the TLS keyword on the first 3967 // declaration to determine the kind. Do we need to be compatible here? 3968 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3969 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3970 Diag(OldLocation, PrevDiag); 3971 } 3972 } 3973 3974 // C++ doesn't have tentative definitions, so go right ahead and check here. 3975 if (getLangOpts().CPlusPlus && 3976 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3977 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3978 Old->getCanonicalDecl()->isConstexpr()) { 3979 // This definition won't be a definition any more once it's been merged. 3980 Diag(New->getLocation(), 3981 diag::warn_deprecated_redundant_constexpr_static_def); 3982 } else if (VarDecl *Def = Old->getDefinition()) { 3983 if (checkVarDeclRedefinition(Def, New)) 3984 return; 3985 } 3986 } 3987 3988 if (haveIncompatibleLanguageLinkages(Old, New)) { 3989 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3990 Diag(OldLocation, PrevDiag); 3991 New->setInvalidDecl(); 3992 return; 3993 } 3994 3995 // Merge "used" flag. 3996 if (Old->getMostRecentDecl()->isUsed(false)) 3997 New->setIsUsed(); 3998 3999 // Keep a chain of previous declarations. 4000 New->setPreviousDecl(Old); 4001 if (NewTemplate) 4002 NewTemplate->setPreviousDecl(OldTemplate); 4003 adjustDeclContextForDeclaratorDecl(New, Old); 4004 4005 // Inherit access appropriately. 4006 New->setAccess(Old->getAccess()); 4007 if (NewTemplate) 4008 NewTemplate->setAccess(New->getAccess()); 4009 4010 if (Old->isInline()) 4011 New->setImplicitlyInline(); 4012 } 4013 4014 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4015 SourceManager &SrcMgr = getSourceManager(); 4016 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4017 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4018 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4019 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4020 auto &HSI = PP.getHeaderSearchInfo(); 4021 StringRef HdrFilename = 4022 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4023 4024 auto noteFromModuleOrInclude = [&](Module *Mod, 4025 SourceLocation IncLoc) -> bool { 4026 // Redefinition errors with modules are common with non modular mapped 4027 // headers, example: a non-modular header H in module A that also gets 4028 // included directly in a TU. Pointing twice to the same header/definition 4029 // is confusing, try to get better diagnostics when modules is on. 4030 if (IncLoc.isValid()) { 4031 if (Mod) { 4032 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4033 << HdrFilename.str() << Mod->getFullModuleName(); 4034 if (!Mod->DefinitionLoc.isInvalid()) 4035 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4036 << Mod->getFullModuleName(); 4037 } else { 4038 Diag(IncLoc, diag::note_redefinition_include_same_file) 4039 << HdrFilename.str(); 4040 } 4041 return true; 4042 } 4043 4044 return false; 4045 }; 4046 4047 // Is it the same file and same offset? Provide more information on why 4048 // this leads to a redefinition error. 4049 bool EmittedDiag = false; 4050 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4051 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4052 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4053 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4054 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4055 4056 // If the header has no guards, emit a note suggesting one. 4057 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4058 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4059 4060 if (EmittedDiag) 4061 return; 4062 } 4063 4064 // Redefinition coming from different files or couldn't do better above. 4065 if (Old->getLocation().isValid()) 4066 Diag(Old->getLocation(), diag::note_previous_definition); 4067 } 4068 4069 /// We've just determined that \p Old and \p New both appear to be definitions 4070 /// of the same variable. Either diagnose or fix the problem. 4071 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4072 if (!hasVisibleDefinition(Old) && 4073 (New->getFormalLinkage() == InternalLinkage || 4074 New->isInline() || 4075 New->getDescribedVarTemplate() || 4076 New->getNumTemplateParameterLists() || 4077 New->getDeclContext()->isDependentContext())) { 4078 // The previous definition is hidden, and multiple definitions are 4079 // permitted (in separate TUs). Demote this to a declaration. 4080 New->demoteThisDefinitionToDeclaration(); 4081 4082 // Make the canonical definition visible. 4083 if (auto *OldTD = Old->getDescribedVarTemplate()) 4084 makeMergedDefinitionVisible(OldTD); 4085 makeMergedDefinitionVisible(Old); 4086 return false; 4087 } else { 4088 Diag(New->getLocation(), diag::err_redefinition) << New; 4089 notePreviousDefinition(Old, New->getLocation()); 4090 New->setInvalidDecl(); 4091 return true; 4092 } 4093 } 4094 4095 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4096 /// no declarator (e.g. "struct foo;") is parsed. 4097 Decl * 4098 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4099 RecordDecl *&AnonRecord) { 4100 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4101 AnonRecord); 4102 } 4103 4104 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4105 // disambiguate entities defined in different scopes. 4106 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4107 // compatibility. 4108 // We will pick our mangling number depending on which version of MSVC is being 4109 // targeted. 4110 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4111 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4112 ? S->getMSCurManglingNumber() 4113 : S->getMSLastManglingNumber(); 4114 } 4115 4116 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4117 if (!Context.getLangOpts().CPlusPlus) 4118 return; 4119 4120 if (isa<CXXRecordDecl>(Tag->getParent())) { 4121 // If this tag is the direct child of a class, number it if 4122 // it is anonymous. 4123 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4124 return; 4125 MangleNumberingContext &MCtx = 4126 Context.getManglingNumberContext(Tag->getParent()); 4127 Context.setManglingNumber( 4128 Tag, MCtx.getManglingNumber( 4129 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4130 return; 4131 } 4132 4133 // If this tag isn't a direct child of a class, number it if it is local. 4134 Decl *ManglingContextDecl; 4135 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4136 Tag->getDeclContext(), ManglingContextDecl)) { 4137 Context.setManglingNumber( 4138 Tag, MCtx->getManglingNumber( 4139 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4140 } 4141 } 4142 4143 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4144 TypedefNameDecl *NewTD) { 4145 if (TagFromDeclSpec->isInvalidDecl()) 4146 return; 4147 4148 // Do nothing if the tag already has a name for linkage purposes. 4149 if (TagFromDeclSpec->hasNameForLinkage()) 4150 return; 4151 4152 // A well-formed anonymous tag must always be a TUK_Definition. 4153 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4154 4155 // The type must match the tag exactly; no qualifiers allowed. 4156 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4157 Context.getTagDeclType(TagFromDeclSpec))) { 4158 if (getLangOpts().CPlusPlus) 4159 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4160 return; 4161 } 4162 4163 // If we've already computed linkage for the anonymous tag, then 4164 // adding a typedef name for the anonymous decl can change that 4165 // linkage, which might be a serious problem. Diagnose this as 4166 // unsupported and ignore the typedef name. TODO: we should 4167 // pursue this as a language defect and establish a formal rule 4168 // for how to handle it. 4169 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4170 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4171 4172 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4173 tagLoc = getLocForEndOfToken(tagLoc); 4174 4175 llvm::SmallString<40> textToInsert; 4176 textToInsert += ' '; 4177 textToInsert += NewTD->getIdentifier()->getName(); 4178 Diag(tagLoc, diag::note_typedef_changes_linkage) 4179 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4180 return; 4181 } 4182 4183 // Otherwise, set this is the anon-decl typedef for the tag. 4184 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4185 } 4186 4187 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4188 switch (T) { 4189 case DeclSpec::TST_class: 4190 return 0; 4191 case DeclSpec::TST_struct: 4192 return 1; 4193 case DeclSpec::TST_interface: 4194 return 2; 4195 case DeclSpec::TST_union: 4196 return 3; 4197 case DeclSpec::TST_enum: 4198 return 4; 4199 default: 4200 llvm_unreachable("unexpected type specifier"); 4201 } 4202 } 4203 4204 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4205 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4206 /// parameters to cope with template friend declarations. 4207 Decl * 4208 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4209 MultiTemplateParamsArg TemplateParams, 4210 bool IsExplicitInstantiation, 4211 RecordDecl *&AnonRecord) { 4212 Decl *TagD = nullptr; 4213 TagDecl *Tag = nullptr; 4214 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4215 DS.getTypeSpecType() == DeclSpec::TST_struct || 4216 DS.getTypeSpecType() == DeclSpec::TST_interface || 4217 DS.getTypeSpecType() == DeclSpec::TST_union || 4218 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4219 TagD = DS.getRepAsDecl(); 4220 4221 if (!TagD) // We probably had an error 4222 return nullptr; 4223 4224 // Note that the above type specs guarantee that the 4225 // type rep is a Decl, whereas in many of the others 4226 // it's a Type. 4227 if (isa<TagDecl>(TagD)) 4228 Tag = cast<TagDecl>(TagD); 4229 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4230 Tag = CTD->getTemplatedDecl(); 4231 } 4232 4233 if (Tag) { 4234 handleTagNumbering(Tag, S); 4235 Tag->setFreeStanding(); 4236 if (Tag->isInvalidDecl()) 4237 return Tag; 4238 } 4239 4240 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4241 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4242 // or incomplete types shall not be restrict-qualified." 4243 if (TypeQuals & DeclSpec::TQ_restrict) 4244 Diag(DS.getRestrictSpecLoc(), 4245 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4246 << DS.getSourceRange(); 4247 } 4248 4249 if (DS.isInlineSpecified()) 4250 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4251 << getLangOpts().CPlusPlus17; 4252 4253 if (DS.isConstexprSpecified()) { 4254 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4255 // and definitions of functions and variables. 4256 if (Tag) 4257 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4258 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4259 else 4260 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4261 // Don't emit warnings after this error. 4262 return TagD; 4263 } 4264 4265 DiagnoseFunctionSpecifiers(DS); 4266 4267 if (DS.isFriendSpecified()) { 4268 // If we're dealing with a decl but not a TagDecl, assume that 4269 // whatever routines created it handled the friendship aspect. 4270 if (TagD && !Tag) 4271 return nullptr; 4272 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4273 } 4274 4275 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4276 bool IsExplicitSpecialization = 4277 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4278 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4279 !IsExplicitInstantiation && !IsExplicitSpecialization && 4280 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4281 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4282 // nested-name-specifier unless it is an explicit instantiation 4283 // or an explicit specialization. 4284 // 4285 // FIXME: We allow class template partial specializations here too, per the 4286 // obvious intent of DR1819. 4287 // 4288 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4289 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4290 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4291 return nullptr; 4292 } 4293 4294 // Track whether this decl-specifier declares anything. 4295 bool DeclaresAnything = true; 4296 4297 // Handle anonymous struct definitions. 4298 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4299 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4300 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4301 if (getLangOpts().CPlusPlus || 4302 Record->getDeclContext()->isRecord()) { 4303 // If CurContext is a DeclContext that can contain statements, 4304 // RecursiveASTVisitor won't visit the decls that 4305 // BuildAnonymousStructOrUnion() will put into CurContext. 4306 // Also store them here so that they can be part of the 4307 // DeclStmt that gets created in this case. 4308 // FIXME: Also return the IndirectFieldDecls created by 4309 // BuildAnonymousStructOr union, for the same reason? 4310 if (CurContext->isFunctionOrMethod()) 4311 AnonRecord = Record; 4312 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4313 Context.getPrintingPolicy()); 4314 } 4315 4316 DeclaresAnything = false; 4317 } 4318 } 4319 4320 // C11 6.7.2.1p2: 4321 // A struct-declaration that does not declare an anonymous structure or 4322 // anonymous union shall contain a struct-declarator-list. 4323 // 4324 // This rule also existed in C89 and C99; the grammar for struct-declaration 4325 // did not permit a struct-declaration without a struct-declarator-list. 4326 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4327 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4328 // Check for Microsoft C extension: anonymous struct/union member. 4329 // Handle 2 kinds of anonymous struct/union: 4330 // struct STRUCT; 4331 // union UNION; 4332 // and 4333 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4334 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4335 if ((Tag && Tag->getDeclName()) || 4336 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4337 RecordDecl *Record = nullptr; 4338 if (Tag) 4339 Record = dyn_cast<RecordDecl>(Tag); 4340 else if (const RecordType *RT = 4341 DS.getRepAsType().get()->getAsStructureType()) 4342 Record = RT->getDecl(); 4343 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4344 Record = UT->getDecl(); 4345 4346 if (Record && getLangOpts().MicrosoftExt) { 4347 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4348 << Record->isUnion() << DS.getSourceRange(); 4349 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4350 } 4351 4352 DeclaresAnything = false; 4353 } 4354 } 4355 4356 // Skip all the checks below if we have a type error. 4357 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4358 (TagD && TagD->isInvalidDecl())) 4359 return TagD; 4360 4361 if (getLangOpts().CPlusPlus && 4362 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4363 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4364 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4365 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4366 DeclaresAnything = false; 4367 4368 if (!DS.isMissingDeclaratorOk()) { 4369 // Customize diagnostic for a typedef missing a name. 4370 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4371 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4372 << DS.getSourceRange(); 4373 else 4374 DeclaresAnything = false; 4375 } 4376 4377 if (DS.isModulePrivateSpecified() && 4378 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4379 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4380 << Tag->getTagKind() 4381 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4382 4383 ActOnDocumentableDecl(TagD); 4384 4385 // C 6.7/2: 4386 // A declaration [...] shall declare at least a declarator [...], a tag, 4387 // or the members of an enumeration. 4388 // C++ [dcl.dcl]p3: 4389 // [If there are no declarators], and except for the declaration of an 4390 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4391 // names into the program, or shall redeclare a name introduced by a 4392 // previous declaration. 4393 if (!DeclaresAnything) { 4394 // In C, we allow this as a (popular) extension / bug. Don't bother 4395 // producing further diagnostics for redundant qualifiers after this. 4396 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4397 return TagD; 4398 } 4399 4400 // C++ [dcl.stc]p1: 4401 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4402 // init-declarator-list of the declaration shall not be empty. 4403 // C++ [dcl.fct.spec]p1: 4404 // If a cv-qualifier appears in a decl-specifier-seq, the 4405 // init-declarator-list of the declaration shall not be empty. 4406 // 4407 // Spurious qualifiers here appear to be valid in C. 4408 unsigned DiagID = diag::warn_standalone_specifier; 4409 if (getLangOpts().CPlusPlus) 4410 DiagID = diag::ext_standalone_specifier; 4411 4412 // Note that a linkage-specification sets a storage class, but 4413 // 'extern "C" struct foo;' is actually valid and not theoretically 4414 // useless. 4415 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4416 if (SCS == DeclSpec::SCS_mutable) 4417 // Since mutable is not a viable storage class specifier in C, there is 4418 // no reason to treat it as an extension. Instead, diagnose as an error. 4419 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4420 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4421 Diag(DS.getStorageClassSpecLoc(), DiagID) 4422 << DeclSpec::getSpecifierName(SCS); 4423 } 4424 4425 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4426 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4427 << DeclSpec::getSpecifierName(TSCS); 4428 if (DS.getTypeQualifiers()) { 4429 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4430 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4431 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4432 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4433 // Restrict is covered above. 4434 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4435 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4436 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4437 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4438 } 4439 4440 // Warn about ignored type attributes, for example: 4441 // __attribute__((aligned)) struct A; 4442 // Attributes should be placed after tag to apply to type declaration. 4443 if (!DS.getAttributes().empty()) { 4444 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4445 if (TypeSpecType == DeclSpec::TST_class || 4446 TypeSpecType == DeclSpec::TST_struct || 4447 TypeSpecType == DeclSpec::TST_interface || 4448 TypeSpecType == DeclSpec::TST_union || 4449 TypeSpecType == DeclSpec::TST_enum) { 4450 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4451 attrs = attrs->getNext()) 4452 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4453 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4454 } 4455 } 4456 4457 return TagD; 4458 } 4459 4460 /// We are trying to inject an anonymous member into the given scope; 4461 /// check if there's an existing declaration that can't be overloaded. 4462 /// 4463 /// \return true if this is a forbidden redeclaration 4464 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4465 Scope *S, 4466 DeclContext *Owner, 4467 DeclarationName Name, 4468 SourceLocation NameLoc, 4469 bool IsUnion) { 4470 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4471 Sema::ForVisibleRedeclaration); 4472 if (!SemaRef.LookupName(R, S)) return false; 4473 4474 // Pick a representative declaration. 4475 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4476 assert(PrevDecl && "Expected a non-null Decl"); 4477 4478 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4479 return false; 4480 4481 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4482 << IsUnion << Name; 4483 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4484 4485 return true; 4486 } 4487 4488 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4489 /// anonymous struct or union AnonRecord into the owning context Owner 4490 /// and scope S. This routine will be invoked just after we realize 4491 /// that an unnamed union or struct is actually an anonymous union or 4492 /// struct, e.g., 4493 /// 4494 /// @code 4495 /// union { 4496 /// int i; 4497 /// float f; 4498 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4499 /// // f into the surrounding scope.x 4500 /// @endcode 4501 /// 4502 /// This routine is recursive, injecting the names of nested anonymous 4503 /// structs/unions into the owning context and scope as well. 4504 static bool 4505 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4506 RecordDecl *AnonRecord, AccessSpecifier AS, 4507 SmallVectorImpl<NamedDecl *> &Chaining) { 4508 bool Invalid = false; 4509 4510 // Look every FieldDecl and IndirectFieldDecl with a name. 4511 for (auto *D : AnonRecord->decls()) { 4512 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4513 cast<NamedDecl>(D)->getDeclName()) { 4514 ValueDecl *VD = cast<ValueDecl>(D); 4515 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4516 VD->getLocation(), 4517 AnonRecord->isUnion())) { 4518 // C++ [class.union]p2: 4519 // The names of the members of an anonymous union shall be 4520 // distinct from the names of any other entity in the 4521 // scope in which the anonymous union is declared. 4522 Invalid = true; 4523 } else { 4524 // C++ [class.union]p2: 4525 // For the purpose of name lookup, after the anonymous union 4526 // definition, the members of the anonymous union are 4527 // considered to have been defined in the scope in which the 4528 // anonymous union is declared. 4529 unsigned OldChainingSize = Chaining.size(); 4530 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4531 Chaining.append(IF->chain_begin(), IF->chain_end()); 4532 else 4533 Chaining.push_back(VD); 4534 4535 assert(Chaining.size() >= 2); 4536 NamedDecl **NamedChain = 4537 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4538 for (unsigned i = 0; i < Chaining.size(); i++) 4539 NamedChain[i] = Chaining[i]; 4540 4541 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4542 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4543 VD->getType(), {NamedChain, Chaining.size()}); 4544 4545 for (const auto *Attr : VD->attrs()) 4546 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4547 4548 IndirectField->setAccess(AS); 4549 IndirectField->setImplicit(); 4550 SemaRef.PushOnScopeChains(IndirectField, S); 4551 4552 // That includes picking up the appropriate access specifier. 4553 if (AS != AS_none) IndirectField->setAccess(AS); 4554 4555 Chaining.resize(OldChainingSize); 4556 } 4557 } 4558 } 4559 4560 return Invalid; 4561 } 4562 4563 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4564 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4565 /// illegal input values are mapped to SC_None. 4566 static StorageClass 4567 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4568 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4569 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4570 "Parser allowed 'typedef' as storage class VarDecl."); 4571 switch (StorageClassSpec) { 4572 case DeclSpec::SCS_unspecified: return SC_None; 4573 case DeclSpec::SCS_extern: 4574 if (DS.isExternInLinkageSpec()) 4575 return SC_None; 4576 return SC_Extern; 4577 case DeclSpec::SCS_static: return SC_Static; 4578 case DeclSpec::SCS_auto: return SC_Auto; 4579 case DeclSpec::SCS_register: return SC_Register; 4580 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4581 // Illegal SCSs map to None: error reporting is up to the caller. 4582 case DeclSpec::SCS_mutable: // Fall through. 4583 case DeclSpec::SCS_typedef: return SC_None; 4584 } 4585 llvm_unreachable("unknown storage class specifier"); 4586 } 4587 4588 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4589 assert(Record->hasInClassInitializer()); 4590 4591 for (const auto *I : Record->decls()) { 4592 const auto *FD = dyn_cast<FieldDecl>(I); 4593 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4594 FD = IFD->getAnonField(); 4595 if (FD && FD->hasInClassInitializer()) 4596 return FD->getLocation(); 4597 } 4598 4599 llvm_unreachable("couldn't find in-class initializer"); 4600 } 4601 4602 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4603 SourceLocation DefaultInitLoc) { 4604 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4605 return; 4606 4607 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4608 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4609 } 4610 4611 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4612 CXXRecordDecl *AnonUnion) { 4613 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4614 return; 4615 4616 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4617 } 4618 4619 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4620 /// anonymous structure or union. Anonymous unions are a C++ feature 4621 /// (C++ [class.union]) and a C11 feature; anonymous structures 4622 /// are a C11 feature and GNU C++ extension. 4623 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4624 AccessSpecifier AS, 4625 RecordDecl *Record, 4626 const PrintingPolicy &Policy) { 4627 DeclContext *Owner = Record->getDeclContext(); 4628 4629 // Diagnose whether this anonymous struct/union is an extension. 4630 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4631 Diag(Record->getLocation(), diag::ext_anonymous_union); 4632 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4633 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4634 else if (!Record->isUnion() && !getLangOpts().C11) 4635 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4636 4637 // C and C++ require different kinds of checks for anonymous 4638 // structs/unions. 4639 bool Invalid = false; 4640 if (getLangOpts().CPlusPlus) { 4641 const char *PrevSpec = nullptr; 4642 unsigned DiagID; 4643 if (Record->isUnion()) { 4644 // C++ [class.union]p6: 4645 // Anonymous unions declared in a named namespace or in the 4646 // global namespace shall be declared static. 4647 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4648 (isa<TranslationUnitDecl>(Owner) || 4649 (isa<NamespaceDecl>(Owner) && 4650 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4651 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4652 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4653 4654 // Recover by adding 'static'. 4655 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4656 PrevSpec, DiagID, Policy); 4657 } 4658 // C++ [class.union]p6: 4659 // A storage class is not allowed in a declaration of an 4660 // anonymous union in a class scope. 4661 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4662 isa<RecordDecl>(Owner)) { 4663 Diag(DS.getStorageClassSpecLoc(), 4664 diag::err_anonymous_union_with_storage_spec) 4665 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4666 4667 // Recover by removing the storage specifier. 4668 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4669 SourceLocation(), 4670 PrevSpec, DiagID, Context.getPrintingPolicy()); 4671 } 4672 } 4673 4674 // Ignore const/volatile/restrict qualifiers. 4675 if (DS.getTypeQualifiers()) { 4676 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4677 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4678 << Record->isUnion() << "const" 4679 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4680 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4681 Diag(DS.getVolatileSpecLoc(), 4682 diag::ext_anonymous_struct_union_qualified) 4683 << Record->isUnion() << "volatile" 4684 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4685 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4686 Diag(DS.getRestrictSpecLoc(), 4687 diag::ext_anonymous_struct_union_qualified) 4688 << Record->isUnion() << "restrict" 4689 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4690 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4691 Diag(DS.getAtomicSpecLoc(), 4692 diag::ext_anonymous_struct_union_qualified) 4693 << Record->isUnion() << "_Atomic" 4694 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4695 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4696 Diag(DS.getUnalignedSpecLoc(), 4697 diag::ext_anonymous_struct_union_qualified) 4698 << Record->isUnion() << "__unaligned" 4699 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4700 4701 DS.ClearTypeQualifiers(); 4702 } 4703 4704 // C++ [class.union]p2: 4705 // The member-specification of an anonymous union shall only 4706 // define non-static data members. [Note: nested types and 4707 // functions cannot be declared within an anonymous union. ] 4708 for (auto *Mem : Record->decls()) { 4709 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4710 // C++ [class.union]p3: 4711 // An anonymous union shall not have private or protected 4712 // members (clause 11). 4713 assert(FD->getAccess() != AS_none); 4714 if (FD->getAccess() != AS_public) { 4715 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4716 << Record->isUnion() << (FD->getAccess() == AS_protected); 4717 Invalid = true; 4718 } 4719 4720 // C++ [class.union]p1 4721 // An object of a class with a non-trivial constructor, a non-trivial 4722 // copy constructor, a non-trivial destructor, or a non-trivial copy 4723 // assignment operator cannot be a member of a union, nor can an 4724 // array of such objects. 4725 if (CheckNontrivialField(FD)) 4726 Invalid = true; 4727 } else if (Mem->isImplicit()) { 4728 // Any implicit members are fine. 4729 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4730 // This is a type that showed up in an 4731 // elaborated-type-specifier inside the anonymous struct or 4732 // union, but which actually declares a type outside of the 4733 // anonymous struct or union. It's okay. 4734 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4735 if (!MemRecord->isAnonymousStructOrUnion() && 4736 MemRecord->getDeclName()) { 4737 // Visual C++ allows type definition in anonymous struct or union. 4738 if (getLangOpts().MicrosoftExt) 4739 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4740 << Record->isUnion(); 4741 else { 4742 // This is a nested type declaration. 4743 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4744 << Record->isUnion(); 4745 Invalid = true; 4746 } 4747 } else { 4748 // This is an anonymous type definition within another anonymous type. 4749 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4750 // not part of standard C++. 4751 Diag(MemRecord->getLocation(), 4752 diag::ext_anonymous_record_with_anonymous_type) 4753 << Record->isUnion(); 4754 } 4755 } else if (isa<AccessSpecDecl>(Mem)) { 4756 // Any access specifier is fine. 4757 } else if (isa<StaticAssertDecl>(Mem)) { 4758 // In C++1z, static_assert declarations are also fine. 4759 } else { 4760 // We have something that isn't a non-static data 4761 // member. Complain about it. 4762 unsigned DK = diag::err_anonymous_record_bad_member; 4763 if (isa<TypeDecl>(Mem)) 4764 DK = diag::err_anonymous_record_with_type; 4765 else if (isa<FunctionDecl>(Mem)) 4766 DK = diag::err_anonymous_record_with_function; 4767 else if (isa<VarDecl>(Mem)) 4768 DK = diag::err_anonymous_record_with_static; 4769 4770 // Visual C++ allows type definition in anonymous struct or union. 4771 if (getLangOpts().MicrosoftExt && 4772 DK == diag::err_anonymous_record_with_type) 4773 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4774 << Record->isUnion(); 4775 else { 4776 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4777 Invalid = true; 4778 } 4779 } 4780 } 4781 4782 // C++11 [class.union]p8 (DR1460): 4783 // At most one variant member of a union may have a 4784 // brace-or-equal-initializer. 4785 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4786 Owner->isRecord()) 4787 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4788 cast<CXXRecordDecl>(Record)); 4789 } 4790 4791 if (!Record->isUnion() && !Owner->isRecord()) { 4792 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4793 << getLangOpts().CPlusPlus; 4794 Invalid = true; 4795 } 4796 4797 // Mock up a declarator. 4798 Declarator Dc(DS, DeclaratorContext::MemberContext); 4799 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4800 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4801 4802 // Create a declaration for this anonymous struct/union. 4803 NamedDecl *Anon = nullptr; 4804 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4805 Anon = FieldDecl::Create(Context, OwningClass, 4806 DS.getLocStart(), 4807 Record->getLocation(), 4808 /*IdentifierInfo=*/nullptr, 4809 Context.getTypeDeclType(Record), 4810 TInfo, 4811 /*BitWidth=*/nullptr, /*Mutable=*/false, 4812 /*InitStyle=*/ICIS_NoInit); 4813 Anon->setAccess(AS); 4814 if (getLangOpts().CPlusPlus) 4815 FieldCollector->Add(cast<FieldDecl>(Anon)); 4816 } else { 4817 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4818 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4819 if (SCSpec == DeclSpec::SCS_mutable) { 4820 // mutable can only appear on non-static class members, so it's always 4821 // an error here 4822 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4823 Invalid = true; 4824 SC = SC_None; 4825 } 4826 4827 Anon = VarDecl::Create(Context, Owner, 4828 DS.getLocStart(), 4829 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4830 Context.getTypeDeclType(Record), 4831 TInfo, SC); 4832 4833 // Default-initialize the implicit variable. This initialization will be 4834 // trivial in almost all cases, except if a union member has an in-class 4835 // initializer: 4836 // union { int n = 0; }; 4837 ActOnUninitializedDecl(Anon); 4838 } 4839 Anon->setImplicit(); 4840 4841 // Mark this as an anonymous struct/union type. 4842 Record->setAnonymousStructOrUnion(true); 4843 4844 // Add the anonymous struct/union object to the current 4845 // context. We'll be referencing this object when we refer to one of 4846 // its members. 4847 Owner->addDecl(Anon); 4848 4849 // Inject the members of the anonymous struct/union into the owning 4850 // context and into the identifier resolver chain for name lookup 4851 // purposes. 4852 SmallVector<NamedDecl*, 2> Chain; 4853 Chain.push_back(Anon); 4854 4855 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4856 Invalid = true; 4857 4858 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4859 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4860 Decl *ManglingContextDecl; 4861 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4862 NewVD->getDeclContext(), ManglingContextDecl)) { 4863 Context.setManglingNumber( 4864 NewVD, MCtx->getManglingNumber( 4865 NewVD, getMSManglingNumber(getLangOpts(), S))); 4866 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4867 } 4868 } 4869 } 4870 4871 if (Invalid) 4872 Anon->setInvalidDecl(); 4873 4874 return Anon; 4875 } 4876 4877 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4878 /// Microsoft C anonymous structure. 4879 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4880 /// Example: 4881 /// 4882 /// struct A { int a; }; 4883 /// struct B { struct A; int b; }; 4884 /// 4885 /// void foo() { 4886 /// B var; 4887 /// var.a = 3; 4888 /// } 4889 /// 4890 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4891 RecordDecl *Record) { 4892 assert(Record && "expected a record!"); 4893 4894 // Mock up a declarator. 4895 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4896 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4897 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4898 4899 auto *ParentDecl = cast<RecordDecl>(CurContext); 4900 QualType RecTy = Context.getTypeDeclType(Record); 4901 4902 // Create a declaration for this anonymous struct. 4903 NamedDecl *Anon = FieldDecl::Create(Context, 4904 ParentDecl, 4905 DS.getLocStart(), 4906 DS.getLocStart(), 4907 /*IdentifierInfo=*/nullptr, 4908 RecTy, 4909 TInfo, 4910 /*BitWidth=*/nullptr, /*Mutable=*/false, 4911 /*InitStyle=*/ICIS_NoInit); 4912 Anon->setImplicit(); 4913 4914 // Add the anonymous struct object to the current context. 4915 CurContext->addDecl(Anon); 4916 4917 // Inject the members of the anonymous struct into the current 4918 // context and into the identifier resolver chain for name lookup 4919 // purposes. 4920 SmallVector<NamedDecl*, 2> Chain; 4921 Chain.push_back(Anon); 4922 4923 RecordDecl *RecordDef = Record->getDefinition(); 4924 if (RequireCompleteType(Anon->getLocation(), RecTy, 4925 diag::err_field_incomplete) || 4926 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4927 AS_none, Chain)) { 4928 Anon->setInvalidDecl(); 4929 ParentDecl->setInvalidDecl(); 4930 } 4931 4932 return Anon; 4933 } 4934 4935 /// GetNameForDeclarator - Determine the full declaration name for the 4936 /// given Declarator. 4937 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4938 return GetNameFromUnqualifiedId(D.getName()); 4939 } 4940 4941 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4942 DeclarationNameInfo 4943 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4944 DeclarationNameInfo NameInfo; 4945 NameInfo.setLoc(Name.StartLocation); 4946 4947 switch (Name.getKind()) { 4948 4949 case UnqualifiedIdKind::IK_ImplicitSelfParam: 4950 case UnqualifiedIdKind::IK_Identifier: 4951 NameInfo.setName(Name.Identifier); 4952 NameInfo.setLoc(Name.StartLocation); 4953 return NameInfo; 4954 4955 case UnqualifiedIdKind::IK_DeductionGuideName: { 4956 // C++ [temp.deduct.guide]p3: 4957 // The simple-template-id shall name a class template specialization. 4958 // The template-name shall be the same identifier as the template-name 4959 // of the simple-template-id. 4960 // These together intend to imply that the template-name shall name a 4961 // class template. 4962 // FIXME: template<typename T> struct X {}; 4963 // template<typename T> using Y = X<T>; 4964 // Y(int) -> Y<int>; 4965 // satisfies these rules but does not name a class template. 4966 TemplateName TN = Name.TemplateName.get().get(); 4967 auto *Template = TN.getAsTemplateDecl(); 4968 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4969 Diag(Name.StartLocation, 4970 diag::err_deduction_guide_name_not_class_template) 4971 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4972 if (Template) 4973 Diag(Template->getLocation(), diag::note_template_decl_here); 4974 return DeclarationNameInfo(); 4975 } 4976 4977 NameInfo.setName( 4978 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4979 NameInfo.setLoc(Name.StartLocation); 4980 return NameInfo; 4981 } 4982 4983 case UnqualifiedIdKind::IK_OperatorFunctionId: 4984 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4985 Name.OperatorFunctionId.Operator)); 4986 NameInfo.setLoc(Name.StartLocation); 4987 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4988 = Name.OperatorFunctionId.SymbolLocations[0]; 4989 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4990 = Name.EndLocation.getRawEncoding(); 4991 return NameInfo; 4992 4993 case UnqualifiedIdKind::IK_LiteralOperatorId: 4994 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4995 Name.Identifier)); 4996 NameInfo.setLoc(Name.StartLocation); 4997 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4998 return NameInfo; 4999 5000 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5001 TypeSourceInfo *TInfo; 5002 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5003 if (Ty.isNull()) 5004 return DeclarationNameInfo(); 5005 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5006 Context.getCanonicalType(Ty))); 5007 NameInfo.setLoc(Name.StartLocation); 5008 NameInfo.setNamedTypeInfo(TInfo); 5009 return NameInfo; 5010 } 5011 5012 case UnqualifiedIdKind::IK_ConstructorName: { 5013 TypeSourceInfo *TInfo; 5014 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5015 if (Ty.isNull()) 5016 return DeclarationNameInfo(); 5017 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5018 Context.getCanonicalType(Ty))); 5019 NameInfo.setLoc(Name.StartLocation); 5020 NameInfo.setNamedTypeInfo(TInfo); 5021 return NameInfo; 5022 } 5023 5024 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5025 // In well-formed code, we can only have a constructor 5026 // template-id that refers to the current context, so go there 5027 // to find the actual type being constructed. 5028 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5029 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5030 return DeclarationNameInfo(); 5031 5032 // Determine the type of the class being constructed. 5033 QualType CurClassType = Context.getTypeDeclType(CurClass); 5034 5035 // FIXME: Check two things: that the template-id names the same type as 5036 // CurClassType, and that the template-id does not occur when the name 5037 // was qualified. 5038 5039 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5040 Context.getCanonicalType(CurClassType))); 5041 NameInfo.setLoc(Name.StartLocation); 5042 // FIXME: should we retrieve TypeSourceInfo? 5043 NameInfo.setNamedTypeInfo(nullptr); 5044 return NameInfo; 5045 } 5046 5047 case UnqualifiedIdKind::IK_DestructorName: { 5048 TypeSourceInfo *TInfo; 5049 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5050 if (Ty.isNull()) 5051 return DeclarationNameInfo(); 5052 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5053 Context.getCanonicalType(Ty))); 5054 NameInfo.setLoc(Name.StartLocation); 5055 NameInfo.setNamedTypeInfo(TInfo); 5056 return NameInfo; 5057 } 5058 5059 case UnqualifiedIdKind::IK_TemplateId: { 5060 TemplateName TName = Name.TemplateId->Template.get(); 5061 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5062 return Context.getNameForTemplate(TName, TNameLoc); 5063 } 5064 5065 } // switch (Name.getKind()) 5066 5067 llvm_unreachable("Unknown name kind"); 5068 } 5069 5070 static QualType getCoreType(QualType Ty) { 5071 do { 5072 if (Ty->isPointerType() || Ty->isReferenceType()) 5073 Ty = Ty->getPointeeType(); 5074 else if (Ty->isArrayType()) 5075 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5076 else 5077 return Ty.withoutLocalFastQualifiers(); 5078 } while (true); 5079 } 5080 5081 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5082 /// and Definition have "nearly" matching parameters. This heuristic is 5083 /// used to improve diagnostics in the case where an out-of-line function 5084 /// definition doesn't match any declaration within the class or namespace. 5085 /// Also sets Params to the list of indices to the parameters that differ 5086 /// between the declaration and the definition. If hasSimilarParameters 5087 /// returns true and Params is empty, then all of the parameters match. 5088 static bool hasSimilarParameters(ASTContext &Context, 5089 FunctionDecl *Declaration, 5090 FunctionDecl *Definition, 5091 SmallVectorImpl<unsigned> &Params) { 5092 Params.clear(); 5093 if (Declaration->param_size() != Definition->param_size()) 5094 return false; 5095 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5096 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5097 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5098 5099 // The parameter types are identical 5100 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5101 continue; 5102 5103 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5104 QualType DefParamBaseTy = getCoreType(DefParamTy); 5105 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5106 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5107 5108 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5109 (DeclTyName && DeclTyName == DefTyName)) 5110 Params.push_back(Idx); 5111 else // The two parameters aren't even close 5112 return false; 5113 } 5114 5115 return true; 5116 } 5117 5118 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5119 /// declarator needs to be rebuilt in the current instantiation. 5120 /// Any bits of declarator which appear before the name are valid for 5121 /// consideration here. That's specifically the type in the decl spec 5122 /// and the base type in any member-pointer chunks. 5123 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5124 DeclarationName Name) { 5125 // The types we specifically need to rebuild are: 5126 // - typenames, typeofs, and decltypes 5127 // - types which will become injected class names 5128 // Of course, we also need to rebuild any type referencing such a 5129 // type. It's safest to just say "dependent", but we call out a 5130 // few cases here. 5131 5132 DeclSpec &DS = D.getMutableDeclSpec(); 5133 switch (DS.getTypeSpecType()) { 5134 case DeclSpec::TST_typename: 5135 case DeclSpec::TST_typeofType: 5136 case DeclSpec::TST_underlyingType: 5137 case DeclSpec::TST_atomic: { 5138 // Grab the type from the parser. 5139 TypeSourceInfo *TSI = nullptr; 5140 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5141 if (T.isNull() || !T->isDependentType()) break; 5142 5143 // Make sure there's a type source info. This isn't really much 5144 // of a waste; most dependent types should have type source info 5145 // attached already. 5146 if (!TSI) 5147 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5148 5149 // Rebuild the type in the current instantiation. 5150 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5151 if (!TSI) return true; 5152 5153 // Store the new type back in the decl spec. 5154 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5155 DS.UpdateTypeRep(LocType); 5156 break; 5157 } 5158 5159 case DeclSpec::TST_decltype: 5160 case DeclSpec::TST_typeofExpr: { 5161 Expr *E = DS.getRepAsExpr(); 5162 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5163 if (Result.isInvalid()) return true; 5164 DS.UpdateExprRep(Result.get()); 5165 break; 5166 } 5167 5168 default: 5169 // Nothing to do for these decl specs. 5170 break; 5171 } 5172 5173 // It doesn't matter what order we do this in. 5174 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5175 DeclaratorChunk &Chunk = D.getTypeObject(I); 5176 5177 // The only type information in the declarator which can come 5178 // before the declaration name is the base type of a member 5179 // pointer. 5180 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5181 continue; 5182 5183 // Rebuild the scope specifier in-place. 5184 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5185 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5186 return true; 5187 } 5188 5189 return false; 5190 } 5191 5192 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5193 D.setFunctionDefinitionKind(FDK_Declaration); 5194 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5195 5196 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5197 Dcl && Dcl->getDeclContext()->isFileContext()) 5198 Dcl->setTopLevelDeclInObjCContainer(); 5199 5200 if (getLangOpts().OpenCL) 5201 setCurrentOpenCLExtensionForDecl(Dcl); 5202 5203 return Dcl; 5204 } 5205 5206 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5207 /// If T is the name of a class, then each of the following shall have a 5208 /// name different from T: 5209 /// - every static data member of class T; 5210 /// - every member function of class T 5211 /// - every member of class T that is itself a type; 5212 /// \returns true if the declaration name violates these rules. 5213 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5214 DeclarationNameInfo NameInfo) { 5215 DeclarationName Name = NameInfo.getName(); 5216 5217 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5218 while (Record && Record->isAnonymousStructOrUnion()) 5219 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5220 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5221 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5222 return true; 5223 } 5224 5225 return false; 5226 } 5227 5228 /// \brief Diagnose a declaration whose declarator-id has the given 5229 /// nested-name-specifier. 5230 /// 5231 /// \param SS The nested-name-specifier of the declarator-id. 5232 /// 5233 /// \param DC The declaration context to which the nested-name-specifier 5234 /// resolves. 5235 /// 5236 /// \param Name The name of the entity being declared. 5237 /// 5238 /// \param Loc The location of the name of the entity being declared. 5239 /// 5240 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5241 /// we're declaring an explicit / partial specialization / instantiation. 5242 /// 5243 /// \returns true if we cannot safely recover from this error, false otherwise. 5244 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5245 DeclarationName Name, 5246 SourceLocation Loc, bool IsTemplateId) { 5247 DeclContext *Cur = CurContext; 5248 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5249 Cur = Cur->getParent(); 5250 5251 // If the user provided a superfluous scope specifier that refers back to the 5252 // class in which the entity is already declared, diagnose and ignore it. 5253 // 5254 // class X { 5255 // void X::f(); 5256 // }; 5257 // 5258 // Note, it was once ill-formed to give redundant qualification in all 5259 // contexts, but that rule was removed by DR482. 5260 if (Cur->Equals(DC)) { 5261 if (Cur->isRecord()) { 5262 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5263 : diag::err_member_extra_qualification) 5264 << Name << FixItHint::CreateRemoval(SS.getRange()); 5265 SS.clear(); 5266 } else { 5267 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5268 } 5269 return false; 5270 } 5271 5272 // Check whether the qualifying scope encloses the scope of the original 5273 // declaration. For a template-id, we perform the checks in 5274 // CheckTemplateSpecializationScope. 5275 if (!Cur->Encloses(DC) && !IsTemplateId) { 5276 if (Cur->isRecord()) 5277 Diag(Loc, diag::err_member_qualification) 5278 << Name << SS.getRange(); 5279 else if (isa<TranslationUnitDecl>(DC)) 5280 Diag(Loc, diag::err_invalid_declarator_global_scope) 5281 << Name << SS.getRange(); 5282 else if (isa<FunctionDecl>(Cur)) 5283 Diag(Loc, diag::err_invalid_declarator_in_function) 5284 << Name << SS.getRange(); 5285 else if (isa<BlockDecl>(Cur)) 5286 Diag(Loc, diag::err_invalid_declarator_in_block) 5287 << Name << SS.getRange(); 5288 else 5289 Diag(Loc, diag::err_invalid_declarator_scope) 5290 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5291 5292 return true; 5293 } 5294 5295 if (Cur->isRecord()) { 5296 // Cannot qualify members within a class. 5297 Diag(Loc, diag::err_member_qualification) 5298 << Name << SS.getRange(); 5299 SS.clear(); 5300 5301 // C++ constructors and destructors with incorrect scopes can break 5302 // our AST invariants by having the wrong underlying types. If 5303 // that's the case, then drop this declaration entirely. 5304 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5305 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5306 !Context.hasSameType(Name.getCXXNameType(), 5307 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5308 return true; 5309 5310 return false; 5311 } 5312 5313 // C++11 [dcl.meaning]p1: 5314 // [...] "The nested-name-specifier of the qualified declarator-id shall 5315 // not begin with a decltype-specifer" 5316 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5317 while (SpecLoc.getPrefix()) 5318 SpecLoc = SpecLoc.getPrefix(); 5319 if (dyn_cast_or_null<DecltypeType>( 5320 SpecLoc.getNestedNameSpecifier()->getAsType())) 5321 Diag(Loc, diag::err_decltype_in_declarator) 5322 << SpecLoc.getTypeLoc().getSourceRange(); 5323 5324 return false; 5325 } 5326 5327 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5328 MultiTemplateParamsArg TemplateParamLists) { 5329 // TODO: consider using NameInfo for diagnostic. 5330 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5331 DeclarationName Name = NameInfo.getName(); 5332 5333 // All of these full declarators require an identifier. If it doesn't have 5334 // one, the ParsedFreeStandingDeclSpec action should be used. 5335 if (D.isDecompositionDeclarator()) { 5336 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5337 } else if (!Name) { 5338 if (!D.isInvalidType()) // Reject this if we think it is valid. 5339 Diag(D.getDeclSpec().getLocStart(), 5340 diag::err_declarator_need_ident) 5341 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5342 return nullptr; 5343 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5344 return nullptr; 5345 5346 // The scope passed in may not be a decl scope. Zip up the scope tree until 5347 // we find one that is. 5348 while ((S->getFlags() & Scope::DeclScope) == 0 || 5349 (S->getFlags() & Scope::TemplateParamScope) != 0) 5350 S = S->getParent(); 5351 5352 DeclContext *DC = CurContext; 5353 if (D.getCXXScopeSpec().isInvalid()) 5354 D.setInvalidType(); 5355 else if (D.getCXXScopeSpec().isSet()) { 5356 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5357 UPPC_DeclarationQualifier)) 5358 return nullptr; 5359 5360 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5361 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5362 if (!DC || isa<EnumDecl>(DC)) { 5363 // If we could not compute the declaration context, it's because the 5364 // declaration context is dependent but does not refer to a class, 5365 // class template, or class template partial specialization. Complain 5366 // and return early, to avoid the coming semantic disaster. 5367 Diag(D.getIdentifierLoc(), 5368 diag::err_template_qualified_declarator_no_match) 5369 << D.getCXXScopeSpec().getScopeRep() 5370 << D.getCXXScopeSpec().getRange(); 5371 return nullptr; 5372 } 5373 bool IsDependentContext = DC->isDependentContext(); 5374 5375 if (!IsDependentContext && 5376 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5377 return nullptr; 5378 5379 // If a class is incomplete, do not parse entities inside it. 5380 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5381 Diag(D.getIdentifierLoc(), 5382 diag::err_member_def_undefined_record) 5383 << Name << DC << D.getCXXScopeSpec().getRange(); 5384 return nullptr; 5385 } 5386 if (!D.getDeclSpec().isFriendSpecified()) { 5387 if (diagnoseQualifiedDeclaration( 5388 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5389 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5390 if (DC->isRecord()) 5391 return nullptr; 5392 5393 D.setInvalidType(); 5394 } 5395 } 5396 5397 // Check whether we need to rebuild the type of the given 5398 // declaration in the current instantiation. 5399 if (EnteringContext && IsDependentContext && 5400 TemplateParamLists.size() != 0) { 5401 ContextRAII SavedContext(*this, DC); 5402 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5403 D.setInvalidType(); 5404 } 5405 } 5406 5407 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5408 QualType R = TInfo->getType(); 5409 5410 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5411 UPPC_DeclarationType)) 5412 D.setInvalidType(); 5413 5414 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5415 forRedeclarationInCurContext()); 5416 5417 // See if this is a redefinition of a variable in the same scope. 5418 if (!D.getCXXScopeSpec().isSet()) { 5419 bool IsLinkageLookup = false; 5420 bool CreateBuiltins = false; 5421 5422 // If the declaration we're planning to build will be a function 5423 // or object with linkage, then look for another declaration with 5424 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5425 // 5426 // If the declaration we're planning to build will be declared with 5427 // external linkage in the translation unit, create any builtin with 5428 // the same name. 5429 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5430 /* Do nothing*/; 5431 else if (CurContext->isFunctionOrMethod() && 5432 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5433 R->isFunctionType())) { 5434 IsLinkageLookup = true; 5435 CreateBuiltins = 5436 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5437 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5438 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5439 CreateBuiltins = true; 5440 5441 if (IsLinkageLookup) { 5442 Previous.clear(LookupRedeclarationWithLinkage); 5443 Previous.setRedeclarationKind(ForExternalRedeclaration); 5444 } 5445 5446 LookupName(Previous, S, CreateBuiltins); 5447 } else { // Something like "int foo::x;" 5448 LookupQualifiedName(Previous, DC); 5449 5450 // C++ [dcl.meaning]p1: 5451 // When the declarator-id is qualified, the declaration shall refer to a 5452 // previously declared member of the class or namespace to which the 5453 // qualifier refers (or, in the case of a namespace, of an element of the 5454 // inline namespace set of that namespace (7.3.1)) or to a specialization 5455 // thereof; [...] 5456 // 5457 // Note that we already checked the context above, and that we do not have 5458 // enough information to make sure that Previous contains the declaration 5459 // we want to match. For example, given: 5460 // 5461 // class X { 5462 // void f(); 5463 // void f(float); 5464 // }; 5465 // 5466 // void X::f(int) { } // ill-formed 5467 // 5468 // In this case, Previous will point to the overload set 5469 // containing the two f's declared in X, but neither of them 5470 // matches. 5471 5472 // C++ [dcl.meaning]p1: 5473 // [...] the member shall not merely have been introduced by a 5474 // using-declaration in the scope of the class or namespace nominated by 5475 // the nested-name-specifier of the declarator-id. 5476 RemoveUsingDecls(Previous); 5477 } 5478 5479 if (Previous.isSingleResult() && 5480 Previous.getFoundDecl()->isTemplateParameter()) { 5481 // Maybe we will complain about the shadowed template parameter. 5482 if (!D.isInvalidType()) 5483 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5484 Previous.getFoundDecl()); 5485 5486 // Just pretend that we didn't see the previous declaration. 5487 Previous.clear(); 5488 } 5489 5490 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5491 // Forget that the previous declaration is the injected-class-name. 5492 Previous.clear(); 5493 5494 // In C++, the previous declaration we find might be a tag type 5495 // (class or enum). In this case, the new declaration will hide the 5496 // tag type. Note that this applies to functions, function templates, and 5497 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5498 if (Previous.isSingleTagDecl() && 5499 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5500 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5501 Previous.clear(); 5502 5503 // Check that there are no default arguments other than in the parameters 5504 // of a function declaration (C++ only). 5505 if (getLangOpts().CPlusPlus) 5506 CheckExtraCXXDefaultArguments(D); 5507 5508 NamedDecl *New; 5509 5510 bool AddToScope = true; 5511 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5512 if (TemplateParamLists.size()) { 5513 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5514 return nullptr; 5515 } 5516 5517 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5518 } else if (R->isFunctionType()) { 5519 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5520 TemplateParamLists, 5521 AddToScope); 5522 } else { 5523 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5524 AddToScope); 5525 } 5526 5527 if (!New) 5528 return nullptr; 5529 5530 // If this has an identifier and is not a function template specialization, 5531 // add it to the scope stack. 5532 if (New->getDeclName() && AddToScope) { 5533 // Only make a locally-scoped extern declaration visible if it is the first 5534 // declaration of this entity. Qualified lookup for such an entity should 5535 // only find this declaration if there is no visible declaration of it. 5536 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5537 PushOnScopeChains(New, S, AddToContext); 5538 if (!AddToContext) 5539 CurContext->addHiddenDecl(New); 5540 } 5541 5542 if (isInOpenMPDeclareTargetContext()) 5543 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5544 5545 return New; 5546 } 5547 5548 /// Helper method to turn variable array types into constant array 5549 /// types in certain situations which would otherwise be errors (for 5550 /// GCC compatibility). 5551 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5552 ASTContext &Context, 5553 bool &SizeIsNegative, 5554 llvm::APSInt &Oversized) { 5555 // This method tries to turn a variable array into a constant 5556 // array even when the size isn't an ICE. This is necessary 5557 // for compatibility with code that depends on gcc's buggy 5558 // constant expression folding, like struct {char x[(int)(char*)2];} 5559 SizeIsNegative = false; 5560 Oversized = 0; 5561 5562 if (T->isDependentType()) 5563 return QualType(); 5564 5565 QualifierCollector Qs; 5566 const Type *Ty = Qs.strip(T); 5567 5568 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5569 QualType Pointee = PTy->getPointeeType(); 5570 QualType FixedType = 5571 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5572 Oversized); 5573 if (FixedType.isNull()) return FixedType; 5574 FixedType = Context.getPointerType(FixedType); 5575 return Qs.apply(Context, FixedType); 5576 } 5577 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5578 QualType Inner = PTy->getInnerType(); 5579 QualType FixedType = 5580 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5581 Oversized); 5582 if (FixedType.isNull()) return FixedType; 5583 FixedType = Context.getParenType(FixedType); 5584 return Qs.apply(Context, FixedType); 5585 } 5586 5587 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5588 if (!VLATy) 5589 return QualType(); 5590 // FIXME: We should probably handle this case 5591 if (VLATy->getElementType()->isVariablyModifiedType()) 5592 return QualType(); 5593 5594 llvm::APSInt Res; 5595 if (!VLATy->getSizeExpr() || 5596 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5597 return QualType(); 5598 5599 // Check whether the array size is negative. 5600 if (Res.isSigned() && Res.isNegative()) { 5601 SizeIsNegative = true; 5602 return QualType(); 5603 } 5604 5605 // Check whether the array is too large to be addressed. 5606 unsigned ActiveSizeBits 5607 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5608 Res); 5609 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5610 Oversized = Res; 5611 return QualType(); 5612 } 5613 5614 return Context.getConstantArrayType(VLATy->getElementType(), 5615 Res, ArrayType::Normal, 0); 5616 } 5617 5618 static void 5619 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5620 SrcTL = SrcTL.getUnqualifiedLoc(); 5621 DstTL = DstTL.getUnqualifiedLoc(); 5622 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5623 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5624 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5625 DstPTL.getPointeeLoc()); 5626 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5627 return; 5628 } 5629 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5630 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5631 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5632 DstPTL.getInnerLoc()); 5633 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5634 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5635 return; 5636 } 5637 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5638 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5639 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5640 TypeLoc DstElemTL = DstATL.getElementLoc(); 5641 DstElemTL.initializeFullCopy(SrcElemTL); 5642 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5643 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5644 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5645 } 5646 5647 /// Helper method to turn variable array types into constant array 5648 /// types in certain situations which would otherwise be errors (for 5649 /// GCC compatibility). 5650 static TypeSourceInfo* 5651 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5652 ASTContext &Context, 5653 bool &SizeIsNegative, 5654 llvm::APSInt &Oversized) { 5655 QualType FixedTy 5656 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5657 SizeIsNegative, Oversized); 5658 if (FixedTy.isNull()) 5659 return nullptr; 5660 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5661 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5662 FixedTInfo->getTypeLoc()); 5663 return FixedTInfo; 5664 } 5665 5666 /// \brief Register the given locally-scoped extern "C" declaration so 5667 /// that it can be found later for redeclarations. We include any extern "C" 5668 /// declaration that is not visible in the translation unit here, not just 5669 /// function-scope declarations. 5670 void 5671 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5672 if (!getLangOpts().CPlusPlus && 5673 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5674 // Don't need to track declarations in the TU in C. 5675 return; 5676 5677 // Note that we have a locally-scoped external with this name. 5678 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5679 } 5680 5681 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5682 // FIXME: We can have multiple results via __attribute__((overloadable)). 5683 auto Result = Context.getExternCContextDecl()->lookup(Name); 5684 return Result.empty() ? nullptr : *Result.begin(); 5685 } 5686 5687 /// \brief Diagnose function specifiers on a declaration of an identifier that 5688 /// does not identify a function. 5689 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5690 // FIXME: We should probably indicate the identifier in question to avoid 5691 // confusion for constructs like "virtual int a(), b;" 5692 if (DS.isVirtualSpecified()) 5693 Diag(DS.getVirtualSpecLoc(), 5694 diag::err_virtual_non_function); 5695 5696 if (DS.isExplicitSpecified()) 5697 Diag(DS.getExplicitSpecLoc(), 5698 diag::err_explicit_non_function); 5699 5700 if (DS.isNoreturnSpecified()) 5701 Diag(DS.getNoreturnSpecLoc(), 5702 diag::err_noreturn_non_function); 5703 } 5704 5705 NamedDecl* 5706 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5707 TypeSourceInfo *TInfo, LookupResult &Previous) { 5708 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5709 if (D.getCXXScopeSpec().isSet()) { 5710 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5711 << D.getCXXScopeSpec().getRange(); 5712 D.setInvalidType(); 5713 // Pretend we didn't see the scope specifier. 5714 DC = CurContext; 5715 Previous.clear(); 5716 } 5717 5718 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5719 5720 if (D.getDeclSpec().isInlineSpecified()) 5721 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5722 << getLangOpts().CPlusPlus17; 5723 if (D.getDeclSpec().isConstexprSpecified()) 5724 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5725 << 1; 5726 5727 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5728 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5729 Diag(D.getName().StartLocation, 5730 diag::err_deduction_guide_invalid_specifier) 5731 << "typedef"; 5732 else 5733 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5734 << D.getName().getSourceRange(); 5735 return nullptr; 5736 } 5737 5738 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5739 if (!NewTD) return nullptr; 5740 5741 // Handle attributes prior to checking for duplicates in MergeVarDecl 5742 ProcessDeclAttributes(S, NewTD, D); 5743 5744 CheckTypedefForVariablyModifiedType(S, NewTD); 5745 5746 bool Redeclaration = D.isRedeclaration(); 5747 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5748 D.setRedeclaration(Redeclaration); 5749 return ND; 5750 } 5751 5752 void 5753 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5754 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5755 // then it shall have block scope. 5756 // Note that variably modified types must be fixed before merging the decl so 5757 // that redeclarations will match. 5758 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5759 QualType T = TInfo->getType(); 5760 if (T->isVariablyModifiedType()) { 5761 setFunctionHasBranchProtectedScope(); 5762 5763 if (S->getFnParent() == nullptr) { 5764 bool SizeIsNegative; 5765 llvm::APSInt Oversized; 5766 TypeSourceInfo *FixedTInfo = 5767 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5768 SizeIsNegative, 5769 Oversized); 5770 if (FixedTInfo) { 5771 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5772 NewTD->setTypeSourceInfo(FixedTInfo); 5773 } else { 5774 if (SizeIsNegative) 5775 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5776 else if (T->isVariableArrayType()) 5777 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5778 else if (Oversized.getBoolValue()) 5779 Diag(NewTD->getLocation(), diag::err_array_too_large) 5780 << Oversized.toString(10); 5781 else 5782 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5783 NewTD->setInvalidDecl(); 5784 } 5785 } 5786 } 5787 } 5788 5789 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5790 /// declares a typedef-name, either using the 'typedef' type specifier or via 5791 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5792 NamedDecl* 5793 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5794 LookupResult &Previous, bool &Redeclaration) { 5795 5796 // Find the shadowed declaration before filtering for scope. 5797 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5798 5799 // Merge the decl with the existing one if appropriate. If the decl is 5800 // in an outer scope, it isn't the same thing. 5801 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5802 /*AllowInlineNamespace*/false); 5803 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5804 if (!Previous.empty()) { 5805 Redeclaration = true; 5806 MergeTypedefNameDecl(S, NewTD, Previous); 5807 } 5808 5809 if (ShadowedDecl && !Redeclaration) 5810 CheckShadow(NewTD, ShadowedDecl, Previous); 5811 5812 // If this is the C FILE type, notify the AST context. 5813 if (IdentifierInfo *II = NewTD->getIdentifier()) 5814 if (!NewTD->isInvalidDecl() && 5815 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5816 if (II->isStr("FILE")) 5817 Context.setFILEDecl(NewTD); 5818 else if (II->isStr("jmp_buf")) 5819 Context.setjmp_bufDecl(NewTD); 5820 else if (II->isStr("sigjmp_buf")) 5821 Context.setsigjmp_bufDecl(NewTD); 5822 else if (II->isStr("ucontext_t")) 5823 Context.setucontext_tDecl(NewTD); 5824 } 5825 5826 return NewTD; 5827 } 5828 5829 /// \brief Determines whether the given declaration is an out-of-scope 5830 /// previous declaration. 5831 /// 5832 /// This routine should be invoked when name lookup has found a 5833 /// previous declaration (PrevDecl) that is not in the scope where a 5834 /// new declaration by the same name is being introduced. If the new 5835 /// declaration occurs in a local scope, previous declarations with 5836 /// linkage may still be considered previous declarations (C99 5837 /// 6.2.2p4-5, C++ [basic.link]p6). 5838 /// 5839 /// \param PrevDecl the previous declaration found by name 5840 /// lookup 5841 /// 5842 /// \param DC the context in which the new declaration is being 5843 /// declared. 5844 /// 5845 /// \returns true if PrevDecl is an out-of-scope previous declaration 5846 /// for a new delcaration with the same name. 5847 static bool 5848 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5849 ASTContext &Context) { 5850 if (!PrevDecl) 5851 return false; 5852 5853 if (!PrevDecl->hasLinkage()) 5854 return false; 5855 5856 if (Context.getLangOpts().CPlusPlus) { 5857 // C++ [basic.link]p6: 5858 // If there is a visible declaration of an entity with linkage 5859 // having the same name and type, ignoring entities declared 5860 // outside the innermost enclosing namespace scope, the block 5861 // scope declaration declares that same entity and receives the 5862 // linkage of the previous declaration. 5863 DeclContext *OuterContext = DC->getRedeclContext(); 5864 if (!OuterContext->isFunctionOrMethod()) 5865 // This rule only applies to block-scope declarations. 5866 return false; 5867 5868 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5869 if (PrevOuterContext->isRecord()) 5870 // We found a member function: ignore it. 5871 return false; 5872 5873 // Find the innermost enclosing namespace for the new and 5874 // previous declarations. 5875 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5876 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5877 5878 // The previous declaration is in a different namespace, so it 5879 // isn't the same function. 5880 if (!OuterContext->Equals(PrevOuterContext)) 5881 return false; 5882 } 5883 5884 return true; 5885 } 5886 5887 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5888 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5889 if (!SS.isSet()) return; 5890 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5891 } 5892 5893 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5894 QualType type = decl->getType(); 5895 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5896 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5897 // Various kinds of declaration aren't allowed to be __autoreleasing. 5898 unsigned kind = -1U; 5899 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5900 if (var->hasAttr<BlocksAttr>()) 5901 kind = 0; // __block 5902 else if (!var->hasLocalStorage()) 5903 kind = 1; // global 5904 } else if (isa<ObjCIvarDecl>(decl)) { 5905 kind = 3; // ivar 5906 } else if (isa<FieldDecl>(decl)) { 5907 kind = 2; // field 5908 } 5909 5910 if (kind != -1U) { 5911 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5912 << kind; 5913 } 5914 } else if (lifetime == Qualifiers::OCL_None) { 5915 // Try to infer lifetime. 5916 if (!type->isObjCLifetimeType()) 5917 return false; 5918 5919 lifetime = type->getObjCARCImplicitLifetime(); 5920 type = Context.getLifetimeQualifiedType(type, lifetime); 5921 decl->setType(type); 5922 } 5923 5924 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5925 // Thread-local variables cannot have lifetime. 5926 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5927 var->getTLSKind()) { 5928 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5929 << var->getType(); 5930 return true; 5931 } 5932 } 5933 5934 return false; 5935 } 5936 5937 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5938 // Ensure that an auto decl is deduced otherwise the checks below might cache 5939 // the wrong linkage. 5940 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5941 5942 // 'weak' only applies to declarations with external linkage. 5943 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5944 if (!ND.isExternallyVisible()) { 5945 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5946 ND.dropAttr<WeakAttr>(); 5947 } 5948 } 5949 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5950 if (ND.isExternallyVisible()) { 5951 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5952 ND.dropAttr<WeakRefAttr>(); 5953 ND.dropAttr<AliasAttr>(); 5954 } 5955 } 5956 5957 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5958 if (VD->hasInit()) { 5959 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5960 assert(VD->isThisDeclarationADefinition() && 5961 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5962 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5963 VD->dropAttr<AliasAttr>(); 5964 } 5965 } 5966 } 5967 5968 // 'selectany' only applies to externally visible variable declarations. 5969 // It does not apply to functions. 5970 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5971 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5972 S.Diag(Attr->getLocation(), 5973 diag::err_attribute_selectany_non_extern_data); 5974 ND.dropAttr<SelectAnyAttr>(); 5975 } 5976 } 5977 5978 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5979 // dll attributes require external linkage. Static locals may have external 5980 // linkage but still cannot be explicitly imported or exported. 5981 auto *VD = dyn_cast<VarDecl>(&ND); 5982 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5983 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5984 << &ND << Attr; 5985 ND.setInvalidDecl(); 5986 } 5987 } 5988 5989 // Virtual functions cannot be marked as 'notail'. 5990 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5991 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5992 if (MD->isVirtual()) { 5993 S.Diag(ND.getLocation(), 5994 diag::err_invalid_attribute_on_virtual_function) 5995 << Attr; 5996 ND.dropAttr<NotTailCalledAttr>(); 5997 } 5998 } 5999 6000 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6001 NamedDecl *NewDecl, 6002 bool IsSpecialization, 6003 bool IsDefinition) { 6004 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6005 return; 6006 6007 bool IsTemplate = false; 6008 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6009 OldDecl = OldTD->getTemplatedDecl(); 6010 IsTemplate = true; 6011 if (!IsSpecialization) 6012 IsDefinition = false; 6013 } 6014 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6015 NewDecl = NewTD->getTemplatedDecl(); 6016 IsTemplate = true; 6017 } 6018 6019 if (!OldDecl || !NewDecl) 6020 return; 6021 6022 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6023 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6024 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6025 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6026 6027 // dllimport and dllexport are inheritable attributes so we have to exclude 6028 // inherited attribute instances. 6029 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6030 (NewExportAttr && !NewExportAttr->isInherited()); 6031 6032 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6033 // the only exception being explicit specializations. 6034 // Implicitly generated declarations are also excluded for now because there 6035 // is no other way to switch these to use dllimport or dllexport. 6036 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6037 6038 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6039 // Allow with a warning for free functions and global variables. 6040 bool JustWarn = false; 6041 if (!OldDecl->isCXXClassMember()) { 6042 auto *VD = dyn_cast<VarDecl>(OldDecl); 6043 if (VD && !VD->getDescribedVarTemplate()) 6044 JustWarn = true; 6045 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6046 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6047 JustWarn = true; 6048 } 6049 6050 // We cannot change a declaration that's been used because IR has already 6051 // been emitted. Dllimported functions will still work though (modulo 6052 // address equality) as they can use the thunk. 6053 if (OldDecl->isUsed()) 6054 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6055 JustWarn = false; 6056 6057 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6058 : diag::err_attribute_dll_redeclaration; 6059 S.Diag(NewDecl->getLocation(), DiagID) 6060 << NewDecl 6061 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6062 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6063 if (!JustWarn) { 6064 NewDecl->setInvalidDecl(); 6065 return; 6066 } 6067 } 6068 6069 // A redeclaration is not allowed to drop a dllimport attribute, the only 6070 // exceptions being inline function definitions (except for function 6071 // templates), local extern declarations, qualified friend declarations or 6072 // special MSVC extension: in the last case, the declaration is treated as if 6073 // it were marked dllexport. 6074 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6075 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6076 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6077 // Ignore static data because out-of-line definitions are diagnosed 6078 // separately. 6079 IsStaticDataMember = VD->isStaticDataMember(); 6080 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6081 VarDecl::DeclarationOnly; 6082 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6083 IsInline = FD->isInlined(); 6084 IsQualifiedFriend = FD->getQualifier() && 6085 FD->getFriendObjectKind() == Decl::FOK_Declared; 6086 } 6087 6088 if (OldImportAttr && !HasNewAttr && 6089 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6090 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6091 if (IsMicrosoft && IsDefinition) { 6092 S.Diag(NewDecl->getLocation(), 6093 diag::warn_redeclaration_without_import_attribute) 6094 << NewDecl; 6095 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6096 NewDecl->dropAttr<DLLImportAttr>(); 6097 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6098 NewImportAttr->getRange(), S.Context, 6099 NewImportAttr->getSpellingListIndex())); 6100 } else { 6101 S.Diag(NewDecl->getLocation(), 6102 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6103 << NewDecl << OldImportAttr; 6104 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6105 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6106 OldDecl->dropAttr<DLLImportAttr>(); 6107 NewDecl->dropAttr<DLLImportAttr>(); 6108 } 6109 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6110 // In MinGW, seeing a function declared inline drops the dllimport 6111 // attribute. 6112 OldDecl->dropAttr<DLLImportAttr>(); 6113 NewDecl->dropAttr<DLLImportAttr>(); 6114 S.Diag(NewDecl->getLocation(), 6115 diag::warn_dllimport_dropped_from_inline_function) 6116 << NewDecl << OldImportAttr; 6117 } 6118 6119 // A specialization of a class template member function is processed here 6120 // since it's a redeclaration. If the parent class is dllexport, the 6121 // specialization inherits that attribute. This doesn't happen automatically 6122 // since the parent class isn't instantiated until later. 6123 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6124 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6125 !NewImportAttr && !NewExportAttr) { 6126 if (const DLLExportAttr *ParentExportAttr = 6127 MD->getParent()->getAttr<DLLExportAttr>()) { 6128 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6129 NewAttr->setInherited(true); 6130 NewDecl->addAttr(NewAttr); 6131 } 6132 } 6133 } 6134 } 6135 6136 /// Given that we are within the definition of the given function, 6137 /// will that definition behave like C99's 'inline', where the 6138 /// definition is discarded except for optimization purposes? 6139 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6140 // Try to avoid calling GetGVALinkageForFunction. 6141 6142 // All cases of this require the 'inline' keyword. 6143 if (!FD->isInlined()) return false; 6144 6145 // This is only possible in C++ with the gnu_inline attribute. 6146 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6147 return false; 6148 6149 // Okay, go ahead and call the relatively-more-expensive function. 6150 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6151 } 6152 6153 /// Determine whether a variable is extern "C" prior to attaching 6154 /// an initializer. We can't just call isExternC() here, because that 6155 /// will also compute and cache whether the declaration is externally 6156 /// visible, which might change when we attach the initializer. 6157 /// 6158 /// This can only be used if the declaration is known to not be a 6159 /// redeclaration of an internal linkage declaration. 6160 /// 6161 /// For instance: 6162 /// 6163 /// auto x = []{}; 6164 /// 6165 /// Attaching the initializer here makes this declaration not externally 6166 /// visible, because its type has internal linkage. 6167 /// 6168 /// FIXME: This is a hack. 6169 template<typename T> 6170 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6171 if (S.getLangOpts().CPlusPlus) { 6172 // In C++, the overloadable attribute negates the effects of extern "C". 6173 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6174 return false; 6175 6176 // So do CUDA's host/device attributes. 6177 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6178 D->template hasAttr<CUDAHostAttr>())) 6179 return false; 6180 } 6181 return D->isExternC(); 6182 } 6183 6184 static bool shouldConsiderLinkage(const VarDecl *VD) { 6185 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6186 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6187 return VD->hasExternalStorage(); 6188 if (DC->isFileContext()) 6189 return true; 6190 if (DC->isRecord()) 6191 return false; 6192 llvm_unreachable("Unexpected context"); 6193 } 6194 6195 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6196 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6197 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6198 isa<OMPDeclareReductionDecl>(DC)) 6199 return true; 6200 if (DC->isRecord()) 6201 return false; 6202 llvm_unreachable("Unexpected context"); 6203 } 6204 6205 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6206 AttributeList::Kind Kind) { 6207 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6208 if (L->getKind() == Kind) 6209 return true; 6210 return false; 6211 } 6212 6213 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6214 AttributeList::Kind Kind) { 6215 // Check decl attributes on the DeclSpec. 6216 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6217 return true; 6218 6219 // Walk the declarator structure, checking decl attributes that were in a type 6220 // position to the decl itself. 6221 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6222 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6223 return true; 6224 } 6225 6226 // Finally, check attributes on the decl itself. 6227 return hasParsedAttr(S, PD.getAttributes(), Kind); 6228 } 6229 6230 /// Adjust the \c DeclContext for a function or variable that might be a 6231 /// function-local external declaration. 6232 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6233 if (!DC->isFunctionOrMethod()) 6234 return false; 6235 6236 // If this is a local extern function or variable declared within a function 6237 // template, don't add it into the enclosing namespace scope until it is 6238 // instantiated; it might have a dependent type right now. 6239 if (DC->isDependentContext()) 6240 return true; 6241 6242 // C++11 [basic.link]p7: 6243 // When a block scope declaration of an entity with linkage is not found to 6244 // refer to some other declaration, then that entity is a member of the 6245 // innermost enclosing namespace. 6246 // 6247 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6248 // semantically-enclosing namespace, not a lexically-enclosing one. 6249 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6250 DC = DC->getParent(); 6251 return true; 6252 } 6253 6254 /// \brief Returns true if given declaration has external C language linkage. 6255 static bool isDeclExternC(const Decl *D) { 6256 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6257 return FD->isExternC(); 6258 if (const auto *VD = dyn_cast<VarDecl>(D)) 6259 return VD->isExternC(); 6260 6261 llvm_unreachable("Unknown type of decl!"); 6262 } 6263 6264 NamedDecl *Sema::ActOnVariableDeclarator( 6265 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6266 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6267 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6268 QualType R = TInfo->getType(); 6269 DeclarationName Name = GetNameForDeclarator(D).getName(); 6270 6271 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6272 6273 if (D.isDecompositionDeclarator()) { 6274 // Take the name of the first declarator as our name for diagnostic 6275 // purposes. 6276 auto &Decomp = D.getDecompositionDeclarator(); 6277 if (!Decomp.bindings().empty()) { 6278 II = Decomp.bindings()[0].Name; 6279 Name = II; 6280 } 6281 } else if (!II) { 6282 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6283 return nullptr; 6284 } 6285 6286 if (getLangOpts().OpenCL) { 6287 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6288 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6289 // argument. 6290 if (R->isImageType() || R->isPipeType()) { 6291 Diag(D.getIdentifierLoc(), 6292 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6293 << R; 6294 D.setInvalidType(); 6295 return nullptr; 6296 } 6297 6298 // OpenCL v1.2 s6.9.r: 6299 // The event type cannot be used to declare a program scope variable. 6300 // OpenCL v2.0 s6.9.q: 6301 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6302 if (NULL == S->getParent()) { 6303 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6304 Diag(D.getIdentifierLoc(), 6305 diag::err_invalid_type_for_program_scope_var) << R; 6306 D.setInvalidType(); 6307 return nullptr; 6308 } 6309 } 6310 6311 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6312 QualType NR = R; 6313 while (NR->isPointerType()) { 6314 if (NR->isFunctionPointerType()) { 6315 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6316 D.setInvalidType(); 6317 break; 6318 } 6319 NR = NR->getPointeeType(); 6320 } 6321 6322 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6323 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6324 // half array type (unless the cl_khr_fp16 extension is enabled). 6325 if (Context.getBaseElementType(R)->isHalfType()) { 6326 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6327 D.setInvalidType(); 6328 } 6329 } 6330 6331 if (R->isSamplerT()) { 6332 // OpenCL v1.2 s6.9.b p4: 6333 // The sampler type cannot be used with the __local and __global address 6334 // space qualifiers. 6335 if (R.getAddressSpace() == LangAS::opencl_local || 6336 R.getAddressSpace() == LangAS::opencl_global) { 6337 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6338 } 6339 6340 // OpenCL v1.2 s6.12.14.1: 6341 // A global sampler must be declared with either the constant address 6342 // space qualifier or with the const qualifier. 6343 if (DC->isTranslationUnit() && 6344 !(R.getAddressSpace() == LangAS::opencl_constant || 6345 R.isConstQualified())) { 6346 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6347 D.setInvalidType(); 6348 } 6349 } 6350 6351 // OpenCL v1.2 s6.9.r: 6352 // The event type cannot be used with the __local, __constant and __global 6353 // address space qualifiers. 6354 if (R->isEventT()) { 6355 if (R.getAddressSpace() != LangAS::opencl_private) { 6356 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6357 D.setInvalidType(); 6358 } 6359 } 6360 } 6361 6362 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6363 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6364 6365 // dllimport globals without explicit storage class are treated as extern. We 6366 // have to change the storage class this early to get the right DeclContext. 6367 if (SC == SC_None && !DC->isRecord() && 6368 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6369 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6370 SC = SC_Extern; 6371 6372 DeclContext *OriginalDC = DC; 6373 bool IsLocalExternDecl = SC == SC_Extern && 6374 adjustContextForLocalExternDecl(DC); 6375 6376 if (SCSpec == DeclSpec::SCS_mutable) { 6377 // mutable can only appear on non-static class members, so it's always 6378 // an error here 6379 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6380 D.setInvalidType(); 6381 SC = SC_None; 6382 } 6383 6384 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6385 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6386 D.getDeclSpec().getStorageClassSpecLoc())) { 6387 // In C++11, the 'register' storage class specifier is deprecated. 6388 // Suppress the warning in system macros, it's used in macros in some 6389 // popular C system headers, such as in glibc's htonl() macro. 6390 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6391 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6392 : diag::warn_deprecated_register) 6393 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6394 } 6395 6396 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6397 6398 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6399 // C99 6.9p2: The storage-class specifiers auto and register shall not 6400 // appear in the declaration specifiers in an external declaration. 6401 // Global Register+Asm is a GNU extension we support. 6402 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6403 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6404 D.setInvalidType(); 6405 } 6406 } 6407 6408 bool IsMemberSpecialization = false; 6409 bool IsVariableTemplateSpecialization = false; 6410 bool IsPartialSpecialization = false; 6411 bool IsVariableTemplate = false; 6412 VarDecl *NewVD = nullptr; 6413 VarTemplateDecl *NewTemplate = nullptr; 6414 TemplateParameterList *TemplateParams = nullptr; 6415 if (!getLangOpts().CPlusPlus) { 6416 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6417 D.getIdentifierLoc(), II, 6418 R, TInfo, SC); 6419 6420 if (R->getContainedDeducedType()) 6421 ParsingInitForAutoVars.insert(NewVD); 6422 6423 if (D.isInvalidType()) 6424 NewVD->setInvalidDecl(); 6425 } else { 6426 bool Invalid = false; 6427 6428 if (DC->isRecord() && !CurContext->isRecord()) { 6429 // This is an out-of-line definition of a static data member. 6430 switch (SC) { 6431 case SC_None: 6432 break; 6433 case SC_Static: 6434 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6435 diag::err_static_out_of_line) 6436 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6437 break; 6438 case SC_Auto: 6439 case SC_Register: 6440 case SC_Extern: 6441 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6442 // to names of variables declared in a block or to function parameters. 6443 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6444 // of class members 6445 6446 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6447 diag::err_storage_class_for_static_member) 6448 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6449 break; 6450 case SC_PrivateExtern: 6451 llvm_unreachable("C storage class in c++!"); 6452 } 6453 } 6454 6455 if (SC == SC_Static && CurContext->isRecord()) { 6456 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6457 if (RD->isLocalClass()) 6458 Diag(D.getIdentifierLoc(), 6459 diag::err_static_data_member_not_allowed_in_local_class) 6460 << Name << RD->getDeclName(); 6461 6462 // C++98 [class.union]p1: If a union contains a static data member, 6463 // the program is ill-formed. C++11 drops this restriction. 6464 if (RD->isUnion()) 6465 Diag(D.getIdentifierLoc(), 6466 getLangOpts().CPlusPlus11 6467 ? diag::warn_cxx98_compat_static_data_member_in_union 6468 : diag::ext_static_data_member_in_union) << Name; 6469 // We conservatively disallow static data members in anonymous structs. 6470 else if (!RD->getDeclName()) 6471 Diag(D.getIdentifierLoc(), 6472 diag::err_static_data_member_not_allowed_in_anon_struct) 6473 << Name << RD->isUnion(); 6474 } 6475 } 6476 6477 // Match up the template parameter lists with the scope specifier, then 6478 // determine whether we have a template or a template specialization. 6479 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6480 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6481 D.getCXXScopeSpec(), 6482 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6483 ? D.getName().TemplateId 6484 : nullptr, 6485 TemplateParamLists, 6486 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6487 6488 if (TemplateParams) { 6489 if (!TemplateParams->size() && 6490 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6491 // There is an extraneous 'template<>' for this variable. Complain 6492 // about it, but allow the declaration of the variable. 6493 Diag(TemplateParams->getTemplateLoc(), 6494 diag::err_template_variable_noparams) 6495 << II 6496 << SourceRange(TemplateParams->getTemplateLoc(), 6497 TemplateParams->getRAngleLoc()); 6498 TemplateParams = nullptr; 6499 } else { 6500 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6501 // This is an explicit specialization or a partial specialization. 6502 // FIXME: Check that we can declare a specialization here. 6503 IsVariableTemplateSpecialization = true; 6504 IsPartialSpecialization = TemplateParams->size() > 0; 6505 } else { // if (TemplateParams->size() > 0) 6506 // This is a template declaration. 6507 IsVariableTemplate = true; 6508 6509 // Check that we can declare a template here. 6510 if (CheckTemplateDeclScope(S, TemplateParams)) 6511 return nullptr; 6512 6513 // Only C++1y supports variable templates (N3651). 6514 Diag(D.getIdentifierLoc(), 6515 getLangOpts().CPlusPlus14 6516 ? diag::warn_cxx11_compat_variable_template 6517 : diag::ext_variable_template); 6518 } 6519 } 6520 } else { 6521 assert((Invalid || 6522 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6523 "should have a 'template<>' for this decl"); 6524 } 6525 6526 if (IsVariableTemplateSpecialization) { 6527 SourceLocation TemplateKWLoc = 6528 TemplateParamLists.size() > 0 6529 ? TemplateParamLists[0]->getTemplateLoc() 6530 : SourceLocation(); 6531 DeclResult Res = ActOnVarTemplateSpecialization( 6532 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6533 IsPartialSpecialization); 6534 if (Res.isInvalid()) 6535 return nullptr; 6536 NewVD = cast<VarDecl>(Res.get()); 6537 AddToScope = false; 6538 } else if (D.isDecompositionDeclarator()) { 6539 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6540 D.getIdentifierLoc(), R, TInfo, SC, 6541 Bindings); 6542 } else 6543 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6544 D.getIdentifierLoc(), II, R, TInfo, SC); 6545 6546 // If this is supposed to be a variable template, create it as such. 6547 if (IsVariableTemplate) { 6548 NewTemplate = 6549 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6550 TemplateParams, NewVD); 6551 NewVD->setDescribedVarTemplate(NewTemplate); 6552 } 6553 6554 // If this decl has an auto type in need of deduction, make a note of the 6555 // Decl so we can diagnose uses of it in its own initializer. 6556 if (R->getContainedDeducedType()) 6557 ParsingInitForAutoVars.insert(NewVD); 6558 6559 if (D.isInvalidType() || Invalid) { 6560 NewVD->setInvalidDecl(); 6561 if (NewTemplate) 6562 NewTemplate->setInvalidDecl(); 6563 } 6564 6565 SetNestedNameSpecifier(NewVD, D); 6566 6567 // If we have any template parameter lists that don't directly belong to 6568 // the variable (matching the scope specifier), store them. 6569 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6570 if (TemplateParamLists.size() > VDTemplateParamLists) 6571 NewVD->setTemplateParameterListsInfo( 6572 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6573 6574 if (D.getDeclSpec().isConstexprSpecified()) { 6575 NewVD->setConstexpr(true); 6576 // C++1z [dcl.spec.constexpr]p1: 6577 // A static data member declared with the constexpr specifier is 6578 // implicitly an inline variable. 6579 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6580 NewVD->setImplicitlyInline(); 6581 } 6582 } 6583 6584 if (D.getDeclSpec().isInlineSpecified()) { 6585 if (!getLangOpts().CPlusPlus) { 6586 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6587 << 0; 6588 } else if (CurContext->isFunctionOrMethod()) { 6589 // 'inline' is not allowed on block scope variable declaration. 6590 Diag(D.getDeclSpec().getInlineSpecLoc(), 6591 diag::err_inline_declaration_block_scope) << Name 6592 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6593 } else { 6594 Diag(D.getDeclSpec().getInlineSpecLoc(), 6595 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6596 : diag::ext_inline_variable); 6597 NewVD->setInlineSpecified(); 6598 } 6599 } 6600 6601 // Set the lexical context. If the declarator has a C++ scope specifier, the 6602 // lexical context will be different from the semantic context. 6603 NewVD->setLexicalDeclContext(CurContext); 6604 if (NewTemplate) 6605 NewTemplate->setLexicalDeclContext(CurContext); 6606 6607 if (IsLocalExternDecl) { 6608 if (D.isDecompositionDeclarator()) 6609 for (auto *B : Bindings) 6610 B->setLocalExternDecl(); 6611 else 6612 NewVD->setLocalExternDecl(); 6613 } 6614 6615 bool EmitTLSUnsupportedError = false; 6616 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6617 // C++11 [dcl.stc]p4: 6618 // When thread_local is applied to a variable of block scope the 6619 // storage-class-specifier static is implied if it does not appear 6620 // explicitly. 6621 // Core issue: 'static' is not implied if the variable is declared 6622 // 'extern'. 6623 if (NewVD->hasLocalStorage() && 6624 (SCSpec != DeclSpec::SCS_unspecified || 6625 TSCS != DeclSpec::TSCS_thread_local || 6626 !DC->isFunctionOrMethod())) 6627 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6628 diag::err_thread_non_global) 6629 << DeclSpec::getSpecifierName(TSCS); 6630 else if (!Context.getTargetInfo().isTLSSupported()) { 6631 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6632 // Postpone error emission until we've collected attributes required to 6633 // figure out whether it's a host or device variable and whether the 6634 // error should be ignored. 6635 EmitTLSUnsupportedError = true; 6636 // We still need to mark the variable as TLS so it shows up in AST with 6637 // proper storage class for other tools to use even if we're not going 6638 // to emit any code for it. 6639 NewVD->setTSCSpec(TSCS); 6640 } else 6641 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6642 diag::err_thread_unsupported); 6643 } else 6644 NewVD->setTSCSpec(TSCS); 6645 } 6646 6647 // C99 6.7.4p3 6648 // An inline definition of a function with external linkage shall 6649 // not contain a definition of a modifiable object with static or 6650 // thread storage duration... 6651 // We only apply this when the function is required to be defined 6652 // elsewhere, i.e. when the function is not 'extern inline'. Note 6653 // that a local variable with thread storage duration still has to 6654 // be marked 'static'. Also note that it's possible to get these 6655 // semantics in C++ using __attribute__((gnu_inline)). 6656 if (SC == SC_Static && S->getFnParent() != nullptr && 6657 !NewVD->getType().isConstQualified()) { 6658 FunctionDecl *CurFD = getCurFunctionDecl(); 6659 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6660 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6661 diag::warn_static_local_in_extern_inline); 6662 MaybeSuggestAddingStaticToDecl(CurFD); 6663 } 6664 } 6665 6666 if (D.getDeclSpec().isModulePrivateSpecified()) { 6667 if (IsVariableTemplateSpecialization) 6668 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6669 << (IsPartialSpecialization ? 1 : 0) 6670 << FixItHint::CreateRemoval( 6671 D.getDeclSpec().getModulePrivateSpecLoc()); 6672 else if (IsMemberSpecialization) 6673 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6674 << 2 6675 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6676 else if (NewVD->hasLocalStorage()) 6677 Diag(NewVD->getLocation(), diag::err_module_private_local) 6678 << 0 << NewVD->getDeclName() 6679 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6680 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6681 else { 6682 NewVD->setModulePrivate(); 6683 if (NewTemplate) 6684 NewTemplate->setModulePrivate(); 6685 for (auto *B : Bindings) 6686 B->setModulePrivate(); 6687 } 6688 } 6689 6690 // Handle attributes prior to checking for duplicates in MergeVarDecl 6691 ProcessDeclAttributes(S, NewVD, D); 6692 6693 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6694 if (EmitTLSUnsupportedError && 6695 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6696 (getLangOpts().OpenMPIsDevice && 6697 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6698 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6699 diag::err_thread_unsupported); 6700 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6701 // storage [duration]." 6702 if (SC == SC_None && S->getFnParent() != nullptr && 6703 (NewVD->hasAttr<CUDASharedAttr>() || 6704 NewVD->hasAttr<CUDAConstantAttr>())) { 6705 NewVD->setStorageClass(SC_Static); 6706 } 6707 } 6708 6709 // Ensure that dllimport globals without explicit storage class are treated as 6710 // extern. The storage class is set above using parsed attributes. Now we can 6711 // check the VarDecl itself. 6712 assert(!NewVD->hasAttr<DLLImportAttr>() || 6713 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6714 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6715 6716 // In auto-retain/release, infer strong retension for variables of 6717 // retainable type. 6718 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6719 NewVD->setInvalidDecl(); 6720 6721 // Handle GNU asm-label extension (encoded as an attribute). 6722 if (Expr *E = (Expr*)D.getAsmLabel()) { 6723 // The parser guarantees this is a string. 6724 StringLiteral *SE = cast<StringLiteral>(E); 6725 StringRef Label = SE->getString(); 6726 if (S->getFnParent() != nullptr) { 6727 switch (SC) { 6728 case SC_None: 6729 case SC_Auto: 6730 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6731 break; 6732 case SC_Register: 6733 // Local Named register 6734 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6735 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6736 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6737 break; 6738 case SC_Static: 6739 case SC_Extern: 6740 case SC_PrivateExtern: 6741 break; 6742 } 6743 } else if (SC == SC_Register) { 6744 // Global Named register 6745 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6746 const auto &TI = Context.getTargetInfo(); 6747 bool HasSizeMismatch; 6748 6749 if (!TI.isValidGCCRegisterName(Label)) 6750 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6751 else if (!TI.validateGlobalRegisterVariable(Label, 6752 Context.getTypeSize(R), 6753 HasSizeMismatch)) 6754 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6755 else if (HasSizeMismatch) 6756 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6757 } 6758 6759 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6760 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6761 NewVD->setInvalidDecl(true); 6762 } 6763 } 6764 6765 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6766 Context, Label, 0)); 6767 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6768 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6769 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6770 if (I != ExtnameUndeclaredIdentifiers.end()) { 6771 if (isDeclExternC(NewVD)) { 6772 NewVD->addAttr(I->second); 6773 ExtnameUndeclaredIdentifiers.erase(I); 6774 } else 6775 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6776 << /*Variable*/1 << NewVD; 6777 } 6778 } 6779 6780 // Find the shadowed declaration before filtering for scope. 6781 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6782 ? getShadowedDeclaration(NewVD, Previous) 6783 : nullptr; 6784 6785 // Don't consider existing declarations that are in a different 6786 // scope and are out-of-semantic-context declarations (if the new 6787 // declaration has linkage). 6788 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6789 D.getCXXScopeSpec().isNotEmpty() || 6790 IsMemberSpecialization || 6791 IsVariableTemplateSpecialization); 6792 6793 // Check whether the previous declaration is in the same block scope. This 6794 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6795 if (getLangOpts().CPlusPlus && 6796 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6797 NewVD->setPreviousDeclInSameBlockScope( 6798 Previous.isSingleResult() && !Previous.isShadowed() && 6799 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6800 6801 if (!getLangOpts().CPlusPlus) { 6802 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6803 } else { 6804 // If this is an explicit specialization of a static data member, check it. 6805 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6806 CheckMemberSpecialization(NewVD, Previous)) 6807 NewVD->setInvalidDecl(); 6808 6809 // Merge the decl with the existing one if appropriate. 6810 if (!Previous.empty()) { 6811 if (Previous.isSingleResult() && 6812 isa<FieldDecl>(Previous.getFoundDecl()) && 6813 D.getCXXScopeSpec().isSet()) { 6814 // The user tried to define a non-static data member 6815 // out-of-line (C++ [dcl.meaning]p1). 6816 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6817 << D.getCXXScopeSpec().getRange(); 6818 Previous.clear(); 6819 NewVD->setInvalidDecl(); 6820 } 6821 } else if (D.getCXXScopeSpec().isSet()) { 6822 // No previous declaration in the qualifying scope. 6823 Diag(D.getIdentifierLoc(), diag::err_no_member) 6824 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6825 << D.getCXXScopeSpec().getRange(); 6826 NewVD->setInvalidDecl(); 6827 } 6828 6829 if (!IsVariableTemplateSpecialization) 6830 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6831 6832 if (NewTemplate) { 6833 VarTemplateDecl *PrevVarTemplate = 6834 NewVD->getPreviousDecl() 6835 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6836 : nullptr; 6837 6838 // Check the template parameter list of this declaration, possibly 6839 // merging in the template parameter list from the previous variable 6840 // template declaration. 6841 if (CheckTemplateParameterList( 6842 TemplateParams, 6843 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6844 : nullptr, 6845 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6846 DC->isDependentContext()) 6847 ? TPC_ClassTemplateMember 6848 : TPC_VarTemplate)) 6849 NewVD->setInvalidDecl(); 6850 6851 // If we are providing an explicit specialization of a static variable 6852 // template, make a note of that. 6853 if (PrevVarTemplate && 6854 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6855 PrevVarTemplate->setMemberSpecialization(); 6856 } 6857 } 6858 6859 // Diagnose shadowed variables iff this isn't a redeclaration. 6860 if (ShadowedDecl && !D.isRedeclaration()) 6861 CheckShadow(NewVD, ShadowedDecl, Previous); 6862 6863 ProcessPragmaWeak(S, NewVD); 6864 6865 // If this is the first declaration of an extern C variable, update 6866 // the map of such variables. 6867 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6868 isIncompleteDeclExternC(*this, NewVD)) 6869 RegisterLocallyScopedExternCDecl(NewVD, S); 6870 6871 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6872 Decl *ManglingContextDecl; 6873 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6874 NewVD->getDeclContext(), ManglingContextDecl)) { 6875 Context.setManglingNumber( 6876 NewVD, MCtx->getManglingNumber( 6877 NewVD, getMSManglingNumber(getLangOpts(), S))); 6878 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6879 } 6880 } 6881 6882 // Special handling of variable named 'main'. 6883 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6884 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6885 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6886 6887 // C++ [basic.start.main]p3 6888 // A program that declares a variable main at global scope is ill-formed. 6889 if (getLangOpts().CPlusPlus) 6890 Diag(D.getLocStart(), diag::err_main_global_variable); 6891 6892 // In C, and external-linkage variable named main results in undefined 6893 // behavior. 6894 else if (NewVD->hasExternalFormalLinkage()) 6895 Diag(D.getLocStart(), diag::warn_main_redefined); 6896 } 6897 6898 if (D.isRedeclaration() && !Previous.empty()) { 6899 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6900 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6901 D.isFunctionDefinition()); 6902 } 6903 6904 if (NewTemplate) { 6905 if (NewVD->isInvalidDecl()) 6906 NewTemplate->setInvalidDecl(); 6907 ActOnDocumentableDecl(NewTemplate); 6908 return NewTemplate; 6909 } 6910 6911 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6912 CompleteMemberSpecialization(NewVD, Previous); 6913 6914 return NewVD; 6915 } 6916 6917 /// Enum describing the %select options in diag::warn_decl_shadow. 6918 enum ShadowedDeclKind { 6919 SDK_Local, 6920 SDK_Global, 6921 SDK_StaticMember, 6922 SDK_Field, 6923 SDK_Typedef, 6924 SDK_Using 6925 }; 6926 6927 /// Determine what kind of declaration we're shadowing. 6928 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6929 const DeclContext *OldDC) { 6930 if (isa<TypeAliasDecl>(ShadowedDecl)) 6931 return SDK_Using; 6932 else if (isa<TypedefDecl>(ShadowedDecl)) 6933 return SDK_Typedef; 6934 else if (isa<RecordDecl>(OldDC)) 6935 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6936 6937 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6938 } 6939 6940 /// Return the location of the capture if the given lambda captures the given 6941 /// variable \p VD, or an invalid source location otherwise. 6942 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6943 const VarDecl *VD) { 6944 for (const Capture &Capture : LSI->Captures) { 6945 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6946 return Capture.getLocation(); 6947 } 6948 return SourceLocation(); 6949 } 6950 6951 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6952 const LookupResult &R) { 6953 // Only diagnose if we're shadowing an unambiguous field or variable. 6954 if (R.getResultKind() != LookupResult::Found) 6955 return false; 6956 6957 // Return false if warning is ignored. 6958 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6959 } 6960 6961 /// \brief Return the declaration shadowed by the given variable \p D, or null 6962 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6963 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6964 const LookupResult &R) { 6965 if (!shouldWarnIfShadowedDecl(Diags, R)) 6966 return nullptr; 6967 6968 // Don't diagnose declarations at file scope. 6969 if (D->hasGlobalStorage()) 6970 return nullptr; 6971 6972 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6973 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6974 ? ShadowedDecl 6975 : nullptr; 6976 } 6977 6978 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6979 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6980 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6981 const LookupResult &R) { 6982 // Don't warn if typedef declaration is part of a class 6983 if (D->getDeclContext()->isRecord()) 6984 return nullptr; 6985 6986 if (!shouldWarnIfShadowedDecl(Diags, R)) 6987 return nullptr; 6988 6989 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6990 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6991 } 6992 6993 /// \brief Diagnose variable or built-in function shadowing. Implements 6994 /// -Wshadow. 6995 /// 6996 /// This method is called whenever a VarDecl is added to a "useful" 6997 /// scope. 6998 /// 6999 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7000 /// \param R the lookup of the name 7001 /// 7002 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7003 const LookupResult &R) { 7004 DeclContext *NewDC = D->getDeclContext(); 7005 7006 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7007 // Fields are not shadowed by variables in C++ static methods. 7008 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7009 if (MD->isStatic()) 7010 return; 7011 7012 // Fields shadowed by constructor parameters are a special case. Usually 7013 // the constructor initializes the field with the parameter. 7014 if (isa<CXXConstructorDecl>(NewDC)) 7015 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7016 // Remember that this was shadowed so we can either warn about its 7017 // modification or its existence depending on warning settings. 7018 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7019 return; 7020 } 7021 } 7022 7023 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7024 if (shadowedVar->isExternC()) { 7025 // For shadowing external vars, make sure that we point to the global 7026 // declaration, not a locally scoped extern declaration. 7027 for (auto I : shadowedVar->redecls()) 7028 if (I->isFileVarDecl()) { 7029 ShadowedDecl = I; 7030 break; 7031 } 7032 } 7033 7034 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7035 7036 unsigned WarningDiag = diag::warn_decl_shadow; 7037 SourceLocation CaptureLoc; 7038 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7039 isa<CXXMethodDecl>(NewDC)) { 7040 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7041 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7042 if (RD->getLambdaCaptureDefault() == LCD_None) { 7043 // Try to avoid warnings for lambdas with an explicit capture list. 7044 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7045 // Warn only when the lambda captures the shadowed decl explicitly. 7046 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7047 if (CaptureLoc.isInvalid()) 7048 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7049 } else { 7050 // Remember that this was shadowed so we can avoid the warning if the 7051 // shadowed decl isn't captured and the warning settings allow it. 7052 cast<LambdaScopeInfo>(getCurFunction()) 7053 ->ShadowingDecls.push_back( 7054 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7055 return; 7056 } 7057 } 7058 7059 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7060 // A variable can't shadow a local variable in an enclosing scope, if 7061 // they are separated by a non-capturing declaration context. 7062 for (DeclContext *ParentDC = NewDC; 7063 ParentDC && !ParentDC->Equals(OldDC); 7064 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7065 // Only block literals, captured statements, and lambda expressions 7066 // can capture; other scopes don't. 7067 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7068 !isLambdaCallOperator(ParentDC)) { 7069 return; 7070 } 7071 } 7072 } 7073 } 7074 } 7075 7076 // Only warn about certain kinds of shadowing for class members. 7077 if (NewDC && NewDC->isRecord()) { 7078 // In particular, don't warn about shadowing non-class members. 7079 if (!OldDC->isRecord()) 7080 return; 7081 7082 // TODO: should we warn about static data members shadowing 7083 // static data members from base classes? 7084 7085 // TODO: don't diagnose for inaccessible shadowed members. 7086 // This is hard to do perfectly because we might friend the 7087 // shadowing context, but that's just a false negative. 7088 } 7089 7090 7091 DeclarationName Name = R.getLookupName(); 7092 7093 // Emit warning and note. 7094 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7095 return; 7096 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7097 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7098 if (!CaptureLoc.isInvalid()) 7099 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7100 << Name << /*explicitly*/ 1; 7101 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7102 } 7103 7104 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7105 /// when these variables are captured by the lambda. 7106 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7107 for (const auto &Shadow : LSI->ShadowingDecls) { 7108 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7109 // Try to avoid the warning when the shadowed decl isn't captured. 7110 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7111 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7112 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7113 ? diag::warn_decl_shadow_uncaptured_local 7114 : diag::warn_decl_shadow) 7115 << Shadow.VD->getDeclName() 7116 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7117 if (!CaptureLoc.isInvalid()) 7118 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7119 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7120 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7121 } 7122 } 7123 7124 /// \brief Check -Wshadow without the advantage of a previous lookup. 7125 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7126 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7127 return; 7128 7129 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7130 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7131 LookupName(R, S); 7132 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7133 CheckShadow(D, ShadowedDecl, R); 7134 } 7135 7136 /// Check if 'E', which is an expression that is about to be modified, refers 7137 /// to a constructor parameter that shadows a field. 7138 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7139 // Quickly ignore expressions that can't be shadowing ctor parameters. 7140 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7141 return; 7142 E = E->IgnoreParenImpCasts(); 7143 auto *DRE = dyn_cast<DeclRefExpr>(E); 7144 if (!DRE) 7145 return; 7146 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7147 auto I = ShadowingDecls.find(D); 7148 if (I == ShadowingDecls.end()) 7149 return; 7150 const NamedDecl *ShadowedDecl = I->second; 7151 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7152 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7153 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7154 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7155 7156 // Avoid issuing multiple warnings about the same decl. 7157 ShadowingDecls.erase(I); 7158 } 7159 7160 /// Check for conflict between this global or extern "C" declaration and 7161 /// previous global or extern "C" declarations. This is only used in C++. 7162 template<typename T> 7163 static bool checkGlobalOrExternCConflict( 7164 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7165 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7166 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7167 7168 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7169 // The common case: this global doesn't conflict with any extern "C" 7170 // declaration. 7171 return false; 7172 } 7173 7174 if (Prev) { 7175 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7176 // Both the old and new declarations have C language linkage. This is a 7177 // redeclaration. 7178 Previous.clear(); 7179 Previous.addDecl(Prev); 7180 return true; 7181 } 7182 7183 // This is a global, non-extern "C" declaration, and there is a previous 7184 // non-global extern "C" declaration. Diagnose if this is a variable 7185 // declaration. 7186 if (!isa<VarDecl>(ND)) 7187 return false; 7188 } else { 7189 // The declaration is extern "C". Check for any declaration in the 7190 // translation unit which might conflict. 7191 if (IsGlobal) { 7192 // We have already performed the lookup into the translation unit. 7193 IsGlobal = false; 7194 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7195 I != E; ++I) { 7196 if (isa<VarDecl>(*I)) { 7197 Prev = *I; 7198 break; 7199 } 7200 } 7201 } else { 7202 DeclContext::lookup_result R = 7203 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7204 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7205 I != E; ++I) { 7206 if (isa<VarDecl>(*I)) { 7207 Prev = *I; 7208 break; 7209 } 7210 // FIXME: If we have any other entity with this name in global scope, 7211 // the declaration is ill-formed, but that is a defect: it breaks the 7212 // 'stat' hack, for instance. Only variables can have mangled name 7213 // clashes with extern "C" declarations, so only they deserve a 7214 // diagnostic. 7215 } 7216 } 7217 7218 if (!Prev) 7219 return false; 7220 } 7221 7222 // Use the first declaration's location to ensure we point at something which 7223 // is lexically inside an extern "C" linkage-spec. 7224 assert(Prev && "should have found a previous declaration to diagnose"); 7225 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7226 Prev = FD->getFirstDecl(); 7227 else 7228 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7229 7230 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7231 << IsGlobal << ND; 7232 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7233 << IsGlobal; 7234 return false; 7235 } 7236 7237 /// Apply special rules for handling extern "C" declarations. Returns \c true 7238 /// if we have found that this is a redeclaration of some prior entity. 7239 /// 7240 /// Per C++ [dcl.link]p6: 7241 /// Two declarations [for a function or variable] with C language linkage 7242 /// with the same name that appear in different scopes refer to the same 7243 /// [entity]. An entity with C language linkage shall not be declared with 7244 /// the same name as an entity in global scope. 7245 template<typename T> 7246 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7247 LookupResult &Previous) { 7248 if (!S.getLangOpts().CPlusPlus) { 7249 // In C, when declaring a global variable, look for a corresponding 'extern' 7250 // variable declared in function scope. We don't need this in C++, because 7251 // we find local extern decls in the surrounding file-scope DeclContext. 7252 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7253 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7254 Previous.clear(); 7255 Previous.addDecl(Prev); 7256 return true; 7257 } 7258 } 7259 return false; 7260 } 7261 7262 // A declaration in the translation unit can conflict with an extern "C" 7263 // declaration. 7264 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7265 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7266 7267 // An extern "C" declaration can conflict with a declaration in the 7268 // translation unit or can be a redeclaration of an extern "C" declaration 7269 // in another scope. 7270 if (isIncompleteDeclExternC(S,ND)) 7271 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7272 7273 // Neither global nor extern "C": nothing to do. 7274 return false; 7275 } 7276 7277 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7278 // If the decl is already known invalid, don't check it. 7279 if (NewVD->isInvalidDecl()) 7280 return; 7281 7282 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7283 QualType T = TInfo->getType(); 7284 7285 // Defer checking an 'auto' type until its initializer is attached. 7286 if (T->isUndeducedType()) 7287 return; 7288 7289 if (NewVD->hasAttrs()) 7290 CheckAlignasUnderalignment(NewVD); 7291 7292 if (T->isObjCObjectType()) { 7293 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7294 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7295 T = Context.getObjCObjectPointerType(T); 7296 NewVD->setType(T); 7297 } 7298 7299 // Emit an error if an address space was applied to decl with local storage. 7300 // This includes arrays of objects with address space qualifiers, but not 7301 // automatic variables that point to other address spaces. 7302 // ISO/IEC TR 18037 S5.1.2 7303 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7304 T.getAddressSpace() != LangAS::Default) { 7305 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7306 NewVD->setInvalidDecl(); 7307 return; 7308 } 7309 7310 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7311 // scope. 7312 if (getLangOpts().OpenCLVersion == 120 && 7313 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7314 NewVD->isStaticLocal()) { 7315 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7316 NewVD->setInvalidDecl(); 7317 return; 7318 } 7319 7320 if (getLangOpts().OpenCL) { 7321 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7322 if (NewVD->hasAttr<BlocksAttr>()) { 7323 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7324 return; 7325 } 7326 7327 if (T->isBlockPointerType()) { 7328 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7329 // can't use 'extern' storage class. 7330 if (!T.isConstQualified()) { 7331 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7332 << 0 /*const*/; 7333 NewVD->setInvalidDecl(); 7334 return; 7335 } 7336 if (NewVD->hasExternalStorage()) { 7337 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7338 NewVD->setInvalidDecl(); 7339 return; 7340 } 7341 } 7342 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7343 // __constant address space. 7344 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7345 // variables inside a function can also be declared in the global 7346 // address space. 7347 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7348 NewVD->hasExternalStorage()) { 7349 if (!T->isSamplerT() && 7350 !(T.getAddressSpace() == LangAS::opencl_constant || 7351 (T.getAddressSpace() == LangAS::opencl_global && 7352 getLangOpts().OpenCLVersion == 200))) { 7353 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7354 if (getLangOpts().OpenCLVersion == 200) 7355 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7356 << Scope << "global or constant"; 7357 else 7358 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7359 << Scope << "constant"; 7360 NewVD->setInvalidDecl(); 7361 return; 7362 } 7363 } else { 7364 if (T.getAddressSpace() == LangAS::opencl_global) { 7365 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7366 << 1 /*is any function*/ << "global"; 7367 NewVD->setInvalidDecl(); 7368 return; 7369 } 7370 if (T.getAddressSpace() == LangAS::opencl_constant || 7371 T.getAddressSpace() == LangAS::opencl_local) { 7372 FunctionDecl *FD = getCurFunctionDecl(); 7373 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7374 // in functions. 7375 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7376 if (T.getAddressSpace() == LangAS::opencl_constant) 7377 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7378 << 0 /*non-kernel only*/ << "constant"; 7379 else 7380 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7381 << 0 /*non-kernel only*/ << "local"; 7382 NewVD->setInvalidDecl(); 7383 return; 7384 } 7385 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7386 // in the outermost scope of a kernel function. 7387 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7388 if (!getCurScope()->isFunctionScope()) { 7389 if (T.getAddressSpace() == LangAS::opencl_constant) 7390 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7391 << "constant"; 7392 else 7393 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7394 << "local"; 7395 NewVD->setInvalidDecl(); 7396 return; 7397 } 7398 } 7399 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7400 // Do not allow other address spaces on automatic variable. 7401 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7402 NewVD->setInvalidDecl(); 7403 return; 7404 } 7405 } 7406 } 7407 7408 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7409 && !NewVD->hasAttr<BlocksAttr>()) { 7410 if (getLangOpts().getGC() != LangOptions::NonGC) 7411 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7412 else { 7413 assert(!getLangOpts().ObjCAutoRefCount); 7414 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7415 } 7416 } 7417 7418 bool isVM = T->isVariablyModifiedType(); 7419 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7420 NewVD->hasAttr<BlocksAttr>()) 7421 setFunctionHasBranchProtectedScope(); 7422 7423 if ((isVM && NewVD->hasLinkage()) || 7424 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7425 bool SizeIsNegative; 7426 llvm::APSInt Oversized; 7427 TypeSourceInfo *FixedTInfo = 7428 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7429 SizeIsNegative, Oversized); 7430 if (!FixedTInfo && T->isVariableArrayType()) { 7431 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7432 // FIXME: This won't give the correct result for 7433 // int a[10][n]; 7434 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7435 7436 if (NewVD->isFileVarDecl()) 7437 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7438 << SizeRange; 7439 else if (NewVD->isStaticLocal()) 7440 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7441 << SizeRange; 7442 else 7443 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7444 << SizeRange; 7445 NewVD->setInvalidDecl(); 7446 return; 7447 } 7448 7449 if (!FixedTInfo) { 7450 if (NewVD->isFileVarDecl()) 7451 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7452 else 7453 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7454 NewVD->setInvalidDecl(); 7455 return; 7456 } 7457 7458 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7459 NewVD->setType(FixedTInfo->getType()); 7460 NewVD->setTypeSourceInfo(FixedTInfo); 7461 } 7462 7463 if (T->isVoidType()) { 7464 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7465 // of objects and functions. 7466 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7467 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7468 << T; 7469 NewVD->setInvalidDecl(); 7470 return; 7471 } 7472 } 7473 7474 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7475 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7476 NewVD->setInvalidDecl(); 7477 return; 7478 } 7479 7480 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7481 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7482 NewVD->setInvalidDecl(); 7483 return; 7484 } 7485 7486 if (NewVD->isConstexpr() && !T->isDependentType() && 7487 RequireLiteralType(NewVD->getLocation(), T, 7488 diag::err_constexpr_var_non_literal)) { 7489 NewVD->setInvalidDecl(); 7490 return; 7491 } 7492 } 7493 7494 /// \brief Perform semantic checking on a newly-created variable 7495 /// declaration. 7496 /// 7497 /// This routine performs all of the type-checking required for a 7498 /// variable declaration once it has been built. It is used both to 7499 /// check variables after they have been parsed and their declarators 7500 /// have been translated into a declaration, and to check variables 7501 /// that have been instantiated from a template. 7502 /// 7503 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7504 /// 7505 /// Returns true if the variable declaration is a redeclaration. 7506 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7507 CheckVariableDeclarationType(NewVD); 7508 7509 // If the decl is already known invalid, don't check it. 7510 if (NewVD->isInvalidDecl()) 7511 return false; 7512 7513 // If we did not find anything by this name, look for a non-visible 7514 // extern "C" declaration with the same name. 7515 if (Previous.empty() && 7516 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7517 Previous.setShadowed(); 7518 7519 if (!Previous.empty()) { 7520 MergeVarDecl(NewVD, Previous); 7521 return true; 7522 } 7523 return false; 7524 } 7525 7526 namespace { 7527 struct FindOverriddenMethod { 7528 Sema *S; 7529 CXXMethodDecl *Method; 7530 7531 /// Member lookup function that determines whether a given C++ 7532 /// method overrides a method in a base class, to be used with 7533 /// CXXRecordDecl::lookupInBases(). 7534 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7535 RecordDecl *BaseRecord = 7536 Specifier->getType()->getAs<RecordType>()->getDecl(); 7537 7538 DeclarationName Name = Method->getDeclName(); 7539 7540 // FIXME: Do we care about other names here too? 7541 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7542 // We really want to find the base class destructor here. 7543 QualType T = S->Context.getTypeDeclType(BaseRecord); 7544 CanQualType CT = S->Context.getCanonicalType(T); 7545 7546 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7547 } 7548 7549 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7550 Path.Decls = Path.Decls.slice(1)) { 7551 NamedDecl *D = Path.Decls.front(); 7552 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7553 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7554 return true; 7555 } 7556 } 7557 7558 return false; 7559 } 7560 }; 7561 7562 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7563 } // end anonymous namespace 7564 7565 /// \brief Report an error regarding overriding, along with any relevant 7566 /// overridden methods. 7567 /// 7568 /// \param DiagID the primary error to report. 7569 /// \param MD the overriding method. 7570 /// \param OEK which overrides to include as notes. 7571 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7572 OverrideErrorKind OEK = OEK_All) { 7573 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7574 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7575 // This check (& the OEK parameter) could be replaced by a predicate, but 7576 // without lambdas that would be overkill. This is still nicer than writing 7577 // out the diag loop 3 times. 7578 if ((OEK == OEK_All) || 7579 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7580 (OEK == OEK_Deleted && O->isDeleted())) 7581 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7582 } 7583 } 7584 7585 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7586 /// and if so, check that it's a valid override and remember it. 7587 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7588 // Look for methods in base classes that this method might override. 7589 CXXBasePaths Paths; 7590 FindOverriddenMethod FOM; 7591 FOM.Method = MD; 7592 FOM.S = this; 7593 bool hasDeletedOverridenMethods = false; 7594 bool hasNonDeletedOverridenMethods = false; 7595 bool AddedAny = false; 7596 if (DC->lookupInBases(FOM, Paths)) { 7597 for (auto *I : Paths.found_decls()) { 7598 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7599 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7600 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7601 !CheckOverridingFunctionAttributes(MD, OldMD) && 7602 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7603 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7604 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7605 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7606 AddedAny = true; 7607 } 7608 } 7609 } 7610 } 7611 7612 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7613 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7614 } 7615 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7616 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7617 } 7618 7619 return AddedAny; 7620 } 7621 7622 namespace { 7623 // Struct for holding all of the extra arguments needed by 7624 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7625 struct ActOnFDArgs { 7626 Scope *S; 7627 Declarator &D; 7628 MultiTemplateParamsArg TemplateParamLists; 7629 bool AddToScope; 7630 }; 7631 } // end anonymous namespace 7632 7633 namespace { 7634 7635 // Callback to only accept typo corrections that have a non-zero edit distance. 7636 // Also only accept corrections that have the same parent decl. 7637 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7638 public: 7639 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7640 CXXRecordDecl *Parent) 7641 : Context(Context), OriginalFD(TypoFD), 7642 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7643 7644 bool ValidateCandidate(const TypoCorrection &candidate) override { 7645 if (candidate.getEditDistance() == 0) 7646 return false; 7647 7648 SmallVector<unsigned, 1> MismatchedParams; 7649 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7650 CDeclEnd = candidate.end(); 7651 CDecl != CDeclEnd; ++CDecl) { 7652 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7653 7654 if (FD && !FD->hasBody() && 7655 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7656 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7657 CXXRecordDecl *Parent = MD->getParent(); 7658 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7659 return true; 7660 } else if (!ExpectedParent) { 7661 return true; 7662 } 7663 } 7664 } 7665 7666 return false; 7667 } 7668 7669 private: 7670 ASTContext &Context; 7671 FunctionDecl *OriginalFD; 7672 CXXRecordDecl *ExpectedParent; 7673 }; 7674 7675 } // end anonymous namespace 7676 7677 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7678 TypoCorrectedFunctionDefinitions.insert(F); 7679 } 7680 7681 /// \brief Generate diagnostics for an invalid function redeclaration. 7682 /// 7683 /// This routine handles generating the diagnostic messages for an invalid 7684 /// function redeclaration, including finding possible similar declarations 7685 /// or performing typo correction if there are no previous declarations with 7686 /// the same name. 7687 /// 7688 /// Returns a NamedDecl iff typo correction was performed and substituting in 7689 /// the new declaration name does not cause new errors. 7690 static NamedDecl *DiagnoseInvalidRedeclaration( 7691 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7692 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7693 DeclarationName Name = NewFD->getDeclName(); 7694 DeclContext *NewDC = NewFD->getDeclContext(); 7695 SmallVector<unsigned, 1> MismatchedParams; 7696 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7697 TypoCorrection Correction; 7698 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7699 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7700 : diag::err_member_decl_does_not_match; 7701 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7702 IsLocalFriend ? Sema::LookupLocalFriendName 7703 : Sema::LookupOrdinaryName, 7704 Sema::ForVisibleRedeclaration); 7705 7706 NewFD->setInvalidDecl(); 7707 if (IsLocalFriend) 7708 SemaRef.LookupName(Prev, S); 7709 else 7710 SemaRef.LookupQualifiedName(Prev, NewDC); 7711 assert(!Prev.isAmbiguous() && 7712 "Cannot have an ambiguity in previous-declaration lookup"); 7713 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7714 if (!Prev.empty()) { 7715 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7716 Func != FuncEnd; ++Func) { 7717 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7718 if (FD && 7719 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7720 // Add 1 to the index so that 0 can mean the mismatch didn't 7721 // involve a parameter 7722 unsigned ParamNum = 7723 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7724 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7725 } 7726 } 7727 // If the qualified name lookup yielded nothing, try typo correction 7728 } else if ((Correction = SemaRef.CorrectTypo( 7729 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7730 &ExtraArgs.D.getCXXScopeSpec(), 7731 llvm::make_unique<DifferentNameValidatorCCC>( 7732 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7733 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7734 // Set up everything for the call to ActOnFunctionDeclarator 7735 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7736 ExtraArgs.D.getIdentifierLoc()); 7737 Previous.clear(); 7738 Previous.setLookupName(Correction.getCorrection()); 7739 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7740 CDeclEnd = Correction.end(); 7741 CDecl != CDeclEnd; ++CDecl) { 7742 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7743 if (FD && !FD->hasBody() && 7744 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7745 Previous.addDecl(FD); 7746 } 7747 } 7748 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7749 7750 NamedDecl *Result; 7751 // Retry building the function declaration with the new previous 7752 // declarations, and with errors suppressed. 7753 { 7754 // Trap errors. 7755 Sema::SFINAETrap Trap(SemaRef); 7756 7757 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7758 // pieces need to verify the typo-corrected C++ declaration and hopefully 7759 // eliminate the need for the parameter pack ExtraArgs. 7760 Result = SemaRef.ActOnFunctionDeclarator( 7761 ExtraArgs.S, ExtraArgs.D, 7762 Correction.getCorrectionDecl()->getDeclContext(), 7763 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7764 ExtraArgs.AddToScope); 7765 7766 if (Trap.hasErrorOccurred()) 7767 Result = nullptr; 7768 } 7769 7770 if (Result) { 7771 // Determine which correction we picked. 7772 Decl *Canonical = Result->getCanonicalDecl(); 7773 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7774 I != E; ++I) 7775 if ((*I)->getCanonicalDecl() == Canonical) 7776 Correction.setCorrectionDecl(*I); 7777 7778 // Let Sema know about the correction. 7779 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7780 SemaRef.diagnoseTypo( 7781 Correction, 7782 SemaRef.PDiag(IsLocalFriend 7783 ? diag::err_no_matching_local_friend_suggest 7784 : diag::err_member_decl_does_not_match_suggest) 7785 << Name << NewDC << IsDefinition); 7786 return Result; 7787 } 7788 7789 // Pretend the typo correction never occurred 7790 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7791 ExtraArgs.D.getIdentifierLoc()); 7792 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7793 Previous.clear(); 7794 Previous.setLookupName(Name); 7795 } 7796 7797 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7798 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7799 7800 bool NewFDisConst = false; 7801 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7802 NewFDisConst = NewMD->isConst(); 7803 7804 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7805 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7806 NearMatch != NearMatchEnd; ++NearMatch) { 7807 FunctionDecl *FD = NearMatch->first; 7808 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7809 bool FDisConst = MD && MD->isConst(); 7810 bool IsMember = MD || !IsLocalFriend; 7811 7812 // FIXME: These notes are poorly worded for the local friend case. 7813 if (unsigned Idx = NearMatch->second) { 7814 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7815 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7816 if (Loc.isInvalid()) Loc = FD->getLocation(); 7817 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7818 : diag::note_local_decl_close_param_match) 7819 << Idx << FDParam->getType() 7820 << NewFD->getParamDecl(Idx - 1)->getType(); 7821 } else if (FDisConst != NewFDisConst) { 7822 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7823 << NewFDisConst << FD->getSourceRange().getEnd(); 7824 } else 7825 SemaRef.Diag(FD->getLocation(), 7826 IsMember ? diag::note_member_def_close_match 7827 : diag::note_local_decl_close_match); 7828 } 7829 return nullptr; 7830 } 7831 7832 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7833 switch (D.getDeclSpec().getStorageClassSpec()) { 7834 default: llvm_unreachable("Unknown storage class!"); 7835 case DeclSpec::SCS_auto: 7836 case DeclSpec::SCS_register: 7837 case DeclSpec::SCS_mutable: 7838 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7839 diag::err_typecheck_sclass_func); 7840 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7841 D.setInvalidType(); 7842 break; 7843 case DeclSpec::SCS_unspecified: break; 7844 case DeclSpec::SCS_extern: 7845 if (D.getDeclSpec().isExternInLinkageSpec()) 7846 return SC_None; 7847 return SC_Extern; 7848 case DeclSpec::SCS_static: { 7849 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7850 // C99 6.7.1p5: 7851 // The declaration of an identifier for a function that has 7852 // block scope shall have no explicit storage-class specifier 7853 // other than extern 7854 // See also (C++ [dcl.stc]p4). 7855 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7856 diag::err_static_block_func); 7857 break; 7858 } else 7859 return SC_Static; 7860 } 7861 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7862 } 7863 7864 // No explicit storage class has already been returned 7865 return SC_None; 7866 } 7867 7868 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7869 DeclContext *DC, QualType &R, 7870 TypeSourceInfo *TInfo, 7871 StorageClass SC, 7872 bool &IsVirtualOkay) { 7873 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7874 DeclarationName Name = NameInfo.getName(); 7875 7876 FunctionDecl *NewFD = nullptr; 7877 bool isInline = D.getDeclSpec().isInlineSpecified(); 7878 7879 if (!SemaRef.getLangOpts().CPlusPlus) { 7880 // Determine whether the function was written with a 7881 // prototype. This true when: 7882 // - there is a prototype in the declarator, or 7883 // - the type R of the function is some kind of typedef or other non- 7884 // attributed reference to a type name (which eventually refers to a 7885 // function type). 7886 bool HasPrototype = 7887 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7888 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7889 7890 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7891 D.getLocStart(), NameInfo, R, 7892 TInfo, SC, isInline, 7893 HasPrototype, false); 7894 if (D.isInvalidType()) 7895 NewFD->setInvalidDecl(); 7896 7897 return NewFD; 7898 } 7899 7900 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7901 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7902 7903 // Check that the return type is not an abstract class type. 7904 // For record types, this is done by the AbstractClassUsageDiagnoser once 7905 // the class has been completely parsed. 7906 if (!DC->isRecord() && 7907 SemaRef.RequireNonAbstractType( 7908 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7909 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7910 D.setInvalidType(); 7911 7912 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7913 // This is a C++ constructor declaration. 7914 assert(DC->isRecord() && 7915 "Constructors can only be declared in a member context"); 7916 7917 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7918 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7919 D.getLocStart(), NameInfo, 7920 R, TInfo, isExplicit, isInline, 7921 /*isImplicitlyDeclared=*/false, 7922 isConstexpr); 7923 7924 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7925 // This is a C++ destructor declaration. 7926 if (DC->isRecord()) { 7927 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7928 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7929 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7930 SemaRef.Context, Record, 7931 D.getLocStart(), 7932 NameInfo, R, TInfo, isInline, 7933 /*isImplicitlyDeclared=*/false); 7934 7935 // If the class is complete, then we now create the implicit exception 7936 // specification. If the class is incomplete or dependent, we can't do 7937 // it yet. 7938 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7939 Record->getDefinition() && !Record->isBeingDefined() && 7940 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7941 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7942 } 7943 7944 IsVirtualOkay = true; 7945 return NewDD; 7946 7947 } else { 7948 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7949 D.setInvalidType(); 7950 7951 // Create a FunctionDecl to satisfy the function definition parsing 7952 // code path. 7953 return FunctionDecl::Create(SemaRef.Context, DC, 7954 D.getLocStart(), 7955 D.getIdentifierLoc(), Name, R, TInfo, 7956 SC, isInline, 7957 /*hasPrototype=*/true, isConstexpr); 7958 } 7959 7960 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7961 if (!DC->isRecord()) { 7962 SemaRef.Diag(D.getIdentifierLoc(), 7963 diag::err_conv_function_not_member); 7964 return nullptr; 7965 } 7966 7967 SemaRef.CheckConversionDeclarator(D, R, SC); 7968 IsVirtualOkay = true; 7969 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7970 D.getLocStart(), NameInfo, 7971 R, TInfo, isInline, isExplicit, 7972 isConstexpr, SourceLocation()); 7973 7974 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7975 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7976 7977 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7978 isExplicit, NameInfo, R, TInfo, 7979 D.getLocEnd()); 7980 } else if (DC->isRecord()) { 7981 // If the name of the function is the same as the name of the record, 7982 // then this must be an invalid constructor that has a return type. 7983 // (The parser checks for a return type and makes the declarator a 7984 // constructor if it has no return type). 7985 if (Name.getAsIdentifierInfo() && 7986 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7987 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7988 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7989 << SourceRange(D.getIdentifierLoc()); 7990 return nullptr; 7991 } 7992 7993 // This is a C++ method declaration. 7994 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7995 cast<CXXRecordDecl>(DC), 7996 D.getLocStart(), NameInfo, R, 7997 TInfo, SC, isInline, 7998 isConstexpr, SourceLocation()); 7999 IsVirtualOkay = !Ret->isStatic(); 8000 return Ret; 8001 } else { 8002 bool isFriend = 8003 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8004 if (!isFriend && SemaRef.CurContext->isRecord()) 8005 return nullptr; 8006 8007 // Determine whether the function was written with a 8008 // prototype. This true when: 8009 // - we're in C++ (where every function has a prototype), 8010 return FunctionDecl::Create(SemaRef.Context, DC, 8011 D.getLocStart(), 8012 NameInfo, R, TInfo, SC, isInline, 8013 true/*HasPrototype*/, isConstexpr); 8014 } 8015 } 8016 8017 enum OpenCLParamType { 8018 ValidKernelParam, 8019 PtrPtrKernelParam, 8020 PtrKernelParam, 8021 InvalidAddrSpacePtrKernelParam, 8022 InvalidKernelParam, 8023 RecordKernelParam 8024 }; 8025 8026 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8027 if (PT->isPointerType()) { 8028 QualType PointeeType = PT->getPointeeType(); 8029 if (PointeeType->isPointerType()) 8030 return PtrPtrKernelParam; 8031 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8032 PointeeType.getAddressSpace() == LangAS::opencl_private || 8033 PointeeType.getAddressSpace() == LangAS::Default) 8034 return InvalidAddrSpacePtrKernelParam; 8035 return PtrKernelParam; 8036 } 8037 8038 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 8039 // be used as builtin types. 8040 8041 if (PT->isImageType()) 8042 return PtrKernelParam; 8043 8044 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8045 return InvalidKernelParam; 8046 8047 // OpenCL extension spec v1.2 s9.5: 8048 // This extension adds support for half scalar and vector types as built-in 8049 // types that can be used for arithmetic operations, conversions etc. 8050 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8051 return InvalidKernelParam; 8052 8053 if (PT->isRecordType()) 8054 return RecordKernelParam; 8055 8056 return ValidKernelParam; 8057 } 8058 8059 static void checkIsValidOpenCLKernelParameter( 8060 Sema &S, 8061 Declarator &D, 8062 ParmVarDecl *Param, 8063 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8064 QualType PT = Param->getType(); 8065 8066 // Cache the valid types we encounter to avoid rechecking structs that are 8067 // used again 8068 if (ValidTypes.count(PT.getTypePtr())) 8069 return; 8070 8071 switch (getOpenCLKernelParameterType(S, PT)) { 8072 case PtrPtrKernelParam: 8073 // OpenCL v1.2 s6.9.a: 8074 // A kernel function argument cannot be declared as a 8075 // pointer to a pointer type. 8076 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8077 D.setInvalidType(); 8078 return; 8079 8080 case InvalidAddrSpacePtrKernelParam: 8081 // OpenCL v1.0 s6.5: 8082 // __kernel function arguments declared to be a pointer of a type can point 8083 // to one of the following address spaces only : __global, __local or 8084 // __constant. 8085 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8086 D.setInvalidType(); 8087 return; 8088 8089 // OpenCL v1.2 s6.9.k: 8090 // Arguments to kernel functions in a program cannot be declared with the 8091 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8092 // uintptr_t or a struct and/or union that contain fields declared to be 8093 // one of these built-in scalar types. 8094 8095 case InvalidKernelParam: 8096 // OpenCL v1.2 s6.8 n: 8097 // A kernel function argument cannot be declared 8098 // of event_t type. 8099 // Do not diagnose half type since it is diagnosed as invalid argument 8100 // type for any function elsewhere. 8101 if (!PT->isHalfType()) 8102 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8103 D.setInvalidType(); 8104 return; 8105 8106 case PtrKernelParam: 8107 case ValidKernelParam: 8108 ValidTypes.insert(PT.getTypePtr()); 8109 return; 8110 8111 case RecordKernelParam: 8112 break; 8113 } 8114 8115 // Track nested structs we will inspect 8116 SmallVector<const Decl *, 4> VisitStack; 8117 8118 // Track where we are in the nested structs. Items will migrate from 8119 // VisitStack to HistoryStack as we do the DFS for bad field. 8120 SmallVector<const FieldDecl *, 4> HistoryStack; 8121 HistoryStack.push_back(nullptr); 8122 8123 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8124 VisitStack.push_back(PD); 8125 8126 assert(VisitStack.back() && "First decl null?"); 8127 8128 do { 8129 const Decl *Next = VisitStack.pop_back_val(); 8130 if (!Next) { 8131 assert(!HistoryStack.empty()); 8132 // Found a marker, we have gone up a level 8133 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8134 ValidTypes.insert(Hist->getType().getTypePtr()); 8135 8136 continue; 8137 } 8138 8139 // Adds everything except the original parameter declaration (which is not a 8140 // field itself) to the history stack. 8141 const RecordDecl *RD; 8142 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8143 HistoryStack.push_back(Field); 8144 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8145 } else { 8146 RD = cast<RecordDecl>(Next); 8147 } 8148 8149 // Add a null marker so we know when we've gone back up a level 8150 VisitStack.push_back(nullptr); 8151 8152 for (const auto *FD : RD->fields()) { 8153 QualType QT = FD->getType(); 8154 8155 if (ValidTypes.count(QT.getTypePtr())) 8156 continue; 8157 8158 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8159 if (ParamType == ValidKernelParam) 8160 continue; 8161 8162 if (ParamType == RecordKernelParam) { 8163 VisitStack.push_back(FD); 8164 continue; 8165 } 8166 8167 // OpenCL v1.2 s6.9.p: 8168 // Arguments to kernel functions that are declared to be a struct or union 8169 // do not allow OpenCL objects to be passed as elements of the struct or 8170 // union. 8171 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8172 ParamType == InvalidAddrSpacePtrKernelParam) { 8173 S.Diag(Param->getLocation(), 8174 diag::err_record_with_pointers_kernel_param) 8175 << PT->isUnionType() 8176 << PT; 8177 } else { 8178 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8179 } 8180 8181 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8182 << PD->getDeclName(); 8183 8184 // We have an error, now let's go back up through history and show where 8185 // the offending field came from 8186 for (ArrayRef<const FieldDecl *>::const_iterator 8187 I = HistoryStack.begin() + 1, 8188 E = HistoryStack.end(); 8189 I != E; ++I) { 8190 const FieldDecl *OuterField = *I; 8191 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8192 << OuterField->getType(); 8193 } 8194 8195 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8196 << QT->isPointerType() 8197 << QT; 8198 D.setInvalidType(); 8199 return; 8200 } 8201 } while (!VisitStack.empty()); 8202 } 8203 8204 /// Find the DeclContext in which a tag is implicitly declared if we see an 8205 /// elaborated type specifier in the specified context, and lookup finds 8206 /// nothing. 8207 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8208 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8209 DC = DC->getParent(); 8210 return DC; 8211 } 8212 8213 /// Find the Scope in which a tag is implicitly declared if we see an 8214 /// elaborated type specifier in the specified context, and lookup finds 8215 /// nothing. 8216 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8217 while (S->isClassScope() || 8218 (LangOpts.CPlusPlus && 8219 S->isFunctionPrototypeScope()) || 8220 ((S->getFlags() & Scope::DeclScope) == 0) || 8221 (S->getEntity() && S->getEntity()->isTransparentContext())) 8222 S = S->getParent(); 8223 return S; 8224 } 8225 8226 NamedDecl* 8227 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8228 TypeSourceInfo *TInfo, LookupResult &Previous, 8229 MultiTemplateParamsArg TemplateParamLists, 8230 bool &AddToScope) { 8231 QualType R = TInfo->getType(); 8232 8233 assert(R.getTypePtr()->isFunctionType()); 8234 8235 // TODO: consider using NameInfo for diagnostic. 8236 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8237 DeclarationName Name = NameInfo.getName(); 8238 StorageClass SC = getFunctionStorageClass(*this, D); 8239 8240 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8241 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8242 diag::err_invalid_thread) 8243 << DeclSpec::getSpecifierName(TSCS); 8244 8245 if (D.isFirstDeclarationOfMember()) 8246 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8247 D.getIdentifierLoc()); 8248 8249 bool isFriend = false; 8250 FunctionTemplateDecl *FunctionTemplate = nullptr; 8251 bool isMemberSpecialization = false; 8252 bool isFunctionTemplateSpecialization = false; 8253 8254 bool isDependentClassScopeExplicitSpecialization = false; 8255 bool HasExplicitTemplateArgs = false; 8256 TemplateArgumentListInfo TemplateArgs; 8257 8258 bool isVirtualOkay = false; 8259 8260 DeclContext *OriginalDC = DC; 8261 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8262 8263 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8264 isVirtualOkay); 8265 if (!NewFD) return nullptr; 8266 8267 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8268 NewFD->setTopLevelDeclInObjCContainer(); 8269 8270 // Set the lexical context. If this is a function-scope declaration, or has a 8271 // C++ scope specifier, or is the object of a friend declaration, the lexical 8272 // context will be different from the semantic context. 8273 NewFD->setLexicalDeclContext(CurContext); 8274 8275 if (IsLocalExternDecl) 8276 NewFD->setLocalExternDecl(); 8277 8278 if (getLangOpts().CPlusPlus) { 8279 bool isInline = D.getDeclSpec().isInlineSpecified(); 8280 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8281 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8282 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8283 isFriend = D.getDeclSpec().isFriendSpecified(); 8284 if (isFriend && !isInline && D.isFunctionDefinition()) { 8285 // C++ [class.friend]p5 8286 // A function can be defined in a friend declaration of a 8287 // class . . . . Such a function is implicitly inline. 8288 NewFD->setImplicitlyInline(); 8289 } 8290 8291 // If this is a method defined in an __interface, and is not a constructor 8292 // or an overloaded operator, then set the pure flag (isVirtual will already 8293 // return true). 8294 if (const CXXRecordDecl *Parent = 8295 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8296 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8297 NewFD->setPure(true); 8298 8299 // C++ [class.union]p2 8300 // A union can have member functions, but not virtual functions. 8301 if (isVirtual && Parent->isUnion()) 8302 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8303 } 8304 8305 SetNestedNameSpecifier(NewFD, D); 8306 isMemberSpecialization = false; 8307 isFunctionTemplateSpecialization = false; 8308 if (D.isInvalidType()) 8309 NewFD->setInvalidDecl(); 8310 8311 // Match up the template parameter lists with the scope specifier, then 8312 // determine whether we have a template or a template specialization. 8313 bool Invalid = false; 8314 if (TemplateParameterList *TemplateParams = 8315 MatchTemplateParametersToScopeSpecifier( 8316 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8317 D.getCXXScopeSpec(), 8318 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8319 ? D.getName().TemplateId 8320 : nullptr, 8321 TemplateParamLists, isFriend, isMemberSpecialization, 8322 Invalid)) { 8323 if (TemplateParams->size() > 0) { 8324 // This is a function template 8325 8326 // Check that we can declare a template here. 8327 if (CheckTemplateDeclScope(S, TemplateParams)) 8328 NewFD->setInvalidDecl(); 8329 8330 // A destructor cannot be a template. 8331 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8332 Diag(NewFD->getLocation(), diag::err_destructor_template); 8333 NewFD->setInvalidDecl(); 8334 } 8335 8336 // If we're adding a template to a dependent context, we may need to 8337 // rebuilding some of the types used within the template parameter list, 8338 // now that we know what the current instantiation is. 8339 if (DC->isDependentContext()) { 8340 ContextRAII SavedContext(*this, DC); 8341 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8342 Invalid = true; 8343 } 8344 8345 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8346 NewFD->getLocation(), 8347 Name, TemplateParams, 8348 NewFD); 8349 FunctionTemplate->setLexicalDeclContext(CurContext); 8350 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8351 8352 // For source fidelity, store the other template param lists. 8353 if (TemplateParamLists.size() > 1) { 8354 NewFD->setTemplateParameterListsInfo(Context, 8355 TemplateParamLists.drop_back(1)); 8356 } 8357 } else { 8358 // This is a function template specialization. 8359 isFunctionTemplateSpecialization = true; 8360 // For source fidelity, store all the template param lists. 8361 if (TemplateParamLists.size() > 0) 8362 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8363 8364 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8365 if (isFriend) { 8366 // We want to remove the "template<>", found here. 8367 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8368 8369 // If we remove the template<> and the name is not a 8370 // template-id, we're actually silently creating a problem: 8371 // the friend declaration will refer to an untemplated decl, 8372 // and clearly the user wants a template specialization. So 8373 // we need to insert '<>' after the name. 8374 SourceLocation InsertLoc; 8375 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8376 InsertLoc = D.getName().getSourceRange().getEnd(); 8377 InsertLoc = getLocForEndOfToken(InsertLoc); 8378 } 8379 8380 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8381 << Name << RemoveRange 8382 << FixItHint::CreateRemoval(RemoveRange) 8383 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8384 } 8385 } 8386 } 8387 else { 8388 // All template param lists were matched against the scope specifier: 8389 // this is NOT (an explicit specialization of) a template. 8390 if (TemplateParamLists.size() > 0) 8391 // For source fidelity, store all the template param lists. 8392 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8393 } 8394 8395 if (Invalid) { 8396 NewFD->setInvalidDecl(); 8397 if (FunctionTemplate) 8398 FunctionTemplate->setInvalidDecl(); 8399 } 8400 8401 // C++ [dcl.fct.spec]p5: 8402 // The virtual specifier shall only be used in declarations of 8403 // nonstatic class member functions that appear within a 8404 // member-specification of a class declaration; see 10.3. 8405 // 8406 if (isVirtual && !NewFD->isInvalidDecl()) { 8407 if (!isVirtualOkay) { 8408 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8409 diag::err_virtual_non_function); 8410 } else if (!CurContext->isRecord()) { 8411 // 'virtual' was specified outside of the class. 8412 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8413 diag::err_virtual_out_of_class) 8414 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8415 } else if (NewFD->getDescribedFunctionTemplate()) { 8416 // C++ [temp.mem]p3: 8417 // A member function template shall not be virtual. 8418 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8419 diag::err_virtual_member_function_template) 8420 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8421 } else { 8422 // Okay: Add virtual to the method. 8423 NewFD->setVirtualAsWritten(true); 8424 } 8425 8426 if (getLangOpts().CPlusPlus14 && 8427 NewFD->getReturnType()->isUndeducedType()) 8428 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8429 } 8430 8431 if (getLangOpts().CPlusPlus14 && 8432 (NewFD->isDependentContext() || 8433 (isFriend && CurContext->isDependentContext())) && 8434 NewFD->getReturnType()->isUndeducedType()) { 8435 // If the function template is referenced directly (for instance, as a 8436 // member of the current instantiation), pretend it has a dependent type. 8437 // This is not really justified by the standard, but is the only sane 8438 // thing to do. 8439 // FIXME: For a friend function, we have not marked the function as being 8440 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8441 const FunctionProtoType *FPT = 8442 NewFD->getType()->castAs<FunctionProtoType>(); 8443 QualType Result = 8444 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8445 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8446 FPT->getExtProtoInfo())); 8447 } 8448 8449 // C++ [dcl.fct.spec]p3: 8450 // The inline specifier shall not appear on a block scope function 8451 // declaration. 8452 if (isInline && !NewFD->isInvalidDecl()) { 8453 if (CurContext->isFunctionOrMethod()) { 8454 // 'inline' is not allowed on block scope function declaration. 8455 Diag(D.getDeclSpec().getInlineSpecLoc(), 8456 diag::err_inline_declaration_block_scope) << Name 8457 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8458 } 8459 } 8460 8461 // C++ [dcl.fct.spec]p6: 8462 // The explicit specifier shall be used only in the declaration of a 8463 // constructor or conversion function within its class definition; 8464 // see 12.3.1 and 12.3.2. 8465 if (isExplicit && !NewFD->isInvalidDecl() && 8466 !isa<CXXDeductionGuideDecl>(NewFD)) { 8467 if (!CurContext->isRecord()) { 8468 // 'explicit' was specified outside of the class. 8469 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8470 diag::err_explicit_out_of_class) 8471 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8472 } else if (!isa<CXXConstructorDecl>(NewFD) && 8473 !isa<CXXConversionDecl>(NewFD)) { 8474 // 'explicit' was specified on a function that wasn't a constructor 8475 // or conversion function. 8476 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8477 diag::err_explicit_non_ctor_or_conv_function) 8478 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8479 } 8480 } 8481 8482 if (isConstexpr) { 8483 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8484 // are implicitly inline. 8485 NewFD->setImplicitlyInline(); 8486 8487 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8488 // be either constructors or to return a literal type. Therefore, 8489 // destructors cannot be declared constexpr. 8490 if (isa<CXXDestructorDecl>(NewFD)) 8491 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8492 } 8493 8494 // If __module_private__ was specified, mark the function accordingly. 8495 if (D.getDeclSpec().isModulePrivateSpecified()) { 8496 if (isFunctionTemplateSpecialization) { 8497 SourceLocation ModulePrivateLoc 8498 = D.getDeclSpec().getModulePrivateSpecLoc(); 8499 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8500 << 0 8501 << FixItHint::CreateRemoval(ModulePrivateLoc); 8502 } else { 8503 NewFD->setModulePrivate(); 8504 if (FunctionTemplate) 8505 FunctionTemplate->setModulePrivate(); 8506 } 8507 } 8508 8509 if (isFriend) { 8510 if (FunctionTemplate) { 8511 FunctionTemplate->setObjectOfFriendDecl(); 8512 FunctionTemplate->setAccess(AS_public); 8513 } 8514 NewFD->setObjectOfFriendDecl(); 8515 NewFD->setAccess(AS_public); 8516 } 8517 8518 // If a function is defined as defaulted or deleted, mark it as such now. 8519 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8520 // definition kind to FDK_Definition. 8521 switch (D.getFunctionDefinitionKind()) { 8522 case FDK_Declaration: 8523 case FDK_Definition: 8524 break; 8525 8526 case FDK_Defaulted: 8527 NewFD->setDefaulted(); 8528 break; 8529 8530 case FDK_Deleted: 8531 NewFD->setDeletedAsWritten(); 8532 break; 8533 } 8534 8535 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8536 D.isFunctionDefinition()) { 8537 // C++ [class.mfct]p2: 8538 // A member function may be defined (8.4) in its class definition, in 8539 // which case it is an inline member function (7.1.2) 8540 NewFD->setImplicitlyInline(); 8541 } 8542 8543 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8544 !CurContext->isRecord()) { 8545 // C++ [class.static]p1: 8546 // A data or function member of a class may be declared static 8547 // in a class definition, in which case it is a static member of 8548 // the class. 8549 8550 // Complain about the 'static' specifier if it's on an out-of-line 8551 // member function definition. 8552 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8553 diag::err_static_out_of_line) 8554 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8555 } 8556 8557 // C++11 [except.spec]p15: 8558 // A deallocation function with no exception-specification is treated 8559 // as if it were specified with noexcept(true). 8560 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8561 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8562 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8563 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8564 NewFD->setType(Context.getFunctionType( 8565 FPT->getReturnType(), FPT->getParamTypes(), 8566 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8567 } 8568 8569 // Filter out previous declarations that don't match the scope. 8570 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8571 D.getCXXScopeSpec().isNotEmpty() || 8572 isMemberSpecialization || 8573 isFunctionTemplateSpecialization); 8574 8575 // Handle GNU asm-label extension (encoded as an attribute). 8576 if (Expr *E = (Expr*) D.getAsmLabel()) { 8577 // The parser guarantees this is a string. 8578 StringLiteral *SE = cast<StringLiteral>(E); 8579 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8580 SE->getString(), 0)); 8581 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8582 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8583 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8584 if (I != ExtnameUndeclaredIdentifiers.end()) { 8585 if (isDeclExternC(NewFD)) { 8586 NewFD->addAttr(I->second); 8587 ExtnameUndeclaredIdentifiers.erase(I); 8588 } else 8589 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8590 << /*Variable*/0 << NewFD; 8591 } 8592 } 8593 8594 // Copy the parameter declarations from the declarator D to the function 8595 // declaration NewFD, if they are available. First scavenge them into Params. 8596 SmallVector<ParmVarDecl*, 16> Params; 8597 unsigned FTIIdx; 8598 if (D.isFunctionDeclarator(FTIIdx)) { 8599 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8600 8601 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8602 // function that takes no arguments, not a function that takes a 8603 // single void argument. 8604 // We let through "const void" here because Sema::GetTypeForDeclarator 8605 // already checks for that case. 8606 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8607 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8608 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8609 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8610 Param->setDeclContext(NewFD); 8611 Params.push_back(Param); 8612 8613 if (Param->isInvalidDecl()) 8614 NewFD->setInvalidDecl(); 8615 } 8616 } 8617 8618 if (!getLangOpts().CPlusPlus) { 8619 // In C, find all the tag declarations from the prototype and move them 8620 // into the function DeclContext. Remove them from the surrounding tag 8621 // injection context of the function, which is typically but not always 8622 // the TU. 8623 DeclContext *PrototypeTagContext = 8624 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8625 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8626 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8627 8628 // We don't want to reparent enumerators. Look at their parent enum 8629 // instead. 8630 if (!TD) { 8631 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8632 TD = cast<EnumDecl>(ECD->getDeclContext()); 8633 } 8634 if (!TD) 8635 continue; 8636 DeclContext *TagDC = TD->getLexicalDeclContext(); 8637 if (!TagDC->containsDecl(TD)) 8638 continue; 8639 TagDC->removeDecl(TD); 8640 TD->setDeclContext(NewFD); 8641 NewFD->addDecl(TD); 8642 8643 // Preserve the lexical DeclContext if it is not the surrounding tag 8644 // injection context of the FD. In this example, the semantic context of 8645 // E will be f and the lexical context will be S, while both the 8646 // semantic and lexical contexts of S will be f: 8647 // void f(struct S { enum E { a } f; } s); 8648 if (TagDC != PrototypeTagContext) 8649 TD->setLexicalDeclContext(TagDC); 8650 } 8651 } 8652 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8653 // When we're declaring a function with a typedef, typeof, etc as in the 8654 // following example, we'll need to synthesize (unnamed) 8655 // parameters for use in the declaration. 8656 // 8657 // @code 8658 // typedef void fn(int); 8659 // fn f; 8660 // @endcode 8661 8662 // Synthesize a parameter for each argument type. 8663 for (const auto &AI : FT->param_types()) { 8664 ParmVarDecl *Param = 8665 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8666 Param->setScopeInfo(0, Params.size()); 8667 Params.push_back(Param); 8668 } 8669 } else { 8670 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8671 "Should not need args for typedef of non-prototype fn"); 8672 } 8673 8674 // Finally, we know we have the right number of parameters, install them. 8675 NewFD->setParams(Params); 8676 8677 if (D.getDeclSpec().isNoreturnSpecified()) 8678 NewFD->addAttr( 8679 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8680 Context, 0)); 8681 8682 // Functions returning a variably modified type violate C99 6.7.5.2p2 8683 // because all functions have linkage. 8684 if (!NewFD->isInvalidDecl() && 8685 NewFD->getReturnType()->isVariablyModifiedType()) { 8686 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8687 NewFD->setInvalidDecl(); 8688 } 8689 8690 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8691 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8692 !NewFD->hasAttr<SectionAttr>()) { 8693 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8694 PragmaClangTextSection.SectionName, 8695 PragmaClangTextSection.PragmaLocation)); 8696 } 8697 8698 // Apply an implicit SectionAttr if #pragma code_seg is active. 8699 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8700 !NewFD->hasAttr<SectionAttr>()) { 8701 NewFD->addAttr( 8702 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8703 CodeSegStack.CurrentValue->getString(), 8704 CodeSegStack.CurrentPragmaLocation)); 8705 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8706 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8707 ASTContext::PSF_Read, 8708 NewFD)) 8709 NewFD->dropAttr<SectionAttr>(); 8710 } 8711 8712 // Handle attributes. 8713 ProcessDeclAttributes(S, NewFD, D); 8714 8715 if (getLangOpts().OpenCL) { 8716 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8717 // type declaration will generate a compilation error. 8718 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8719 if (AddressSpace != LangAS::Default) { 8720 Diag(NewFD->getLocation(), 8721 diag::err_opencl_return_value_with_address_space); 8722 NewFD->setInvalidDecl(); 8723 } 8724 } 8725 8726 if (!getLangOpts().CPlusPlus) { 8727 // Perform semantic checking on the function declaration. 8728 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8729 CheckMain(NewFD, D.getDeclSpec()); 8730 8731 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8732 CheckMSVCRTEntryPoint(NewFD); 8733 8734 if (!NewFD->isInvalidDecl()) 8735 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8736 isMemberSpecialization)); 8737 else if (!Previous.empty()) 8738 // Recover gracefully from an invalid redeclaration. 8739 D.setRedeclaration(true); 8740 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8741 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8742 "previous declaration set still overloaded"); 8743 8744 // Diagnose no-prototype function declarations with calling conventions that 8745 // don't support variadic calls. Only do this in C and do it after merging 8746 // possibly prototyped redeclarations. 8747 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8748 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8749 CallingConv CC = FT->getExtInfo().getCC(); 8750 if (!supportsVariadicCall(CC)) { 8751 // Windows system headers sometimes accidentally use stdcall without 8752 // (void) parameters, so we relax this to a warning. 8753 int DiagID = 8754 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8755 Diag(NewFD->getLocation(), DiagID) 8756 << FunctionType::getNameForCallConv(CC); 8757 } 8758 } 8759 } else { 8760 // C++11 [replacement.functions]p3: 8761 // The program's definitions shall not be specified as inline. 8762 // 8763 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8764 // 8765 // Suppress the diagnostic if the function is __attribute__((used)), since 8766 // that forces an external definition to be emitted. 8767 if (D.getDeclSpec().isInlineSpecified() && 8768 NewFD->isReplaceableGlobalAllocationFunction() && 8769 !NewFD->hasAttr<UsedAttr>()) 8770 Diag(D.getDeclSpec().getInlineSpecLoc(), 8771 diag::ext_operator_new_delete_declared_inline) 8772 << NewFD->getDeclName(); 8773 8774 // If the declarator is a template-id, translate the parser's template 8775 // argument list into our AST format. 8776 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8777 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8778 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8779 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8780 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8781 TemplateId->NumArgs); 8782 translateTemplateArguments(TemplateArgsPtr, 8783 TemplateArgs); 8784 8785 HasExplicitTemplateArgs = true; 8786 8787 if (NewFD->isInvalidDecl()) { 8788 HasExplicitTemplateArgs = false; 8789 } else if (FunctionTemplate) { 8790 // Function template with explicit template arguments. 8791 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8792 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8793 8794 HasExplicitTemplateArgs = false; 8795 } else { 8796 assert((isFunctionTemplateSpecialization || 8797 D.getDeclSpec().isFriendSpecified()) && 8798 "should have a 'template<>' for this decl"); 8799 // "friend void foo<>(int);" is an implicit specialization decl. 8800 isFunctionTemplateSpecialization = true; 8801 } 8802 } else if (isFriend && isFunctionTemplateSpecialization) { 8803 // This combination is only possible in a recovery case; the user 8804 // wrote something like: 8805 // template <> friend void foo(int); 8806 // which we're recovering from as if the user had written: 8807 // friend void foo<>(int); 8808 // Go ahead and fake up a template id. 8809 HasExplicitTemplateArgs = true; 8810 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8811 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8812 } 8813 8814 // We do not add HD attributes to specializations here because 8815 // they may have different constexpr-ness compared to their 8816 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8817 // may end up with different effective targets. Instead, a 8818 // specialization inherits its target attributes from its template 8819 // in the CheckFunctionTemplateSpecialization() call below. 8820 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8821 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8822 8823 // If it's a friend (and only if it's a friend), it's possible 8824 // that either the specialized function type or the specialized 8825 // template is dependent, and therefore matching will fail. In 8826 // this case, don't check the specialization yet. 8827 bool InstantiationDependent = false; 8828 if (isFunctionTemplateSpecialization && isFriend && 8829 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8830 TemplateSpecializationType::anyDependentTemplateArguments( 8831 TemplateArgs, 8832 InstantiationDependent))) { 8833 assert(HasExplicitTemplateArgs && 8834 "friend function specialization without template args"); 8835 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8836 Previous)) 8837 NewFD->setInvalidDecl(); 8838 } else if (isFunctionTemplateSpecialization) { 8839 if (CurContext->isDependentContext() && CurContext->isRecord() 8840 && !isFriend) { 8841 isDependentClassScopeExplicitSpecialization = true; 8842 } else if (!NewFD->isInvalidDecl() && 8843 CheckFunctionTemplateSpecialization( 8844 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8845 Previous)) 8846 NewFD->setInvalidDecl(); 8847 8848 // C++ [dcl.stc]p1: 8849 // A storage-class-specifier shall not be specified in an explicit 8850 // specialization (14.7.3) 8851 FunctionTemplateSpecializationInfo *Info = 8852 NewFD->getTemplateSpecializationInfo(); 8853 if (Info && SC != SC_None) { 8854 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8855 Diag(NewFD->getLocation(), 8856 diag::err_explicit_specialization_inconsistent_storage_class) 8857 << SC 8858 << FixItHint::CreateRemoval( 8859 D.getDeclSpec().getStorageClassSpecLoc()); 8860 8861 else 8862 Diag(NewFD->getLocation(), 8863 diag::ext_explicit_specialization_storage_class) 8864 << FixItHint::CreateRemoval( 8865 D.getDeclSpec().getStorageClassSpecLoc()); 8866 } 8867 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8868 if (CheckMemberSpecialization(NewFD, Previous)) 8869 NewFD->setInvalidDecl(); 8870 } 8871 8872 // Perform semantic checking on the function declaration. 8873 if (!isDependentClassScopeExplicitSpecialization) { 8874 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8875 CheckMain(NewFD, D.getDeclSpec()); 8876 8877 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8878 CheckMSVCRTEntryPoint(NewFD); 8879 8880 if (!NewFD->isInvalidDecl()) 8881 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8882 isMemberSpecialization)); 8883 else if (!Previous.empty()) 8884 // Recover gracefully from an invalid redeclaration. 8885 D.setRedeclaration(true); 8886 } 8887 8888 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8889 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8890 "previous declaration set still overloaded"); 8891 8892 NamedDecl *PrincipalDecl = (FunctionTemplate 8893 ? cast<NamedDecl>(FunctionTemplate) 8894 : NewFD); 8895 8896 if (isFriend && NewFD->getPreviousDecl()) { 8897 AccessSpecifier Access = AS_public; 8898 if (!NewFD->isInvalidDecl()) 8899 Access = NewFD->getPreviousDecl()->getAccess(); 8900 8901 NewFD->setAccess(Access); 8902 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8903 } 8904 8905 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8906 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8907 PrincipalDecl->setNonMemberOperator(); 8908 8909 // If we have a function template, check the template parameter 8910 // list. This will check and merge default template arguments. 8911 if (FunctionTemplate) { 8912 FunctionTemplateDecl *PrevTemplate = 8913 FunctionTemplate->getPreviousDecl(); 8914 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8915 PrevTemplate ? PrevTemplate->getTemplateParameters() 8916 : nullptr, 8917 D.getDeclSpec().isFriendSpecified() 8918 ? (D.isFunctionDefinition() 8919 ? TPC_FriendFunctionTemplateDefinition 8920 : TPC_FriendFunctionTemplate) 8921 : (D.getCXXScopeSpec().isSet() && 8922 DC && DC->isRecord() && 8923 DC->isDependentContext()) 8924 ? TPC_ClassTemplateMember 8925 : TPC_FunctionTemplate); 8926 } 8927 8928 if (NewFD->isInvalidDecl()) { 8929 // Ignore all the rest of this. 8930 } else if (!D.isRedeclaration()) { 8931 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8932 AddToScope }; 8933 // Fake up an access specifier if it's supposed to be a class member. 8934 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8935 NewFD->setAccess(AS_public); 8936 8937 // Qualified decls generally require a previous declaration. 8938 if (D.getCXXScopeSpec().isSet()) { 8939 // ...with the major exception of templated-scope or 8940 // dependent-scope friend declarations. 8941 8942 // TODO: we currently also suppress this check in dependent 8943 // contexts because (1) the parameter depth will be off when 8944 // matching friend templates and (2) we might actually be 8945 // selecting a friend based on a dependent factor. But there 8946 // are situations where these conditions don't apply and we 8947 // can actually do this check immediately. 8948 if (isFriend && 8949 (TemplateParamLists.size() || 8950 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8951 CurContext->isDependentContext())) { 8952 // ignore these 8953 } else { 8954 // The user tried to provide an out-of-line definition for a 8955 // function that is a member of a class or namespace, but there 8956 // was no such member function declared (C++ [class.mfct]p2, 8957 // C++ [namespace.memdef]p2). For example: 8958 // 8959 // class X { 8960 // void f() const; 8961 // }; 8962 // 8963 // void X::f() { } // ill-formed 8964 // 8965 // Complain about this problem, and attempt to suggest close 8966 // matches (e.g., those that differ only in cv-qualifiers and 8967 // whether the parameter types are references). 8968 8969 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8970 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8971 AddToScope = ExtraArgs.AddToScope; 8972 return Result; 8973 } 8974 } 8975 8976 // Unqualified local friend declarations are required to resolve 8977 // to something. 8978 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8979 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8980 *this, Previous, NewFD, ExtraArgs, true, S)) { 8981 AddToScope = ExtraArgs.AddToScope; 8982 return Result; 8983 } 8984 } 8985 } else if (!D.isFunctionDefinition() && 8986 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8987 !isFriend && !isFunctionTemplateSpecialization && 8988 !isMemberSpecialization) { 8989 // An out-of-line member function declaration must also be a 8990 // definition (C++ [class.mfct]p2). 8991 // Note that this is not the case for explicit specializations of 8992 // function templates or member functions of class templates, per 8993 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8994 // extension for compatibility with old SWIG code which likes to 8995 // generate them. 8996 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8997 << D.getCXXScopeSpec().getRange(); 8998 } 8999 } 9000 9001 ProcessPragmaWeak(S, NewFD); 9002 checkAttributesAfterMerging(*this, *NewFD); 9003 9004 AddKnownFunctionAttributes(NewFD); 9005 9006 if (NewFD->hasAttr<OverloadableAttr>() && 9007 !NewFD->getType()->getAs<FunctionProtoType>()) { 9008 Diag(NewFD->getLocation(), 9009 diag::err_attribute_overloadable_no_prototype) 9010 << NewFD; 9011 9012 // Turn this into a variadic function with no parameters. 9013 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9014 FunctionProtoType::ExtProtoInfo EPI( 9015 Context.getDefaultCallingConvention(true, false)); 9016 EPI.Variadic = true; 9017 EPI.ExtInfo = FT->getExtInfo(); 9018 9019 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9020 NewFD->setType(R); 9021 } 9022 9023 // If there's a #pragma GCC visibility in scope, and this isn't a class 9024 // member, set the visibility of this function. 9025 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9026 AddPushedVisibilityAttribute(NewFD); 9027 9028 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9029 // marking the function. 9030 AddCFAuditedAttribute(NewFD); 9031 9032 // If this is a function definition, check if we have to apply optnone due to 9033 // a pragma. 9034 if(D.isFunctionDefinition()) 9035 AddRangeBasedOptnone(NewFD); 9036 9037 // If this is the first declaration of an extern C variable, update 9038 // the map of such variables. 9039 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9040 isIncompleteDeclExternC(*this, NewFD)) 9041 RegisterLocallyScopedExternCDecl(NewFD, S); 9042 9043 // Set this FunctionDecl's range up to the right paren. 9044 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9045 9046 if (D.isRedeclaration() && !Previous.empty()) { 9047 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9048 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9049 isMemberSpecialization || 9050 isFunctionTemplateSpecialization, 9051 D.isFunctionDefinition()); 9052 } 9053 9054 if (getLangOpts().CUDA) { 9055 IdentifierInfo *II = NewFD->getIdentifier(); 9056 if (II && 9057 II->isStr(getLangOpts().HIP ? "hipConfigureCall" 9058 : "cudaConfigureCall") && 9059 !NewFD->isInvalidDecl() && 9060 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9061 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9062 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9063 Context.setcudaConfigureCallDecl(NewFD); 9064 } 9065 9066 // Variadic functions, other than a *declaration* of printf, are not allowed 9067 // in device-side CUDA code, unless someone passed 9068 // -fcuda-allow-variadic-functions. 9069 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9070 (NewFD->hasAttr<CUDADeviceAttr>() || 9071 NewFD->hasAttr<CUDAGlobalAttr>()) && 9072 !(II && II->isStr("printf") && NewFD->isExternC() && 9073 !D.isFunctionDefinition())) { 9074 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9075 } 9076 } 9077 9078 MarkUnusedFileScopedDecl(NewFD); 9079 9080 if (getLangOpts().CPlusPlus) { 9081 if (FunctionTemplate) { 9082 if (NewFD->isInvalidDecl()) 9083 FunctionTemplate->setInvalidDecl(); 9084 return FunctionTemplate; 9085 } 9086 9087 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9088 CompleteMemberSpecialization(NewFD, Previous); 9089 } 9090 9091 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9092 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9093 if ((getLangOpts().OpenCLVersion >= 120) 9094 && (SC == SC_Static)) { 9095 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9096 D.setInvalidType(); 9097 } 9098 9099 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9100 if (!NewFD->getReturnType()->isVoidType()) { 9101 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9102 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9103 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9104 : FixItHint()); 9105 D.setInvalidType(); 9106 } 9107 9108 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9109 for (auto Param : NewFD->parameters()) 9110 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9111 } 9112 for (const ParmVarDecl *Param : NewFD->parameters()) { 9113 QualType PT = Param->getType(); 9114 9115 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9116 // types. 9117 if (getLangOpts().OpenCLVersion >= 200) { 9118 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9119 QualType ElemTy = PipeTy->getElementType(); 9120 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9121 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9122 D.setInvalidType(); 9123 } 9124 } 9125 } 9126 } 9127 9128 // Here we have an function template explicit specialization at class scope. 9129 // The actual specialization will be postponed to template instatiation 9130 // time via the ClassScopeFunctionSpecializationDecl node. 9131 if (isDependentClassScopeExplicitSpecialization) { 9132 ClassScopeFunctionSpecializationDecl *NewSpec = 9133 ClassScopeFunctionSpecializationDecl::Create( 9134 Context, CurContext, NewFD->getLocation(), 9135 cast<CXXMethodDecl>(NewFD), 9136 HasExplicitTemplateArgs, TemplateArgs); 9137 CurContext->addDecl(NewSpec); 9138 AddToScope = false; 9139 } 9140 9141 // Diagnose availability attributes. Availability cannot be used on functions 9142 // that are run during load/unload. 9143 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9144 if (NewFD->hasAttr<ConstructorAttr>()) { 9145 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9146 << 1; 9147 NewFD->dropAttr<AvailabilityAttr>(); 9148 } 9149 if (NewFD->hasAttr<DestructorAttr>()) { 9150 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9151 << 2; 9152 NewFD->dropAttr<AvailabilityAttr>(); 9153 } 9154 } 9155 9156 return NewFD; 9157 } 9158 9159 /// \brief Checks if the new declaration declared in dependent context must be 9160 /// put in the same redeclaration chain as the specified declaration. 9161 /// 9162 /// \param D Declaration that is checked. 9163 /// \param PrevDecl Previous declaration found with proper lookup method for the 9164 /// same declaration name. 9165 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9166 /// belongs to. 9167 /// 9168 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9169 // Any declarations should be put into redeclaration chains except for 9170 // friend declaration in a dependent context that names a function in 9171 // namespace scope. 9172 // 9173 // This allows to compile code like: 9174 // 9175 // void func(); 9176 // template<typename T> class C1 { friend void func() { } }; 9177 // template<typename T> class C2 { friend void func() { } }; 9178 // 9179 // This code snippet is a valid code unless both templates are instantiated. 9180 return !(D->getLexicalDeclContext()->isDependentContext() && 9181 D->getDeclContext()->isFileContext() && 9182 D->getFriendObjectKind() != Decl::FOK_None); 9183 } 9184 9185 /// \brief Check the target attribute of the function for MultiVersion 9186 /// validity. 9187 /// 9188 /// Returns true if there was an error, false otherwise. 9189 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9190 const auto *TA = FD->getAttr<TargetAttr>(); 9191 assert(TA && "MultiVersion Candidate requires a target attribute"); 9192 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9193 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9194 enum ErrType { Feature = 0, Architecture = 1 }; 9195 9196 if (!ParseInfo.Architecture.empty() && 9197 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9198 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9199 << Architecture << ParseInfo.Architecture; 9200 return true; 9201 } 9202 9203 for (const auto &Feat : ParseInfo.Features) { 9204 auto BareFeat = StringRef{Feat}.substr(1); 9205 if (Feat[0] == '-') { 9206 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9207 << Feature << ("no-" + BareFeat).str(); 9208 return true; 9209 } 9210 9211 if (!TargetInfo.validateCpuSupports(BareFeat) || 9212 !TargetInfo.isValidFeatureName(BareFeat)) { 9213 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9214 << Feature << BareFeat; 9215 return true; 9216 } 9217 } 9218 return false; 9219 } 9220 9221 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9222 const FunctionDecl *NewFD, 9223 bool CausesMV) { 9224 enum DoesntSupport { 9225 FuncTemplates = 0, 9226 VirtFuncs = 1, 9227 DeducedReturn = 2, 9228 Constructors = 3, 9229 Destructors = 4, 9230 DeletedFuncs = 5, 9231 DefaultedFuncs = 6 9232 }; 9233 enum Different { 9234 CallingConv = 0, 9235 ReturnType = 1, 9236 ConstexprSpec = 2, 9237 InlineSpec = 3, 9238 StorageClass = 4, 9239 Linkage = 5 9240 }; 9241 9242 // For now, disallow all other attributes. These should be opt-in, but 9243 // an analysis of all of them is a future FIXME. 9244 if (CausesMV && OldFD && 9245 std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) { 9246 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs); 9247 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9248 return true; 9249 } 9250 9251 if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1) 9252 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs); 9253 9254 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9255 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9256 << FuncTemplates; 9257 9258 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9259 if (NewCXXFD->isVirtual()) 9260 return S.Diag(NewCXXFD->getLocation(), 9261 diag::err_multiversion_doesnt_support) 9262 << VirtFuncs; 9263 9264 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9265 return S.Diag(NewCXXCtor->getLocation(), 9266 diag::err_multiversion_doesnt_support) 9267 << Constructors; 9268 9269 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9270 return S.Diag(NewCXXDtor->getLocation(), 9271 diag::err_multiversion_doesnt_support) 9272 << Destructors; 9273 } 9274 9275 if (NewFD->isDeleted()) 9276 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9277 << DeletedFuncs; 9278 9279 if (NewFD->isDefaulted()) 9280 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9281 << DefaultedFuncs; 9282 9283 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9284 const auto *NewType = cast<FunctionType>(NewQType); 9285 QualType NewReturnType = NewType->getReturnType(); 9286 9287 if (NewReturnType->isUndeducedType()) 9288 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9289 << DeducedReturn; 9290 9291 // Only allow transition to MultiVersion if it hasn't been used. 9292 if (OldFD && CausesMV && OldFD->isUsed(false)) 9293 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9294 9295 // Ensure the return type is identical. 9296 if (OldFD) { 9297 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9298 const auto *OldType = cast<FunctionType>(OldQType); 9299 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9300 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9301 9302 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9303 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9304 << CallingConv; 9305 9306 QualType OldReturnType = OldType->getReturnType(); 9307 9308 if (OldReturnType != NewReturnType) 9309 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9310 << ReturnType; 9311 9312 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9313 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9314 << ConstexprSpec; 9315 9316 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9317 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9318 << InlineSpec; 9319 9320 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9321 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9322 << StorageClass; 9323 9324 if (OldFD->isExternC() != NewFD->isExternC()) 9325 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9326 << Linkage; 9327 9328 if (S.CheckEquivalentExceptionSpec( 9329 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9330 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9331 return true; 9332 } 9333 return false; 9334 } 9335 9336 /// \brief Check the validity of a mulitversion function declaration. 9337 /// Also sets the multiversion'ness' of the function itself. 9338 /// 9339 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9340 /// 9341 /// Returns true if there was an error, false otherwise. 9342 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9343 bool &Redeclaration, NamedDecl *&OldDecl, 9344 bool &MergeTypeWithPrevious, 9345 LookupResult &Previous) { 9346 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9347 if (NewFD->isMain()) { 9348 if (NewTA && NewTA->isDefaultVersion()) { 9349 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9350 NewFD->setInvalidDecl(); 9351 return true; 9352 } 9353 return false; 9354 } 9355 9356 // If there is no matching previous decl, only 'default' can 9357 // cause MultiVersioning. 9358 if (!OldDecl) { 9359 if (NewTA && NewTA->isDefaultVersion()) { 9360 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 9361 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9362 NewFD->setInvalidDecl(); 9363 return true; 9364 } 9365 if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) { 9366 NewFD->setInvalidDecl(); 9367 return true; 9368 } 9369 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9370 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9371 NewFD->setInvalidDecl(); 9372 return true; 9373 } 9374 9375 NewFD->setIsMultiVersion(); 9376 } 9377 return false; 9378 } 9379 9380 if (OldDecl->getDeclContext()->getRedeclContext() != 9381 NewFD->getDeclContext()->getRedeclContext()) 9382 return false; 9383 9384 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9385 // Unresolved 'using' statements (the other way OldDecl can be not a function) 9386 // likely cannot cause a problem here. 9387 if (!OldFD) 9388 return false; 9389 9390 if (!OldFD->isMultiVersion() && !NewTA) 9391 return false; 9392 9393 if (OldFD->isMultiVersion() && !NewTA) { 9394 S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl); 9395 NewFD->setInvalidDecl(); 9396 return true; 9397 } 9398 9399 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9400 // Sort order doesn't matter, it just needs to be consistent. 9401 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end()); 9402 9403 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9404 if (!OldFD->isMultiVersion()) { 9405 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9406 // to change, this is a simple redeclaration. 9407 if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()) 9408 return false; 9409 9410 // Otherwise, this decl causes MultiVersioning. 9411 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9412 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9413 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9414 NewFD->setInvalidDecl(); 9415 return true; 9416 } 9417 9418 if (!OldFD->getType()->getAs<FunctionProtoType>()) { 9419 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9420 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9421 NewFD->setInvalidDecl(); 9422 return true; 9423 } 9424 9425 if (CheckMultiVersionValue(S, NewFD)) { 9426 NewFD->setInvalidDecl(); 9427 return true; 9428 } 9429 9430 if (CheckMultiVersionValue(S, OldFD)) { 9431 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9432 NewFD->setInvalidDecl(); 9433 return true; 9434 } 9435 9436 TargetAttr::ParsedTargetAttr OldParsed = 9437 OldTA->parse(std::less<std::string>()); 9438 9439 if (OldParsed == NewParsed) { 9440 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9441 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9442 NewFD->setInvalidDecl(); 9443 return true; 9444 } 9445 9446 for (const auto *FD : OldFD->redecls()) { 9447 const auto *CurTA = FD->getAttr<TargetAttr>(); 9448 if (!CurTA || CurTA->isInherited()) { 9449 S.Diag(FD->getLocation(), diag::err_target_required_in_redecl); 9450 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9451 NewFD->setInvalidDecl(); 9452 return true; 9453 } 9454 } 9455 9456 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) { 9457 NewFD->setInvalidDecl(); 9458 return true; 9459 } 9460 9461 OldFD->setIsMultiVersion(); 9462 NewFD->setIsMultiVersion(); 9463 Redeclaration = false; 9464 MergeTypeWithPrevious = false; 9465 OldDecl = nullptr; 9466 Previous.clear(); 9467 return false; 9468 } 9469 9470 bool UseMemberUsingDeclRules = 9471 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9472 9473 // Next, check ALL non-overloads to see if this is a redeclaration of a 9474 // previous member of the MultiVersion set. 9475 for (NamedDecl *ND : Previous) { 9476 FunctionDecl *CurFD = ND->getAsFunction(); 9477 if (!CurFD) 9478 continue; 9479 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9480 continue; 9481 9482 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9483 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9484 NewFD->setIsMultiVersion(); 9485 Redeclaration = true; 9486 OldDecl = ND; 9487 return false; 9488 } 9489 9490 TargetAttr::ParsedTargetAttr CurParsed = 9491 CurTA->parse(std::less<std::string>()); 9492 9493 if (CurParsed == NewParsed) { 9494 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9495 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9496 NewFD->setInvalidDecl(); 9497 return true; 9498 } 9499 } 9500 9501 // Else, this is simply a non-redecl case. 9502 if (CheckMultiVersionValue(S, NewFD)) { 9503 NewFD->setInvalidDecl(); 9504 return true; 9505 } 9506 9507 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) { 9508 NewFD->setInvalidDecl(); 9509 return true; 9510 } 9511 9512 NewFD->setIsMultiVersion(); 9513 Redeclaration = false; 9514 MergeTypeWithPrevious = false; 9515 OldDecl = nullptr; 9516 Previous.clear(); 9517 return false; 9518 } 9519 9520 /// \brief Perform semantic checking of a new function declaration. 9521 /// 9522 /// Performs semantic analysis of the new function declaration 9523 /// NewFD. This routine performs all semantic checking that does not 9524 /// require the actual declarator involved in the declaration, and is 9525 /// used both for the declaration of functions as they are parsed 9526 /// (called via ActOnDeclarator) and for the declaration of functions 9527 /// that have been instantiated via C++ template instantiation (called 9528 /// via InstantiateDecl). 9529 /// 9530 /// \param IsMemberSpecialization whether this new function declaration is 9531 /// a member specialization (that replaces any definition provided by the 9532 /// previous declaration). 9533 /// 9534 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9535 /// 9536 /// \returns true if the function declaration is a redeclaration. 9537 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9538 LookupResult &Previous, 9539 bool IsMemberSpecialization) { 9540 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9541 "Variably modified return types are not handled here"); 9542 9543 // Determine whether the type of this function should be merged with 9544 // a previous visible declaration. This never happens for functions in C++, 9545 // and always happens in C if the previous declaration was visible. 9546 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9547 !Previous.isShadowed(); 9548 9549 bool Redeclaration = false; 9550 NamedDecl *OldDecl = nullptr; 9551 bool MayNeedOverloadableChecks = false; 9552 9553 // Merge or overload the declaration with an existing declaration of 9554 // the same name, if appropriate. 9555 if (!Previous.empty()) { 9556 // Determine whether NewFD is an overload of PrevDecl or 9557 // a declaration that requires merging. If it's an overload, 9558 // there's no more work to do here; we'll just add the new 9559 // function to the scope. 9560 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9561 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9562 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9563 Redeclaration = true; 9564 OldDecl = Candidate; 9565 } 9566 } else { 9567 MayNeedOverloadableChecks = true; 9568 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9569 /*NewIsUsingDecl*/ false)) { 9570 case Ovl_Match: 9571 Redeclaration = true; 9572 break; 9573 9574 case Ovl_NonFunction: 9575 Redeclaration = true; 9576 break; 9577 9578 case Ovl_Overload: 9579 Redeclaration = false; 9580 break; 9581 } 9582 } 9583 } 9584 9585 // Check for a previous extern "C" declaration with this name. 9586 if (!Redeclaration && 9587 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9588 if (!Previous.empty()) { 9589 // This is an extern "C" declaration with the same name as a previous 9590 // declaration, and thus redeclares that entity... 9591 Redeclaration = true; 9592 OldDecl = Previous.getFoundDecl(); 9593 MergeTypeWithPrevious = false; 9594 9595 // ... except in the presence of __attribute__((overloadable)). 9596 if (OldDecl->hasAttr<OverloadableAttr>() || 9597 NewFD->hasAttr<OverloadableAttr>()) { 9598 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9599 MayNeedOverloadableChecks = true; 9600 Redeclaration = false; 9601 OldDecl = nullptr; 9602 } 9603 } 9604 } 9605 } 9606 9607 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 9608 MergeTypeWithPrevious, Previous)) 9609 return Redeclaration; 9610 9611 // C++11 [dcl.constexpr]p8: 9612 // A constexpr specifier for a non-static member function that is not 9613 // a constructor declares that member function to be const. 9614 // 9615 // This needs to be delayed until we know whether this is an out-of-line 9616 // definition of a static member function. 9617 // 9618 // This rule is not present in C++1y, so we produce a backwards 9619 // compatibility warning whenever it happens in C++11. 9620 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9621 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9622 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9623 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9624 CXXMethodDecl *OldMD = nullptr; 9625 if (OldDecl) 9626 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9627 if (!OldMD || !OldMD->isStatic()) { 9628 const FunctionProtoType *FPT = 9629 MD->getType()->castAs<FunctionProtoType>(); 9630 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9631 EPI.TypeQuals |= Qualifiers::Const; 9632 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9633 FPT->getParamTypes(), EPI)); 9634 9635 // Warn that we did this, if we're not performing template instantiation. 9636 // In that case, we'll have warned already when the template was defined. 9637 if (!inTemplateInstantiation()) { 9638 SourceLocation AddConstLoc; 9639 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9640 .IgnoreParens().getAs<FunctionTypeLoc>()) 9641 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9642 9643 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9644 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9645 } 9646 } 9647 } 9648 9649 if (Redeclaration) { 9650 // NewFD and OldDecl represent declarations that need to be 9651 // merged. 9652 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9653 NewFD->setInvalidDecl(); 9654 return Redeclaration; 9655 } 9656 9657 Previous.clear(); 9658 Previous.addDecl(OldDecl); 9659 9660 if (FunctionTemplateDecl *OldTemplateDecl = 9661 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9662 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 9663 NewFD->setPreviousDeclaration(OldFD); 9664 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9665 FunctionTemplateDecl *NewTemplateDecl 9666 = NewFD->getDescribedFunctionTemplate(); 9667 assert(NewTemplateDecl && "Template/non-template mismatch"); 9668 if (NewFD->isCXXClassMember()) { 9669 NewFD->setAccess(OldTemplateDecl->getAccess()); 9670 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9671 } 9672 9673 // If this is an explicit specialization of a member that is a function 9674 // template, mark it as a member specialization. 9675 if (IsMemberSpecialization && 9676 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9677 NewTemplateDecl->setMemberSpecialization(); 9678 assert(OldTemplateDecl->isMemberSpecialization()); 9679 // Explicit specializations of a member template do not inherit deleted 9680 // status from the parent member template that they are specializing. 9681 if (OldFD->isDeleted()) { 9682 // FIXME: This assert will not hold in the presence of modules. 9683 assert(OldFD->getCanonicalDecl() == OldFD); 9684 // FIXME: We need an update record for this AST mutation. 9685 OldFD->setDeletedAsWritten(false); 9686 } 9687 } 9688 9689 } else { 9690 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9691 auto *OldFD = cast<FunctionDecl>(OldDecl); 9692 // This needs to happen first so that 'inline' propagates. 9693 NewFD->setPreviousDeclaration(OldFD); 9694 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9695 if (NewFD->isCXXClassMember()) 9696 NewFD->setAccess(OldFD->getAccess()); 9697 } 9698 } 9699 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9700 !NewFD->getAttr<OverloadableAttr>()) { 9701 assert((Previous.empty() || 9702 llvm::any_of(Previous, 9703 [](const NamedDecl *ND) { 9704 return ND->hasAttr<OverloadableAttr>(); 9705 })) && 9706 "Non-redecls shouldn't happen without overloadable present"); 9707 9708 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9709 const auto *FD = dyn_cast<FunctionDecl>(ND); 9710 return FD && !FD->hasAttr<OverloadableAttr>(); 9711 }); 9712 9713 if (OtherUnmarkedIter != Previous.end()) { 9714 Diag(NewFD->getLocation(), 9715 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9716 Diag((*OtherUnmarkedIter)->getLocation(), 9717 diag::note_attribute_overloadable_prev_overload) 9718 << false; 9719 9720 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9721 } 9722 } 9723 9724 // Semantic checking for this function declaration (in isolation). 9725 9726 if (getLangOpts().CPlusPlus) { 9727 // C++-specific checks. 9728 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9729 CheckConstructor(Constructor); 9730 } else if (CXXDestructorDecl *Destructor = 9731 dyn_cast<CXXDestructorDecl>(NewFD)) { 9732 CXXRecordDecl *Record = Destructor->getParent(); 9733 QualType ClassType = Context.getTypeDeclType(Record); 9734 9735 // FIXME: Shouldn't we be able to perform this check even when the class 9736 // type is dependent? Both gcc and edg can handle that. 9737 if (!ClassType->isDependentType()) { 9738 DeclarationName Name 9739 = Context.DeclarationNames.getCXXDestructorName( 9740 Context.getCanonicalType(ClassType)); 9741 if (NewFD->getDeclName() != Name) { 9742 Diag(NewFD->getLocation(), diag::err_destructor_name); 9743 NewFD->setInvalidDecl(); 9744 return Redeclaration; 9745 } 9746 } 9747 } else if (CXXConversionDecl *Conversion 9748 = dyn_cast<CXXConversionDecl>(NewFD)) { 9749 ActOnConversionDeclarator(Conversion); 9750 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9751 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9752 CheckDeductionGuideTemplate(TD); 9753 9754 // A deduction guide is not on the list of entities that can be 9755 // explicitly specialized. 9756 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9757 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9758 << /*explicit specialization*/ 1; 9759 } 9760 9761 // Find any virtual functions that this function overrides. 9762 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9763 if (!Method->isFunctionTemplateSpecialization() && 9764 !Method->getDescribedFunctionTemplate() && 9765 Method->isCanonicalDecl()) { 9766 if (AddOverriddenMethods(Method->getParent(), Method)) { 9767 // If the function was marked as "static", we have a problem. 9768 if (NewFD->getStorageClass() == SC_Static) { 9769 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9770 } 9771 } 9772 } 9773 9774 if (Method->isStatic()) 9775 checkThisInStaticMemberFunctionType(Method); 9776 } 9777 9778 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9779 if (NewFD->isOverloadedOperator() && 9780 CheckOverloadedOperatorDeclaration(NewFD)) { 9781 NewFD->setInvalidDecl(); 9782 return Redeclaration; 9783 } 9784 9785 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9786 if (NewFD->getLiteralIdentifier() && 9787 CheckLiteralOperatorDeclaration(NewFD)) { 9788 NewFD->setInvalidDecl(); 9789 return Redeclaration; 9790 } 9791 9792 // In C++, check default arguments now that we have merged decls. Unless 9793 // the lexical context is the class, because in this case this is done 9794 // during delayed parsing anyway. 9795 if (!CurContext->isRecord()) 9796 CheckCXXDefaultArguments(NewFD); 9797 9798 // If this function declares a builtin function, check the type of this 9799 // declaration against the expected type for the builtin. 9800 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9801 ASTContext::GetBuiltinTypeError Error; 9802 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9803 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9804 // If the type of the builtin differs only in its exception 9805 // specification, that's OK. 9806 // FIXME: If the types do differ in this way, it would be better to 9807 // retain the 'noexcept' form of the type. 9808 if (!T.isNull() && 9809 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9810 NewFD->getType())) 9811 // The type of this function differs from the type of the builtin, 9812 // so forget about the builtin entirely. 9813 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9814 } 9815 9816 // If this function is declared as being extern "C", then check to see if 9817 // the function returns a UDT (class, struct, or union type) that is not C 9818 // compatible, and if it does, warn the user. 9819 // But, issue any diagnostic on the first declaration only. 9820 if (Previous.empty() && NewFD->isExternC()) { 9821 QualType R = NewFD->getReturnType(); 9822 if (R->isIncompleteType() && !R->isVoidType()) 9823 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9824 << NewFD << R; 9825 else if (!R.isPODType(Context) && !R->isVoidType() && 9826 !R->isObjCObjectPointerType()) 9827 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9828 } 9829 9830 // C++1z [dcl.fct]p6: 9831 // [...] whether the function has a non-throwing exception-specification 9832 // [is] part of the function type 9833 // 9834 // This results in an ABI break between C++14 and C++17 for functions whose 9835 // declared type includes an exception-specification in a parameter or 9836 // return type. (Exception specifications on the function itself are OK in 9837 // most cases, and exception specifications are not permitted in most other 9838 // contexts where they could make it into a mangling.) 9839 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 9840 auto HasNoexcept = [&](QualType T) -> bool { 9841 // Strip off declarator chunks that could be between us and a function 9842 // type. We don't need to look far, exception specifications are very 9843 // restricted prior to C++17. 9844 if (auto *RT = T->getAs<ReferenceType>()) 9845 T = RT->getPointeeType(); 9846 else if (T->isAnyPointerType()) 9847 T = T->getPointeeType(); 9848 else if (auto *MPT = T->getAs<MemberPointerType>()) 9849 T = MPT->getPointeeType(); 9850 if (auto *FPT = T->getAs<FunctionProtoType>()) 9851 if (FPT->isNothrow()) 9852 return true; 9853 return false; 9854 }; 9855 9856 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9857 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9858 for (QualType T : FPT->param_types()) 9859 AnyNoexcept |= HasNoexcept(T); 9860 if (AnyNoexcept) 9861 Diag(NewFD->getLocation(), 9862 diag::warn_cxx17_compat_exception_spec_in_signature) 9863 << NewFD; 9864 } 9865 9866 if (!Redeclaration && LangOpts.CUDA) 9867 checkCUDATargetOverload(NewFD, Previous); 9868 } 9869 return Redeclaration; 9870 } 9871 9872 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9873 // C++11 [basic.start.main]p3: 9874 // A program that [...] declares main to be inline, static or 9875 // constexpr is ill-formed. 9876 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9877 // appear in a declaration of main. 9878 // static main is not an error under C99, but we should warn about it. 9879 // We accept _Noreturn main as an extension. 9880 if (FD->getStorageClass() == SC_Static) 9881 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9882 ? diag::err_static_main : diag::warn_static_main) 9883 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9884 if (FD->isInlineSpecified()) 9885 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9886 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9887 if (DS.isNoreturnSpecified()) { 9888 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9889 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9890 Diag(NoreturnLoc, diag::ext_noreturn_main); 9891 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9892 << FixItHint::CreateRemoval(NoreturnRange); 9893 } 9894 if (FD->isConstexpr()) { 9895 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9896 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9897 FD->setConstexpr(false); 9898 } 9899 9900 if (getLangOpts().OpenCL) { 9901 Diag(FD->getLocation(), diag::err_opencl_no_main) 9902 << FD->hasAttr<OpenCLKernelAttr>(); 9903 FD->setInvalidDecl(); 9904 return; 9905 } 9906 9907 QualType T = FD->getType(); 9908 assert(T->isFunctionType() && "function decl is not of function type"); 9909 const FunctionType* FT = T->castAs<FunctionType>(); 9910 9911 // Set default calling convention for main() 9912 if (FT->getCallConv() != CC_C) { 9913 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 9914 FD->setType(QualType(FT, 0)); 9915 T = Context.getCanonicalType(FD->getType()); 9916 } 9917 9918 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9919 // In C with GNU extensions we allow main() to have non-integer return 9920 // type, but we should warn about the extension, and we disable the 9921 // implicit-return-zero rule. 9922 9923 // GCC in C mode accepts qualified 'int'. 9924 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9925 FD->setHasImplicitReturnZero(true); 9926 else { 9927 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9928 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9929 if (RTRange.isValid()) 9930 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9931 << FixItHint::CreateReplacement(RTRange, "int"); 9932 } 9933 } else { 9934 // In C and C++, main magically returns 0 if you fall off the end; 9935 // set the flag which tells us that. 9936 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9937 9938 // All the standards say that main() should return 'int'. 9939 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9940 FD->setHasImplicitReturnZero(true); 9941 else { 9942 // Otherwise, this is just a flat-out error. 9943 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9944 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9945 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9946 : FixItHint()); 9947 FD->setInvalidDecl(true); 9948 } 9949 } 9950 9951 // Treat protoless main() as nullary. 9952 if (isa<FunctionNoProtoType>(FT)) return; 9953 9954 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9955 unsigned nparams = FTP->getNumParams(); 9956 assert(FD->getNumParams() == nparams); 9957 9958 bool HasExtraParameters = (nparams > 3); 9959 9960 if (FTP->isVariadic()) { 9961 Diag(FD->getLocation(), diag::ext_variadic_main); 9962 // FIXME: if we had information about the location of the ellipsis, we 9963 // could add a FixIt hint to remove it as a parameter. 9964 } 9965 9966 // Darwin passes an undocumented fourth argument of type char**. If 9967 // other platforms start sprouting these, the logic below will start 9968 // getting shifty. 9969 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9970 HasExtraParameters = false; 9971 9972 if (HasExtraParameters) { 9973 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9974 FD->setInvalidDecl(true); 9975 nparams = 3; 9976 } 9977 9978 // FIXME: a lot of the following diagnostics would be improved 9979 // if we had some location information about types. 9980 9981 QualType CharPP = 9982 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9983 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9984 9985 for (unsigned i = 0; i < nparams; ++i) { 9986 QualType AT = FTP->getParamType(i); 9987 9988 bool mismatch = true; 9989 9990 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9991 mismatch = false; 9992 else if (Expected[i] == CharPP) { 9993 // As an extension, the following forms are okay: 9994 // char const ** 9995 // char const * const * 9996 // char * const * 9997 9998 QualifierCollector qs; 9999 const PointerType* PT; 10000 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10001 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10002 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10003 Context.CharTy)) { 10004 qs.removeConst(); 10005 mismatch = !qs.empty(); 10006 } 10007 } 10008 10009 if (mismatch) { 10010 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10011 // TODO: suggest replacing given type with expected type 10012 FD->setInvalidDecl(true); 10013 } 10014 } 10015 10016 if (nparams == 1 && !FD->isInvalidDecl()) { 10017 Diag(FD->getLocation(), diag::warn_main_one_arg); 10018 } 10019 10020 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10021 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10022 FD->setInvalidDecl(); 10023 } 10024 } 10025 10026 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10027 QualType T = FD->getType(); 10028 assert(T->isFunctionType() && "function decl is not of function type"); 10029 const FunctionType *FT = T->castAs<FunctionType>(); 10030 10031 // Set an implicit return of 'zero' if the function can return some integral, 10032 // enumeration, pointer or nullptr type. 10033 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10034 FT->getReturnType()->isAnyPointerType() || 10035 FT->getReturnType()->isNullPtrType()) 10036 // DllMain is exempt because a return value of zero means it failed. 10037 if (FD->getName() != "DllMain") 10038 FD->setHasImplicitReturnZero(true); 10039 10040 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10041 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10042 FD->setInvalidDecl(); 10043 } 10044 } 10045 10046 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10047 // FIXME: Need strict checking. In C89, we need to check for 10048 // any assignment, increment, decrement, function-calls, or 10049 // commas outside of a sizeof. In C99, it's the same list, 10050 // except that the aforementioned are allowed in unevaluated 10051 // expressions. Everything else falls under the 10052 // "may accept other forms of constant expressions" exception. 10053 // (We never end up here for C++, so the constant expression 10054 // rules there don't matter.) 10055 const Expr *Culprit; 10056 if (Init->isConstantInitializer(Context, false, &Culprit)) 10057 return false; 10058 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10059 << Culprit->getSourceRange(); 10060 return true; 10061 } 10062 10063 namespace { 10064 // Visits an initialization expression to see if OrigDecl is evaluated in 10065 // its own initialization and throws a warning if it does. 10066 class SelfReferenceChecker 10067 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10068 Sema &S; 10069 Decl *OrigDecl; 10070 bool isRecordType; 10071 bool isPODType; 10072 bool isReferenceType; 10073 10074 bool isInitList; 10075 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10076 10077 public: 10078 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10079 10080 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10081 S(S), OrigDecl(OrigDecl) { 10082 isPODType = false; 10083 isRecordType = false; 10084 isReferenceType = false; 10085 isInitList = false; 10086 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10087 isPODType = VD->getType().isPODType(S.Context); 10088 isRecordType = VD->getType()->isRecordType(); 10089 isReferenceType = VD->getType()->isReferenceType(); 10090 } 10091 } 10092 10093 // For most expressions, just call the visitor. For initializer lists, 10094 // track the index of the field being initialized since fields are 10095 // initialized in order allowing use of previously initialized fields. 10096 void CheckExpr(Expr *E) { 10097 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10098 if (!InitList) { 10099 Visit(E); 10100 return; 10101 } 10102 10103 // Track and increment the index here. 10104 isInitList = true; 10105 InitFieldIndex.push_back(0); 10106 for (auto Child : InitList->children()) { 10107 CheckExpr(cast<Expr>(Child)); 10108 ++InitFieldIndex.back(); 10109 } 10110 InitFieldIndex.pop_back(); 10111 } 10112 10113 // Returns true if MemberExpr is checked and no further checking is needed. 10114 // Returns false if additional checking is required. 10115 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10116 llvm::SmallVector<FieldDecl*, 4> Fields; 10117 Expr *Base = E; 10118 bool ReferenceField = false; 10119 10120 // Get the field memebers used. 10121 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10122 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10123 if (!FD) 10124 return false; 10125 Fields.push_back(FD); 10126 if (FD->getType()->isReferenceType()) 10127 ReferenceField = true; 10128 Base = ME->getBase()->IgnoreParenImpCasts(); 10129 } 10130 10131 // Keep checking only if the base Decl is the same. 10132 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10133 if (!DRE || DRE->getDecl() != OrigDecl) 10134 return false; 10135 10136 // A reference field can be bound to an unininitialized field. 10137 if (CheckReference && !ReferenceField) 10138 return true; 10139 10140 // Convert FieldDecls to their index number. 10141 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10142 for (const FieldDecl *I : llvm::reverse(Fields)) 10143 UsedFieldIndex.push_back(I->getFieldIndex()); 10144 10145 // See if a warning is needed by checking the first difference in index 10146 // numbers. If field being used has index less than the field being 10147 // initialized, then the use is safe. 10148 for (auto UsedIter = UsedFieldIndex.begin(), 10149 UsedEnd = UsedFieldIndex.end(), 10150 OrigIter = InitFieldIndex.begin(), 10151 OrigEnd = InitFieldIndex.end(); 10152 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10153 if (*UsedIter < *OrigIter) 10154 return true; 10155 if (*UsedIter > *OrigIter) 10156 break; 10157 } 10158 10159 // TODO: Add a different warning which will print the field names. 10160 HandleDeclRefExpr(DRE); 10161 return true; 10162 } 10163 10164 // For most expressions, the cast is directly above the DeclRefExpr. 10165 // For conditional operators, the cast can be outside the conditional 10166 // operator if both expressions are DeclRefExpr's. 10167 void HandleValue(Expr *E) { 10168 E = E->IgnoreParens(); 10169 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10170 HandleDeclRefExpr(DRE); 10171 return; 10172 } 10173 10174 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10175 Visit(CO->getCond()); 10176 HandleValue(CO->getTrueExpr()); 10177 HandleValue(CO->getFalseExpr()); 10178 return; 10179 } 10180 10181 if (BinaryConditionalOperator *BCO = 10182 dyn_cast<BinaryConditionalOperator>(E)) { 10183 Visit(BCO->getCond()); 10184 HandleValue(BCO->getFalseExpr()); 10185 return; 10186 } 10187 10188 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10189 HandleValue(OVE->getSourceExpr()); 10190 return; 10191 } 10192 10193 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10194 if (BO->getOpcode() == BO_Comma) { 10195 Visit(BO->getLHS()); 10196 HandleValue(BO->getRHS()); 10197 return; 10198 } 10199 } 10200 10201 if (isa<MemberExpr>(E)) { 10202 if (isInitList) { 10203 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10204 false /*CheckReference*/)) 10205 return; 10206 } 10207 10208 Expr *Base = E->IgnoreParenImpCasts(); 10209 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10210 // Check for static member variables and don't warn on them. 10211 if (!isa<FieldDecl>(ME->getMemberDecl())) 10212 return; 10213 Base = ME->getBase()->IgnoreParenImpCasts(); 10214 } 10215 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10216 HandleDeclRefExpr(DRE); 10217 return; 10218 } 10219 10220 Visit(E); 10221 } 10222 10223 // Reference types not handled in HandleValue are handled here since all 10224 // uses of references are bad, not just r-value uses. 10225 void VisitDeclRefExpr(DeclRefExpr *E) { 10226 if (isReferenceType) 10227 HandleDeclRefExpr(E); 10228 } 10229 10230 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10231 if (E->getCastKind() == CK_LValueToRValue) { 10232 HandleValue(E->getSubExpr()); 10233 return; 10234 } 10235 10236 Inherited::VisitImplicitCastExpr(E); 10237 } 10238 10239 void VisitMemberExpr(MemberExpr *E) { 10240 if (isInitList) { 10241 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10242 return; 10243 } 10244 10245 // Don't warn on arrays since they can be treated as pointers. 10246 if (E->getType()->canDecayToPointerType()) return; 10247 10248 // Warn when a non-static method call is followed by non-static member 10249 // field accesses, which is followed by a DeclRefExpr. 10250 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10251 bool Warn = (MD && !MD->isStatic()); 10252 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10253 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10254 if (!isa<FieldDecl>(ME->getMemberDecl())) 10255 Warn = false; 10256 Base = ME->getBase()->IgnoreParenImpCasts(); 10257 } 10258 10259 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10260 if (Warn) 10261 HandleDeclRefExpr(DRE); 10262 return; 10263 } 10264 10265 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10266 // Visit that expression. 10267 Visit(Base); 10268 } 10269 10270 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10271 Expr *Callee = E->getCallee(); 10272 10273 if (isa<UnresolvedLookupExpr>(Callee)) 10274 return Inherited::VisitCXXOperatorCallExpr(E); 10275 10276 Visit(Callee); 10277 for (auto Arg: E->arguments()) 10278 HandleValue(Arg->IgnoreParenImpCasts()); 10279 } 10280 10281 void VisitUnaryOperator(UnaryOperator *E) { 10282 // For POD record types, addresses of its own members are well-defined. 10283 if (E->getOpcode() == UO_AddrOf && isRecordType && 10284 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10285 if (!isPODType) 10286 HandleValue(E->getSubExpr()); 10287 return; 10288 } 10289 10290 if (E->isIncrementDecrementOp()) { 10291 HandleValue(E->getSubExpr()); 10292 return; 10293 } 10294 10295 Inherited::VisitUnaryOperator(E); 10296 } 10297 10298 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10299 10300 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10301 if (E->getConstructor()->isCopyConstructor()) { 10302 Expr *ArgExpr = E->getArg(0); 10303 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10304 if (ILE->getNumInits() == 1) 10305 ArgExpr = ILE->getInit(0); 10306 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10307 if (ICE->getCastKind() == CK_NoOp) 10308 ArgExpr = ICE->getSubExpr(); 10309 HandleValue(ArgExpr); 10310 return; 10311 } 10312 Inherited::VisitCXXConstructExpr(E); 10313 } 10314 10315 void VisitCallExpr(CallExpr *E) { 10316 // Treat std::move as a use. 10317 if (E->isCallToStdMove()) { 10318 HandleValue(E->getArg(0)); 10319 return; 10320 } 10321 10322 Inherited::VisitCallExpr(E); 10323 } 10324 10325 void VisitBinaryOperator(BinaryOperator *E) { 10326 if (E->isCompoundAssignmentOp()) { 10327 HandleValue(E->getLHS()); 10328 Visit(E->getRHS()); 10329 return; 10330 } 10331 10332 Inherited::VisitBinaryOperator(E); 10333 } 10334 10335 // A custom visitor for BinaryConditionalOperator is needed because the 10336 // regular visitor would check the condition and true expression separately 10337 // but both point to the same place giving duplicate diagnostics. 10338 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10339 Visit(E->getCond()); 10340 Visit(E->getFalseExpr()); 10341 } 10342 10343 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10344 Decl* ReferenceDecl = DRE->getDecl(); 10345 if (OrigDecl != ReferenceDecl) return; 10346 unsigned diag; 10347 if (isReferenceType) { 10348 diag = diag::warn_uninit_self_reference_in_reference_init; 10349 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10350 diag = diag::warn_static_self_reference_in_init; 10351 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10352 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10353 DRE->getDecl()->getType()->isRecordType()) { 10354 diag = diag::warn_uninit_self_reference_in_init; 10355 } else { 10356 // Local variables will be handled by the CFG analysis. 10357 return; 10358 } 10359 10360 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10361 S.PDiag(diag) 10362 << DRE->getDecl() 10363 << OrigDecl->getLocation() 10364 << DRE->getSourceRange()); 10365 } 10366 }; 10367 10368 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10369 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10370 bool DirectInit) { 10371 // Parameters arguments are occassionially constructed with itself, 10372 // for instance, in recursive functions. Skip them. 10373 if (isa<ParmVarDecl>(OrigDecl)) 10374 return; 10375 10376 E = E->IgnoreParens(); 10377 10378 // Skip checking T a = a where T is not a record or reference type. 10379 // Doing so is a way to silence uninitialized warnings. 10380 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10381 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10382 if (ICE->getCastKind() == CK_LValueToRValue) 10383 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10384 if (DRE->getDecl() == OrigDecl) 10385 return; 10386 10387 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10388 } 10389 } // end anonymous namespace 10390 10391 namespace { 10392 // Simple wrapper to add the name of a variable or (if no variable is 10393 // available) a DeclarationName into a diagnostic. 10394 struct VarDeclOrName { 10395 VarDecl *VDecl; 10396 DeclarationName Name; 10397 10398 friend const Sema::SemaDiagnosticBuilder & 10399 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10400 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10401 } 10402 }; 10403 } // end anonymous namespace 10404 10405 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10406 DeclarationName Name, QualType Type, 10407 TypeSourceInfo *TSI, 10408 SourceRange Range, bool DirectInit, 10409 Expr *Init) { 10410 bool IsInitCapture = !VDecl; 10411 assert((!VDecl || !VDecl->isInitCapture()) && 10412 "init captures are expected to be deduced prior to initialization"); 10413 10414 VarDeclOrName VN{VDecl, Name}; 10415 10416 DeducedType *Deduced = Type->getContainedDeducedType(); 10417 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10418 10419 // C++11 [dcl.spec.auto]p3 10420 if (!Init) { 10421 assert(VDecl && "no init for init capture deduction?"); 10422 10423 // Except for class argument deduction, and then for an initializing 10424 // declaration only, i.e. no static at class scope or extern. 10425 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10426 VDecl->hasExternalStorage() || 10427 VDecl->isStaticDataMember()) { 10428 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10429 << VDecl->getDeclName() << Type; 10430 return QualType(); 10431 } 10432 } 10433 10434 ArrayRef<Expr*> DeduceInits; 10435 if (Init) 10436 DeduceInits = Init; 10437 10438 if (DirectInit) { 10439 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10440 DeduceInits = PL->exprs(); 10441 } 10442 10443 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10444 assert(VDecl && "non-auto type for init capture deduction?"); 10445 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10446 InitializationKind Kind = InitializationKind::CreateForInit( 10447 VDecl->getLocation(), DirectInit, Init); 10448 // FIXME: Initialization should not be taking a mutable list of inits. 10449 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10450 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10451 InitsCopy); 10452 } 10453 10454 if (DirectInit) { 10455 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10456 DeduceInits = IL->inits(); 10457 } 10458 10459 // Deduction only works if we have exactly one source expression. 10460 if (DeduceInits.empty()) { 10461 // It isn't possible to write this directly, but it is possible to 10462 // end up in this situation with "auto x(some_pack...);" 10463 Diag(Init->getLocStart(), IsInitCapture 10464 ? diag::err_init_capture_no_expression 10465 : diag::err_auto_var_init_no_expression) 10466 << VN << Type << Range; 10467 return QualType(); 10468 } 10469 10470 if (DeduceInits.size() > 1) { 10471 Diag(DeduceInits[1]->getLocStart(), 10472 IsInitCapture ? diag::err_init_capture_multiple_expressions 10473 : diag::err_auto_var_init_multiple_expressions) 10474 << VN << Type << Range; 10475 return QualType(); 10476 } 10477 10478 Expr *DeduceInit = DeduceInits[0]; 10479 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10480 Diag(Init->getLocStart(), IsInitCapture 10481 ? diag::err_init_capture_paren_braces 10482 : diag::err_auto_var_init_paren_braces) 10483 << isa<InitListExpr>(Init) << VN << Type << Range; 10484 return QualType(); 10485 } 10486 10487 // Expressions default to 'id' when we're in a debugger. 10488 bool DefaultedAnyToId = false; 10489 if (getLangOpts().DebuggerCastResultToId && 10490 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10491 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10492 if (Result.isInvalid()) { 10493 return QualType(); 10494 } 10495 Init = Result.get(); 10496 DefaultedAnyToId = true; 10497 } 10498 10499 // C++ [dcl.decomp]p1: 10500 // If the assignment-expression [...] has array type A and no ref-qualifier 10501 // is present, e has type cv A 10502 if (VDecl && isa<DecompositionDecl>(VDecl) && 10503 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10504 DeduceInit->getType()->isConstantArrayType()) 10505 return Context.getQualifiedType(DeduceInit->getType(), 10506 Type.getQualifiers()); 10507 10508 QualType DeducedType; 10509 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10510 if (!IsInitCapture) 10511 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10512 else if (isa<InitListExpr>(Init)) 10513 Diag(Range.getBegin(), 10514 diag::err_init_capture_deduction_failure_from_init_list) 10515 << VN 10516 << (DeduceInit->getType().isNull() ? TSI->getType() 10517 : DeduceInit->getType()) 10518 << DeduceInit->getSourceRange(); 10519 else 10520 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10521 << VN << TSI->getType() 10522 << (DeduceInit->getType().isNull() ? TSI->getType() 10523 : DeduceInit->getType()) 10524 << DeduceInit->getSourceRange(); 10525 } 10526 10527 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10528 // 'id' instead of a specific object type prevents most of our usual 10529 // checks. 10530 // We only want to warn outside of template instantiations, though: 10531 // inside a template, the 'id' could have come from a parameter. 10532 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10533 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10534 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10535 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10536 } 10537 10538 return DeducedType; 10539 } 10540 10541 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10542 Expr *Init) { 10543 QualType DeducedType = deduceVarTypeFromInitializer( 10544 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10545 VDecl->getSourceRange(), DirectInit, Init); 10546 if (DeducedType.isNull()) { 10547 VDecl->setInvalidDecl(); 10548 return true; 10549 } 10550 10551 VDecl->setType(DeducedType); 10552 assert(VDecl->isLinkageValid()); 10553 10554 // In ARC, infer lifetime. 10555 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10556 VDecl->setInvalidDecl(); 10557 10558 // If this is a redeclaration, check that the type we just deduced matches 10559 // the previously declared type. 10560 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10561 // We never need to merge the type, because we cannot form an incomplete 10562 // array of auto, nor deduce such a type. 10563 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10564 } 10565 10566 // Check the deduced type is valid for a variable declaration. 10567 CheckVariableDeclarationType(VDecl); 10568 return VDecl->isInvalidDecl(); 10569 } 10570 10571 /// AddInitializerToDecl - Adds the initializer Init to the 10572 /// declaration dcl. If DirectInit is true, this is C++ direct 10573 /// initialization rather than copy initialization. 10574 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10575 // If there is no declaration, there was an error parsing it. Just ignore 10576 // the initializer. 10577 if (!RealDecl || RealDecl->isInvalidDecl()) { 10578 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10579 return; 10580 } 10581 10582 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10583 // Pure-specifiers are handled in ActOnPureSpecifier. 10584 Diag(Method->getLocation(), diag::err_member_function_initialization) 10585 << Method->getDeclName() << Init->getSourceRange(); 10586 Method->setInvalidDecl(); 10587 return; 10588 } 10589 10590 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10591 if (!VDecl) { 10592 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10593 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10594 RealDecl->setInvalidDecl(); 10595 return; 10596 } 10597 10598 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10599 if (VDecl->getType()->isUndeducedType()) { 10600 // Attempt typo correction early so that the type of the init expression can 10601 // be deduced based on the chosen correction if the original init contains a 10602 // TypoExpr. 10603 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10604 if (!Res.isUsable()) { 10605 RealDecl->setInvalidDecl(); 10606 return; 10607 } 10608 Init = Res.get(); 10609 10610 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10611 return; 10612 } 10613 10614 // dllimport cannot be used on variable definitions. 10615 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10616 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10617 VDecl->setInvalidDecl(); 10618 return; 10619 } 10620 10621 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10622 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10623 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10624 VDecl->setInvalidDecl(); 10625 return; 10626 } 10627 10628 if (!VDecl->getType()->isDependentType()) { 10629 // A definition must end up with a complete type, which means it must be 10630 // complete with the restriction that an array type might be completed by 10631 // the initializer; note that later code assumes this restriction. 10632 QualType BaseDeclType = VDecl->getType(); 10633 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10634 BaseDeclType = Array->getElementType(); 10635 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10636 diag::err_typecheck_decl_incomplete_type)) { 10637 RealDecl->setInvalidDecl(); 10638 return; 10639 } 10640 10641 // The variable can not have an abstract class type. 10642 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10643 diag::err_abstract_type_in_decl, 10644 AbstractVariableType)) 10645 VDecl->setInvalidDecl(); 10646 } 10647 10648 // If adding the initializer will turn this declaration into a definition, 10649 // and we already have a definition for this variable, diagnose or otherwise 10650 // handle the situation. 10651 VarDecl *Def; 10652 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10653 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10654 !VDecl->isThisDeclarationADemotedDefinition() && 10655 checkVarDeclRedefinition(Def, VDecl)) 10656 return; 10657 10658 if (getLangOpts().CPlusPlus) { 10659 // C++ [class.static.data]p4 10660 // If a static data member is of const integral or const 10661 // enumeration type, its declaration in the class definition can 10662 // specify a constant-initializer which shall be an integral 10663 // constant expression (5.19). In that case, the member can appear 10664 // in integral constant expressions. The member shall still be 10665 // defined in a namespace scope if it is used in the program and the 10666 // namespace scope definition shall not contain an initializer. 10667 // 10668 // We already performed a redefinition check above, but for static 10669 // data members we also need to check whether there was an in-class 10670 // declaration with an initializer. 10671 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10672 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10673 << VDecl->getDeclName(); 10674 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10675 diag::note_previous_initializer) 10676 << 0; 10677 return; 10678 } 10679 10680 if (VDecl->hasLocalStorage()) 10681 setFunctionHasBranchProtectedScope(); 10682 10683 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10684 VDecl->setInvalidDecl(); 10685 return; 10686 } 10687 } 10688 10689 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10690 // a kernel function cannot be initialized." 10691 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10692 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10693 VDecl->setInvalidDecl(); 10694 return; 10695 } 10696 10697 // Get the decls type and save a reference for later, since 10698 // CheckInitializerTypes may change it. 10699 QualType DclT = VDecl->getType(), SavT = DclT; 10700 10701 // Expressions default to 'id' when we're in a debugger 10702 // and we are assigning it to a variable of Objective-C pointer type. 10703 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10704 Init->getType() == Context.UnknownAnyTy) { 10705 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10706 if (Result.isInvalid()) { 10707 VDecl->setInvalidDecl(); 10708 return; 10709 } 10710 Init = Result.get(); 10711 } 10712 10713 // Perform the initialization. 10714 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10715 if (!VDecl->isInvalidDecl()) { 10716 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10717 InitializationKind Kind = InitializationKind::CreateForInit( 10718 VDecl->getLocation(), DirectInit, Init); 10719 10720 MultiExprArg Args = Init; 10721 if (CXXDirectInit) 10722 Args = MultiExprArg(CXXDirectInit->getExprs(), 10723 CXXDirectInit->getNumExprs()); 10724 10725 // Try to correct any TypoExprs in the initialization arguments. 10726 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10727 ExprResult Res = CorrectDelayedTyposInExpr( 10728 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10729 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10730 return Init.Failed() ? ExprError() : E; 10731 }); 10732 if (Res.isInvalid()) { 10733 VDecl->setInvalidDecl(); 10734 } else if (Res.get() != Args[Idx]) { 10735 Args[Idx] = Res.get(); 10736 } 10737 } 10738 if (VDecl->isInvalidDecl()) 10739 return; 10740 10741 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10742 /*TopLevelOfInitList=*/false, 10743 /*TreatUnavailableAsInvalid=*/false); 10744 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10745 if (Result.isInvalid()) { 10746 VDecl->setInvalidDecl(); 10747 return; 10748 } 10749 10750 Init = Result.getAs<Expr>(); 10751 } 10752 10753 // Check for self-references within variable initializers. 10754 // Variables declared within a function/method body (except for references) 10755 // are handled by a dataflow analysis. 10756 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10757 VDecl->getType()->isReferenceType()) { 10758 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10759 } 10760 10761 // If the type changed, it means we had an incomplete type that was 10762 // completed by the initializer. For example: 10763 // int ary[] = { 1, 3, 5 }; 10764 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10765 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10766 VDecl->setType(DclT); 10767 10768 if (!VDecl->isInvalidDecl()) { 10769 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10770 10771 if (VDecl->hasAttr<BlocksAttr>()) 10772 checkRetainCycles(VDecl, Init); 10773 10774 // It is safe to assign a weak reference into a strong variable. 10775 // Although this code can still have problems: 10776 // id x = self.weakProp; 10777 // id y = self.weakProp; 10778 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10779 // paths through the function. This should be revisited if 10780 // -Wrepeated-use-of-weak is made flow-sensitive. 10781 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10782 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10783 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10784 Init->getLocStart())) 10785 getCurFunction()->markSafeWeakUse(Init); 10786 } 10787 10788 // The initialization is usually a full-expression. 10789 // 10790 // FIXME: If this is a braced initialization of an aggregate, it is not 10791 // an expression, and each individual field initializer is a separate 10792 // full-expression. For instance, in: 10793 // 10794 // struct Temp { ~Temp(); }; 10795 // struct S { S(Temp); }; 10796 // struct T { S a, b; } t = { Temp(), Temp() } 10797 // 10798 // we should destroy the first Temp before constructing the second. 10799 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10800 false, 10801 VDecl->isConstexpr()); 10802 if (Result.isInvalid()) { 10803 VDecl->setInvalidDecl(); 10804 return; 10805 } 10806 Init = Result.get(); 10807 10808 // Attach the initializer to the decl. 10809 VDecl->setInit(Init); 10810 10811 if (VDecl->isLocalVarDecl()) { 10812 // Don't check the initializer if the declaration is malformed. 10813 if (VDecl->isInvalidDecl()) { 10814 // do nothing 10815 10816 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10817 // This is true even in OpenCL C++. 10818 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10819 CheckForConstantInitializer(Init, DclT); 10820 10821 // Otherwise, C++ does not restrict the initializer. 10822 } else if (getLangOpts().CPlusPlus) { 10823 // do nothing 10824 10825 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10826 // static storage duration shall be constant expressions or string literals. 10827 } else if (VDecl->getStorageClass() == SC_Static) { 10828 CheckForConstantInitializer(Init, DclT); 10829 10830 // C89 is stricter than C99 for aggregate initializers. 10831 // C89 6.5.7p3: All the expressions [...] in an initializer list 10832 // for an object that has aggregate or union type shall be 10833 // constant expressions. 10834 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10835 isa<InitListExpr>(Init)) { 10836 const Expr *Culprit; 10837 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10838 Diag(Culprit->getExprLoc(), 10839 diag::ext_aggregate_init_not_constant) 10840 << Culprit->getSourceRange(); 10841 } 10842 } 10843 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10844 VDecl->getLexicalDeclContext()->isRecord()) { 10845 // This is an in-class initialization for a static data member, e.g., 10846 // 10847 // struct S { 10848 // static const int value = 17; 10849 // }; 10850 10851 // C++ [class.mem]p4: 10852 // A member-declarator can contain a constant-initializer only 10853 // if it declares a static member (9.4) of const integral or 10854 // const enumeration type, see 9.4.2. 10855 // 10856 // C++11 [class.static.data]p3: 10857 // If a non-volatile non-inline const static data member is of integral 10858 // or enumeration type, its declaration in the class definition can 10859 // specify a brace-or-equal-initializer in which every initializer-clause 10860 // that is an assignment-expression is a constant expression. A static 10861 // data member of literal type can be declared in the class definition 10862 // with the constexpr specifier; if so, its declaration shall specify a 10863 // brace-or-equal-initializer in which every initializer-clause that is 10864 // an assignment-expression is a constant expression. 10865 10866 // Do nothing on dependent types. 10867 if (DclT->isDependentType()) { 10868 10869 // Allow any 'static constexpr' members, whether or not they are of literal 10870 // type. We separately check that every constexpr variable is of literal 10871 // type. 10872 } else if (VDecl->isConstexpr()) { 10873 10874 // Require constness. 10875 } else if (!DclT.isConstQualified()) { 10876 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10877 << Init->getSourceRange(); 10878 VDecl->setInvalidDecl(); 10879 10880 // We allow integer constant expressions in all cases. 10881 } else if (DclT->isIntegralOrEnumerationType()) { 10882 // Check whether the expression is a constant expression. 10883 SourceLocation Loc; 10884 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10885 // In C++11, a non-constexpr const static data member with an 10886 // in-class initializer cannot be volatile. 10887 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10888 else if (Init->isValueDependent()) 10889 ; // Nothing to check. 10890 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10891 ; // Ok, it's an ICE! 10892 else if (Init->isEvaluatable(Context)) { 10893 // If we can constant fold the initializer through heroics, accept it, 10894 // but report this as a use of an extension for -pedantic. 10895 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10896 << Init->getSourceRange(); 10897 } else { 10898 // Otherwise, this is some crazy unknown case. Report the issue at the 10899 // location provided by the isIntegerConstantExpr failed check. 10900 Diag(Loc, diag::err_in_class_initializer_non_constant) 10901 << Init->getSourceRange(); 10902 VDecl->setInvalidDecl(); 10903 } 10904 10905 // We allow foldable floating-point constants as an extension. 10906 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10907 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10908 // it anyway and provide a fixit to add the 'constexpr'. 10909 if (getLangOpts().CPlusPlus11) { 10910 Diag(VDecl->getLocation(), 10911 diag::ext_in_class_initializer_float_type_cxx11) 10912 << DclT << Init->getSourceRange(); 10913 Diag(VDecl->getLocStart(), 10914 diag::note_in_class_initializer_float_type_cxx11) 10915 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10916 } else { 10917 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10918 << DclT << Init->getSourceRange(); 10919 10920 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10921 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10922 << Init->getSourceRange(); 10923 VDecl->setInvalidDecl(); 10924 } 10925 } 10926 10927 // Suggest adding 'constexpr' in C++11 for literal types. 10928 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10929 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10930 << DclT << Init->getSourceRange() 10931 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10932 VDecl->setConstexpr(true); 10933 10934 } else { 10935 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10936 << DclT << Init->getSourceRange(); 10937 VDecl->setInvalidDecl(); 10938 } 10939 } else if (VDecl->isFileVarDecl()) { 10940 // In C, extern is typically used to avoid tentative definitions when 10941 // declaring variables in headers, but adding an intializer makes it a 10942 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 10943 // In C++, extern is often used to give implictly static const variables 10944 // external linkage, so don't warn in that case. If selectany is present, 10945 // this might be header code intended for C and C++ inclusion, so apply the 10946 // C++ rules. 10947 if (VDecl->getStorageClass() == SC_Extern && 10948 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10949 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10950 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10951 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10952 Diag(VDecl->getLocation(), diag::warn_extern_init); 10953 10954 // C99 6.7.8p4. All file scoped initializers need to be constant. 10955 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10956 CheckForConstantInitializer(Init, DclT); 10957 } 10958 10959 // We will represent direct-initialization similarly to copy-initialization: 10960 // int x(1); -as-> int x = 1; 10961 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10962 // 10963 // Clients that want to distinguish between the two forms, can check for 10964 // direct initializer using VarDecl::getInitStyle(). 10965 // A major benefit is that clients that don't particularly care about which 10966 // exactly form was it (like the CodeGen) can handle both cases without 10967 // special case code. 10968 10969 // C++ 8.5p11: 10970 // The form of initialization (using parentheses or '=') is generally 10971 // insignificant, but does matter when the entity being initialized has a 10972 // class type. 10973 if (CXXDirectInit) { 10974 assert(DirectInit && "Call-style initializer must be direct init."); 10975 VDecl->setInitStyle(VarDecl::CallInit); 10976 } else if (DirectInit) { 10977 // This must be list-initialization. No other way is direct-initialization. 10978 VDecl->setInitStyle(VarDecl::ListInit); 10979 } 10980 10981 CheckCompleteVariableDeclaration(VDecl); 10982 } 10983 10984 /// ActOnInitializerError - Given that there was an error parsing an 10985 /// initializer for the given declaration, try to return to some form 10986 /// of sanity. 10987 void Sema::ActOnInitializerError(Decl *D) { 10988 // Our main concern here is re-establishing invariants like "a 10989 // variable's type is either dependent or complete". 10990 if (!D || D->isInvalidDecl()) return; 10991 10992 VarDecl *VD = dyn_cast<VarDecl>(D); 10993 if (!VD) return; 10994 10995 // Bindings are not usable if we can't make sense of the initializer. 10996 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10997 for (auto *BD : DD->bindings()) 10998 BD->setInvalidDecl(); 10999 11000 // Auto types are meaningless if we can't make sense of the initializer. 11001 if (ParsingInitForAutoVars.count(D)) { 11002 D->setInvalidDecl(); 11003 return; 11004 } 11005 11006 QualType Ty = VD->getType(); 11007 if (Ty->isDependentType()) return; 11008 11009 // Require a complete type. 11010 if (RequireCompleteType(VD->getLocation(), 11011 Context.getBaseElementType(Ty), 11012 diag::err_typecheck_decl_incomplete_type)) { 11013 VD->setInvalidDecl(); 11014 return; 11015 } 11016 11017 // Require a non-abstract type. 11018 if (RequireNonAbstractType(VD->getLocation(), Ty, 11019 diag::err_abstract_type_in_decl, 11020 AbstractVariableType)) { 11021 VD->setInvalidDecl(); 11022 return; 11023 } 11024 11025 // Don't bother complaining about constructors or destructors, 11026 // though. 11027 } 11028 11029 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11030 // If there is no declaration, there was an error parsing it. Just ignore it. 11031 if (!RealDecl) 11032 return; 11033 11034 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11035 QualType Type = Var->getType(); 11036 11037 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11038 if (isa<DecompositionDecl>(RealDecl)) { 11039 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11040 Var->setInvalidDecl(); 11041 return; 11042 } 11043 11044 if (Type->isUndeducedType() && 11045 DeduceVariableDeclarationType(Var, false, nullptr)) 11046 return; 11047 11048 // C++11 [class.static.data]p3: A static data member can be declared with 11049 // the constexpr specifier; if so, its declaration shall specify 11050 // a brace-or-equal-initializer. 11051 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11052 // the definition of a variable [...] or the declaration of a static data 11053 // member. 11054 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11055 !Var->isThisDeclarationADemotedDefinition()) { 11056 if (Var->isStaticDataMember()) { 11057 // C++1z removes the relevant rule; the in-class declaration is always 11058 // a definition there. 11059 if (!getLangOpts().CPlusPlus17) { 11060 Diag(Var->getLocation(), 11061 diag::err_constexpr_static_mem_var_requires_init) 11062 << Var->getDeclName(); 11063 Var->setInvalidDecl(); 11064 return; 11065 } 11066 } else { 11067 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11068 Var->setInvalidDecl(); 11069 return; 11070 } 11071 } 11072 11073 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11074 // be initialized. 11075 if (!Var->isInvalidDecl() && 11076 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11077 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11078 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11079 Var->setInvalidDecl(); 11080 return; 11081 } 11082 11083 switch (Var->isThisDeclarationADefinition()) { 11084 case VarDecl::Definition: 11085 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11086 break; 11087 11088 // We have an out-of-line definition of a static data member 11089 // that has an in-class initializer, so we type-check this like 11090 // a declaration. 11091 // 11092 LLVM_FALLTHROUGH; 11093 11094 case VarDecl::DeclarationOnly: 11095 // It's only a declaration. 11096 11097 // Block scope. C99 6.7p7: If an identifier for an object is 11098 // declared with no linkage (C99 6.2.2p6), the type for the 11099 // object shall be complete. 11100 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11101 !Var->hasLinkage() && !Var->isInvalidDecl() && 11102 RequireCompleteType(Var->getLocation(), Type, 11103 diag::err_typecheck_decl_incomplete_type)) 11104 Var->setInvalidDecl(); 11105 11106 // Make sure that the type is not abstract. 11107 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11108 RequireNonAbstractType(Var->getLocation(), Type, 11109 diag::err_abstract_type_in_decl, 11110 AbstractVariableType)) 11111 Var->setInvalidDecl(); 11112 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11113 Var->getStorageClass() == SC_PrivateExtern) { 11114 Diag(Var->getLocation(), diag::warn_private_extern); 11115 Diag(Var->getLocation(), diag::note_private_extern); 11116 } 11117 11118 return; 11119 11120 case VarDecl::TentativeDefinition: 11121 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11122 // object that has file scope without an initializer, and without a 11123 // storage-class specifier or with the storage-class specifier "static", 11124 // constitutes a tentative definition. Note: A tentative definition with 11125 // external linkage is valid (C99 6.2.2p5). 11126 if (!Var->isInvalidDecl()) { 11127 if (const IncompleteArrayType *ArrayT 11128 = Context.getAsIncompleteArrayType(Type)) { 11129 if (RequireCompleteType(Var->getLocation(), 11130 ArrayT->getElementType(), 11131 diag::err_illegal_decl_array_incomplete_type)) 11132 Var->setInvalidDecl(); 11133 } else if (Var->getStorageClass() == SC_Static) { 11134 // C99 6.9.2p3: If the declaration of an identifier for an object is 11135 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11136 // declared type shall not be an incomplete type. 11137 // NOTE: code such as the following 11138 // static struct s; 11139 // struct s { int a; }; 11140 // is accepted by gcc. Hence here we issue a warning instead of 11141 // an error and we do not invalidate the static declaration. 11142 // NOTE: to avoid multiple warnings, only check the first declaration. 11143 if (Var->isFirstDecl()) 11144 RequireCompleteType(Var->getLocation(), Type, 11145 diag::ext_typecheck_decl_incomplete_type); 11146 } 11147 } 11148 11149 // Record the tentative definition; we're done. 11150 if (!Var->isInvalidDecl()) 11151 TentativeDefinitions.push_back(Var); 11152 return; 11153 } 11154 11155 // Provide a specific diagnostic for uninitialized variable 11156 // definitions with incomplete array type. 11157 if (Type->isIncompleteArrayType()) { 11158 Diag(Var->getLocation(), 11159 diag::err_typecheck_incomplete_array_needs_initializer); 11160 Var->setInvalidDecl(); 11161 return; 11162 } 11163 11164 // Provide a specific diagnostic for uninitialized variable 11165 // definitions with reference type. 11166 if (Type->isReferenceType()) { 11167 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11168 << Var->getDeclName() 11169 << SourceRange(Var->getLocation(), Var->getLocation()); 11170 Var->setInvalidDecl(); 11171 return; 11172 } 11173 11174 // Do not attempt to type-check the default initializer for a 11175 // variable with dependent type. 11176 if (Type->isDependentType()) 11177 return; 11178 11179 if (Var->isInvalidDecl()) 11180 return; 11181 11182 if (!Var->hasAttr<AliasAttr>()) { 11183 if (RequireCompleteType(Var->getLocation(), 11184 Context.getBaseElementType(Type), 11185 diag::err_typecheck_decl_incomplete_type)) { 11186 Var->setInvalidDecl(); 11187 return; 11188 } 11189 } else { 11190 return; 11191 } 11192 11193 // The variable can not have an abstract class type. 11194 if (RequireNonAbstractType(Var->getLocation(), Type, 11195 diag::err_abstract_type_in_decl, 11196 AbstractVariableType)) { 11197 Var->setInvalidDecl(); 11198 return; 11199 } 11200 11201 // Check for jumps past the implicit initializer. C++0x 11202 // clarifies that this applies to a "variable with automatic 11203 // storage duration", not a "local variable". 11204 // C++11 [stmt.dcl]p3 11205 // A program that jumps from a point where a variable with automatic 11206 // storage duration is not in scope to a point where it is in scope is 11207 // ill-formed unless the variable has scalar type, class type with a 11208 // trivial default constructor and a trivial destructor, a cv-qualified 11209 // version of one of these types, or an array of one of the preceding 11210 // types and is declared without an initializer. 11211 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11212 if (const RecordType *Record 11213 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11214 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11215 // Mark the function (if we're in one) for further checking even if the 11216 // looser rules of C++11 do not require such checks, so that we can 11217 // diagnose incompatibilities with C++98. 11218 if (!CXXRecord->isPOD()) 11219 setFunctionHasBranchProtectedScope(); 11220 } 11221 } 11222 11223 // C++03 [dcl.init]p9: 11224 // If no initializer is specified for an object, and the 11225 // object is of (possibly cv-qualified) non-POD class type (or 11226 // array thereof), the object shall be default-initialized; if 11227 // the object is of const-qualified type, the underlying class 11228 // type shall have a user-declared default 11229 // constructor. Otherwise, if no initializer is specified for 11230 // a non- static object, the object and its subobjects, if 11231 // any, have an indeterminate initial value); if the object 11232 // or any of its subobjects are of const-qualified type, the 11233 // program is ill-formed. 11234 // C++0x [dcl.init]p11: 11235 // If no initializer is specified for an object, the object is 11236 // default-initialized; [...]. 11237 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11238 InitializationKind Kind 11239 = InitializationKind::CreateDefault(Var->getLocation()); 11240 11241 InitializationSequence InitSeq(*this, Entity, Kind, None); 11242 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11243 if (Init.isInvalid()) 11244 Var->setInvalidDecl(); 11245 else if (Init.get()) { 11246 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11247 // This is important for template substitution. 11248 Var->setInitStyle(VarDecl::CallInit); 11249 } 11250 11251 CheckCompleteVariableDeclaration(Var); 11252 } 11253 } 11254 11255 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11256 // If there is no declaration, there was an error parsing it. Ignore it. 11257 if (!D) 11258 return; 11259 11260 VarDecl *VD = dyn_cast<VarDecl>(D); 11261 if (!VD) { 11262 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11263 D->setInvalidDecl(); 11264 return; 11265 } 11266 11267 VD->setCXXForRangeDecl(true); 11268 11269 // for-range-declaration cannot be given a storage class specifier. 11270 int Error = -1; 11271 switch (VD->getStorageClass()) { 11272 case SC_None: 11273 break; 11274 case SC_Extern: 11275 Error = 0; 11276 break; 11277 case SC_Static: 11278 Error = 1; 11279 break; 11280 case SC_PrivateExtern: 11281 Error = 2; 11282 break; 11283 case SC_Auto: 11284 Error = 3; 11285 break; 11286 case SC_Register: 11287 Error = 4; 11288 break; 11289 } 11290 if (Error != -1) { 11291 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11292 << VD->getDeclName() << Error; 11293 D->setInvalidDecl(); 11294 } 11295 } 11296 11297 StmtResult 11298 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11299 IdentifierInfo *Ident, 11300 ParsedAttributes &Attrs, 11301 SourceLocation AttrEnd) { 11302 // C++1y [stmt.iter]p1: 11303 // A range-based for statement of the form 11304 // for ( for-range-identifier : for-range-initializer ) statement 11305 // is equivalent to 11306 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11307 DeclSpec DS(Attrs.getPool().getFactory()); 11308 11309 const char *PrevSpec; 11310 unsigned DiagID; 11311 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11312 getPrintingPolicy()); 11313 11314 Declarator D(DS, DeclaratorContext::ForContext); 11315 D.SetIdentifier(Ident, IdentLoc); 11316 D.takeAttributes(Attrs, AttrEnd); 11317 11318 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11319 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 11320 EmptyAttrs, IdentLoc); 11321 Decl *Var = ActOnDeclarator(S, D); 11322 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11323 FinalizeDeclaration(Var); 11324 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11325 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11326 } 11327 11328 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11329 if (var->isInvalidDecl()) return; 11330 11331 if (getLangOpts().OpenCL) { 11332 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11333 // initialiser 11334 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11335 !var->hasInit()) { 11336 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11337 << 1 /*Init*/; 11338 var->setInvalidDecl(); 11339 return; 11340 } 11341 } 11342 11343 // In Objective-C, don't allow jumps past the implicit initialization of a 11344 // local retaining variable. 11345 if (getLangOpts().ObjC1 && 11346 var->hasLocalStorage()) { 11347 switch (var->getType().getObjCLifetime()) { 11348 case Qualifiers::OCL_None: 11349 case Qualifiers::OCL_ExplicitNone: 11350 case Qualifiers::OCL_Autoreleasing: 11351 break; 11352 11353 case Qualifiers::OCL_Weak: 11354 case Qualifiers::OCL_Strong: 11355 setFunctionHasBranchProtectedScope(); 11356 break; 11357 } 11358 } 11359 11360 if (var->hasLocalStorage() && 11361 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11362 setFunctionHasBranchProtectedScope(); 11363 11364 // Warn about externally-visible variables being defined without a 11365 // prior declaration. We only want to do this for global 11366 // declarations, but we also specifically need to avoid doing it for 11367 // class members because the linkage of an anonymous class can 11368 // change if it's later given a typedef name. 11369 if (var->isThisDeclarationADefinition() && 11370 var->getDeclContext()->getRedeclContext()->isFileContext() && 11371 var->isExternallyVisible() && var->hasLinkage() && 11372 !var->isInline() && !var->getDescribedVarTemplate() && 11373 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11374 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11375 var->getLocation())) { 11376 // Find a previous declaration that's not a definition. 11377 VarDecl *prev = var->getPreviousDecl(); 11378 while (prev && prev->isThisDeclarationADefinition()) 11379 prev = prev->getPreviousDecl(); 11380 11381 if (!prev) 11382 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11383 } 11384 11385 // Cache the result of checking for constant initialization. 11386 Optional<bool> CacheHasConstInit; 11387 const Expr *CacheCulprit; 11388 auto checkConstInit = [&]() mutable { 11389 if (!CacheHasConstInit) 11390 CacheHasConstInit = var->getInit()->isConstantInitializer( 11391 Context, var->getType()->isReferenceType(), &CacheCulprit); 11392 return *CacheHasConstInit; 11393 }; 11394 11395 if (var->getTLSKind() == VarDecl::TLS_Static) { 11396 if (var->getType().isDestructedType()) { 11397 // GNU C++98 edits for __thread, [basic.start.term]p3: 11398 // The type of an object with thread storage duration shall not 11399 // have a non-trivial destructor. 11400 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11401 if (getLangOpts().CPlusPlus11) 11402 Diag(var->getLocation(), diag::note_use_thread_local); 11403 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11404 if (!checkConstInit()) { 11405 // GNU C++98 edits for __thread, [basic.start.init]p4: 11406 // An object of thread storage duration shall not require dynamic 11407 // initialization. 11408 // FIXME: Need strict checking here. 11409 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11410 << CacheCulprit->getSourceRange(); 11411 if (getLangOpts().CPlusPlus11) 11412 Diag(var->getLocation(), diag::note_use_thread_local); 11413 } 11414 } 11415 } 11416 11417 // Apply section attributes and pragmas to global variables. 11418 bool GlobalStorage = var->hasGlobalStorage(); 11419 if (GlobalStorage && var->isThisDeclarationADefinition() && 11420 !inTemplateInstantiation()) { 11421 PragmaStack<StringLiteral *> *Stack = nullptr; 11422 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11423 if (var->getType().isConstQualified()) 11424 Stack = &ConstSegStack; 11425 else if (!var->getInit()) { 11426 Stack = &BSSSegStack; 11427 SectionFlags |= ASTContext::PSF_Write; 11428 } else { 11429 Stack = &DataSegStack; 11430 SectionFlags |= ASTContext::PSF_Write; 11431 } 11432 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11433 var->addAttr(SectionAttr::CreateImplicit( 11434 Context, SectionAttr::Declspec_allocate, 11435 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11436 } 11437 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11438 if (UnifySection(SA->getName(), SectionFlags, var)) 11439 var->dropAttr<SectionAttr>(); 11440 11441 // Apply the init_seg attribute if this has an initializer. If the 11442 // initializer turns out to not be dynamic, we'll end up ignoring this 11443 // attribute. 11444 if (CurInitSeg && var->getInit()) 11445 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11446 CurInitSegLoc)); 11447 } 11448 11449 // All the following checks are C++ only. 11450 if (!getLangOpts().CPlusPlus) { 11451 // If this variable must be emitted, add it as an initializer for the 11452 // current module. 11453 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11454 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11455 return; 11456 } 11457 11458 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11459 CheckCompleteDecompositionDeclaration(DD); 11460 11461 QualType type = var->getType(); 11462 if (type->isDependentType()) return; 11463 11464 // __block variables might require us to capture a copy-initializer. 11465 if (var->hasAttr<BlocksAttr>()) { 11466 // It's currently invalid to ever have a __block variable with an 11467 // array type; should we diagnose that here? 11468 11469 // Regardless, we don't want to ignore array nesting when 11470 // constructing this copy. 11471 if (type->isStructureOrClassType()) { 11472 EnterExpressionEvaluationContext scope( 11473 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11474 SourceLocation poi = var->getLocation(); 11475 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11476 ExprResult result 11477 = PerformMoveOrCopyInitialization( 11478 InitializedEntity::InitializeBlock(poi, type, false), 11479 var, var->getType(), varRef, /*AllowNRVO=*/true); 11480 if (!result.isInvalid()) { 11481 result = MaybeCreateExprWithCleanups(result); 11482 Expr *init = result.getAs<Expr>(); 11483 Context.setBlockVarCopyInits(var, init); 11484 } 11485 } 11486 } 11487 11488 Expr *Init = var->getInit(); 11489 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11490 QualType baseType = Context.getBaseElementType(type); 11491 11492 if (Init && !Init->isValueDependent()) { 11493 if (var->isConstexpr()) { 11494 SmallVector<PartialDiagnosticAt, 8> Notes; 11495 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11496 SourceLocation DiagLoc = var->getLocation(); 11497 // If the note doesn't add any useful information other than a source 11498 // location, fold it into the primary diagnostic. 11499 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11500 diag::note_invalid_subexpr_in_const_expr) { 11501 DiagLoc = Notes[0].first; 11502 Notes.clear(); 11503 } 11504 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11505 << var << Init->getSourceRange(); 11506 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11507 Diag(Notes[I].first, Notes[I].second); 11508 } 11509 } else if (var->isUsableInConstantExpressions(Context)) { 11510 // Check whether the initializer of a const variable of integral or 11511 // enumeration type is an ICE now, since we can't tell whether it was 11512 // initialized by a constant expression if we check later. 11513 var->checkInitIsICE(); 11514 } 11515 11516 // Don't emit further diagnostics about constexpr globals since they 11517 // were just diagnosed. 11518 if (!var->isConstexpr() && GlobalStorage && 11519 var->hasAttr<RequireConstantInitAttr>()) { 11520 // FIXME: Need strict checking in C++03 here. 11521 bool DiagErr = getLangOpts().CPlusPlus11 11522 ? !var->checkInitIsICE() : !checkConstInit(); 11523 if (DiagErr) { 11524 auto attr = var->getAttr<RequireConstantInitAttr>(); 11525 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11526 << Init->getSourceRange(); 11527 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11528 << attr->getRange(); 11529 if (getLangOpts().CPlusPlus11) { 11530 APValue Value; 11531 SmallVector<PartialDiagnosticAt, 8> Notes; 11532 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11533 for (auto &it : Notes) 11534 Diag(it.first, it.second); 11535 } else { 11536 Diag(CacheCulprit->getExprLoc(), 11537 diag::note_invalid_subexpr_in_const_expr) 11538 << CacheCulprit->getSourceRange(); 11539 } 11540 } 11541 } 11542 else if (!var->isConstexpr() && IsGlobal && 11543 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11544 var->getLocation())) { 11545 // Warn about globals which don't have a constant initializer. Don't 11546 // warn about globals with a non-trivial destructor because we already 11547 // warned about them. 11548 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11549 if (!(RD && !RD->hasTrivialDestructor())) { 11550 if (!checkConstInit()) 11551 Diag(var->getLocation(), diag::warn_global_constructor) 11552 << Init->getSourceRange(); 11553 } 11554 } 11555 } 11556 11557 // Require the destructor. 11558 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11559 FinalizeVarWithDestructor(var, recordType); 11560 11561 // If this variable must be emitted, add it as an initializer for the current 11562 // module. 11563 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11564 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11565 } 11566 11567 /// \brief Determines if a variable's alignment is dependent. 11568 static bool hasDependentAlignment(VarDecl *VD) { 11569 if (VD->getType()->isDependentType()) 11570 return true; 11571 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11572 if (I->isAlignmentDependent()) 11573 return true; 11574 return false; 11575 } 11576 11577 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11578 /// any semantic actions necessary after any initializer has been attached. 11579 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11580 // Note that we are no longer parsing the initializer for this declaration. 11581 ParsingInitForAutoVars.erase(ThisDecl); 11582 11583 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11584 if (!VD) 11585 return; 11586 11587 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11588 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11589 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11590 if (PragmaClangBSSSection.Valid) 11591 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11592 PragmaClangBSSSection.SectionName, 11593 PragmaClangBSSSection.PragmaLocation)); 11594 if (PragmaClangDataSection.Valid) 11595 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11596 PragmaClangDataSection.SectionName, 11597 PragmaClangDataSection.PragmaLocation)); 11598 if (PragmaClangRodataSection.Valid) 11599 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11600 PragmaClangRodataSection.SectionName, 11601 PragmaClangRodataSection.PragmaLocation)); 11602 } 11603 11604 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11605 for (auto *BD : DD->bindings()) { 11606 FinalizeDeclaration(BD); 11607 } 11608 } 11609 11610 checkAttributesAfterMerging(*this, *VD); 11611 11612 // Perform TLS alignment check here after attributes attached to the variable 11613 // which may affect the alignment have been processed. Only perform the check 11614 // if the target has a maximum TLS alignment (zero means no constraints). 11615 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11616 // Protect the check so that it's not performed on dependent types and 11617 // dependent alignments (we can't determine the alignment in that case). 11618 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11619 !VD->isInvalidDecl()) { 11620 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11621 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11622 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11623 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11624 << (unsigned)MaxAlignChars.getQuantity(); 11625 } 11626 } 11627 } 11628 11629 if (VD->isStaticLocal()) { 11630 if (FunctionDecl *FD = 11631 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11632 // Static locals inherit dll attributes from their function. 11633 if (Attr *A = getDLLAttr(FD)) { 11634 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11635 NewAttr->setInherited(true); 11636 VD->addAttr(NewAttr); 11637 } 11638 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11639 // function, only __shared__ variables may be declared with 11640 // static storage class. 11641 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11642 CUDADiagIfDeviceCode(VD->getLocation(), 11643 diag::err_device_static_local_var) 11644 << CurrentCUDATarget()) 11645 VD->setInvalidDecl(); 11646 } 11647 } 11648 11649 // Perform check for initializers of device-side global variables. 11650 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11651 // 7.5). We must also apply the same checks to all __shared__ 11652 // variables whether they are local or not. CUDA also allows 11653 // constant initializers for __constant__ and __device__ variables. 11654 if (getLangOpts().CUDA) { 11655 const Expr *Init = VD->getInit(); 11656 if (Init && VD->hasGlobalStorage()) { 11657 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11658 VD->hasAttr<CUDASharedAttr>()) { 11659 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11660 bool AllowedInit = false; 11661 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11662 AllowedInit = 11663 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11664 // We'll allow constant initializers even if it's a non-empty 11665 // constructor according to CUDA rules. This deviates from NVCC, 11666 // but allows us to handle things like constexpr constructors. 11667 if (!AllowedInit && 11668 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11669 AllowedInit = VD->getInit()->isConstantInitializer( 11670 Context, VD->getType()->isReferenceType()); 11671 11672 // Also make sure that destructor, if there is one, is empty. 11673 if (AllowedInit) 11674 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11675 AllowedInit = 11676 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11677 11678 if (!AllowedInit) { 11679 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11680 ? diag::err_shared_var_init 11681 : diag::err_dynamic_var_init) 11682 << Init->getSourceRange(); 11683 VD->setInvalidDecl(); 11684 } 11685 } else { 11686 // This is a host-side global variable. Check that the initializer is 11687 // callable from the host side. 11688 const FunctionDecl *InitFn = nullptr; 11689 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11690 InitFn = CE->getConstructor(); 11691 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11692 InitFn = CE->getDirectCallee(); 11693 } 11694 if (InitFn) { 11695 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11696 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11697 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11698 << InitFnTarget << InitFn; 11699 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11700 VD->setInvalidDecl(); 11701 } 11702 } 11703 } 11704 } 11705 } 11706 11707 // Grab the dllimport or dllexport attribute off of the VarDecl. 11708 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11709 11710 // Imported static data members cannot be defined out-of-line. 11711 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11712 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11713 VD->isThisDeclarationADefinition()) { 11714 // We allow definitions of dllimport class template static data members 11715 // with a warning. 11716 CXXRecordDecl *Context = 11717 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11718 bool IsClassTemplateMember = 11719 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11720 Context->getDescribedClassTemplate(); 11721 11722 Diag(VD->getLocation(), 11723 IsClassTemplateMember 11724 ? diag::warn_attribute_dllimport_static_field_definition 11725 : diag::err_attribute_dllimport_static_field_definition); 11726 Diag(IA->getLocation(), diag::note_attribute); 11727 if (!IsClassTemplateMember) 11728 VD->setInvalidDecl(); 11729 } 11730 } 11731 11732 // dllimport/dllexport variables cannot be thread local, their TLS index 11733 // isn't exported with the variable. 11734 if (DLLAttr && VD->getTLSKind()) { 11735 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11736 if (F && getDLLAttr(F)) { 11737 assert(VD->isStaticLocal()); 11738 // But if this is a static local in a dlimport/dllexport function, the 11739 // function will never be inlined, which means the var would never be 11740 // imported, so having it marked import/export is safe. 11741 } else { 11742 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11743 << DLLAttr; 11744 VD->setInvalidDecl(); 11745 } 11746 } 11747 11748 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11749 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11750 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11751 VD->dropAttr<UsedAttr>(); 11752 } 11753 } 11754 11755 const DeclContext *DC = VD->getDeclContext(); 11756 // If there's a #pragma GCC visibility in scope, and this isn't a class 11757 // member, set the visibility of this variable. 11758 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11759 AddPushedVisibilityAttribute(VD); 11760 11761 // FIXME: Warn on unused var template partial specializations. 11762 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11763 MarkUnusedFileScopedDecl(VD); 11764 11765 // Now we have parsed the initializer and can update the table of magic 11766 // tag values. 11767 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11768 !VD->getType()->isIntegralOrEnumerationType()) 11769 return; 11770 11771 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11772 const Expr *MagicValueExpr = VD->getInit(); 11773 if (!MagicValueExpr) { 11774 continue; 11775 } 11776 llvm::APSInt MagicValueInt; 11777 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11778 Diag(I->getRange().getBegin(), 11779 diag::err_type_tag_for_datatype_not_ice) 11780 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11781 continue; 11782 } 11783 if (MagicValueInt.getActiveBits() > 64) { 11784 Diag(I->getRange().getBegin(), 11785 diag::err_type_tag_for_datatype_too_large) 11786 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11787 continue; 11788 } 11789 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11790 RegisterTypeTagForDatatype(I->getArgumentKind(), 11791 MagicValue, 11792 I->getMatchingCType(), 11793 I->getLayoutCompatible(), 11794 I->getMustBeNull()); 11795 } 11796 } 11797 11798 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11799 auto *VD = dyn_cast<VarDecl>(DD); 11800 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11801 } 11802 11803 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11804 ArrayRef<Decl *> Group) { 11805 SmallVector<Decl*, 8> Decls; 11806 11807 if (DS.isTypeSpecOwned()) 11808 Decls.push_back(DS.getRepAsDecl()); 11809 11810 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11811 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11812 bool DiagnosedMultipleDecomps = false; 11813 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11814 bool DiagnosedNonDeducedAuto = false; 11815 11816 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11817 if (Decl *D = Group[i]) { 11818 // For declarators, there are some additional syntactic-ish checks we need 11819 // to perform. 11820 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11821 if (!FirstDeclaratorInGroup) 11822 FirstDeclaratorInGroup = DD; 11823 if (!FirstDecompDeclaratorInGroup) 11824 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11825 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11826 !hasDeducedAuto(DD)) 11827 FirstNonDeducedAutoInGroup = DD; 11828 11829 if (FirstDeclaratorInGroup != DD) { 11830 // A decomposition declaration cannot be combined with any other 11831 // declaration in the same group. 11832 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11833 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11834 diag::err_decomp_decl_not_alone) 11835 << FirstDeclaratorInGroup->getSourceRange() 11836 << DD->getSourceRange(); 11837 DiagnosedMultipleDecomps = true; 11838 } 11839 11840 // A declarator that uses 'auto' in any way other than to declare a 11841 // variable with a deduced type cannot be combined with any other 11842 // declarator in the same group. 11843 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11844 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11845 diag::err_auto_non_deduced_not_alone) 11846 << FirstNonDeducedAutoInGroup->getType() 11847 ->hasAutoForTrailingReturnType() 11848 << FirstDeclaratorInGroup->getSourceRange() 11849 << DD->getSourceRange(); 11850 DiagnosedNonDeducedAuto = true; 11851 } 11852 } 11853 } 11854 11855 Decls.push_back(D); 11856 } 11857 } 11858 11859 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11860 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11861 handleTagNumbering(Tag, S); 11862 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11863 getLangOpts().CPlusPlus) 11864 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11865 } 11866 } 11867 11868 return BuildDeclaratorGroup(Decls); 11869 } 11870 11871 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11872 /// group, performing any necessary semantic checking. 11873 Sema::DeclGroupPtrTy 11874 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11875 // C++14 [dcl.spec.auto]p7: (DR1347) 11876 // If the type that replaces the placeholder type is not the same in each 11877 // deduction, the program is ill-formed. 11878 if (Group.size() > 1) { 11879 QualType Deduced; 11880 VarDecl *DeducedDecl = nullptr; 11881 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11882 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11883 if (!D || D->isInvalidDecl()) 11884 break; 11885 DeducedType *DT = D->getType()->getContainedDeducedType(); 11886 if (!DT || DT->getDeducedType().isNull()) 11887 continue; 11888 if (Deduced.isNull()) { 11889 Deduced = DT->getDeducedType(); 11890 DeducedDecl = D; 11891 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11892 auto *AT = dyn_cast<AutoType>(DT); 11893 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11894 diag::err_auto_different_deductions) 11895 << (AT ? (unsigned)AT->getKeyword() : 3) 11896 << Deduced << DeducedDecl->getDeclName() 11897 << DT->getDeducedType() << D->getDeclName() 11898 << DeducedDecl->getInit()->getSourceRange() 11899 << D->getInit()->getSourceRange(); 11900 D->setInvalidDecl(); 11901 break; 11902 } 11903 } 11904 } 11905 11906 ActOnDocumentableDecls(Group); 11907 11908 return DeclGroupPtrTy::make( 11909 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11910 } 11911 11912 void Sema::ActOnDocumentableDecl(Decl *D) { 11913 ActOnDocumentableDecls(D); 11914 } 11915 11916 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11917 // Don't parse the comment if Doxygen diagnostics are ignored. 11918 if (Group.empty() || !Group[0]) 11919 return; 11920 11921 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11922 Group[0]->getLocation()) && 11923 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11924 Group[0]->getLocation())) 11925 return; 11926 11927 if (Group.size() >= 2) { 11928 // This is a decl group. Normally it will contain only declarations 11929 // produced from declarator list. But in case we have any definitions or 11930 // additional declaration references: 11931 // 'typedef struct S {} S;' 11932 // 'typedef struct S *S;' 11933 // 'struct S *pS;' 11934 // FinalizeDeclaratorGroup adds these as separate declarations. 11935 Decl *MaybeTagDecl = Group[0]; 11936 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11937 Group = Group.slice(1); 11938 } 11939 } 11940 11941 // See if there are any new comments that are not attached to a decl. 11942 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11943 if (!Comments.empty() && 11944 !Comments.back()->isAttached()) { 11945 // There is at least one comment that not attached to a decl. 11946 // Maybe it should be attached to one of these decls? 11947 // 11948 // Note that this way we pick up not only comments that precede the 11949 // declaration, but also comments that *follow* the declaration -- thanks to 11950 // the lookahead in the lexer: we've consumed the semicolon and looked 11951 // ahead through comments. 11952 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11953 Context.getCommentForDecl(Group[i], &PP); 11954 } 11955 } 11956 11957 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11958 /// to introduce parameters into function prototype scope. 11959 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11960 const DeclSpec &DS = D.getDeclSpec(); 11961 11962 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11963 11964 // C++03 [dcl.stc]p2 also permits 'auto'. 11965 StorageClass SC = SC_None; 11966 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11967 SC = SC_Register; 11968 // In C++11, the 'register' storage class specifier is deprecated. 11969 // In C++17, it is not allowed, but we tolerate it as an extension. 11970 if (getLangOpts().CPlusPlus11) { 11971 Diag(DS.getStorageClassSpecLoc(), 11972 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 11973 : diag::warn_deprecated_register) 11974 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11975 } 11976 } else if (getLangOpts().CPlusPlus && 11977 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11978 SC = SC_Auto; 11979 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11980 Diag(DS.getStorageClassSpecLoc(), 11981 diag::err_invalid_storage_class_in_func_decl); 11982 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11983 } 11984 11985 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11986 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11987 << DeclSpec::getSpecifierName(TSCS); 11988 if (DS.isInlineSpecified()) 11989 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11990 << getLangOpts().CPlusPlus17; 11991 if (DS.isConstexprSpecified()) 11992 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11993 << 0; 11994 11995 DiagnoseFunctionSpecifiers(DS); 11996 11997 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11998 QualType parmDeclType = TInfo->getType(); 11999 12000 if (getLangOpts().CPlusPlus) { 12001 // Check that there are no default arguments inside the type of this 12002 // parameter. 12003 CheckExtraCXXDefaultArguments(D); 12004 12005 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12006 if (D.getCXXScopeSpec().isSet()) { 12007 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12008 << D.getCXXScopeSpec().getRange(); 12009 D.getCXXScopeSpec().clear(); 12010 } 12011 } 12012 12013 // Ensure we have a valid name 12014 IdentifierInfo *II = nullptr; 12015 if (D.hasName()) { 12016 II = D.getIdentifier(); 12017 if (!II) { 12018 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12019 << GetNameForDeclarator(D).getName(); 12020 D.setInvalidType(true); 12021 } 12022 } 12023 12024 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12025 if (II) { 12026 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12027 ForVisibleRedeclaration); 12028 LookupName(R, S); 12029 if (R.isSingleResult()) { 12030 NamedDecl *PrevDecl = R.getFoundDecl(); 12031 if (PrevDecl->isTemplateParameter()) { 12032 // Maybe we will complain about the shadowed template parameter. 12033 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12034 // Just pretend that we didn't see the previous declaration. 12035 PrevDecl = nullptr; 12036 } else if (S->isDeclScope(PrevDecl)) { 12037 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12038 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12039 12040 // Recover by removing the name 12041 II = nullptr; 12042 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12043 D.setInvalidType(true); 12044 } 12045 } 12046 } 12047 12048 // Temporarily put parameter variables in the translation unit, not 12049 // the enclosing context. This prevents them from accidentally 12050 // looking like class members in C++. 12051 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 12052 D.getLocStart(), 12053 D.getIdentifierLoc(), II, 12054 parmDeclType, TInfo, 12055 SC); 12056 12057 if (D.isInvalidType()) 12058 New->setInvalidDecl(); 12059 12060 assert(S->isFunctionPrototypeScope()); 12061 assert(S->getFunctionPrototypeDepth() >= 1); 12062 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12063 S->getNextFunctionPrototypeIndex()); 12064 12065 // Add the parameter declaration into this scope. 12066 S->AddDecl(New); 12067 if (II) 12068 IdResolver.AddDecl(New); 12069 12070 ProcessDeclAttributes(S, New, D); 12071 12072 if (D.getDeclSpec().isModulePrivateSpecified()) 12073 Diag(New->getLocation(), diag::err_module_private_local) 12074 << 1 << New->getDeclName() 12075 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12076 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12077 12078 if (New->hasAttr<BlocksAttr>()) { 12079 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12080 } 12081 return New; 12082 } 12083 12084 /// \brief Synthesizes a variable for a parameter arising from a 12085 /// typedef. 12086 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12087 SourceLocation Loc, 12088 QualType T) { 12089 /* FIXME: setting StartLoc == Loc. 12090 Would it be worth to modify callers so as to provide proper source 12091 location for the unnamed parameters, embedding the parameter's type? */ 12092 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12093 T, Context.getTrivialTypeSourceInfo(T, Loc), 12094 SC_None, nullptr); 12095 Param->setImplicit(); 12096 return Param; 12097 } 12098 12099 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12100 // Don't diagnose unused-parameter errors in template instantiations; we 12101 // will already have done so in the template itself. 12102 if (inTemplateInstantiation()) 12103 return; 12104 12105 for (const ParmVarDecl *Parameter : Parameters) { 12106 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12107 !Parameter->hasAttr<UnusedAttr>()) { 12108 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12109 << Parameter->getDeclName(); 12110 } 12111 } 12112 } 12113 12114 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12115 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12116 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12117 return; 12118 12119 // Warn if the return value is pass-by-value and larger than the specified 12120 // threshold. 12121 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12122 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12123 if (Size > LangOpts.NumLargeByValueCopy) 12124 Diag(D->getLocation(), diag::warn_return_value_size) 12125 << D->getDeclName() << Size; 12126 } 12127 12128 // Warn if any parameter is pass-by-value and larger than the specified 12129 // threshold. 12130 for (const ParmVarDecl *Parameter : Parameters) { 12131 QualType T = Parameter->getType(); 12132 if (T->isDependentType() || !T.isPODType(Context)) 12133 continue; 12134 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12135 if (Size > LangOpts.NumLargeByValueCopy) 12136 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12137 << Parameter->getDeclName() << Size; 12138 } 12139 } 12140 12141 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12142 SourceLocation NameLoc, IdentifierInfo *Name, 12143 QualType T, TypeSourceInfo *TSInfo, 12144 StorageClass SC) { 12145 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12146 if (getLangOpts().ObjCAutoRefCount && 12147 T.getObjCLifetime() == Qualifiers::OCL_None && 12148 T->isObjCLifetimeType()) { 12149 12150 Qualifiers::ObjCLifetime lifetime; 12151 12152 // Special cases for arrays: 12153 // - if it's const, use __unsafe_unretained 12154 // - otherwise, it's an error 12155 if (T->isArrayType()) { 12156 if (!T.isConstQualified()) { 12157 DelayedDiagnostics.add( 12158 sema::DelayedDiagnostic::makeForbiddenType( 12159 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12160 } 12161 lifetime = Qualifiers::OCL_ExplicitNone; 12162 } else { 12163 lifetime = T->getObjCARCImplicitLifetime(); 12164 } 12165 T = Context.getLifetimeQualifiedType(T, lifetime); 12166 } 12167 12168 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12169 Context.getAdjustedParameterType(T), 12170 TSInfo, SC, nullptr); 12171 12172 // Parameters can not be abstract class types. 12173 // For record types, this is done by the AbstractClassUsageDiagnoser once 12174 // the class has been completely parsed. 12175 if (!CurContext->isRecord() && 12176 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12177 AbstractParamType)) 12178 New->setInvalidDecl(); 12179 12180 // Parameter declarators cannot be interface types. All ObjC objects are 12181 // passed by reference. 12182 if (T->isObjCObjectType()) { 12183 SourceLocation TypeEndLoc = 12184 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 12185 Diag(NameLoc, 12186 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12187 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12188 T = Context.getObjCObjectPointerType(T); 12189 New->setType(T); 12190 } 12191 12192 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12193 // duration shall not be qualified by an address-space qualifier." 12194 // Since all parameters have automatic store duration, they can not have 12195 // an address space. 12196 if (T.getAddressSpace() != LangAS::Default && 12197 // OpenCL allows function arguments declared to be an array of a type 12198 // to be qualified with an address space. 12199 !(getLangOpts().OpenCL && 12200 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12201 Diag(NameLoc, diag::err_arg_with_address_space); 12202 New->setInvalidDecl(); 12203 } 12204 12205 return New; 12206 } 12207 12208 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12209 SourceLocation LocAfterDecls) { 12210 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12211 12212 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12213 // for a K&R function. 12214 if (!FTI.hasPrototype) { 12215 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12216 --i; 12217 if (FTI.Params[i].Param == nullptr) { 12218 SmallString<256> Code; 12219 llvm::raw_svector_ostream(Code) 12220 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12221 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12222 << FTI.Params[i].Ident 12223 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12224 12225 // Implicitly declare the argument as type 'int' for lack of a better 12226 // type. 12227 AttributeFactory attrs; 12228 DeclSpec DS(attrs); 12229 const char* PrevSpec; // unused 12230 unsigned DiagID; // unused 12231 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12232 DiagID, Context.getPrintingPolicy()); 12233 // Use the identifier location for the type source range. 12234 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12235 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12236 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12237 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12238 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12239 } 12240 } 12241 } 12242 } 12243 12244 Decl * 12245 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12246 MultiTemplateParamsArg TemplateParameterLists, 12247 SkipBodyInfo *SkipBody) { 12248 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12249 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12250 Scope *ParentScope = FnBodyScope->getParent(); 12251 12252 D.setFunctionDefinitionKind(FDK_Definition); 12253 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12254 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12255 } 12256 12257 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12258 Consumer.HandleInlineFunctionDefinition(D); 12259 } 12260 12261 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12262 const FunctionDecl*& PossibleZeroParamPrototype) { 12263 // Don't warn about invalid declarations. 12264 if (FD->isInvalidDecl()) 12265 return false; 12266 12267 // Or declarations that aren't global. 12268 if (!FD->isGlobal()) 12269 return false; 12270 12271 // Don't warn about C++ member functions. 12272 if (isa<CXXMethodDecl>(FD)) 12273 return false; 12274 12275 // Don't warn about 'main'. 12276 if (FD->isMain()) 12277 return false; 12278 12279 // Don't warn about inline functions. 12280 if (FD->isInlined()) 12281 return false; 12282 12283 // Don't warn about function templates. 12284 if (FD->getDescribedFunctionTemplate()) 12285 return false; 12286 12287 // Don't warn about function template specializations. 12288 if (FD->isFunctionTemplateSpecialization()) 12289 return false; 12290 12291 // Don't warn for OpenCL kernels. 12292 if (FD->hasAttr<OpenCLKernelAttr>()) 12293 return false; 12294 12295 // Don't warn on explicitly deleted functions. 12296 if (FD->isDeleted()) 12297 return false; 12298 12299 bool MissingPrototype = true; 12300 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12301 Prev; Prev = Prev->getPreviousDecl()) { 12302 // Ignore any declarations that occur in function or method 12303 // scope, because they aren't visible from the header. 12304 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12305 continue; 12306 12307 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12308 if (FD->getNumParams() == 0) 12309 PossibleZeroParamPrototype = Prev; 12310 break; 12311 } 12312 12313 return MissingPrototype; 12314 } 12315 12316 void 12317 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12318 const FunctionDecl *EffectiveDefinition, 12319 SkipBodyInfo *SkipBody) { 12320 const FunctionDecl *Definition = EffectiveDefinition; 12321 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12322 // If this is a friend function defined in a class template, it does not 12323 // have a body until it is used, nevertheless it is a definition, see 12324 // [temp.inst]p2: 12325 // 12326 // ... for the purpose of determining whether an instantiated redeclaration 12327 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12328 // corresponds to a definition in the template is considered to be a 12329 // definition. 12330 // 12331 // The following code must produce redefinition error: 12332 // 12333 // template<typename T> struct C20 { friend void func_20() {} }; 12334 // C20<int> c20i; 12335 // void func_20() {} 12336 // 12337 for (auto I : FD->redecls()) { 12338 if (I != FD && !I->isInvalidDecl() && 12339 I->getFriendObjectKind() != Decl::FOK_None) { 12340 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12341 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12342 // A merged copy of the same function, instantiated as a member of 12343 // the same class, is OK. 12344 if (declaresSameEntity(OrigFD, Original) && 12345 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12346 cast<Decl>(FD->getLexicalDeclContext()))) 12347 continue; 12348 } 12349 12350 if (Original->isThisDeclarationADefinition()) { 12351 Definition = I; 12352 break; 12353 } 12354 } 12355 } 12356 } 12357 } 12358 if (!Definition) 12359 return; 12360 12361 if (canRedefineFunction(Definition, getLangOpts())) 12362 return; 12363 12364 // Don't emit an error when this is redefinition of a typo-corrected 12365 // definition. 12366 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12367 return; 12368 12369 // If we don't have a visible definition of the function, and it's inline or 12370 // a template, skip the new definition. 12371 if (SkipBody && !hasVisibleDefinition(Definition) && 12372 (Definition->getFormalLinkage() == InternalLinkage || 12373 Definition->isInlined() || 12374 Definition->getDescribedFunctionTemplate() || 12375 Definition->getNumTemplateParameterLists())) { 12376 SkipBody->ShouldSkip = true; 12377 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12378 makeMergedDefinitionVisible(TD); 12379 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12380 return; 12381 } 12382 12383 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12384 Definition->getStorageClass() == SC_Extern) 12385 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12386 << FD->getDeclName() << getLangOpts().CPlusPlus; 12387 else 12388 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12389 12390 Diag(Definition->getLocation(), diag::note_previous_definition); 12391 FD->setInvalidDecl(); 12392 } 12393 12394 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12395 Sema &S) { 12396 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12397 12398 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12399 LSI->CallOperator = CallOperator; 12400 LSI->Lambda = LambdaClass; 12401 LSI->ReturnType = CallOperator->getReturnType(); 12402 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12403 12404 if (LCD == LCD_None) 12405 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12406 else if (LCD == LCD_ByCopy) 12407 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12408 else if (LCD == LCD_ByRef) 12409 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12410 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12411 12412 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12413 LSI->Mutable = !CallOperator->isConst(); 12414 12415 // Add the captures to the LSI so they can be noted as already 12416 // captured within tryCaptureVar. 12417 auto I = LambdaClass->field_begin(); 12418 for (const auto &C : LambdaClass->captures()) { 12419 if (C.capturesVariable()) { 12420 VarDecl *VD = C.getCapturedVar(); 12421 if (VD->isInitCapture()) 12422 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12423 QualType CaptureType = VD->getType(); 12424 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12425 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12426 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12427 /*EllipsisLoc*/C.isPackExpansion() 12428 ? C.getEllipsisLoc() : SourceLocation(), 12429 CaptureType, /*Expr*/ nullptr); 12430 12431 } else if (C.capturesThis()) { 12432 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12433 /*Expr*/ nullptr, 12434 C.getCaptureKind() == LCK_StarThis); 12435 } else { 12436 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12437 } 12438 ++I; 12439 } 12440 } 12441 12442 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12443 SkipBodyInfo *SkipBody) { 12444 if (!D) { 12445 // Parsing the function declaration failed in some way. Push on a fake scope 12446 // anyway so we can try to parse the function body. 12447 PushFunctionScope(); 12448 return D; 12449 } 12450 12451 FunctionDecl *FD = nullptr; 12452 12453 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12454 FD = FunTmpl->getTemplatedDecl(); 12455 else 12456 FD = cast<FunctionDecl>(D); 12457 12458 // Check for defining attributes before the check for redefinition. 12459 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12460 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12461 FD->dropAttr<AliasAttr>(); 12462 FD->setInvalidDecl(); 12463 } 12464 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12465 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12466 FD->dropAttr<IFuncAttr>(); 12467 FD->setInvalidDecl(); 12468 } 12469 12470 // See if this is a redefinition. If 'will have body' is already set, then 12471 // these checks were already performed when it was set. 12472 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12473 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12474 12475 // If we're skipping the body, we're done. Don't enter the scope. 12476 if (SkipBody && SkipBody->ShouldSkip) 12477 return D; 12478 } 12479 12480 // Mark this function as "will have a body eventually". This lets users to 12481 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12482 // this function. 12483 FD->setWillHaveBody(); 12484 12485 // If we are instantiating a generic lambda call operator, push 12486 // a LambdaScopeInfo onto the function stack. But use the information 12487 // that's already been calculated (ActOnLambdaExpr) to prime the current 12488 // LambdaScopeInfo. 12489 // When the template operator is being specialized, the LambdaScopeInfo, 12490 // has to be properly restored so that tryCaptureVariable doesn't try 12491 // and capture any new variables. In addition when calculating potential 12492 // captures during transformation of nested lambdas, it is necessary to 12493 // have the LSI properly restored. 12494 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12495 assert(inTemplateInstantiation() && 12496 "There should be an active template instantiation on the stack " 12497 "when instantiating a generic lambda!"); 12498 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12499 } else { 12500 // Enter a new function scope 12501 PushFunctionScope(); 12502 } 12503 12504 // Builtin functions cannot be defined. 12505 if (unsigned BuiltinID = FD->getBuiltinID()) { 12506 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12507 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12508 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12509 FD->setInvalidDecl(); 12510 } 12511 } 12512 12513 // The return type of a function definition must be complete 12514 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12515 QualType ResultType = FD->getReturnType(); 12516 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12517 !FD->isInvalidDecl() && 12518 RequireCompleteType(FD->getLocation(), ResultType, 12519 diag::err_func_def_incomplete_result)) 12520 FD->setInvalidDecl(); 12521 12522 if (FnBodyScope) 12523 PushDeclContext(FnBodyScope, FD); 12524 12525 // Check the validity of our function parameters 12526 CheckParmsForFunctionDef(FD->parameters(), 12527 /*CheckParameterNames=*/true); 12528 12529 // Add non-parameter declarations already in the function to the current 12530 // scope. 12531 if (FnBodyScope) { 12532 for (Decl *NPD : FD->decls()) { 12533 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12534 if (!NonParmDecl) 12535 continue; 12536 assert(!isa<ParmVarDecl>(NonParmDecl) && 12537 "parameters should not be in newly created FD yet"); 12538 12539 // If the decl has a name, make it accessible in the current scope. 12540 if (NonParmDecl->getDeclName()) 12541 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12542 12543 // Similarly, dive into enums and fish their constants out, making them 12544 // accessible in this scope. 12545 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12546 for (auto *EI : ED->enumerators()) 12547 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12548 } 12549 } 12550 } 12551 12552 // Introduce our parameters into the function scope 12553 for (auto Param : FD->parameters()) { 12554 Param->setOwningFunction(FD); 12555 12556 // If this has an identifier, add it to the scope stack. 12557 if (Param->getIdentifier() && FnBodyScope) { 12558 CheckShadow(FnBodyScope, Param); 12559 12560 PushOnScopeChains(Param, FnBodyScope); 12561 } 12562 } 12563 12564 // Ensure that the function's exception specification is instantiated. 12565 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12566 ResolveExceptionSpec(D->getLocation(), FPT); 12567 12568 // dllimport cannot be applied to non-inline function definitions. 12569 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12570 !FD->isTemplateInstantiation()) { 12571 assert(!FD->hasAttr<DLLExportAttr>()); 12572 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12573 FD->setInvalidDecl(); 12574 return D; 12575 } 12576 // We want to attach documentation to original Decl (which might be 12577 // a function template). 12578 ActOnDocumentableDecl(D); 12579 if (getCurLexicalContext()->isObjCContainer() && 12580 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12581 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12582 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12583 12584 return D; 12585 } 12586 12587 /// \brief Given the set of return statements within a function body, 12588 /// compute the variables that are subject to the named return value 12589 /// optimization. 12590 /// 12591 /// Each of the variables that is subject to the named return value 12592 /// optimization will be marked as NRVO variables in the AST, and any 12593 /// return statement that has a marked NRVO variable as its NRVO candidate can 12594 /// use the named return value optimization. 12595 /// 12596 /// This function applies a very simplistic algorithm for NRVO: if every return 12597 /// statement in the scope of a variable has the same NRVO candidate, that 12598 /// candidate is an NRVO variable. 12599 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12600 ReturnStmt **Returns = Scope->Returns.data(); 12601 12602 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12603 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12604 if (!NRVOCandidate->isNRVOVariable()) 12605 Returns[I]->setNRVOCandidate(nullptr); 12606 } 12607 } 12608 } 12609 12610 bool Sema::canDelayFunctionBody(const Declarator &D) { 12611 // We can't delay parsing the body of a constexpr function template (yet). 12612 if (D.getDeclSpec().isConstexprSpecified()) 12613 return false; 12614 12615 // We can't delay parsing the body of a function template with a deduced 12616 // return type (yet). 12617 if (D.getDeclSpec().hasAutoTypeSpec()) { 12618 // If the placeholder introduces a non-deduced trailing return type, 12619 // we can still delay parsing it. 12620 if (D.getNumTypeObjects()) { 12621 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12622 if (Outer.Kind == DeclaratorChunk::Function && 12623 Outer.Fun.hasTrailingReturnType()) { 12624 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12625 return Ty.isNull() || !Ty->isUndeducedType(); 12626 } 12627 } 12628 return false; 12629 } 12630 12631 return true; 12632 } 12633 12634 bool Sema::canSkipFunctionBody(Decl *D) { 12635 // We cannot skip the body of a function (or function template) which is 12636 // constexpr, since we may need to evaluate its body in order to parse the 12637 // rest of the file. 12638 // We cannot skip the body of a function with an undeduced return type, 12639 // because any callers of that function need to know the type. 12640 if (const FunctionDecl *FD = D->getAsFunction()) 12641 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12642 return false; 12643 return Consumer.shouldSkipFunctionBody(D); 12644 } 12645 12646 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12647 if (!Decl) 12648 return nullptr; 12649 if (FunctionDecl *FD = Decl->getAsFunction()) 12650 FD->setHasSkippedBody(); 12651 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 12652 MD->setHasSkippedBody(); 12653 return Decl; 12654 } 12655 12656 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12657 return ActOnFinishFunctionBody(D, BodyArg, false); 12658 } 12659 12660 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12661 bool IsInstantiation) { 12662 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12663 12664 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12665 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12666 12667 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12668 CheckCompletedCoroutineBody(FD, Body); 12669 12670 if (FD) { 12671 FD->setBody(Body); 12672 FD->setWillHaveBody(false); 12673 12674 if (getLangOpts().CPlusPlus14) { 12675 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12676 FD->getReturnType()->isUndeducedType()) { 12677 // If the function has a deduced result type but contains no 'return' 12678 // statements, the result type as written must be exactly 'auto', and 12679 // the deduced result type is 'void'. 12680 if (!FD->getReturnType()->getAs<AutoType>()) { 12681 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12682 << FD->getReturnType(); 12683 FD->setInvalidDecl(); 12684 } else { 12685 // Substitute 'void' for the 'auto' in the type. 12686 TypeLoc ResultType = getReturnTypeLoc(FD); 12687 Context.adjustDeducedFunctionResultType( 12688 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12689 } 12690 } 12691 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12692 // In C++11, we don't use 'auto' deduction rules for lambda call 12693 // operators because we don't support return type deduction. 12694 auto *LSI = getCurLambda(); 12695 if (LSI->HasImplicitReturnType) { 12696 deduceClosureReturnType(*LSI); 12697 12698 // C++11 [expr.prim.lambda]p4: 12699 // [...] if there are no return statements in the compound-statement 12700 // [the deduced type is] the type void 12701 QualType RetType = 12702 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12703 12704 // Update the return type to the deduced type. 12705 const FunctionProtoType *Proto = 12706 FD->getType()->getAs<FunctionProtoType>(); 12707 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12708 Proto->getExtProtoInfo())); 12709 } 12710 } 12711 12712 // If the function implicitly returns zero (like 'main') or is naked, 12713 // don't complain about missing return statements. 12714 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12715 WP.disableCheckFallThrough(); 12716 12717 // MSVC permits the use of pure specifier (=0) on function definition, 12718 // defined at class scope, warn about this non-standard construct. 12719 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12720 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12721 12722 if (!FD->isInvalidDecl()) { 12723 // Don't diagnose unused parameters of defaulted or deleted functions. 12724 if (!FD->isDeleted() && !FD->isDefaulted()) 12725 DiagnoseUnusedParameters(FD->parameters()); 12726 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12727 FD->getReturnType(), FD); 12728 12729 // If this is a structor, we need a vtable. 12730 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12731 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12732 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12733 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12734 12735 // Try to apply the named return value optimization. We have to check 12736 // if we can do this here because lambdas keep return statements around 12737 // to deduce an implicit return type. 12738 if (FD->getReturnType()->isRecordType() && 12739 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 12740 computeNRVO(Body, getCurFunction()); 12741 } 12742 12743 // GNU warning -Wmissing-prototypes: 12744 // Warn if a global function is defined without a previous 12745 // prototype declaration. This warning is issued even if the 12746 // definition itself provides a prototype. The aim is to detect 12747 // global functions that fail to be declared in header files. 12748 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12749 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12750 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12751 12752 if (PossibleZeroParamPrototype) { 12753 // We found a declaration that is not a prototype, 12754 // but that could be a zero-parameter prototype 12755 if (TypeSourceInfo *TI = 12756 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12757 TypeLoc TL = TI->getTypeLoc(); 12758 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12759 Diag(PossibleZeroParamPrototype->getLocation(), 12760 diag::note_declaration_not_a_prototype) 12761 << PossibleZeroParamPrototype 12762 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12763 } 12764 } 12765 12766 // GNU warning -Wstrict-prototypes 12767 // Warn if K&R function is defined without a previous declaration. 12768 // This warning is issued only if the definition itself does not provide 12769 // a prototype. Only K&R definitions do not provide a prototype. 12770 // An empty list in a function declarator that is part of a definition 12771 // of that function specifies that the function has no parameters 12772 // (C99 6.7.5.3p14) 12773 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12774 !LangOpts.CPlusPlus) { 12775 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12776 TypeLoc TL = TI->getTypeLoc(); 12777 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12778 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12779 } 12780 } 12781 12782 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12783 const CXXMethodDecl *KeyFunction; 12784 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12785 MD->isVirtual() && 12786 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12787 MD == KeyFunction->getCanonicalDecl()) { 12788 // Update the key-function state if necessary for this ABI. 12789 if (FD->isInlined() && 12790 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12791 Context.setNonKeyFunction(MD); 12792 12793 // If the newly-chosen key function is already defined, then we 12794 // need to mark the vtable as used retroactively. 12795 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12796 const FunctionDecl *Definition; 12797 if (KeyFunction && KeyFunction->isDefined(Definition)) 12798 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12799 } else { 12800 // We just defined they key function; mark the vtable as used. 12801 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12802 } 12803 } 12804 } 12805 12806 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12807 "Function parsing confused"); 12808 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12809 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12810 MD->setBody(Body); 12811 if (!MD->isInvalidDecl()) { 12812 DiagnoseUnusedParameters(MD->parameters()); 12813 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12814 MD->getReturnType(), MD); 12815 12816 if (Body) 12817 computeNRVO(Body, getCurFunction()); 12818 } 12819 if (getCurFunction()->ObjCShouldCallSuper) { 12820 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12821 << MD->getSelector().getAsString(); 12822 getCurFunction()->ObjCShouldCallSuper = false; 12823 } 12824 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12825 const ObjCMethodDecl *InitMethod = nullptr; 12826 bool isDesignated = 12827 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12828 assert(isDesignated && InitMethod); 12829 (void)isDesignated; 12830 12831 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12832 auto IFace = MD->getClassInterface(); 12833 if (!IFace) 12834 return false; 12835 auto SuperD = IFace->getSuperClass(); 12836 if (!SuperD) 12837 return false; 12838 return SuperD->getIdentifier() == 12839 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12840 }; 12841 // Don't issue this warning for unavailable inits or direct subclasses 12842 // of NSObject. 12843 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12844 Diag(MD->getLocation(), 12845 diag::warn_objc_designated_init_missing_super_call); 12846 Diag(InitMethod->getLocation(), 12847 diag::note_objc_designated_init_marked_here); 12848 } 12849 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12850 } 12851 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12852 // Don't issue this warning for unavaialable inits. 12853 if (!MD->isUnavailable()) 12854 Diag(MD->getLocation(), 12855 diag::warn_objc_secondary_init_missing_init_call); 12856 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12857 } 12858 } else { 12859 // Parsing the function declaration failed in some way. Pop the fake scope 12860 // we pushed on. 12861 PopFunctionScopeInfo(ActivePolicy, dcl); 12862 return nullptr; 12863 } 12864 12865 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12866 DiagnoseUnguardedAvailabilityViolations(dcl); 12867 12868 assert(!getCurFunction()->ObjCShouldCallSuper && 12869 "This should only be set for ObjC methods, which should have been " 12870 "handled in the block above."); 12871 12872 // Verify and clean out per-function state. 12873 if (Body && (!FD || !FD->isDefaulted())) { 12874 // C++ constructors that have function-try-blocks can't have return 12875 // statements in the handlers of that block. (C++ [except.handle]p14) 12876 // Verify this. 12877 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12878 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12879 12880 // Verify that gotos and switch cases don't jump into scopes illegally. 12881 if (getCurFunction()->NeedsScopeChecking() && 12882 !PP.isCodeCompletionEnabled()) 12883 DiagnoseInvalidJumps(Body); 12884 12885 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12886 if (!Destructor->getParent()->isDependentType()) 12887 CheckDestructor(Destructor); 12888 12889 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12890 Destructor->getParent()); 12891 } 12892 12893 // If any errors have occurred, clear out any temporaries that may have 12894 // been leftover. This ensures that these temporaries won't be picked up for 12895 // deletion in some later function. 12896 if (getDiagnostics().hasErrorOccurred() || 12897 getDiagnostics().getSuppressAllDiagnostics()) { 12898 DiscardCleanupsInEvaluationContext(); 12899 } 12900 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12901 !isa<FunctionTemplateDecl>(dcl)) { 12902 // Since the body is valid, issue any analysis-based warnings that are 12903 // enabled. 12904 ActivePolicy = &WP; 12905 } 12906 12907 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12908 (!CheckConstexprFunctionDecl(FD) || 12909 !CheckConstexprFunctionBody(FD, Body))) 12910 FD->setInvalidDecl(); 12911 12912 if (FD && FD->hasAttr<NakedAttr>()) { 12913 for (const Stmt *S : Body->children()) { 12914 // Allow local register variables without initializer as they don't 12915 // require prologue. 12916 bool RegisterVariables = false; 12917 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12918 for (const auto *Decl : DS->decls()) { 12919 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12920 RegisterVariables = 12921 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12922 if (!RegisterVariables) 12923 break; 12924 } 12925 } 12926 } 12927 if (RegisterVariables) 12928 continue; 12929 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12930 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12931 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12932 FD->setInvalidDecl(); 12933 break; 12934 } 12935 } 12936 } 12937 12938 assert(ExprCleanupObjects.size() == 12939 ExprEvalContexts.back().NumCleanupObjects && 12940 "Leftover temporaries in function"); 12941 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12942 assert(MaybeODRUseExprs.empty() && 12943 "Leftover expressions for odr-use checking"); 12944 } 12945 12946 if (!IsInstantiation) 12947 PopDeclContext(); 12948 12949 PopFunctionScopeInfo(ActivePolicy, dcl); 12950 // If any errors have occurred, clear out any temporaries that may have 12951 // been leftover. This ensures that these temporaries won't be picked up for 12952 // deletion in some later function. 12953 if (getDiagnostics().hasErrorOccurred()) { 12954 DiscardCleanupsInEvaluationContext(); 12955 } 12956 12957 return dcl; 12958 } 12959 12960 /// When we finish delayed parsing of an attribute, we must attach it to the 12961 /// relevant Decl. 12962 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12963 ParsedAttributes &Attrs) { 12964 // Always attach attributes to the underlying decl. 12965 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12966 D = TD->getTemplatedDecl(); 12967 ProcessDeclAttributeList(S, D, Attrs.getList()); 12968 12969 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12970 if (Method->isStatic()) 12971 checkThisInStaticMemberFunctionAttributes(Method); 12972 } 12973 12974 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12975 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12976 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12977 IdentifierInfo &II, Scope *S) { 12978 // Find the scope in which the identifier is injected and the corresponding 12979 // DeclContext. 12980 // FIXME: C89 does not say what happens if there is no enclosing block scope. 12981 // In that case, we inject the declaration into the translation unit scope 12982 // instead. 12983 Scope *BlockScope = S; 12984 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 12985 BlockScope = BlockScope->getParent(); 12986 12987 Scope *ContextScope = BlockScope; 12988 while (!ContextScope->getEntity()) 12989 ContextScope = ContextScope->getParent(); 12990 ContextRAII SavedContext(*this, ContextScope->getEntity()); 12991 12992 // Before we produce a declaration for an implicitly defined 12993 // function, see whether there was a locally-scoped declaration of 12994 // this name as a function or variable. If so, use that 12995 // (non-visible) declaration, and complain about it. 12996 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 12997 if (ExternCPrev) { 12998 // We still need to inject the function into the enclosing block scope so 12999 // that later (non-call) uses can see it. 13000 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13001 13002 // C89 footnote 38: 13003 // If in fact it is not defined as having type "function returning int", 13004 // the behavior is undefined. 13005 if (!isa<FunctionDecl>(ExternCPrev) || 13006 !Context.typesAreCompatible( 13007 cast<FunctionDecl>(ExternCPrev)->getType(), 13008 Context.getFunctionNoProtoType(Context.IntTy))) { 13009 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13010 << ExternCPrev << !getLangOpts().C99; 13011 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13012 return ExternCPrev; 13013 } 13014 } 13015 13016 // Extension in C99. Legal in C90, but warn about it. 13017 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13018 unsigned diag_id; 13019 if (II.getName().startswith("__builtin_")) 13020 diag_id = diag::warn_builtin_unknown; 13021 else if (getLangOpts().C99 || getLangOpts().OpenCL) 13022 diag_id = diag::ext_implicit_function_decl; 13023 else 13024 diag_id = diag::warn_implicit_function_decl; 13025 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL; 13026 13027 // If we found a prior declaration of this function, don't bother building 13028 // another one. We've already pushed that one into scope, so there's nothing 13029 // more to do. 13030 if (ExternCPrev) 13031 return ExternCPrev; 13032 13033 // Because typo correction is expensive, only do it if the implicit 13034 // function declaration is going to be treated as an error. 13035 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13036 TypoCorrection Corrected; 13037 if (S && 13038 (Corrected = CorrectTypo( 13039 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 13040 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 13041 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13042 /*ErrorRecovery*/false); 13043 } 13044 13045 // Set a Declarator for the implicit definition: int foo(); 13046 const char *Dummy; 13047 AttributeFactory attrFactory; 13048 DeclSpec DS(attrFactory); 13049 unsigned DiagID; 13050 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13051 Context.getPrintingPolicy()); 13052 (void)Error; // Silence warning. 13053 assert(!Error && "Error setting up implicit decl!"); 13054 SourceLocation NoLoc; 13055 Declarator D(DS, DeclaratorContext::BlockContext); 13056 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13057 /*IsAmbiguous=*/false, 13058 /*LParenLoc=*/NoLoc, 13059 /*Params=*/nullptr, 13060 /*NumParams=*/0, 13061 /*EllipsisLoc=*/NoLoc, 13062 /*RParenLoc=*/NoLoc, 13063 /*TypeQuals=*/0, 13064 /*RefQualifierIsLvalueRef=*/true, 13065 /*RefQualifierLoc=*/NoLoc, 13066 /*ConstQualifierLoc=*/NoLoc, 13067 /*VolatileQualifierLoc=*/NoLoc, 13068 /*RestrictQualifierLoc=*/NoLoc, 13069 /*MutableLoc=*/NoLoc, 13070 EST_None, 13071 /*ESpecRange=*/SourceRange(), 13072 /*Exceptions=*/nullptr, 13073 /*ExceptionRanges=*/nullptr, 13074 /*NumExceptions=*/0, 13075 /*NoexceptExpr=*/nullptr, 13076 /*ExceptionSpecTokens=*/nullptr, 13077 /*DeclsInPrototype=*/None, 13078 Loc, Loc, D), 13079 DS.getAttributes(), 13080 SourceLocation()); 13081 D.SetIdentifier(&II, Loc); 13082 13083 // Insert this function into the enclosing block scope. 13084 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13085 FD->setImplicit(); 13086 13087 AddKnownFunctionAttributes(FD); 13088 13089 return FD; 13090 } 13091 13092 /// \brief Adds any function attributes that we know a priori based on 13093 /// the declaration of this function. 13094 /// 13095 /// These attributes can apply both to implicitly-declared builtins 13096 /// (like __builtin___printf_chk) or to library-declared functions 13097 /// like NSLog or printf. 13098 /// 13099 /// We need to check for duplicate attributes both here and where user-written 13100 /// attributes are applied to declarations. 13101 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13102 if (FD->isInvalidDecl()) 13103 return; 13104 13105 // If this is a built-in function, map its builtin attributes to 13106 // actual attributes. 13107 if (unsigned BuiltinID = FD->getBuiltinID()) { 13108 // Handle printf-formatting attributes. 13109 unsigned FormatIdx; 13110 bool HasVAListArg; 13111 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13112 if (!FD->hasAttr<FormatAttr>()) { 13113 const char *fmt = "printf"; 13114 unsigned int NumParams = FD->getNumParams(); 13115 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13116 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13117 fmt = "NSString"; 13118 FD->addAttr(FormatAttr::CreateImplicit(Context, 13119 &Context.Idents.get(fmt), 13120 FormatIdx+1, 13121 HasVAListArg ? 0 : FormatIdx+2, 13122 FD->getLocation())); 13123 } 13124 } 13125 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13126 HasVAListArg)) { 13127 if (!FD->hasAttr<FormatAttr>()) 13128 FD->addAttr(FormatAttr::CreateImplicit(Context, 13129 &Context.Idents.get("scanf"), 13130 FormatIdx+1, 13131 HasVAListArg ? 0 : FormatIdx+2, 13132 FD->getLocation())); 13133 } 13134 13135 // Mark const if we don't care about errno and that is the only thing 13136 // preventing the function from being const. This allows IRgen to use LLVM 13137 // intrinsics for such functions. 13138 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13139 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13140 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13141 13142 // We make "fma" on some platforms const because we know it does not set 13143 // errno in those environments even though it could set errno based on the 13144 // C standard. 13145 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13146 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13147 !FD->hasAttr<ConstAttr>()) { 13148 switch (BuiltinID) { 13149 case Builtin::BI__builtin_fma: 13150 case Builtin::BI__builtin_fmaf: 13151 case Builtin::BI__builtin_fmal: 13152 case Builtin::BIfma: 13153 case Builtin::BIfmaf: 13154 case Builtin::BIfmal: 13155 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13156 break; 13157 default: 13158 break; 13159 } 13160 } 13161 13162 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13163 !FD->hasAttr<ReturnsTwiceAttr>()) 13164 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13165 FD->getLocation())); 13166 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13167 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13168 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13169 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13170 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13171 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13172 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13173 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13174 // Add the appropriate attribute, depending on the CUDA compilation mode 13175 // and which target the builtin belongs to. For example, during host 13176 // compilation, aux builtins are __device__, while the rest are __host__. 13177 if (getLangOpts().CUDAIsDevice != 13178 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13179 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13180 else 13181 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13182 } 13183 } 13184 13185 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13186 // throw, add an implicit nothrow attribute to any extern "C" function we come 13187 // across. 13188 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13189 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13190 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13191 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13192 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13193 } 13194 13195 IdentifierInfo *Name = FD->getIdentifier(); 13196 if (!Name) 13197 return; 13198 if ((!getLangOpts().CPlusPlus && 13199 FD->getDeclContext()->isTranslationUnit()) || 13200 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13201 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13202 LinkageSpecDecl::lang_c)) { 13203 // Okay: this could be a libc/libm/Objective-C function we know 13204 // about. 13205 } else 13206 return; 13207 13208 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13209 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13210 // target-specific builtins, perhaps? 13211 if (!FD->hasAttr<FormatAttr>()) 13212 FD->addAttr(FormatAttr::CreateImplicit(Context, 13213 &Context.Idents.get("printf"), 2, 13214 Name->isStr("vasprintf") ? 0 : 3, 13215 FD->getLocation())); 13216 } 13217 13218 if (Name->isStr("__CFStringMakeConstantString")) { 13219 // We already have a __builtin___CFStringMakeConstantString, 13220 // but builds that use -fno-constant-cfstrings don't go through that. 13221 if (!FD->hasAttr<FormatArgAttr>()) 13222 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13223 FD->getLocation())); 13224 } 13225 } 13226 13227 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13228 TypeSourceInfo *TInfo) { 13229 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13230 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13231 13232 if (!TInfo) { 13233 assert(D.isInvalidType() && "no declarator info for valid type"); 13234 TInfo = Context.getTrivialTypeSourceInfo(T); 13235 } 13236 13237 // Scope manipulation handled by caller. 13238 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 13239 D.getLocStart(), 13240 D.getIdentifierLoc(), 13241 D.getIdentifier(), 13242 TInfo); 13243 13244 // Bail out immediately if we have an invalid declaration. 13245 if (D.isInvalidType()) { 13246 NewTD->setInvalidDecl(); 13247 return NewTD; 13248 } 13249 13250 if (D.getDeclSpec().isModulePrivateSpecified()) { 13251 if (CurContext->isFunctionOrMethod()) 13252 Diag(NewTD->getLocation(), diag::err_module_private_local) 13253 << 2 << NewTD->getDeclName() 13254 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13255 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13256 else 13257 NewTD->setModulePrivate(); 13258 } 13259 13260 // C++ [dcl.typedef]p8: 13261 // If the typedef declaration defines an unnamed class (or 13262 // enum), the first typedef-name declared by the declaration 13263 // to be that class type (or enum type) is used to denote the 13264 // class type (or enum type) for linkage purposes only. 13265 // We need to check whether the type was declared in the declaration. 13266 switch (D.getDeclSpec().getTypeSpecType()) { 13267 case TST_enum: 13268 case TST_struct: 13269 case TST_interface: 13270 case TST_union: 13271 case TST_class: { 13272 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13273 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13274 break; 13275 } 13276 13277 default: 13278 break; 13279 } 13280 13281 return NewTD; 13282 } 13283 13284 /// \brief Check that this is a valid underlying type for an enum declaration. 13285 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13286 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13287 QualType T = TI->getType(); 13288 13289 if (T->isDependentType()) 13290 return false; 13291 13292 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13293 if (BT->isInteger()) 13294 return false; 13295 13296 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13297 return true; 13298 } 13299 13300 /// Check whether this is a valid redeclaration of a previous enumeration. 13301 /// \return true if the redeclaration was invalid. 13302 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13303 QualType EnumUnderlyingTy, bool IsFixed, 13304 const EnumDecl *Prev) { 13305 if (IsScoped != Prev->isScoped()) { 13306 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13307 << Prev->isScoped(); 13308 Diag(Prev->getLocation(), diag::note_previous_declaration); 13309 return true; 13310 } 13311 13312 if (IsFixed && Prev->isFixed()) { 13313 if (!EnumUnderlyingTy->isDependentType() && 13314 !Prev->getIntegerType()->isDependentType() && 13315 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13316 Prev->getIntegerType())) { 13317 // TODO: Highlight the underlying type of the redeclaration. 13318 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13319 << EnumUnderlyingTy << Prev->getIntegerType(); 13320 Diag(Prev->getLocation(), diag::note_previous_declaration) 13321 << Prev->getIntegerTypeRange(); 13322 return true; 13323 } 13324 } else if (IsFixed != Prev->isFixed()) { 13325 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13326 << Prev->isFixed(); 13327 Diag(Prev->getLocation(), diag::note_previous_declaration); 13328 return true; 13329 } 13330 13331 return false; 13332 } 13333 13334 /// \brief Get diagnostic %select index for tag kind for 13335 /// redeclaration diagnostic message. 13336 /// WARNING: Indexes apply to particular diagnostics only! 13337 /// 13338 /// \returns diagnostic %select index. 13339 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13340 switch (Tag) { 13341 case TTK_Struct: return 0; 13342 case TTK_Interface: return 1; 13343 case TTK_Class: return 2; 13344 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13345 } 13346 } 13347 13348 /// \brief Determine if tag kind is a class-key compatible with 13349 /// class for redeclaration (class, struct, or __interface). 13350 /// 13351 /// \returns true iff the tag kind is compatible. 13352 static bool isClassCompatTagKind(TagTypeKind Tag) 13353 { 13354 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13355 } 13356 13357 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13358 TagTypeKind TTK) { 13359 if (isa<TypedefDecl>(PrevDecl)) 13360 return NTK_Typedef; 13361 else if (isa<TypeAliasDecl>(PrevDecl)) 13362 return NTK_TypeAlias; 13363 else if (isa<ClassTemplateDecl>(PrevDecl)) 13364 return NTK_Template; 13365 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13366 return NTK_TypeAliasTemplate; 13367 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13368 return NTK_TemplateTemplateArgument; 13369 switch (TTK) { 13370 case TTK_Struct: 13371 case TTK_Interface: 13372 case TTK_Class: 13373 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13374 case TTK_Union: 13375 return NTK_NonUnion; 13376 case TTK_Enum: 13377 return NTK_NonEnum; 13378 } 13379 llvm_unreachable("invalid TTK"); 13380 } 13381 13382 /// \brief Determine whether a tag with a given kind is acceptable 13383 /// as a redeclaration of the given tag declaration. 13384 /// 13385 /// \returns true if the new tag kind is acceptable, false otherwise. 13386 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13387 TagTypeKind NewTag, bool isDefinition, 13388 SourceLocation NewTagLoc, 13389 const IdentifierInfo *Name) { 13390 // C++ [dcl.type.elab]p3: 13391 // The class-key or enum keyword present in the 13392 // elaborated-type-specifier shall agree in kind with the 13393 // declaration to which the name in the elaborated-type-specifier 13394 // refers. This rule also applies to the form of 13395 // elaborated-type-specifier that declares a class-name or 13396 // friend class since it can be construed as referring to the 13397 // definition of the class. Thus, in any 13398 // elaborated-type-specifier, the enum keyword shall be used to 13399 // refer to an enumeration (7.2), the union class-key shall be 13400 // used to refer to a union (clause 9), and either the class or 13401 // struct class-key shall be used to refer to a class (clause 9) 13402 // declared using the class or struct class-key. 13403 TagTypeKind OldTag = Previous->getTagKind(); 13404 if (!isDefinition || !isClassCompatTagKind(NewTag)) 13405 if (OldTag == NewTag) 13406 return true; 13407 13408 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13409 // Warn about the struct/class tag mismatch. 13410 bool isTemplate = false; 13411 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13412 isTemplate = Record->getDescribedClassTemplate(); 13413 13414 if (inTemplateInstantiation()) { 13415 // In a template instantiation, do not offer fix-its for tag mismatches 13416 // since they usually mess up the template instead of fixing the problem. 13417 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13418 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13419 << getRedeclDiagFromTagKind(OldTag); 13420 return true; 13421 } 13422 13423 if (isDefinition) { 13424 // On definitions, check previous tags and issue a fix-it for each 13425 // one that doesn't match the current tag. 13426 if (Previous->getDefinition()) { 13427 // Don't suggest fix-its for redefinitions. 13428 return true; 13429 } 13430 13431 bool previousMismatch = false; 13432 for (auto I : Previous->redecls()) { 13433 if (I->getTagKind() != NewTag) { 13434 if (!previousMismatch) { 13435 previousMismatch = true; 13436 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13437 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13438 << getRedeclDiagFromTagKind(I->getTagKind()); 13439 } 13440 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13441 << getRedeclDiagFromTagKind(NewTag) 13442 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13443 TypeWithKeyword::getTagTypeKindName(NewTag)); 13444 } 13445 } 13446 return true; 13447 } 13448 13449 // Check for a previous definition. If current tag and definition 13450 // are same type, do nothing. If no definition, but disagree with 13451 // with previous tag type, give a warning, but no fix-it. 13452 const TagDecl *Redecl = Previous->getDefinition() ? 13453 Previous->getDefinition() : Previous; 13454 if (Redecl->getTagKind() == NewTag) { 13455 return true; 13456 } 13457 13458 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13459 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13460 << getRedeclDiagFromTagKind(OldTag); 13461 Diag(Redecl->getLocation(), diag::note_previous_use); 13462 13463 // If there is a previous definition, suggest a fix-it. 13464 if (Previous->getDefinition()) { 13465 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13466 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13467 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13468 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13469 } 13470 13471 return true; 13472 } 13473 return false; 13474 } 13475 13476 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13477 /// from an outer enclosing namespace or file scope inside a friend declaration. 13478 /// This should provide the commented out code in the following snippet: 13479 /// namespace N { 13480 /// struct X; 13481 /// namespace M { 13482 /// struct Y { friend struct /*N::*/ X; }; 13483 /// } 13484 /// } 13485 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13486 SourceLocation NameLoc) { 13487 // While the decl is in a namespace, do repeated lookup of that name and see 13488 // if we get the same namespace back. If we do not, continue until 13489 // translation unit scope, at which point we have a fully qualified NNS. 13490 SmallVector<IdentifierInfo *, 4> Namespaces; 13491 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13492 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13493 // This tag should be declared in a namespace, which can only be enclosed by 13494 // other namespaces. Bail if there's an anonymous namespace in the chain. 13495 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13496 if (!Namespace || Namespace->isAnonymousNamespace()) 13497 return FixItHint(); 13498 IdentifierInfo *II = Namespace->getIdentifier(); 13499 Namespaces.push_back(II); 13500 NamedDecl *Lookup = SemaRef.LookupSingleName( 13501 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13502 if (Lookup == Namespace) 13503 break; 13504 } 13505 13506 // Once we have all the namespaces, reverse them to go outermost first, and 13507 // build an NNS. 13508 SmallString<64> Insertion; 13509 llvm::raw_svector_ostream OS(Insertion); 13510 if (DC->isTranslationUnit()) 13511 OS << "::"; 13512 std::reverse(Namespaces.begin(), Namespaces.end()); 13513 for (auto *II : Namespaces) 13514 OS << II->getName() << "::"; 13515 return FixItHint::CreateInsertion(NameLoc, Insertion); 13516 } 13517 13518 /// \brief Determine whether a tag originally declared in context \p OldDC can 13519 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 13520 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13521 /// using-declaration). 13522 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13523 DeclContext *NewDC) { 13524 OldDC = OldDC->getRedeclContext(); 13525 NewDC = NewDC->getRedeclContext(); 13526 13527 if (OldDC->Equals(NewDC)) 13528 return true; 13529 13530 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13531 // encloses the other). 13532 if (S.getLangOpts().MSVCCompat && 13533 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13534 return true; 13535 13536 return false; 13537 } 13538 13539 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13540 /// former case, Name will be non-null. In the later case, Name will be null. 13541 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13542 /// reference/declaration/definition of a tag. 13543 /// 13544 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13545 /// trailing-type-specifier) other than one in an alias-declaration. 13546 /// 13547 /// \param SkipBody If non-null, will be set to indicate if the caller should 13548 /// skip the definition of this tag and treat it as if it were a declaration. 13549 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13550 SourceLocation KWLoc, CXXScopeSpec &SS, 13551 IdentifierInfo *Name, SourceLocation NameLoc, 13552 AttributeList *Attr, AccessSpecifier AS, 13553 SourceLocation ModulePrivateLoc, 13554 MultiTemplateParamsArg TemplateParameterLists, 13555 bool &OwnedDecl, bool &IsDependent, 13556 SourceLocation ScopedEnumKWLoc, 13557 bool ScopedEnumUsesClassTag, 13558 TypeResult UnderlyingType, 13559 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13560 SkipBodyInfo *SkipBody) { 13561 // If this is not a definition, it must have a name. 13562 IdentifierInfo *OrigName = Name; 13563 assert((Name != nullptr || TUK == TUK_Definition) && 13564 "Nameless record must be a definition!"); 13565 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13566 13567 OwnedDecl = false; 13568 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13569 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13570 13571 // FIXME: Check member specializations more carefully. 13572 bool isMemberSpecialization = false; 13573 bool Invalid = false; 13574 13575 // We only need to do this matching if we have template parameters 13576 // or a scope specifier, which also conveniently avoids this work 13577 // for non-C++ cases. 13578 if (TemplateParameterLists.size() > 0 || 13579 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13580 if (TemplateParameterList *TemplateParams = 13581 MatchTemplateParametersToScopeSpecifier( 13582 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13583 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13584 if (Kind == TTK_Enum) { 13585 Diag(KWLoc, diag::err_enum_template); 13586 return nullptr; 13587 } 13588 13589 if (TemplateParams->size() > 0) { 13590 // This is a declaration or definition of a class template (which may 13591 // be a member of another template). 13592 13593 if (Invalid) 13594 return nullptr; 13595 13596 OwnedDecl = false; 13597 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13598 SS, Name, NameLoc, Attr, 13599 TemplateParams, AS, 13600 ModulePrivateLoc, 13601 /*FriendLoc*/SourceLocation(), 13602 TemplateParameterLists.size()-1, 13603 TemplateParameterLists.data(), 13604 SkipBody); 13605 return Result.get(); 13606 } else { 13607 // The "template<>" header is extraneous. 13608 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13609 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13610 isMemberSpecialization = true; 13611 } 13612 } 13613 } 13614 13615 // Figure out the underlying type if this a enum declaration. We need to do 13616 // this early, because it's needed to detect if this is an incompatible 13617 // redeclaration. 13618 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13619 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 13620 13621 if (Kind == TTK_Enum) { 13622 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 13623 // No underlying type explicitly specified, or we failed to parse the 13624 // type, default to int. 13625 EnumUnderlying = Context.IntTy.getTypePtr(); 13626 } else if (UnderlyingType.get()) { 13627 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13628 // integral type; any cv-qualification is ignored. 13629 TypeSourceInfo *TI = nullptr; 13630 GetTypeFromParser(UnderlyingType.get(), &TI); 13631 EnumUnderlying = TI; 13632 13633 if (CheckEnumUnderlyingType(TI)) 13634 // Recover by falling back to int. 13635 EnumUnderlying = Context.IntTy.getTypePtr(); 13636 13637 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13638 UPPC_FixedUnderlyingType)) 13639 EnumUnderlying = Context.IntTy.getTypePtr(); 13640 13641 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13642 // For MSVC ABI compatibility, unfixed enums must use an underlying type 13643 // of 'int'. However, if this is an unfixed forward declaration, don't set 13644 // the underlying type unless the user enables -fms-compatibility. This 13645 // makes unfixed forward declared enums incomplete and is more conforming. 13646 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 13647 EnumUnderlying = Context.IntTy.getTypePtr(); 13648 } 13649 } 13650 13651 DeclContext *SearchDC = CurContext; 13652 DeclContext *DC = CurContext; 13653 bool isStdBadAlloc = false; 13654 bool isStdAlignValT = false; 13655 13656 RedeclarationKind Redecl = forRedeclarationInCurContext(); 13657 if (TUK == TUK_Friend || TUK == TUK_Reference) 13658 Redecl = NotForRedeclaration; 13659 13660 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13661 /// implemented asks for structural equivalence checking, the returned decl 13662 /// here is passed back to the parser, allowing the tag body to be parsed. 13663 auto createTagFromNewDecl = [&]() -> TagDecl * { 13664 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13665 // If there is an identifier, use the location of the identifier as the 13666 // location of the decl, otherwise use the location of the struct/union 13667 // keyword. 13668 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13669 TagDecl *New = nullptr; 13670 13671 if (Kind == TTK_Enum) { 13672 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13673 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 13674 // If this is an undefined enum, bail. 13675 if (TUK != TUK_Definition && !Invalid) 13676 return nullptr; 13677 if (EnumUnderlying) { 13678 EnumDecl *ED = cast<EnumDecl>(New); 13679 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13680 ED->setIntegerTypeSourceInfo(TI); 13681 else 13682 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13683 ED->setPromotionType(ED->getIntegerType()); 13684 } 13685 } else { // struct/union 13686 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13687 nullptr); 13688 } 13689 13690 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13691 // Add alignment attributes if necessary; these attributes are checked 13692 // when the ASTContext lays out the structure. 13693 // 13694 // It is important for implementing the correct semantics that this 13695 // happen here (in ActOnTag). The #pragma pack stack is 13696 // maintained as a result of parser callbacks which can occur at 13697 // many points during the parsing of a struct declaration (because 13698 // the #pragma tokens are effectively skipped over during the 13699 // parsing of the struct). 13700 if (TUK == TUK_Definition) { 13701 AddAlignmentAttributesForRecord(RD); 13702 AddMsStructLayoutForRecord(RD); 13703 } 13704 } 13705 New->setLexicalDeclContext(CurContext); 13706 return New; 13707 }; 13708 13709 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13710 if (Name && SS.isNotEmpty()) { 13711 // We have a nested-name tag ('struct foo::bar'). 13712 13713 // Check for invalid 'foo::'. 13714 if (SS.isInvalid()) { 13715 Name = nullptr; 13716 goto CreateNewDecl; 13717 } 13718 13719 // If this is a friend or a reference to a class in a dependent 13720 // context, don't try to make a decl for it. 13721 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13722 DC = computeDeclContext(SS, false); 13723 if (!DC) { 13724 IsDependent = true; 13725 return nullptr; 13726 } 13727 } else { 13728 DC = computeDeclContext(SS, true); 13729 if (!DC) { 13730 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13731 << SS.getRange(); 13732 return nullptr; 13733 } 13734 } 13735 13736 if (RequireCompleteDeclContext(SS, DC)) 13737 return nullptr; 13738 13739 SearchDC = DC; 13740 // Look-up name inside 'foo::'. 13741 LookupQualifiedName(Previous, DC); 13742 13743 if (Previous.isAmbiguous()) 13744 return nullptr; 13745 13746 if (Previous.empty()) { 13747 // Name lookup did not find anything. However, if the 13748 // nested-name-specifier refers to the current instantiation, 13749 // and that current instantiation has any dependent base 13750 // classes, we might find something at instantiation time: treat 13751 // this as a dependent elaborated-type-specifier. 13752 // But this only makes any sense for reference-like lookups. 13753 if (Previous.wasNotFoundInCurrentInstantiation() && 13754 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13755 IsDependent = true; 13756 return nullptr; 13757 } 13758 13759 // A tag 'foo::bar' must already exist. 13760 Diag(NameLoc, diag::err_not_tag_in_scope) 13761 << Kind << Name << DC << SS.getRange(); 13762 Name = nullptr; 13763 Invalid = true; 13764 goto CreateNewDecl; 13765 } 13766 } else if (Name) { 13767 // C++14 [class.mem]p14: 13768 // If T is the name of a class, then each of the following shall have a 13769 // name different from T: 13770 // -- every member of class T that is itself a type 13771 if (TUK != TUK_Reference && TUK != TUK_Friend && 13772 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13773 return nullptr; 13774 13775 // If this is a named struct, check to see if there was a previous forward 13776 // declaration or definition. 13777 // FIXME: We're looking into outer scopes here, even when we 13778 // shouldn't be. Doing so can result in ambiguities that we 13779 // shouldn't be diagnosing. 13780 LookupName(Previous, S); 13781 13782 // When declaring or defining a tag, ignore ambiguities introduced 13783 // by types using'ed into this scope. 13784 if (Previous.isAmbiguous() && 13785 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13786 LookupResult::Filter F = Previous.makeFilter(); 13787 while (F.hasNext()) { 13788 NamedDecl *ND = F.next(); 13789 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13790 SearchDC->getRedeclContext())) 13791 F.erase(); 13792 } 13793 F.done(); 13794 } 13795 13796 // C++11 [namespace.memdef]p3: 13797 // If the name in a friend declaration is neither qualified nor 13798 // a template-id and the declaration is a function or an 13799 // elaborated-type-specifier, the lookup to determine whether 13800 // the entity has been previously declared shall not consider 13801 // any scopes outside the innermost enclosing namespace. 13802 // 13803 // MSVC doesn't implement the above rule for types, so a friend tag 13804 // declaration may be a redeclaration of a type declared in an enclosing 13805 // scope. They do implement this rule for friend functions. 13806 // 13807 // Does it matter that this should be by scope instead of by 13808 // semantic context? 13809 if (!Previous.empty() && TUK == TUK_Friend) { 13810 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13811 LookupResult::Filter F = Previous.makeFilter(); 13812 bool FriendSawTagOutsideEnclosingNamespace = false; 13813 while (F.hasNext()) { 13814 NamedDecl *ND = F.next(); 13815 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13816 if (DC->isFileContext() && 13817 !EnclosingNS->Encloses(ND->getDeclContext())) { 13818 if (getLangOpts().MSVCCompat) 13819 FriendSawTagOutsideEnclosingNamespace = true; 13820 else 13821 F.erase(); 13822 } 13823 } 13824 F.done(); 13825 13826 // Diagnose this MSVC extension in the easy case where lookup would have 13827 // unambiguously found something outside the enclosing namespace. 13828 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13829 NamedDecl *ND = Previous.getFoundDecl(); 13830 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13831 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13832 } 13833 } 13834 13835 // Note: there used to be some attempt at recovery here. 13836 if (Previous.isAmbiguous()) 13837 return nullptr; 13838 13839 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13840 // FIXME: This makes sure that we ignore the contexts associated 13841 // with C structs, unions, and enums when looking for a matching 13842 // tag declaration or definition. See the similar lookup tweak 13843 // in Sema::LookupName; is there a better way to deal with this? 13844 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13845 SearchDC = SearchDC->getParent(); 13846 } 13847 } 13848 13849 if (Previous.isSingleResult() && 13850 Previous.getFoundDecl()->isTemplateParameter()) { 13851 // Maybe we will complain about the shadowed template parameter. 13852 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13853 // Just pretend that we didn't see the previous declaration. 13854 Previous.clear(); 13855 } 13856 13857 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13858 DC->Equals(getStdNamespace())) { 13859 if (Name->isStr("bad_alloc")) { 13860 // This is a declaration of or a reference to "std::bad_alloc". 13861 isStdBadAlloc = true; 13862 13863 // If std::bad_alloc has been implicitly declared (but made invisible to 13864 // name lookup), fill in this implicit declaration as the previous 13865 // declaration, so that the declarations get chained appropriately. 13866 if (Previous.empty() && StdBadAlloc) 13867 Previous.addDecl(getStdBadAlloc()); 13868 } else if (Name->isStr("align_val_t")) { 13869 isStdAlignValT = true; 13870 if (Previous.empty() && StdAlignValT) 13871 Previous.addDecl(getStdAlignValT()); 13872 } 13873 } 13874 13875 // If we didn't find a previous declaration, and this is a reference 13876 // (or friend reference), move to the correct scope. In C++, we 13877 // also need to do a redeclaration lookup there, just in case 13878 // there's a shadow friend decl. 13879 if (Name && Previous.empty() && 13880 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13881 if (Invalid) goto CreateNewDecl; 13882 assert(SS.isEmpty()); 13883 13884 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13885 // C++ [basic.scope.pdecl]p5: 13886 // -- for an elaborated-type-specifier of the form 13887 // 13888 // class-key identifier 13889 // 13890 // if the elaborated-type-specifier is used in the 13891 // decl-specifier-seq or parameter-declaration-clause of a 13892 // function defined in namespace scope, the identifier is 13893 // declared as a class-name in the namespace that contains 13894 // the declaration; otherwise, except as a friend 13895 // declaration, the identifier is declared in the smallest 13896 // non-class, non-function-prototype scope that contains the 13897 // declaration. 13898 // 13899 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13900 // C structs and unions. 13901 // 13902 // It is an error in C++ to declare (rather than define) an enum 13903 // type, including via an elaborated type specifier. We'll 13904 // diagnose that later; for now, declare the enum in the same 13905 // scope as we would have picked for any other tag type. 13906 // 13907 // GNU C also supports this behavior as part of its incomplete 13908 // enum types extension, while GNU C++ does not. 13909 // 13910 // Find the context where we'll be declaring the tag. 13911 // FIXME: We would like to maintain the current DeclContext as the 13912 // lexical context, 13913 SearchDC = getTagInjectionContext(SearchDC); 13914 13915 // Find the scope where we'll be declaring the tag. 13916 S = getTagInjectionScope(S, getLangOpts()); 13917 } else { 13918 assert(TUK == TUK_Friend); 13919 // C++ [namespace.memdef]p3: 13920 // If a friend declaration in a non-local class first declares a 13921 // class or function, the friend class or function is a member of 13922 // the innermost enclosing namespace. 13923 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13924 } 13925 13926 // In C++, we need to do a redeclaration lookup to properly 13927 // diagnose some problems. 13928 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13929 // hidden declaration so that we don't get ambiguity errors when using a 13930 // type declared by an elaborated-type-specifier. In C that is not correct 13931 // and we should instead merge compatible types found by lookup. 13932 if (getLangOpts().CPlusPlus) { 13933 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13934 LookupQualifiedName(Previous, SearchDC); 13935 } else { 13936 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13937 LookupName(Previous, S); 13938 } 13939 } 13940 13941 // If we have a known previous declaration to use, then use it. 13942 if (Previous.empty() && SkipBody && SkipBody->Previous) 13943 Previous.addDecl(SkipBody->Previous); 13944 13945 if (!Previous.empty()) { 13946 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13947 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13948 13949 // It's okay to have a tag decl in the same scope as a typedef 13950 // which hides a tag decl in the same scope. Finding this 13951 // insanity with a redeclaration lookup can only actually happen 13952 // in C++. 13953 // 13954 // This is also okay for elaborated-type-specifiers, which is 13955 // technically forbidden by the current standard but which is 13956 // okay according to the likely resolution of an open issue; 13957 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13958 if (getLangOpts().CPlusPlus) { 13959 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13960 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13961 TagDecl *Tag = TT->getDecl(); 13962 if (Tag->getDeclName() == Name && 13963 Tag->getDeclContext()->getRedeclContext() 13964 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13965 PrevDecl = Tag; 13966 Previous.clear(); 13967 Previous.addDecl(Tag); 13968 Previous.resolveKind(); 13969 } 13970 } 13971 } 13972 } 13973 13974 // If this is a redeclaration of a using shadow declaration, it must 13975 // declare a tag in the same context. In MSVC mode, we allow a 13976 // redefinition if either context is within the other. 13977 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13978 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13979 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13980 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13981 !(OldTag && isAcceptableTagRedeclContext( 13982 *this, OldTag->getDeclContext(), SearchDC))) { 13983 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13984 Diag(Shadow->getTargetDecl()->getLocation(), 13985 diag::note_using_decl_target); 13986 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13987 << 0; 13988 // Recover by ignoring the old declaration. 13989 Previous.clear(); 13990 goto CreateNewDecl; 13991 } 13992 } 13993 13994 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13995 // If this is a use of a previous tag, or if the tag is already declared 13996 // in the same scope (so that the definition/declaration completes or 13997 // rementions the tag), reuse the decl. 13998 if (TUK == TUK_Reference || TUK == TUK_Friend || 13999 isDeclInScope(DirectPrevDecl, SearchDC, S, 14000 SS.isNotEmpty() || isMemberSpecialization)) { 14001 // Make sure that this wasn't declared as an enum and now used as a 14002 // struct or something similar. 14003 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14004 TUK == TUK_Definition, KWLoc, 14005 Name)) { 14006 bool SafeToContinue 14007 = (PrevTagDecl->getTagKind() != TTK_Enum && 14008 Kind != TTK_Enum); 14009 if (SafeToContinue) 14010 Diag(KWLoc, diag::err_use_with_wrong_tag) 14011 << Name 14012 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14013 PrevTagDecl->getKindName()); 14014 else 14015 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14016 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14017 14018 if (SafeToContinue) 14019 Kind = PrevTagDecl->getTagKind(); 14020 else { 14021 // Recover by making this an anonymous redefinition. 14022 Name = nullptr; 14023 Previous.clear(); 14024 Invalid = true; 14025 } 14026 } 14027 14028 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14029 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14030 14031 // If this is an elaborated-type-specifier for a scoped enumeration, 14032 // the 'class' keyword is not necessary and not permitted. 14033 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14034 if (ScopedEnum) 14035 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14036 << PrevEnum->isScoped() 14037 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14038 return PrevTagDecl; 14039 } 14040 14041 QualType EnumUnderlyingTy; 14042 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14043 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14044 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14045 EnumUnderlyingTy = QualType(T, 0); 14046 14047 // All conflicts with previous declarations are recovered by 14048 // returning the previous declaration, unless this is a definition, 14049 // in which case we want the caller to bail out. 14050 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14051 ScopedEnum, EnumUnderlyingTy, 14052 IsFixed, PrevEnum)) 14053 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14054 } 14055 14056 // C++11 [class.mem]p1: 14057 // A member shall not be declared twice in the member-specification, 14058 // except that a nested class or member class template can be declared 14059 // and then later defined. 14060 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14061 S->isDeclScope(PrevDecl)) { 14062 Diag(NameLoc, diag::ext_member_redeclared); 14063 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14064 } 14065 14066 if (!Invalid) { 14067 // If this is a use, just return the declaration we found, unless 14068 // we have attributes. 14069 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14070 if (Attr) { 14071 // FIXME: Diagnose these attributes. For now, we create a new 14072 // declaration to hold them. 14073 } else if (TUK == TUK_Reference && 14074 (PrevTagDecl->getFriendObjectKind() == 14075 Decl::FOK_Undeclared || 14076 PrevDecl->getOwningModule() != getCurrentModule()) && 14077 SS.isEmpty()) { 14078 // This declaration is a reference to an existing entity, but 14079 // has different visibility from that entity: it either makes 14080 // a friend visible or it makes a type visible in a new module. 14081 // In either case, create a new declaration. We only do this if 14082 // the declaration would have meant the same thing if no prior 14083 // declaration were found, that is, if it was found in the same 14084 // scope where we would have injected a declaration. 14085 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14086 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14087 return PrevTagDecl; 14088 // This is in the injected scope, create a new declaration in 14089 // that scope. 14090 S = getTagInjectionScope(S, getLangOpts()); 14091 } else { 14092 return PrevTagDecl; 14093 } 14094 } 14095 14096 // Diagnose attempts to redefine a tag. 14097 if (TUK == TUK_Definition) { 14098 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14099 // If we're defining a specialization and the previous definition 14100 // is from an implicit instantiation, don't emit an error 14101 // here; we'll catch this in the general case below. 14102 bool IsExplicitSpecializationAfterInstantiation = false; 14103 if (isMemberSpecialization) { 14104 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14105 IsExplicitSpecializationAfterInstantiation = 14106 RD->getTemplateSpecializationKind() != 14107 TSK_ExplicitSpecialization; 14108 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14109 IsExplicitSpecializationAfterInstantiation = 14110 ED->getTemplateSpecializationKind() != 14111 TSK_ExplicitSpecialization; 14112 } 14113 14114 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14115 // not keep more that one definition around (merge them). However, 14116 // ensure the decl passes the structural compatibility check in 14117 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14118 NamedDecl *Hidden = nullptr; 14119 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14120 // There is a definition of this tag, but it is not visible. We 14121 // explicitly make use of C++'s one definition rule here, and 14122 // assume that this definition is identical to the hidden one 14123 // we already have. Make the existing definition visible and 14124 // use it in place of this one. 14125 if (!getLangOpts().CPlusPlus) { 14126 // Postpone making the old definition visible until after we 14127 // complete parsing the new one and do the structural 14128 // comparison. 14129 SkipBody->CheckSameAsPrevious = true; 14130 SkipBody->New = createTagFromNewDecl(); 14131 SkipBody->Previous = Hidden; 14132 } else { 14133 SkipBody->ShouldSkip = true; 14134 makeMergedDefinitionVisible(Hidden); 14135 } 14136 return Def; 14137 } else if (!IsExplicitSpecializationAfterInstantiation) { 14138 // A redeclaration in function prototype scope in C isn't 14139 // visible elsewhere, so merely issue a warning. 14140 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14141 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14142 else 14143 Diag(NameLoc, diag::err_redefinition) << Name; 14144 notePreviousDefinition(Def, 14145 NameLoc.isValid() ? NameLoc : KWLoc); 14146 // If this is a redefinition, recover by making this 14147 // struct be anonymous, which will make any later 14148 // references get the previous definition. 14149 Name = nullptr; 14150 Previous.clear(); 14151 Invalid = true; 14152 } 14153 } else { 14154 // If the type is currently being defined, complain 14155 // about a nested redefinition. 14156 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14157 if (TD->isBeingDefined()) { 14158 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14159 Diag(PrevTagDecl->getLocation(), 14160 diag::note_previous_definition); 14161 Name = nullptr; 14162 Previous.clear(); 14163 Invalid = true; 14164 } 14165 } 14166 14167 // Okay, this is definition of a previously declared or referenced 14168 // tag. We're going to create a new Decl for it. 14169 } 14170 14171 // Okay, we're going to make a redeclaration. If this is some kind 14172 // of reference, make sure we build the redeclaration in the same DC 14173 // as the original, and ignore the current access specifier. 14174 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14175 SearchDC = PrevTagDecl->getDeclContext(); 14176 AS = AS_none; 14177 } 14178 } 14179 // If we get here we have (another) forward declaration or we 14180 // have a definition. Just create a new decl. 14181 14182 } else { 14183 // If we get here, this is a definition of a new tag type in a nested 14184 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14185 // new decl/type. We set PrevDecl to NULL so that the entities 14186 // have distinct types. 14187 Previous.clear(); 14188 } 14189 // If we get here, we're going to create a new Decl. If PrevDecl 14190 // is non-NULL, it's a definition of the tag declared by 14191 // PrevDecl. If it's NULL, we have a new definition. 14192 14193 // Otherwise, PrevDecl is not a tag, but was found with tag 14194 // lookup. This is only actually possible in C++, where a few 14195 // things like templates still live in the tag namespace. 14196 } else { 14197 // Use a better diagnostic if an elaborated-type-specifier 14198 // found the wrong kind of type on the first 14199 // (non-redeclaration) lookup. 14200 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14201 !Previous.isForRedeclaration()) { 14202 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14203 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14204 << Kind; 14205 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14206 Invalid = true; 14207 14208 // Otherwise, only diagnose if the declaration is in scope. 14209 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14210 SS.isNotEmpty() || isMemberSpecialization)) { 14211 // do nothing 14212 14213 // Diagnose implicit declarations introduced by elaborated types. 14214 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14215 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14216 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14217 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14218 Invalid = true; 14219 14220 // Otherwise it's a declaration. Call out a particularly common 14221 // case here. 14222 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14223 unsigned Kind = 0; 14224 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14225 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14226 << Name << Kind << TND->getUnderlyingType(); 14227 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14228 Invalid = true; 14229 14230 // Otherwise, diagnose. 14231 } else { 14232 // The tag name clashes with something else in the target scope, 14233 // issue an error and recover by making this tag be anonymous. 14234 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14235 notePreviousDefinition(PrevDecl, NameLoc); 14236 Name = nullptr; 14237 Invalid = true; 14238 } 14239 14240 // The existing declaration isn't relevant to us; we're in a 14241 // new scope, so clear out the previous declaration. 14242 Previous.clear(); 14243 } 14244 } 14245 14246 CreateNewDecl: 14247 14248 TagDecl *PrevDecl = nullptr; 14249 if (Previous.isSingleResult()) 14250 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14251 14252 // If there is an identifier, use the location of the identifier as the 14253 // location of the decl, otherwise use the location of the struct/union 14254 // keyword. 14255 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14256 14257 // Otherwise, create a new declaration. If there is a previous 14258 // declaration of the same entity, the two will be linked via 14259 // PrevDecl. 14260 TagDecl *New; 14261 14262 bool IsForwardReference = false; 14263 if (Kind == TTK_Enum) { 14264 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14265 // enum X { A, B, C } D; D should chain to X. 14266 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14267 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14268 ScopedEnumUsesClassTag, IsFixed); 14269 14270 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14271 StdAlignValT = cast<EnumDecl>(New); 14272 14273 // If this is an undefined enum, warn. 14274 if (TUK != TUK_Definition && !Invalid) { 14275 TagDecl *Def; 14276 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 14277 cast<EnumDecl>(New)->isFixed()) { 14278 // C++0x: 7.2p2: opaque-enum-declaration. 14279 // Conflicts are diagnosed above. Do nothing. 14280 } 14281 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14282 Diag(Loc, diag::ext_forward_ref_enum_def) 14283 << New; 14284 Diag(Def->getLocation(), diag::note_previous_definition); 14285 } else { 14286 unsigned DiagID = diag::ext_forward_ref_enum; 14287 if (getLangOpts().MSVCCompat) 14288 DiagID = diag::ext_ms_forward_ref_enum; 14289 else if (getLangOpts().CPlusPlus) 14290 DiagID = diag::err_forward_ref_enum; 14291 Diag(Loc, DiagID); 14292 14293 // If this is a forward-declared reference to an enumeration, make a 14294 // note of it; we won't actually be introducing the declaration into 14295 // the declaration context. 14296 if (TUK == TUK_Reference) 14297 IsForwardReference = true; 14298 } 14299 } 14300 14301 if (EnumUnderlying) { 14302 EnumDecl *ED = cast<EnumDecl>(New); 14303 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14304 ED->setIntegerTypeSourceInfo(TI); 14305 else 14306 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14307 ED->setPromotionType(ED->getIntegerType()); 14308 assert(ED->isComplete() && "enum with type should be complete"); 14309 } 14310 } else { 14311 // struct/union/class 14312 14313 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14314 // struct X { int A; } D; D should chain to X. 14315 if (getLangOpts().CPlusPlus) { 14316 // FIXME: Look for a way to use RecordDecl for simple structs. 14317 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14318 cast_or_null<CXXRecordDecl>(PrevDecl)); 14319 14320 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14321 StdBadAlloc = cast<CXXRecordDecl>(New); 14322 } else 14323 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14324 cast_or_null<RecordDecl>(PrevDecl)); 14325 } 14326 14327 // C++11 [dcl.type]p3: 14328 // A type-specifier-seq shall not define a class or enumeration [...]. 14329 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14330 TUK == TUK_Definition) { 14331 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14332 << Context.getTagDeclType(New); 14333 Invalid = true; 14334 } 14335 14336 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14337 DC->getDeclKind() == Decl::Enum) { 14338 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14339 << Context.getTagDeclType(New); 14340 Invalid = true; 14341 } 14342 14343 // Maybe add qualifier info. 14344 if (SS.isNotEmpty()) { 14345 if (SS.isSet()) { 14346 // If this is either a declaration or a definition, check the 14347 // nested-name-specifier against the current context. 14348 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14349 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14350 isMemberSpecialization)) 14351 Invalid = true; 14352 14353 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14354 if (TemplateParameterLists.size() > 0) { 14355 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14356 } 14357 } 14358 else 14359 Invalid = true; 14360 } 14361 14362 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14363 // Add alignment attributes if necessary; these attributes are checked when 14364 // the ASTContext lays out the structure. 14365 // 14366 // It is important for implementing the correct semantics that this 14367 // happen here (in ActOnTag). The #pragma pack stack is 14368 // maintained as a result of parser callbacks which can occur at 14369 // many points during the parsing of a struct declaration (because 14370 // the #pragma tokens are effectively skipped over during the 14371 // parsing of the struct). 14372 if (TUK == TUK_Definition) { 14373 AddAlignmentAttributesForRecord(RD); 14374 AddMsStructLayoutForRecord(RD); 14375 } 14376 } 14377 14378 if (ModulePrivateLoc.isValid()) { 14379 if (isMemberSpecialization) 14380 Diag(New->getLocation(), diag::err_module_private_specialization) 14381 << 2 14382 << FixItHint::CreateRemoval(ModulePrivateLoc); 14383 // __module_private__ does not apply to local classes. However, we only 14384 // diagnose this as an error when the declaration specifiers are 14385 // freestanding. Here, we just ignore the __module_private__. 14386 else if (!SearchDC->isFunctionOrMethod()) 14387 New->setModulePrivate(); 14388 } 14389 14390 // If this is a specialization of a member class (of a class template), 14391 // check the specialization. 14392 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14393 Invalid = true; 14394 14395 // If we're declaring or defining a tag in function prototype scope in C, 14396 // note that this type can only be used within the function and add it to 14397 // the list of decls to inject into the function definition scope. 14398 if ((Name || Kind == TTK_Enum) && 14399 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14400 if (getLangOpts().CPlusPlus) { 14401 // C++ [dcl.fct]p6: 14402 // Types shall not be defined in return or parameter types. 14403 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14404 Diag(Loc, diag::err_type_defined_in_param_type) 14405 << Name; 14406 Invalid = true; 14407 } 14408 } else if (!PrevDecl) { 14409 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14410 } 14411 } 14412 14413 if (Invalid) 14414 New->setInvalidDecl(); 14415 14416 // Set the lexical context. If the tag has a C++ scope specifier, the 14417 // lexical context will be different from the semantic context. 14418 New->setLexicalDeclContext(CurContext); 14419 14420 // Mark this as a friend decl if applicable. 14421 // In Microsoft mode, a friend declaration also acts as a forward 14422 // declaration so we always pass true to setObjectOfFriendDecl to make 14423 // the tag name visible. 14424 if (TUK == TUK_Friend) 14425 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14426 14427 // Set the access specifier. 14428 if (!Invalid && SearchDC->isRecord()) 14429 SetMemberAccessSpecifier(New, PrevDecl, AS); 14430 14431 if (PrevDecl) 14432 CheckRedeclarationModuleOwnership(New, PrevDecl); 14433 14434 if (TUK == TUK_Definition) 14435 New->startDefinition(); 14436 14437 if (Attr) 14438 ProcessDeclAttributeList(S, New, Attr); 14439 AddPragmaAttributes(S, New); 14440 14441 // If this has an identifier, add it to the scope stack. 14442 if (TUK == TUK_Friend) { 14443 // We might be replacing an existing declaration in the lookup tables; 14444 // if so, borrow its access specifier. 14445 if (PrevDecl) 14446 New->setAccess(PrevDecl->getAccess()); 14447 14448 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14449 DC->makeDeclVisibleInContext(New); 14450 if (Name) // can be null along some error paths 14451 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14452 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14453 } else if (Name) { 14454 S = getNonFieldDeclScope(S); 14455 PushOnScopeChains(New, S, !IsForwardReference); 14456 if (IsForwardReference) 14457 SearchDC->makeDeclVisibleInContext(New); 14458 } else { 14459 CurContext->addDecl(New); 14460 } 14461 14462 // If this is the C FILE type, notify the AST context. 14463 if (IdentifierInfo *II = New->getIdentifier()) 14464 if (!New->isInvalidDecl() && 14465 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14466 II->isStr("FILE")) 14467 Context.setFILEDecl(New); 14468 14469 if (PrevDecl) 14470 mergeDeclAttributes(New, PrevDecl); 14471 14472 // If there's a #pragma GCC visibility in scope, set the visibility of this 14473 // record. 14474 AddPushedVisibilityAttribute(New); 14475 14476 if (isMemberSpecialization && !New->isInvalidDecl()) 14477 CompleteMemberSpecialization(New, Previous); 14478 14479 OwnedDecl = true; 14480 // In C++, don't return an invalid declaration. We can't recover well from 14481 // the cases where we make the type anonymous. 14482 if (Invalid && getLangOpts().CPlusPlus) { 14483 if (New->isBeingDefined()) 14484 if (auto RD = dyn_cast<RecordDecl>(New)) 14485 RD->completeDefinition(); 14486 return nullptr; 14487 } else { 14488 return New; 14489 } 14490 } 14491 14492 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14493 AdjustDeclIfTemplate(TagD); 14494 TagDecl *Tag = cast<TagDecl>(TagD); 14495 14496 // Enter the tag context. 14497 PushDeclContext(S, Tag); 14498 14499 ActOnDocumentableDecl(TagD); 14500 14501 // If there's a #pragma GCC visibility in scope, set the visibility of this 14502 // record. 14503 AddPushedVisibilityAttribute(Tag); 14504 } 14505 14506 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14507 SkipBodyInfo &SkipBody) { 14508 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14509 return false; 14510 14511 // Make the previous decl visible. 14512 makeMergedDefinitionVisible(SkipBody.Previous); 14513 return true; 14514 } 14515 14516 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14517 assert(isa<ObjCContainerDecl>(IDecl) && 14518 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14519 DeclContext *OCD = cast<DeclContext>(IDecl); 14520 assert(getContainingDC(OCD) == CurContext && 14521 "The next DeclContext should be lexically contained in the current one."); 14522 CurContext = OCD; 14523 return IDecl; 14524 } 14525 14526 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14527 SourceLocation FinalLoc, 14528 bool IsFinalSpelledSealed, 14529 SourceLocation LBraceLoc) { 14530 AdjustDeclIfTemplate(TagD); 14531 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14532 14533 FieldCollector->StartClass(); 14534 14535 if (!Record->getIdentifier()) 14536 return; 14537 14538 if (FinalLoc.isValid()) 14539 Record->addAttr(new (Context) 14540 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14541 14542 // C++ [class]p2: 14543 // [...] The class-name is also inserted into the scope of the 14544 // class itself; this is known as the injected-class-name. For 14545 // purposes of access checking, the injected-class-name is treated 14546 // as if it were a public member name. 14547 CXXRecordDecl *InjectedClassName 14548 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14549 Record->getLocStart(), Record->getLocation(), 14550 Record->getIdentifier(), 14551 /*PrevDecl=*/nullptr, 14552 /*DelayTypeCreation=*/true); 14553 Context.getTypeDeclType(InjectedClassName, Record); 14554 InjectedClassName->setImplicit(); 14555 InjectedClassName->setAccess(AS_public); 14556 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14557 InjectedClassName->setDescribedClassTemplate(Template); 14558 PushOnScopeChains(InjectedClassName, S); 14559 assert(InjectedClassName->isInjectedClassName() && 14560 "Broken injected-class-name"); 14561 } 14562 14563 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14564 SourceRange BraceRange) { 14565 AdjustDeclIfTemplate(TagD); 14566 TagDecl *Tag = cast<TagDecl>(TagD); 14567 Tag->setBraceRange(BraceRange); 14568 14569 // Make sure we "complete" the definition even it is invalid. 14570 if (Tag->isBeingDefined()) { 14571 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14572 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14573 RD->completeDefinition(); 14574 } 14575 14576 if (isa<CXXRecordDecl>(Tag)) { 14577 FieldCollector->FinishClass(); 14578 } 14579 14580 // Exit this scope of this tag's definition. 14581 PopDeclContext(); 14582 14583 if (getCurLexicalContext()->isObjCContainer() && 14584 Tag->getDeclContext()->isFileContext()) 14585 Tag->setTopLevelDeclInObjCContainer(); 14586 14587 // Notify the consumer that we've defined a tag. 14588 if (!Tag->isInvalidDecl()) 14589 Consumer.HandleTagDeclDefinition(Tag); 14590 } 14591 14592 void Sema::ActOnObjCContainerFinishDefinition() { 14593 // Exit this scope of this interface definition. 14594 PopDeclContext(); 14595 } 14596 14597 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14598 assert(DC == CurContext && "Mismatch of container contexts"); 14599 OriginalLexicalContext = DC; 14600 ActOnObjCContainerFinishDefinition(); 14601 } 14602 14603 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14604 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14605 OriginalLexicalContext = nullptr; 14606 } 14607 14608 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14609 AdjustDeclIfTemplate(TagD); 14610 TagDecl *Tag = cast<TagDecl>(TagD); 14611 Tag->setInvalidDecl(); 14612 14613 // Make sure we "complete" the definition even it is invalid. 14614 if (Tag->isBeingDefined()) { 14615 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14616 RD->completeDefinition(); 14617 } 14618 14619 // We're undoing ActOnTagStartDefinition here, not 14620 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14621 // the FieldCollector. 14622 14623 PopDeclContext(); 14624 } 14625 14626 // Note that FieldName may be null for anonymous bitfields. 14627 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14628 IdentifierInfo *FieldName, 14629 QualType FieldTy, bool IsMsStruct, 14630 Expr *BitWidth, bool *ZeroWidth) { 14631 // Default to true; that shouldn't confuse checks for emptiness 14632 if (ZeroWidth) 14633 *ZeroWidth = true; 14634 14635 // C99 6.7.2.1p4 - verify the field type. 14636 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14637 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14638 // Handle incomplete types with specific error. 14639 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14640 return ExprError(); 14641 if (FieldName) 14642 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14643 << FieldName << FieldTy << BitWidth->getSourceRange(); 14644 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14645 << FieldTy << BitWidth->getSourceRange(); 14646 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14647 UPPC_BitFieldWidth)) 14648 return ExprError(); 14649 14650 // If the bit-width is type- or value-dependent, don't try to check 14651 // it now. 14652 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14653 return BitWidth; 14654 14655 llvm::APSInt Value; 14656 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14657 if (ICE.isInvalid()) 14658 return ICE; 14659 BitWidth = ICE.get(); 14660 14661 if (Value != 0 && ZeroWidth) 14662 *ZeroWidth = false; 14663 14664 // Zero-width bitfield is ok for anonymous field. 14665 if (Value == 0 && FieldName) 14666 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14667 14668 if (Value.isSigned() && Value.isNegative()) { 14669 if (FieldName) 14670 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14671 << FieldName << Value.toString(10); 14672 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14673 << Value.toString(10); 14674 } 14675 14676 if (!FieldTy->isDependentType()) { 14677 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14678 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14679 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14680 14681 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14682 // ABI. 14683 bool CStdConstraintViolation = 14684 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14685 bool MSBitfieldViolation = 14686 Value.ugt(TypeStorageSize) && 14687 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14688 if (CStdConstraintViolation || MSBitfieldViolation) { 14689 unsigned DiagWidth = 14690 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14691 if (FieldName) 14692 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14693 << FieldName << (unsigned)Value.getZExtValue() 14694 << !CStdConstraintViolation << DiagWidth; 14695 14696 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14697 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14698 << DiagWidth; 14699 } 14700 14701 // Warn on types where the user might conceivably expect to get all 14702 // specified bits as value bits: that's all integral types other than 14703 // 'bool'. 14704 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14705 if (FieldName) 14706 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14707 << FieldName << (unsigned)Value.getZExtValue() 14708 << (unsigned)TypeWidth; 14709 else 14710 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14711 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14712 } 14713 } 14714 14715 return BitWidth; 14716 } 14717 14718 /// ActOnField - Each field of a C struct/union is passed into this in order 14719 /// to create a FieldDecl object for it. 14720 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14721 Declarator &D, Expr *BitfieldWidth) { 14722 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14723 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14724 /*InitStyle=*/ICIS_NoInit, AS_public); 14725 return Res; 14726 } 14727 14728 /// HandleField - Analyze a field of a C struct or a C++ data member. 14729 /// 14730 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14731 SourceLocation DeclStart, 14732 Declarator &D, Expr *BitWidth, 14733 InClassInitStyle InitStyle, 14734 AccessSpecifier AS) { 14735 if (D.isDecompositionDeclarator()) { 14736 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14737 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14738 << Decomp.getSourceRange(); 14739 return nullptr; 14740 } 14741 14742 IdentifierInfo *II = D.getIdentifier(); 14743 SourceLocation Loc = DeclStart; 14744 if (II) Loc = D.getIdentifierLoc(); 14745 14746 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14747 QualType T = TInfo->getType(); 14748 if (getLangOpts().CPlusPlus) { 14749 CheckExtraCXXDefaultArguments(D); 14750 14751 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14752 UPPC_DataMemberType)) { 14753 D.setInvalidType(); 14754 T = Context.IntTy; 14755 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14756 } 14757 } 14758 14759 // TR 18037 does not allow fields to be declared with address spaces. 14760 if (T.getQualifiers().hasAddressSpace() || 14761 T->isDependentAddressSpaceType() || 14762 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 14763 Diag(Loc, diag::err_field_with_address_space); 14764 D.setInvalidType(); 14765 } 14766 14767 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14768 // used as structure or union field: image, sampler, event or block types. 14769 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14770 T->isSamplerT() || T->isBlockPointerType())) { 14771 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14772 D.setInvalidType(); 14773 } 14774 14775 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14776 14777 if (D.getDeclSpec().isInlineSpecified()) 14778 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14779 << getLangOpts().CPlusPlus17; 14780 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14781 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14782 diag::err_invalid_thread) 14783 << DeclSpec::getSpecifierName(TSCS); 14784 14785 // Check to see if this name was declared as a member previously 14786 NamedDecl *PrevDecl = nullptr; 14787 LookupResult Previous(*this, II, Loc, LookupMemberName, 14788 ForVisibleRedeclaration); 14789 LookupName(Previous, S); 14790 switch (Previous.getResultKind()) { 14791 case LookupResult::Found: 14792 case LookupResult::FoundUnresolvedValue: 14793 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14794 break; 14795 14796 case LookupResult::FoundOverloaded: 14797 PrevDecl = Previous.getRepresentativeDecl(); 14798 break; 14799 14800 case LookupResult::NotFound: 14801 case LookupResult::NotFoundInCurrentInstantiation: 14802 case LookupResult::Ambiguous: 14803 break; 14804 } 14805 Previous.suppressDiagnostics(); 14806 14807 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14808 // Maybe we will complain about the shadowed template parameter. 14809 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14810 // Just pretend that we didn't see the previous declaration. 14811 PrevDecl = nullptr; 14812 } 14813 14814 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14815 PrevDecl = nullptr; 14816 14817 bool Mutable 14818 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14819 SourceLocation TSSL = D.getLocStart(); 14820 FieldDecl *NewFD 14821 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14822 TSSL, AS, PrevDecl, &D); 14823 14824 if (NewFD->isInvalidDecl()) 14825 Record->setInvalidDecl(); 14826 14827 if (D.getDeclSpec().isModulePrivateSpecified()) 14828 NewFD->setModulePrivate(); 14829 14830 if (NewFD->isInvalidDecl() && PrevDecl) { 14831 // Don't introduce NewFD into scope; there's already something 14832 // with the same name in the same scope. 14833 } else if (II) { 14834 PushOnScopeChains(NewFD, S); 14835 } else 14836 Record->addDecl(NewFD); 14837 14838 return NewFD; 14839 } 14840 14841 /// \brief Build a new FieldDecl and check its well-formedness. 14842 /// 14843 /// This routine builds a new FieldDecl given the fields name, type, 14844 /// record, etc. \p PrevDecl should refer to any previous declaration 14845 /// with the same name and in the same scope as the field to be 14846 /// created. 14847 /// 14848 /// \returns a new FieldDecl. 14849 /// 14850 /// \todo The Declarator argument is a hack. It will be removed once 14851 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14852 TypeSourceInfo *TInfo, 14853 RecordDecl *Record, SourceLocation Loc, 14854 bool Mutable, Expr *BitWidth, 14855 InClassInitStyle InitStyle, 14856 SourceLocation TSSL, 14857 AccessSpecifier AS, NamedDecl *PrevDecl, 14858 Declarator *D) { 14859 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14860 bool InvalidDecl = false; 14861 if (D) InvalidDecl = D->isInvalidType(); 14862 14863 // If we receive a broken type, recover by assuming 'int' and 14864 // marking this declaration as invalid. 14865 if (T.isNull()) { 14866 InvalidDecl = true; 14867 T = Context.IntTy; 14868 } 14869 14870 QualType EltTy = Context.getBaseElementType(T); 14871 if (!EltTy->isDependentType()) { 14872 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14873 // Fields of incomplete type force their record to be invalid. 14874 Record->setInvalidDecl(); 14875 InvalidDecl = true; 14876 } else { 14877 NamedDecl *Def; 14878 EltTy->isIncompleteType(&Def); 14879 if (Def && Def->isInvalidDecl()) { 14880 Record->setInvalidDecl(); 14881 InvalidDecl = true; 14882 } 14883 } 14884 } 14885 14886 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14887 if (BitWidth && getLangOpts().OpenCL) { 14888 Diag(Loc, diag::err_opencl_bitfields); 14889 InvalidDecl = true; 14890 } 14891 14892 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 14893 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 14894 T.hasQualifiers()) { 14895 InvalidDecl = true; 14896 Diag(Loc, diag::err_anon_bitfield_qualifiers); 14897 } 14898 14899 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14900 // than a variably modified type. 14901 if (!InvalidDecl && T->isVariablyModifiedType()) { 14902 bool SizeIsNegative; 14903 llvm::APSInt Oversized; 14904 14905 TypeSourceInfo *FixedTInfo = 14906 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14907 SizeIsNegative, 14908 Oversized); 14909 if (FixedTInfo) { 14910 Diag(Loc, diag::warn_illegal_constant_array_size); 14911 TInfo = FixedTInfo; 14912 T = FixedTInfo->getType(); 14913 } else { 14914 if (SizeIsNegative) 14915 Diag(Loc, diag::err_typecheck_negative_array_size); 14916 else if (Oversized.getBoolValue()) 14917 Diag(Loc, diag::err_array_too_large) 14918 << Oversized.toString(10); 14919 else 14920 Diag(Loc, diag::err_typecheck_field_variable_size); 14921 InvalidDecl = true; 14922 } 14923 } 14924 14925 // Fields can not have abstract class types 14926 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14927 diag::err_abstract_type_in_decl, 14928 AbstractFieldType)) 14929 InvalidDecl = true; 14930 14931 bool ZeroWidth = false; 14932 if (InvalidDecl) 14933 BitWidth = nullptr; 14934 // If this is declared as a bit-field, check the bit-field. 14935 if (BitWidth) { 14936 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14937 &ZeroWidth).get(); 14938 if (!BitWidth) { 14939 InvalidDecl = true; 14940 BitWidth = nullptr; 14941 ZeroWidth = false; 14942 } 14943 } 14944 14945 // Check that 'mutable' is consistent with the type of the declaration. 14946 if (!InvalidDecl && Mutable) { 14947 unsigned DiagID = 0; 14948 if (T->isReferenceType()) 14949 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14950 : diag::err_mutable_reference; 14951 else if (T.isConstQualified()) 14952 DiagID = diag::err_mutable_const; 14953 14954 if (DiagID) { 14955 SourceLocation ErrLoc = Loc; 14956 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14957 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14958 Diag(ErrLoc, DiagID); 14959 if (DiagID != diag::ext_mutable_reference) { 14960 Mutable = false; 14961 InvalidDecl = true; 14962 } 14963 } 14964 } 14965 14966 // C++11 [class.union]p8 (DR1460): 14967 // At most one variant member of a union may have a 14968 // brace-or-equal-initializer. 14969 if (InitStyle != ICIS_NoInit) 14970 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14971 14972 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14973 BitWidth, Mutable, InitStyle); 14974 if (InvalidDecl) 14975 NewFD->setInvalidDecl(); 14976 14977 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14978 Diag(Loc, diag::err_duplicate_member) << II; 14979 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14980 NewFD->setInvalidDecl(); 14981 } 14982 14983 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14984 if (Record->isUnion()) { 14985 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14986 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14987 if (RDecl->getDefinition()) { 14988 // C++ [class.union]p1: An object of a class with a non-trivial 14989 // constructor, a non-trivial copy constructor, a non-trivial 14990 // destructor, or a non-trivial copy assignment operator 14991 // cannot be a member of a union, nor can an array of such 14992 // objects. 14993 if (CheckNontrivialField(NewFD)) 14994 NewFD->setInvalidDecl(); 14995 } 14996 } 14997 14998 // C++ [class.union]p1: If a union contains a member of reference type, 14999 // the program is ill-formed, except when compiling with MSVC extensions 15000 // enabled. 15001 if (EltTy->isReferenceType()) { 15002 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15003 diag::ext_union_member_of_reference_type : 15004 diag::err_union_member_of_reference_type) 15005 << NewFD->getDeclName() << EltTy; 15006 if (!getLangOpts().MicrosoftExt) 15007 NewFD->setInvalidDecl(); 15008 } 15009 } 15010 } 15011 15012 // FIXME: We need to pass in the attributes given an AST 15013 // representation, not a parser representation. 15014 if (D) { 15015 // FIXME: The current scope is almost... but not entirely... correct here. 15016 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15017 15018 if (NewFD->hasAttrs()) 15019 CheckAlignasUnderalignment(NewFD); 15020 } 15021 15022 // In auto-retain/release, infer strong retension for fields of 15023 // retainable type. 15024 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15025 NewFD->setInvalidDecl(); 15026 15027 if (T.isObjCGCWeak()) 15028 Diag(Loc, diag::warn_attribute_weak_on_field); 15029 15030 NewFD->setAccess(AS); 15031 return NewFD; 15032 } 15033 15034 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15035 assert(FD); 15036 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15037 15038 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15039 return false; 15040 15041 QualType EltTy = Context.getBaseElementType(FD->getType()); 15042 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15043 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15044 if (RDecl->getDefinition()) { 15045 // We check for copy constructors before constructors 15046 // because otherwise we'll never get complaints about 15047 // copy constructors. 15048 15049 CXXSpecialMember member = CXXInvalid; 15050 // We're required to check for any non-trivial constructors. Since the 15051 // implicit default constructor is suppressed if there are any 15052 // user-declared constructors, we just need to check that there is a 15053 // trivial default constructor and a trivial copy constructor. (We don't 15054 // worry about move constructors here, since this is a C++98 check.) 15055 if (RDecl->hasNonTrivialCopyConstructor()) 15056 member = CXXCopyConstructor; 15057 else if (!RDecl->hasTrivialDefaultConstructor()) 15058 member = CXXDefaultConstructor; 15059 else if (RDecl->hasNonTrivialCopyAssignment()) 15060 member = CXXCopyAssignment; 15061 else if (RDecl->hasNonTrivialDestructor()) 15062 member = CXXDestructor; 15063 15064 if (member != CXXInvalid) { 15065 if (!getLangOpts().CPlusPlus11 && 15066 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15067 // Objective-C++ ARC: it is an error to have a non-trivial field of 15068 // a union. However, system headers in Objective-C programs 15069 // occasionally have Objective-C lifetime objects within unions, 15070 // and rather than cause the program to fail, we make those 15071 // members unavailable. 15072 SourceLocation Loc = FD->getLocation(); 15073 if (getSourceManager().isInSystemHeader(Loc)) { 15074 if (!FD->hasAttr<UnavailableAttr>()) 15075 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15076 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15077 return false; 15078 } 15079 } 15080 15081 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15082 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15083 diag::err_illegal_union_or_anon_struct_member) 15084 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15085 DiagnoseNontrivial(RDecl, member); 15086 return !getLangOpts().CPlusPlus11; 15087 } 15088 } 15089 } 15090 15091 return false; 15092 } 15093 15094 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15095 /// AST enum value. 15096 static ObjCIvarDecl::AccessControl 15097 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15098 switch (ivarVisibility) { 15099 default: llvm_unreachable("Unknown visitibility kind"); 15100 case tok::objc_private: return ObjCIvarDecl::Private; 15101 case tok::objc_public: return ObjCIvarDecl::Public; 15102 case tok::objc_protected: return ObjCIvarDecl::Protected; 15103 case tok::objc_package: return ObjCIvarDecl::Package; 15104 } 15105 } 15106 15107 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15108 /// in order to create an IvarDecl object for it. 15109 Decl *Sema::ActOnIvar(Scope *S, 15110 SourceLocation DeclStart, 15111 Declarator &D, Expr *BitfieldWidth, 15112 tok::ObjCKeywordKind Visibility) { 15113 15114 IdentifierInfo *II = D.getIdentifier(); 15115 Expr *BitWidth = (Expr*)BitfieldWidth; 15116 SourceLocation Loc = DeclStart; 15117 if (II) Loc = D.getIdentifierLoc(); 15118 15119 // FIXME: Unnamed fields can be handled in various different ways, for 15120 // example, unnamed unions inject all members into the struct namespace! 15121 15122 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15123 QualType T = TInfo->getType(); 15124 15125 if (BitWidth) { 15126 // 6.7.2.1p3, 6.7.2.1p4 15127 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15128 if (!BitWidth) 15129 D.setInvalidType(); 15130 } else { 15131 // Not a bitfield. 15132 15133 // validate II. 15134 15135 } 15136 if (T->isReferenceType()) { 15137 Diag(Loc, diag::err_ivar_reference_type); 15138 D.setInvalidType(); 15139 } 15140 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15141 // than a variably modified type. 15142 else if (T->isVariablyModifiedType()) { 15143 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15144 D.setInvalidType(); 15145 } 15146 15147 // Get the visibility (access control) for this ivar. 15148 ObjCIvarDecl::AccessControl ac = 15149 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15150 : ObjCIvarDecl::None; 15151 // Must set ivar's DeclContext to its enclosing interface. 15152 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15153 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15154 return nullptr; 15155 ObjCContainerDecl *EnclosingContext; 15156 if (ObjCImplementationDecl *IMPDecl = 15157 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15158 if (LangOpts.ObjCRuntime.isFragile()) { 15159 // Case of ivar declared in an implementation. Context is that of its class. 15160 EnclosingContext = IMPDecl->getClassInterface(); 15161 assert(EnclosingContext && "Implementation has no class interface!"); 15162 } 15163 else 15164 EnclosingContext = EnclosingDecl; 15165 } else { 15166 if (ObjCCategoryDecl *CDecl = 15167 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15168 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15169 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15170 return nullptr; 15171 } 15172 } 15173 EnclosingContext = EnclosingDecl; 15174 } 15175 15176 // Construct the decl. 15177 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15178 DeclStart, Loc, II, T, 15179 TInfo, ac, (Expr *)BitfieldWidth); 15180 15181 if (II) { 15182 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15183 ForVisibleRedeclaration); 15184 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15185 && !isa<TagDecl>(PrevDecl)) { 15186 Diag(Loc, diag::err_duplicate_member) << II; 15187 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15188 NewID->setInvalidDecl(); 15189 } 15190 } 15191 15192 // Process attributes attached to the ivar. 15193 ProcessDeclAttributes(S, NewID, D); 15194 15195 if (D.isInvalidType()) 15196 NewID->setInvalidDecl(); 15197 15198 // In ARC, infer 'retaining' for ivars of retainable type. 15199 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15200 NewID->setInvalidDecl(); 15201 15202 if (D.getDeclSpec().isModulePrivateSpecified()) 15203 NewID->setModulePrivate(); 15204 15205 if (II) { 15206 // FIXME: When interfaces are DeclContexts, we'll need to add 15207 // these to the interface. 15208 S->AddDecl(NewID); 15209 IdResolver.AddDecl(NewID); 15210 } 15211 15212 if (LangOpts.ObjCRuntime.isNonFragile() && 15213 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15214 Diag(Loc, diag::warn_ivars_in_interface); 15215 15216 return NewID; 15217 } 15218 15219 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15220 /// class and class extensions. For every class \@interface and class 15221 /// extension \@interface, if the last ivar is a bitfield of any type, 15222 /// then add an implicit `char :0` ivar to the end of that interface. 15223 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15224 SmallVectorImpl<Decl *> &AllIvarDecls) { 15225 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15226 return; 15227 15228 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15229 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15230 15231 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15232 return; 15233 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15234 if (!ID) { 15235 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15236 if (!CD->IsClassExtension()) 15237 return; 15238 } 15239 // No need to add this to end of @implementation. 15240 else 15241 return; 15242 } 15243 // All conditions are met. Add a new bitfield to the tail end of ivars. 15244 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15245 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15246 15247 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15248 DeclLoc, DeclLoc, nullptr, 15249 Context.CharTy, 15250 Context.getTrivialTypeSourceInfo(Context.CharTy, 15251 DeclLoc), 15252 ObjCIvarDecl::Private, BW, 15253 true); 15254 AllIvarDecls.push_back(Ivar); 15255 } 15256 15257 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15258 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15259 SourceLocation RBrac, AttributeList *Attr) { 15260 assert(EnclosingDecl && "missing record or interface decl"); 15261 15262 // If this is an Objective-C @implementation or category and we have 15263 // new fields here we should reset the layout of the interface since 15264 // it will now change. 15265 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15266 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15267 switch (DC->getKind()) { 15268 default: break; 15269 case Decl::ObjCCategory: 15270 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15271 break; 15272 case Decl::ObjCImplementation: 15273 Context. 15274 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15275 break; 15276 } 15277 } 15278 15279 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15280 15281 // Start counting up the number of named members; make sure to include 15282 // members of anonymous structs and unions in the total. 15283 unsigned NumNamedMembers = 0; 15284 if (Record) { 15285 for (const auto *I : Record->decls()) { 15286 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15287 if (IFD->getDeclName()) 15288 ++NumNamedMembers; 15289 } 15290 } 15291 15292 // Verify that all the fields are okay. 15293 SmallVector<FieldDecl*, 32> RecFields; 15294 15295 bool ObjCFieldLifetimeErrReported = false; 15296 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15297 i != end; ++i) { 15298 FieldDecl *FD = cast<FieldDecl>(*i); 15299 15300 // Get the type for the field. 15301 const Type *FDTy = FD->getType().getTypePtr(); 15302 15303 if (!FD->isAnonymousStructOrUnion()) { 15304 // Remember all fields written by the user. 15305 RecFields.push_back(FD); 15306 } 15307 15308 // If the field is already invalid for some reason, don't emit more 15309 // diagnostics about it. 15310 if (FD->isInvalidDecl()) { 15311 EnclosingDecl->setInvalidDecl(); 15312 continue; 15313 } 15314 15315 // C99 6.7.2.1p2: 15316 // A structure or union shall not contain a member with 15317 // incomplete or function type (hence, a structure shall not 15318 // contain an instance of itself, but may contain a pointer to 15319 // an instance of itself), except that the last member of a 15320 // structure with more than one named member may have incomplete 15321 // array type; such a structure (and any union containing, 15322 // possibly recursively, a member that is such a structure) 15323 // shall not be a member of a structure or an element of an 15324 // array. 15325 bool IsLastField = (i + 1 == Fields.end()); 15326 if (FDTy->isFunctionType()) { 15327 // Field declared as a function. 15328 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15329 << FD->getDeclName(); 15330 FD->setInvalidDecl(); 15331 EnclosingDecl->setInvalidDecl(); 15332 continue; 15333 } else if (FDTy->isIncompleteArrayType() && 15334 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15335 if (Record) { 15336 // Flexible array member. 15337 // Microsoft and g++ is more permissive regarding flexible array. 15338 // It will accept flexible array in union and also 15339 // as the sole element of a struct/class. 15340 unsigned DiagID = 0; 15341 if (!Record->isUnion() && !IsLastField) { 15342 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15343 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15344 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15345 FD->setInvalidDecl(); 15346 EnclosingDecl->setInvalidDecl(); 15347 continue; 15348 } else if (Record->isUnion()) 15349 DiagID = getLangOpts().MicrosoftExt 15350 ? diag::ext_flexible_array_union_ms 15351 : getLangOpts().CPlusPlus 15352 ? diag::ext_flexible_array_union_gnu 15353 : diag::err_flexible_array_union; 15354 else if (NumNamedMembers < 1) 15355 DiagID = getLangOpts().MicrosoftExt 15356 ? diag::ext_flexible_array_empty_aggregate_ms 15357 : getLangOpts().CPlusPlus 15358 ? diag::ext_flexible_array_empty_aggregate_gnu 15359 : diag::err_flexible_array_empty_aggregate; 15360 15361 if (DiagID) 15362 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15363 << Record->getTagKind(); 15364 // While the layout of types that contain virtual bases is not specified 15365 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15366 // virtual bases after the derived members. This would make a flexible 15367 // array member declared at the end of an object not adjacent to the end 15368 // of the type. 15369 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 15370 if (RD->getNumVBases() != 0) 15371 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15372 << FD->getDeclName() << Record->getTagKind(); 15373 if (!getLangOpts().C99) 15374 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15375 << FD->getDeclName() << Record->getTagKind(); 15376 15377 // If the element type has a non-trivial destructor, we would not 15378 // implicitly destroy the elements, so disallow it for now. 15379 // 15380 // FIXME: GCC allows this. We should probably either implicitly delete 15381 // the destructor of the containing class, or just allow this. 15382 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15383 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15384 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15385 << FD->getDeclName() << FD->getType(); 15386 FD->setInvalidDecl(); 15387 EnclosingDecl->setInvalidDecl(); 15388 continue; 15389 } 15390 // Okay, we have a legal flexible array member at the end of the struct. 15391 Record->setHasFlexibleArrayMember(true); 15392 } else { 15393 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15394 // unless they are followed by another ivar. That check is done 15395 // elsewhere, after synthesized ivars are known. 15396 } 15397 } else if (!FDTy->isDependentType() && 15398 RequireCompleteType(FD->getLocation(), FD->getType(), 15399 diag::err_field_incomplete)) { 15400 // Incomplete type 15401 FD->setInvalidDecl(); 15402 EnclosingDecl->setInvalidDecl(); 15403 continue; 15404 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15405 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15406 // A type which contains a flexible array member is considered to be a 15407 // flexible array member. 15408 Record->setHasFlexibleArrayMember(true); 15409 if (!Record->isUnion()) { 15410 // If this is a struct/class and this is not the last element, reject 15411 // it. Note that GCC supports variable sized arrays in the middle of 15412 // structures. 15413 if (!IsLastField) 15414 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15415 << FD->getDeclName() << FD->getType(); 15416 else { 15417 // We support flexible arrays at the end of structs in 15418 // other structs as an extension. 15419 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15420 << FD->getDeclName(); 15421 } 15422 } 15423 } 15424 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15425 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15426 diag::err_abstract_type_in_decl, 15427 AbstractIvarType)) { 15428 // Ivars can not have abstract class types 15429 FD->setInvalidDecl(); 15430 } 15431 if (Record && FDTTy->getDecl()->hasObjectMember()) 15432 Record->setHasObjectMember(true); 15433 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15434 Record->setHasVolatileMember(true); 15435 } else if (FDTy->isObjCObjectType()) { 15436 /// A field cannot be an Objective-c object 15437 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15438 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15439 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15440 FD->setType(T); 15441 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15442 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { 15443 // It's an error in ARC or Weak if a field has lifetime. 15444 // We don't want to report this in a system header, though, 15445 // so we just make the field unavailable. 15446 // FIXME: that's really not sufficient; we need to make the type 15447 // itself invalid to, say, initialize or copy. 15448 QualType T = FD->getType(); 15449 if (T.hasNonTrivialObjCLifetime()) { 15450 SourceLocation loc = FD->getLocation(); 15451 if (getSourceManager().isInSystemHeader(loc)) { 15452 if (!FD->hasAttr<UnavailableAttr>()) { 15453 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15454 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15455 } 15456 } else { 15457 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15458 << T->isBlockPointerType() << Record->getTagKind(); 15459 } 15460 ObjCFieldLifetimeErrReported = true; 15461 } 15462 } else if (getLangOpts().ObjC1 && 15463 getLangOpts().getGC() != LangOptions::NonGC && 15464 Record && !Record->hasObjectMember()) { 15465 if (FD->getType()->isObjCObjectPointerType() || 15466 FD->getType().isObjCGCStrong()) 15467 Record->setHasObjectMember(true); 15468 else if (Context.getAsArrayType(FD->getType())) { 15469 QualType BaseType = Context.getBaseElementType(FD->getType()); 15470 if (BaseType->isRecordType() && 15471 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15472 Record->setHasObjectMember(true); 15473 else if (BaseType->isObjCObjectPointerType() || 15474 BaseType.isObjCGCStrong()) 15475 Record->setHasObjectMember(true); 15476 } 15477 } 15478 15479 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 15480 QualType FT = FD->getType(); 15481 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 15482 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 15483 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 15484 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 15485 Record->setNonTrivialToPrimitiveCopy(true); 15486 if (FT.isDestructedType()) { 15487 Record->setNonTrivialToPrimitiveDestroy(true); 15488 Record->setParamDestroyedInCallee(true); 15489 } 15490 15491 if (const auto *RT = FT->getAs<RecordType>()) { 15492 if (RT->getDecl()->getArgPassingRestrictions() == 15493 RecordDecl::APK_CanNeverPassInRegs) 15494 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15495 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 15496 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15497 } 15498 15499 if (Record && FD->getType().isVolatileQualified()) 15500 Record->setHasVolatileMember(true); 15501 // Keep track of the number of named members. 15502 if (FD->getIdentifier()) 15503 ++NumNamedMembers; 15504 } 15505 15506 // Okay, we successfully defined 'Record'. 15507 if (Record) { 15508 bool Completed = false; 15509 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15510 if (!CXXRecord->isInvalidDecl()) { 15511 // Set access bits correctly on the directly-declared conversions. 15512 for (CXXRecordDecl::conversion_iterator 15513 I = CXXRecord->conversion_begin(), 15514 E = CXXRecord->conversion_end(); I != E; ++I) 15515 I.setAccess((*I)->getAccess()); 15516 } 15517 15518 if (!CXXRecord->isDependentType()) { 15519 if (CXXRecord->hasUserDeclaredDestructor()) { 15520 // Adjust user-defined destructor exception spec. 15521 if (getLangOpts().CPlusPlus11) 15522 AdjustDestructorExceptionSpec(CXXRecord, 15523 CXXRecord->getDestructor()); 15524 } 15525 15526 // Add any implicitly-declared members to this class. 15527 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15528 15529 if (!CXXRecord->isInvalidDecl()) { 15530 // If we have virtual base classes, we may end up finding multiple 15531 // final overriders for a given virtual function. Check for this 15532 // problem now. 15533 if (CXXRecord->getNumVBases()) { 15534 CXXFinalOverriderMap FinalOverriders; 15535 CXXRecord->getFinalOverriders(FinalOverriders); 15536 15537 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15538 MEnd = FinalOverriders.end(); 15539 M != MEnd; ++M) { 15540 for (OverridingMethods::iterator SO = M->second.begin(), 15541 SOEnd = M->second.end(); 15542 SO != SOEnd; ++SO) { 15543 assert(SO->second.size() > 0 && 15544 "Virtual function without overriding functions?"); 15545 if (SO->second.size() == 1) 15546 continue; 15547 15548 // C++ [class.virtual]p2: 15549 // In a derived class, if a virtual member function of a base 15550 // class subobject has more than one final overrider the 15551 // program is ill-formed. 15552 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15553 << (const NamedDecl *)M->first << Record; 15554 Diag(M->first->getLocation(), 15555 diag::note_overridden_virtual_function); 15556 for (OverridingMethods::overriding_iterator 15557 OM = SO->second.begin(), 15558 OMEnd = SO->second.end(); 15559 OM != OMEnd; ++OM) 15560 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15561 << (const NamedDecl *)M->first << OM->Method->getParent(); 15562 15563 Record->setInvalidDecl(); 15564 } 15565 } 15566 CXXRecord->completeDefinition(&FinalOverriders); 15567 Completed = true; 15568 } 15569 } 15570 } 15571 } 15572 15573 if (!Completed) 15574 Record->completeDefinition(); 15575 15576 // We may have deferred checking for a deleted destructor. Check now. 15577 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15578 auto *Dtor = CXXRecord->getDestructor(); 15579 if (Dtor && Dtor->isImplicit() && 15580 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 15581 CXXRecord->setImplicitDestructorIsDeleted(); 15582 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15583 } 15584 } 15585 15586 if (Record->hasAttrs()) { 15587 CheckAlignasUnderalignment(Record); 15588 15589 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15590 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15591 IA->getRange(), IA->getBestCase(), 15592 IA->getSemanticSpelling()); 15593 } 15594 15595 // Check if the structure/union declaration is a type that can have zero 15596 // size in C. For C this is a language extension, for C++ it may cause 15597 // compatibility problems. 15598 bool CheckForZeroSize; 15599 if (!getLangOpts().CPlusPlus) { 15600 CheckForZeroSize = true; 15601 } else { 15602 // For C++ filter out types that cannot be referenced in C code. 15603 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15604 CheckForZeroSize = 15605 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15606 !CXXRecord->isDependentType() && 15607 CXXRecord->isCLike(); 15608 } 15609 if (CheckForZeroSize) { 15610 bool ZeroSize = true; 15611 bool IsEmpty = true; 15612 unsigned NonBitFields = 0; 15613 for (RecordDecl::field_iterator I = Record->field_begin(), 15614 E = Record->field_end(); 15615 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15616 IsEmpty = false; 15617 if (I->isUnnamedBitfield()) { 15618 if (!I->isZeroLengthBitField(Context)) 15619 ZeroSize = false; 15620 } else { 15621 ++NonBitFields; 15622 QualType FieldType = I->getType(); 15623 if (FieldType->isIncompleteType() || 15624 !Context.getTypeSizeInChars(FieldType).isZero()) 15625 ZeroSize = false; 15626 } 15627 } 15628 15629 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15630 // allowed in C++, but warn if its declaration is inside 15631 // extern "C" block. 15632 if (ZeroSize) { 15633 Diag(RecLoc, getLangOpts().CPlusPlus ? 15634 diag::warn_zero_size_struct_union_in_extern_c : 15635 diag::warn_zero_size_struct_union_compat) 15636 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15637 } 15638 15639 // Structs without named members are extension in C (C99 6.7.2.1p7), 15640 // but are accepted by GCC. 15641 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15642 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15643 diag::ext_no_named_members_in_struct_union) 15644 << Record->isUnion(); 15645 } 15646 } 15647 } else { 15648 ObjCIvarDecl **ClsFields = 15649 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15650 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15651 ID->setEndOfDefinitionLoc(RBrac); 15652 // Add ivar's to class's DeclContext. 15653 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15654 ClsFields[i]->setLexicalDeclContext(ID); 15655 ID->addDecl(ClsFields[i]); 15656 } 15657 // Must enforce the rule that ivars in the base classes may not be 15658 // duplicates. 15659 if (ID->getSuperClass()) 15660 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15661 } else if (ObjCImplementationDecl *IMPDecl = 15662 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15663 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15664 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15665 // Ivar declared in @implementation never belongs to the implementation. 15666 // Only it is in implementation's lexical context. 15667 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15668 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15669 IMPDecl->setIvarLBraceLoc(LBrac); 15670 IMPDecl->setIvarRBraceLoc(RBrac); 15671 } else if (ObjCCategoryDecl *CDecl = 15672 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15673 // case of ivars in class extension; all other cases have been 15674 // reported as errors elsewhere. 15675 // FIXME. Class extension does not have a LocEnd field. 15676 // CDecl->setLocEnd(RBrac); 15677 // Add ivar's to class extension's DeclContext. 15678 // Diagnose redeclaration of private ivars. 15679 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15680 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15681 if (IDecl) { 15682 if (const ObjCIvarDecl *ClsIvar = 15683 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15684 Diag(ClsFields[i]->getLocation(), 15685 diag::err_duplicate_ivar_declaration); 15686 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15687 continue; 15688 } 15689 for (const auto *Ext : IDecl->known_extensions()) { 15690 if (const ObjCIvarDecl *ClsExtIvar 15691 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15692 Diag(ClsFields[i]->getLocation(), 15693 diag::err_duplicate_ivar_declaration); 15694 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15695 continue; 15696 } 15697 } 15698 } 15699 ClsFields[i]->setLexicalDeclContext(CDecl); 15700 CDecl->addDecl(ClsFields[i]); 15701 } 15702 CDecl->setIvarLBraceLoc(LBrac); 15703 CDecl->setIvarRBraceLoc(RBrac); 15704 } 15705 } 15706 15707 if (Attr) 15708 ProcessDeclAttributeList(S, Record, Attr); 15709 } 15710 15711 /// \brief Determine whether the given integral value is representable within 15712 /// the given type T. 15713 static bool isRepresentableIntegerValue(ASTContext &Context, 15714 llvm::APSInt &Value, 15715 QualType T) { 15716 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 15717 "Integral type required!"); 15718 unsigned BitWidth = Context.getIntWidth(T); 15719 15720 if (Value.isUnsigned() || Value.isNonNegative()) { 15721 if (T->isSignedIntegerOrEnumerationType()) 15722 --BitWidth; 15723 return Value.getActiveBits() <= BitWidth; 15724 } 15725 return Value.getMinSignedBits() <= BitWidth; 15726 } 15727 15728 // \brief Given an integral type, return the next larger integral type 15729 // (or a NULL type of no such type exists). 15730 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15731 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15732 // enum checking below. 15733 assert((T->isIntegralType(Context) || 15734 T->isEnumeralType()) && "Integral type required!"); 15735 const unsigned NumTypes = 4; 15736 QualType SignedIntegralTypes[NumTypes] = { 15737 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15738 }; 15739 QualType UnsignedIntegralTypes[NumTypes] = { 15740 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15741 Context.UnsignedLongLongTy 15742 }; 15743 15744 unsigned BitWidth = Context.getTypeSize(T); 15745 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15746 : UnsignedIntegralTypes; 15747 for (unsigned I = 0; I != NumTypes; ++I) 15748 if (Context.getTypeSize(Types[I]) > BitWidth) 15749 return Types[I]; 15750 15751 return QualType(); 15752 } 15753 15754 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15755 EnumConstantDecl *LastEnumConst, 15756 SourceLocation IdLoc, 15757 IdentifierInfo *Id, 15758 Expr *Val) { 15759 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15760 llvm::APSInt EnumVal(IntWidth); 15761 QualType EltTy; 15762 15763 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15764 Val = nullptr; 15765 15766 if (Val) 15767 Val = DefaultLvalueConversion(Val).get(); 15768 15769 if (Val) { 15770 if (Enum->isDependentType() || Val->isTypeDependent()) 15771 EltTy = Context.DependentTy; 15772 else { 15773 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15774 !getLangOpts().MSVCCompat) { 15775 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15776 // constant-expression in the enumerator-definition shall be a converted 15777 // constant expression of the underlying type. 15778 EltTy = Enum->getIntegerType(); 15779 ExprResult Converted = 15780 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15781 CCEK_Enumerator); 15782 if (Converted.isInvalid()) 15783 Val = nullptr; 15784 else 15785 Val = Converted.get(); 15786 } else if (!Val->isValueDependent() && 15787 !(Val = VerifyIntegerConstantExpression(Val, 15788 &EnumVal).get())) { 15789 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15790 } else { 15791 if (Enum->isComplete()) { 15792 EltTy = Enum->getIntegerType(); 15793 15794 // In Obj-C and Microsoft mode, require the enumeration value to be 15795 // representable in the underlying type of the enumeration. In C++11, 15796 // we perform a non-narrowing conversion as part of converted constant 15797 // expression checking. 15798 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15799 if (getLangOpts().MSVCCompat) { 15800 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15801 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15802 } else 15803 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15804 } else 15805 Val = ImpCastExprToType(Val, EltTy, 15806 EltTy->isBooleanType() ? 15807 CK_IntegralToBoolean : CK_IntegralCast) 15808 .get(); 15809 } else if (getLangOpts().CPlusPlus) { 15810 // C++11 [dcl.enum]p5: 15811 // If the underlying type is not fixed, the type of each enumerator 15812 // is the type of its initializing value: 15813 // - If an initializer is specified for an enumerator, the 15814 // initializing value has the same type as the expression. 15815 EltTy = Val->getType(); 15816 } else { 15817 // C99 6.7.2.2p2: 15818 // The expression that defines the value of an enumeration constant 15819 // shall be an integer constant expression that has a value 15820 // representable as an int. 15821 15822 // Complain if the value is not representable in an int. 15823 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15824 Diag(IdLoc, diag::ext_enum_value_not_int) 15825 << EnumVal.toString(10) << Val->getSourceRange() 15826 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15827 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15828 // Force the type of the expression to 'int'. 15829 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15830 } 15831 EltTy = Val->getType(); 15832 } 15833 } 15834 } 15835 } 15836 15837 if (!Val) { 15838 if (Enum->isDependentType()) 15839 EltTy = Context.DependentTy; 15840 else if (!LastEnumConst) { 15841 // C++0x [dcl.enum]p5: 15842 // If the underlying type is not fixed, the type of each enumerator 15843 // is the type of its initializing value: 15844 // - If no initializer is specified for the first enumerator, the 15845 // initializing value has an unspecified integral type. 15846 // 15847 // GCC uses 'int' for its unspecified integral type, as does 15848 // C99 6.7.2.2p3. 15849 if (Enum->isFixed()) { 15850 EltTy = Enum->getIntegerType(); 15851 } 15852 else { 15853 EltTy = Context.IntTy; 15854 } 15855 } else { 15856 // Assign the last value + 1. 15857 EnumVal = LastEnumConst->getInitVal(); 15858 ++EnumVal; 15859 EltTy = LastEnumConst->getType(); 15860 15861 // Check for overflow on increment. 15862 if (EnumVal < LastEnumConst->getInitVal()) { 15863 // C++0x [dcl.enum]p5: 15864 // If the underlying type is not fixed, the type of each enumerator 15865 // is the type of its initializing value: 15866 // 15867 // - Otherwise the type of the initializing value is the same as 15868 // the type of the initializing value of the preceding enumerator 15869 // unless the incremented value is not representable in that type, 15870 // in which case the type is an unspecified integral type 15871 // sufficient to contain the incremented value. If no such type 15872 // exists, the program is ill-formed. 15873 QualType T = getNextLargerIntegralType(Context, EltTy); 15874 if (T.isNull() || Enum->isFixed()) { 15875 // There is no integral type larger enough to represent this 15876 // value. Complain, then allow the value to wrap around. 15877 EnumVal = LastEnumConst->getInitVal(); 15878 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15879 ++EnumVal; 15880 if (Enum->isFixed()) 15881 // When the underlying type is fixed, this is ill-formed. 15882 Diag(IdLoc, diag::err_enumerator_wrapped) 15883 << EnumVal.toString(10) 15884 << EltTy; 15885 else 15886 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15887 << EnumVal.toString(10); 15888 } else { 15889 EltTy = T; 15890 } 15891 15892 // Retrieve the last enumerator's value, extent that type to the 15893 // type that is supposed to be large enough to represent the incremented 15894 // value, then increment. 15895 EnumVal = LastEnumConst->getInitVal(); 15896 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15897 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15898 ++EnumVal; 15899 15900 // If we're not in C++, diagnose the overflow of enumerator values, 15901 // which in C99 means that the enumerator value is not representable in 15902 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15903 // permits enumerator values that are representable in some larger 15904 // integral type. 15905 if (!getLangOpts().CPlusPlus && !T.isNull()) 15906 Diag(IdLoc, diag::warn_enum_value_overflow); 15907 } else if (!getLangOpts().CPlusPlus && 15908 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15909 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15910 Diag(IdLoc, diag::ext_enum_value_not_int) 15911 << EnumVal.toString(10) << 1; 15912 } 15913 } 15914 } 15915 15916 if (!EltTy->isDependentType()) { 15917 // Make the enumerator value match the signedness and size of the 15918 // enumerator's type. 15919 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15920 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15921 } 15922 15923 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15924 Val, EnumVal); 15925 } 15926 15927 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15928 SourceLocation IILoc) { 15929 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15930 !getLangOpts().CPlusPlus) 15931 return SkipBodyInfo(); 15932 15933 // We have an anonymous enum definition. Look up the first enumerator to 15934 // determine if we should merge the definition with an existing one and 15935 // skip the body. 15936 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15937 forRedeclarationInCurContext()); 15938 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15939 if (!PrevECD) 15940 return SkipBodyInfo(); 15941 15942 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15943 NamedDecl *Hidden; 15944 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15945 SkipBodyInfo Skip; 15946 Skip.Previous = Hidden; 15947 return Skip; 15948 } 15949 15950 return SkipBodyInfo(); 15951 } 15952 15953 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15954 SourceLocation IdLoc, IdentifierInfo *Id, 15955 AttributeList *Attr, 15956 SourceLocation EqualLoc, Expr *Val) { 15957 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15958 EnumConstantDecl *LastEnumConst = 15959 cast_or_null<EnumConstantDecl>(lastEnumConst); 15960 15961 // The scope passed in may not be a decl scope. Zip up the scope tree until 15962 // we find one that is. 15963 S = getNonFieldDeclScope(S); 15964 15965 // Verify that there isn't already something declared with this name in this 15966 // scope. 15967 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15968 ForVisibleRedeclaration); 15969 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15970 // Maybe we will complain about the shadowed template parameter. 15971 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15972 // Just pretend that we didn't see the previous declaration. 15973 PrevDecl = nullptr; 15974 } 15975 15976 // C++ [class.mem]p15: 15977 // If T is the name of a class, then each of the following shall have a name 15978 // different from T: 15979 // - every enumerator of every member of class T that is an unscoped 15980 // enumerated type 15981 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 15982 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15983 DeclarationNameInfo(Id, IdLoc)); 15984 15985 EnumConstantDecl *New = 15986 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15987 if (!New) 15988 return nullptr; 15989 15990 if (PrevDecl) { 15991 // When in C++, we may get a TagDecl with the same name; in this case the 15992 // enum constant will 'hide' the tag. 15993 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15994 "Received TagDecl when not in C++!"); 15995 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 15996 if (isa<EnumConstantDecl>(PrevDecl)) 15997 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15998 else 15999 Diag(IdLoc, diag::err_redefinition) << Id; 16000 notePreviousDefinition(PrevDecl, IdLoc); 16001 return nullptr; 16002 } 16003 } 16004 16005 // Process attributes. 16006 if (Attr) ProcessDeclAttributeList(S, New, Attr); 16007 AddPragmaAttributes(S, New); 16008 16009 // Register this decl in the current scope stack. 16010 New->setAccess(TheEnumDecl->getAccess()); 16011 PushOnScopeChains(New, S); 16012 16013 ActOnDocumentableDecl(New); 16014 16015 return New; 16016 } 16017 16018 // Returns true when the enum initial expression does not trigger the 16019 // duplicate enum warning. A few common cases are exempted as follows: 16020 // Element2 = Element1 16021 // Element2 = Element1 + 1 16022 // Element2 = Element1 - 1 16023 // Where Element2 and Element1 are from the same enum. 16024 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16025 Expr *InitExpr = ECD->getInitExpr(); 16026 if (!InitExpr) 16027 return true; 16028 InitExpr = InitExpr->IgnoreImpCasts(); 16029 16030 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16031 if (!BO->isAdditiveOp()) 16032 return true; 16033 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16034 if (!IL) 16035 return true; 16036 if (IL->getValue() != 1) 16037 return true; 16038 16039 InitExpr = BO->getLHS(); 16040 } 16041 16042 // This checks if the elements are from the same enum. 16043 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16044 if (!DRE) 16045 return true; 16046 16047 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16048 if (!EnumConstant) 16049 return true; 16050 16051 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16052 Enum) 16053 return true; 16054 16055 return false; 16056 } 16057 16058 // Emits a warning when an element is implicitly set a value that 16059 // a previous element has already been set to. 16060 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16061 EnumDecl *Enum, QualType EnumType) { 16062 // Avoid anonymous enums 16063 if (!Enum->getIdentifier()) 16064 return; 16065 16066 // Only check for small enums. 16067 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16068 return; 16069 16070 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16071 return; 16072 16073 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16074 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16075 16076 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16077 typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap; 16078 16079 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16080 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16081 llvm::APSInt Val = D->getInitVal(); 16082 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16083 }; 16084 16085 DuplicatesVector DupVector; 16086 ValueToVectorMap EnumMap; 16087 16088 // Populate the EnumMap with all values represented by enum constants without 16089 // an initializer. 16090 for (auto *Element : Elements) { 16091 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16092 16093 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16094 // this constant. Skip this enum since it may be ill-formed. 16095 if (!ECD) { 16096 return; 16097 } 16098 16099 // Constants with initalizers are handled in the next loop. 16100 if (ECD->getInitExpr()) 16101 continue; 16102 16103 // Duplicate values are handled in the next loop. 16104 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16105 } 16106 16107 if (EnumMap.size() == 0) 16108 return; 16109 16110 // Create vectors for any values that has duplicates. 16111 for (auto *Element : Elements) { 16112 // The last loop returned if any constant was null. 16113 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16114 if (!ValidDuplicateEnum(ECD, Enum)) 16115 continue; 16116 16117 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16118 if (Iter == EnumMap.end()) 16119 continue; 16120 16121 DeclOrVector& Entry = Iter->second; 16122 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16123 // Ensure constants are different. 16124 if (D == ECD) 16125 continue; 16126 16127 // Create new vector and push values onto it. 16128 auto Vec = llvm::make_unique<ECDVector>(); 16129 Vec->push_back(D); 16130 Vec->push_back(ECD); 16131 16132 // Update entry to point to the duplicates vector. 16133 Entry = Vec.get(); 16134 16135 // Store the vector somewhere we can consult later for quick emission of 16136 // diagnostics. 16137 DupVector.emplace_back(std::move(Vec)); 16138 continue; 16139 } 16140 16141 ECDVector *Vec = Entry.get<ECDVector*>(); 16142 // Make sure constants are not added more than once. 16143 if (*Vec->begin() == ECD) 16144 continue; 16145 16146 Vec->push_back(ECD); 16147 } 16148 16149 // Emit diagnostics. 16150 for (const auto &Vec : DupVector) { 16151 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16152 16153 // Emit warning for one enum constant. 16154 auto *FirstECD = Vec->front(); 16155 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16156 << FirstECD << FirstECD->getInitVal().toString(10) 16157 << FirstECD->getSourceRange(); 16158 16159 // Emit one note for each of the remaining enum constants with 16160 // the same value. 16161 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16162 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16163 << ECD << ECD->getInitVal().toString(10) 16164 << ECD->getSourceRange(); 16165 } 16166 } 16167 16168 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16169 bool AllowMask) const { 16170 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16171 assert(ED->isCompleteDefinition() && "expected enum definition"); 16172 16173 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16174 llvm::APInt &FlagBits = R.first->second; 16175 16176 if (R.second) { 16177 for (auto *E : ED->enumerators()) { 16178 const auto &EVal = E->getInitVal(); 16179 // Only single-bit enumerators introduce new flag values. 16180 if (EVal.isPowerOf2()) 16181 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16182 } 16183 } 16184 16185 // A value is in a flag enum if either its bits are a subset of the enum's 16186 // flag bits (the first condition) or we are allowing masks and the same is 16187 // true of its complement (the second condition). When masks are allowed, we 16188 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16189 // 16190 // While it's true that any value could be used as a mask, the assumption is 16191 // that a mask will have all of the insignificant bits set. Anything else is 16192 // likely a logic error. 16193 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16194 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16195 } 16196 16197 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16198 Decl *EnumDeclX, 16199 ArrayRef<Decl *> Elements, 16200 Scope *S, AttributeList *Attr) { 16201 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16202 QualType EnumType = Context.getTypeDeclType(Enum); 16203 16204 if (Attr) 16205 ProcessDeclAttributeList(S, Enum, Attr); 16206 16207 if (Enum->isDependentType()) { 16208 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16209 EnumConstantDecl *ECD = 16210 cast_or_null<EnumConstantDecl>(Elements[i]); 16211 if (!ECD) continue; 16212 16213 ECD->setType(EnumType); 16214 } 16215 16216 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16217 return; 16218 } 16219 16220 // TODO: If the result value doesn't fit in an int, it must be a long or long 16221 // long value. ISO C does not support this, but GCC does as an extension, 16222 // emit a warning. 16223 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16224 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16225 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16226 16227 // Verify that all the values are okay, compute the size of the values, and 16228 // reverse the list. 16229 unsigned NumNegativeBits = 0; 16230 unsigned NumPositiveBits = 0; 16231 16232 // Keep track of whether all elements have type int. 16233 bool AllElementsInt = true; 16234 16235 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16236 EnumConstantDecl *ECD = 16237 cast_or_null<EnumConstantDecl>(Elements[i]); 16238 if (!ECD) continue; // Already issued a diagnostic. 16239 16240 const llvm::APSInt &InitVal = ECD->getInitVal(); 16241 16242 // Keep track of the size of positive and negative values. 16243 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16244 NumPositiveBits = std::max(NumPositiveBits, 16245 (unsigned)InitVal.getActiveBits()); 16246 else 16247 NumNegativeBits = std::max(NumNegativeBits, 16248 (unsigned)InitVal.getMinSignedBits()); 16249 16250 // Keep track of whether every enum element has type int (very commmon). 16251 if (AllElementsInt) 16252 AllElementsInt = ECD->getType() == Context.IntTy; 16253 } 16254 16255 // Figure out the type that should be used for this enum. 16256 QualType BestType; 16257 unsigned BestWidth; 16258 16259 // C++0x N3000 [conv.prom]p3: 16260 // An rvalue of an unscoped enumeration type whose underlying 16261 // type is not fixed can be converted to an rvalue of the first 16262 // of the following types that can represent all the values of 16263 // the enumeration: int, unsigned int, long int, unsigned long 16264 // int, long long int, or unsigned long long int. 16265 // C99 6.4.4.3p2: 16266 // An identifier declared as an enumeration constant has type int. 16267 // The C99 rule is modified by a gcc extension 16268 QualType BestPromotionType; 16269 16270 bool Packed = Enum->hasAttr<PackedAttr>(); 16271 // -fshort-enums is the equivalent to specifying the packed attribute on all 16272 // enum definitions. 16273 if (LangOpts.ShortEnums) 16274 Packed = true; 16275 16276 // If the enum already has a type because it is fixed or dictated by the 16277 // target, promote that type instead of analyzing the enumerators. 16278 if (Enum->isComplete()) { 16279 BestType = Enum->getIntegerType(); 16280 if (BestType->isPromotableIntegerType()) 16281 BestPromotionType = Context.getPromotedIntegerType(BestType); 16282 else 16283 BestPromotionType = BestType; 16284 16285 BestWidth = Context.getIntWidth(BestType); 16286 } 16287 else if (NumNegativeBits) { 16288 // If there is a negative value, figure out the smallest integer type (of 16289 // int/long/longlong) that fits. 16290 // If it's packed, check also if it fits a char or a short. 16291 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16292 BestType = Context.SignedCharTy; 16293 BestWidth = CharWidth; 16294 } else if (Packed && NumNegativeBits <= ShortWidth && 16295 NumPositiveBits < ShortWidth) { 16296 BestType = Context.ShortTy; 16297 BestWidth = ShortWidth; 16298 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16299 BestType = Context.IntTy; 16300 BestWidth = IntWidth; 16301 } else { 16302 BestWidth = Context.getTargetInfo().getLongWidth(); 16303 16304 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16305 BestType = Context.LongTy; 16306 } else { 16307 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16308 16309 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16310 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16311 BestType = Context.LongLongTy; 16312 } 16313 } 16314 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16315 } else { 16316 // If there is no negative value, figure out the smallest type that fits 16317 // all of the enumerator values. 16318 // If it's packed, check also if it fits a char or a short. 16319 if (Packed && NumPositiveBits <= CharWidth) { 16320 BestType = Context.UnsignedCharTy; 16321 BestPromotionType = Context.IntTy; 16322 BestWidth = CharWidth; 16323 } else if (Packed && NumPositiveBits <= ShortWidth) { 16324 BestType = Context.UnsignedShortTy; 16325 BestPromotionType = Context.IntTy; 16326 BestWidth = ShortWidth; 16327 } else if (NumPositiveBits <= IntWidth) { 16328 BestType = Context.UnsignedIntTy; 16329 BestWidth = IntWidth; 16330 BestPromotionType 16331 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16332 ? Context.UnsignedIntTy : Context.IntTy; 16333 } else if (NumPositiveBits <= 16334 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16335 BestType = Context.UnsignedLongTy; 16336 BestPromotionType 16337 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16338 ? Context.UnsignedLongTy : Context.LongTy; 16339 } else { 16340 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16341 assert(NumPositiveBits <= BestWidth && 16342 "How could an initializer get larger than ULL?"); 16343 BestType = Context.UnsignedLongLongTy; 16344 BestPromotionType 16345 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16346 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16347 } 16348 } 16349 16350 // Loop over all of the enumerator constants, changing their types to match 16351 // the type of the enum if needed. 16352 for (auto *D : Elements) { 16353 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16354 if (!ECD) continue; // Already issued a diagnostic. 16355 16356 // Standard C says the enumerators have int type, but we allow, as an 16357 // extension, the enumerators to be larger than int size. If each 16358 // enumerator value fits in an int, type it as an int, otherwise type it the 16359 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16360 // that X has type 'int', not 'unsigned'. 16361 16362 // Determine whether the value fits into an int. 16363 llvm::APSInt InitVal = ECD->getInitVal(); 16364 16365 // If it fits into an integer type, force it. Otherwise force it to match 16366 // the enum decl type. 16367 QualType NewTy; 16368 unsigned NewWidth; 16369 bool NewSign; 16370 if (!getLangOpts().CPlusPlus && 16371 !Enum->isFixed() && 16372 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16373 NewTy = Context.IntTy; 16374 NewWidth = IntWidth; 16375 NewSign = true; 16376 } else if (ECD->getType() == BestType) { 16377 // Already the right type! 16378 if (getLangOpts().CPlusPlus) 16379 // C++ [dcl.enum]p4: Following the closing brace of an 16380 // enum-specifier, each enumerator has the type of its 16381 // enumeration. 16382 ECD->setType(EnumType); 16383 continue; 16384 } else { 16385 NewTy = BestType; 16386 NewWidth = BestWidth; 16387 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16388 } 16389 16390 // Adjust the APSInt value. 16391 InitVal = InitVal.extOrTrunc(NewWidth); 16392 InitVal.setIsSigned(NewSign); 16393 ECD->setInitVal(InitVal); 16394 16395 // Adjust the Expr initializer and type. 16396 if (ECD->getInitExpr() && 16397 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16398 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16399 CK_IntegralCast, 16400 ECD->getInitExpr(), 16401 /*base paths*/ nullptr, 16402 VK_RValue)); 16403 if (getLangOpts().CPlusPlus) 16404 // C++ [dcl.enum]p4: Following the closing brace of an 16405 // enum-specifier, each enumerator has the type of its 16406 // enumeration. 16407 ECD->setType(EnumType); 16408 else 16409 ECD->setType(NewTy); 16410 } 16411 16412 Enum->completeDefinition(BestType, BestPromotionType, 16413 NumPositiveBits, NumNegativeBits); 16414 16415 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16416 16417 if (Enum->isClosedFlag()) { 16418 for (Decl *D : Elements) { 16419 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16420 if (!ECD) continue; // Already issued a diagnostic. 16421 16422 llvm::APSInt InitVal = ECD->getInitVal(); 16423 if (InitVal != 0 && !InitVal.isPowerOf2() && 16424 !IsValueInFlagEnum(Enum, InitVal, true)) 16425 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16426 << ECD << Enum; 16427 } 16428 } 16429 16430 // Now that the enum type is defined, ensure it's not been underaligned. 16431 if (Enum->hasAttrs()) 16432 CheckAlignasUnderalignment(Enum); 16433 } 16434 16435 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16436 SourceLocation StartLoc, 16437 SourceLocation EndLoc) { 16438 StringLiteral *AsmString = cast<StringLiteral>(expr); 16439 16440 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16441 AsmString, StartLoc, 16442 EndLoc); 16443 CurContext->addDecl(New); 16444 return New; 16445 } 16446 16447 static void checkModuleImportContext(Sema &S, Module *M, 16448 SourceLocation ImportLoc, DeclContext *DC, 16449 bool FromInclude = false) { 16450 SourceLocation ExternCLoc; 16451 16452 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16453 switch (LSD->getLanguage()) { 16454 case LinkageSpecDecl::lang_c: 16455 if (ExternCLoc.isInvalid()) 16456 ExternCLoc = LSD->getLocStart(); 16457 break; 16458 case LinkageSpecDecl::lang_cxx: 16459 break; 16460 } 16461 DC = LSD->getParent(); 16462 } 16463 16464 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 16465 DC = DC->getParent(); 16466 16467 if (!isa<TranslationUnitDecl>(DC)) { 16468 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16469 ? diag::ext_module_import_not_at_top_level_noop 16470 : diag::err_module_import_not_at_top_level_fatal) 16471 << M->getFullModuleName() << DC; 16472 S.Diag(cast<Decl>(DC)->getLocStart(), 16473 diag::note_module_import_not_at_top_level) << DC; 16474 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16475 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16476 << M->getFullModuleName(); 16477 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16478 } 16479 } 16480 16481 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16482 SourceLocation ModuleLoc, 16483 ModuleDeclKind MDK, 16484 ModuleIdPath Path) { 16485 assert(getLangOpts().ModulesTS && 16486 "should only have module decl in modules TS"); 16487 16488 // A module implementation unit requires that we are not compiling a module 16489 // of any kind. A module interface unit requires that we are not compiling a 16490 // module map. 16491 switch (getLangOpts().getCompilingModule()) { 16492 case LangOptions::CMK_None: 16493 // It's OK to compile a module interface as a normal translation unit. 16494 break; 16495 16496 case LangOptions::CMK_ModuleInterface: 16497 if (MDK != ModuleDeclKind::Implementation) 16498 break; 16499 16500 // We were asked to compile a module interface unit but this is a module 16501 // implementation unit. That indicates the 'export' is missing. 16502 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16503 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16504 MDK = ModuleDeclKind::Interface; 16505 break; 16506 16507 case LangOptions::CMK_ModuleMap: 16508 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16509 return nullptr; 16510 } 16511 16512 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16513 16514 // FIXME: Most of this work should be done by the preprocessor rather than 16515 // here, in order to support macro import. 16516 16517 // Only one module-declaration is permitted per source file. 16518 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16519 Diag(ModuleLoc, diag::err_module_redeclaration); 16520 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16521 diag::note_prev_module_declaration); 16522 return nullptr; 16523 } 16524 16525 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16526 // modules, the dots here are just another character that can appear in a 16527 // module name. 16528 std::string ModuleName; 16529 for (auto &Piece : Path) { 16530 if (!ModuleName.empty()) 16531 ModuleName += "."; 16532 ModuleName += Piece.first->getName(); 16533 } 16534 16535 // If a module name was explicitly specified on the command line, it must be 16536 // correct. 16537 if (!getLangOpts().CurrentModule.empty() && 16538 getLangOpts().CurrentModule != ModuleName) { 16539 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16540 << SourceRange(Path.front().second, Path.back().second) 16541 << getLangOpts().CurrentModule; 16542 return nullptr; 16543 } 16544 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16545 16546 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16547 Module *Mod; 16548 16549 switch (MDK) { 16550 case ModuleDeclKind::Interface: { 16551 // We can't have parsed or imported a definition of this module or parsed a 16552 // module map defining it already. 16553 if (auto *M = Map.findModule(ModuleName)) { 16554 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16555 if (M->DefinitionLoc.isValid()) 16556 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16557 else if (const auto *FE = M->getASTFile()) 16558 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16559 << FE->getName(); 16560 Mod = M; 16561 break; 16562 } 16563 16564 // Create a Module for the module that we're defining. 16565 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16566 ModuleScopes.front().Module); 16567 assert(Mod && "module creation should not fail"); 16568 break; 16569 } 16570 16571 case ModuleDeclKind::Partition: 16572 // FIXME: Check we are in a submodule of the named module. 16573 return nullptr; 16574 16575 case ModuleDeclKind::Implementation: 16576 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16577 PP.getIdentifierInfo(ModuleName), Path[0].second); 16578 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16579 /*IsIncludeDirective=*/false); 16580 if (!Mod) { 16581 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 16582 // Create an empty module interface unit for error recovery. 16583 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16584 ModuleScopes.front().Module); 16585 } 16586 break; 16587 } 16588 16589 // Switch from the global module to the named module. 16590 ModuleScopes.back().Module = Mod; 16591 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 16592 VisibleModules.setVisible(Mod, ModuleLoc); 16593 16594 // From now on, we have an owning module for all declarations we see. 16595 // However, those declarations are module-private unless explicitly 16596 // exported. 16597 auto *TU = Context.getTranslationUnitDecl(); 16598 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16599 TU->setLocalOwningModule(Mod); 16600 16601 // FIXME: Create a ModuleDecl. 16602 return nullptr; 16603 } 16604 16605 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16606 SourceLocation ImportLoc, 16607 ModuleIdPath Path) { 16608 Module *Mod = 16609 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16610 /*IsIncludeDirective=*/false); 16611 if (!Mod) 16612 return true; 16613 16614 VisibleModules.setVisible(Mod, ImportLoc); 16615 16616 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16617 16618 // FIXME: we should support importing a submodule within a different submodule 16619 // of the same top-level module. Until we do, make it an error rather than 16620 // silently ignoring the import. 16621 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16622 // warn on a redundant import of the current module? 16623 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16624 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16625 Diag(ImportLoc, getLangOpts().isCompilingModule() 16626 ? diag::err_module_self_import 16627 : diag::err_module_import_in_implementation) 16628 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16629 16630 SmallVector<SourceLocation, 2> IdentifierLocs; 16631 Module *ModCheck = Mod; 16632 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16633 // If we've run out of module parents, just drop the remaining identifiers. 16634 // We need the length to be consistent. 16635 if (!ModCheck) 16636 break; 16637 ModCheck = ModCheck->Parent; 16638 16639 IdentifierLocs.push_back(Path[I].second); 16640 } 16641 16642 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 16643 Mod, IdentifierLocs); 16644 if (!ModuleScopes.empty()) 16645 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16646 CurContext->addDecl(Import); 16647 16648 // Re-export the module if needed. 16649 if (Import->isExported() && 16650 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) 16651 getCurrentModule()->Exports.emplace_back(Mod, false); 16652 16653 return Import; 16654 } 16655 16656 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16657 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16658 BuildModuleInclude(DirectiveLoc, Mod); 16659 } 16660 16661 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16662 // Determine whether we're in the #include buffer for a module. The #includes 16663 // in that buffer do not qualify as module imports; they're just an 16664 // implementation detail of us building the module. 16665 // 16666 // FIXME: Should we even get ActOnModuleInclude calls for those? 16667 bool IsInModuleIncludes = 16668 TUKind == TU_Module && 16669 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16670 16671 bool ShouldAddImport = !IsInModuleIncludes; 16672 16673 // If this module import was due to an inclusion directive, create an 16674 // implicit import declaration to capture it in the AST. 16675 if (ShouldAddImport) { 16676 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16677 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16678 DirectiveLoc, Mod, 16679 DirectiveLoc); 16680 if (!ModuleScopes.empty()) 16681 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16682 TU->addDecl(ImportD); 16683 Consumer.HandleImplicitImportDecl(ImportD); 16684 } 16685 16686 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16687 VisibleModules.setVisible(Mod, DirectiveLoc); 16688 } 16689 16690 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16691 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16692 16693 ModuleScopes.push_back({}); 16694 ModuleScopes.back().Module = Mod; 16695 if (getLangOpts().ModulesLocalVisibility) 16696 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16697 16698 VisibleModules.setVisible(Mod, DirectiveLoc); 16699 16700 // The enclosing context is now part of this module. 16701 // FIXME: Consider creating a child DeclContext to hold the entities 16702 // lexically within the module. 16703 if (getLangOpts().trackLocalOwningModule()) { 16704 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16705 cast<Decl>(DC)->setModuleOwnershipKind( 16706 getLangOpts().ModulesLocalVisibility 16707 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16708 : Decl::ModuleOwnershipKind::Visible); 16709 cast<Decl>(DC)->setLocalOwningModule(Mod); 16710 } 16711 } 16712 } 16713 16714 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16715 if (getLangOpts().ModulesLocalVisibility) { 16716 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16717 // Leaving a module hides namespace names, so our visible namespace cache 16718 // is now out of date. 16719 VisibleNamespaceCache.clear(); 16720 } 16721 16722 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16723 "left the wrong module scope"); 16724 ModuleScopes.pop_back(); 16725 16726 // We got to the end of processing a local module. Create an 16727 // ImportDecl as we would for an imported module. 16728 FileID File = getSourceManager().getFileID(EomLoc); 16729 SourceLocation DirectiveLoc; 16730 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16731 // We reached the end of a #included module header. Use the #include loc. 16732 assert(File != getSourceManager().getMainFileID() && 16733 "end of submodule in main source file"); 16734 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16735 } else { 16736 // We reached an EOM pragma. Use the pragma location. 16737 DirectiveLoc = EomLoc; 16738 } 16739 BuildModuleInclude(DirectiveLoc, Mod); 16740 16741 // Any further declarations are in whatever module we returned to. 16742 if (getLangOpts().trackLocalOwningModule()) { 16743 // The parser guarantees that this is the same context that we entered 16744 // the module within. 16745 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16746 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16747 if (!getCurrentModule()) 16748 cast<Decl>(DC)->setModuleOwnershipKind( 16749 Decl::ModuleOwnershipKind::Unowned); 16750 } 16751 } 16752 } 16753 16754 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16755 Module *Mod) { 16756 // Bail if we're not allowed to implicitly import a module here. 16757 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16758 VisibleModules.isVisible(Mod)) 16759 return; 16760 16761 // Create the implicit import declaration. 16762 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16763 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16764 Loc, Mod, Loc); 16765 TU->addDecl(ImportD); 16766 Consumer.HandleImplicitImportDecl(ImportD); 16767 16768 // Make the module visible. 16769 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16770 VisibleModules.setVisible(Mod, Loc); 16771 } 16772 16773 /// We have parsed the start of an export declaration, including the '{' 16774 /// (if present). 16775 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16776 SourceLocation LBraceLoc) { 16777 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16778 16779 // C++ Modules TS draft: 16780 // An export-declaration shall appear in the purview of a module other than 16781 // the global module. 16782 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 16783 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16784 16785 // An export-declaration [...] shall not contain more than one 16786 // export keyword. 16787 // 16788 // The intent here is that an export-declaration cannot appear within another 16789 // export-declaration. 16790 if (D->isExported()) 16791 Diag(ExportLoc, diag::err_export_within_export); 16792 16793 CurContext->addDecl(D); 16794 PushDeclContext(S, D); 16795 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16796 return D; 16797 } 16798 16799 /// Complete the definition of an export declaration. 16800 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16801 auto *ED = cast<ExportDecl>(D); 16802 if (RBraceLoc.isValid()) 16803 ED->setRBraceLoc(RBraceLoc); 16804 16805 // FIXME: Diagnose export of internal-linkage declaration (including 16806 // anonymous namespace). 16807 16808 PopDeclContext(); 16809 return D; 16810 } 16811 16812 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16813 IdentifierInfo* AliasName, 16814 SourceLocation PragmaLoc, 16815 SourceLocation NameLoc, 16816 SourceLocation AliasNameLoc) { 16817 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16818 LookupOrdinaryName); 16819 AsmLabelAttr *Attr = 16820 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16821 16822 // If a declaration that: 16823 // 1) declares a function or a variable 16824 // 2) has external linkage 16825 // already exists, add a label attribute to it. 16826 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16827 if (isDeclExternC(PrevDecl)) 16828 PrevDecl->addAttr(Attr); 16829 else 16830 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16831 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16832 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16833 } else 16834 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16835 } 16836 16837 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16838 SourceLocation PragmaLoc, 16839 SourceLocation NameLoc) { 16840 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16841 16842 if (PrevDecl) { 16843 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16844 } else { 16845 (void)WeakUndeclaredIdentifiers.insert( 16846 std::pair<IdentifierInfo*,WeakInfo> 16847 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16848 } 16849 } 16850 16851 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16852 IdentifierInfo* AliasName, 16853 SourceLocation PragmaLoc, 16854 SourceLocation NameLoc, 16855 SourceLocation AliasNameLoc) { 16856 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16857 LookupOrdinaryName); 16858 WeakInfo W = WeakInfo(Name, NameLoc); 16859 16860 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16861 if (!PrevDecl->hasAttr<AliasAttr>()) 16862 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16863 DeclApplyPragmaWeak(TUScope, ND, W); 16864 } else { 16865 (void)WeakUndeclaredIdentifiers.insert( 16866 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16867 } 16868 } 16869 16870 Decl *Sema::getObjCDeclContext() const { 16871 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16872 } 16873