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___float128: 136 case tok::kw_wchar_t: 137 case tok::kw_bool: 138 case tok::kw___underlying_type: 139 case tok::kw___auto_type: 140 return true; 141 142 case tok::annot_typename: 143 case tok::kw_char16_t: 144 case tok::kw_char32_t: 145 case tok::kw_typeof: 146 case tok::annot_decltype: 147 case tok::kw_decltype: 148 return getLangOpts().CPlusPlus; 149 150 default: 151 break; 152 } 153 154 return false; 155 } 156 157 namespace { 158 enum class UnqualifiedTypeNameLookupResult { 159 NotFound, 160 FoundNonType, 161 FoundType 162 }; 163 } // end anonymous namespace 164 165 /// \brief Tries to perform unqualified lookup of the type decls in bases for 166 /// dependent class. 167 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 168 /// type decl, \a FoundType if only type decls are found. 169 static UnqualifiedTypeNameLookupResult 170 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 171 SourceLocation NameLoc, 172 const CXXRecordDecl *RD) { 173 if (!RD->hasDefinition()) 174 return UnqualifiedTypeNameLookupResult::NotFound; 175 // Look for type decls in base classes. 176 UnqualifiedTypeNameLookupResult FoundTypeDecl = 177 UnqualifiedTypeNameLookupResult::NotFound; 178 for (const auto &Base : RD->bases()) { 179 const CXXRecordDecl *BaseRD = nullptr; 180 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 181 BaseRD = BaseTT->getAsCXXRecordDecl(); 182 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 183 // Look for type decls in dependent base classes that have known primary 184 // templates. 185 if (!TST || !TST->isDependentType()) 186 continue; 187 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 188 if (!TD) 189 continue; 190 if (auto *BasePrimaryTemplate = 191 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 192 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 193 BaseRD = BasePrimaryTemplate; 194 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 195 if (const ClassTemplatePartialSpecializationDecl *PS = 196 CTD->findPartialSpecialization(Base.getType())) 197 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 198 BaseRD = PS; 199 } 200 } 201 } 202 if (BaseRD) { 203 for (NamedDecl *ND : BaseRD->lookup(&II)) { 204 if (!isa<TypeDecl>(ND)) 205 return UnqualifiedTypeNameLookupResult::FoundNonType; 206 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 207 } 208 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 209 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 210 case UnqualifiedTypeNameLookupResult::FoundNonType: 211 return UnqualifiedTypeNameLookupResult::FoundNonType; 212 case UnqualifiedTypeNameLookupResult::FoundType: 213 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 214 break; 215 case UnqualifiedTypeNameLookupResult::NotFound: 216 break; 217 } 218 } 219 } 220 } 221 222 return FoundTypeDecl; 223 } 224 225 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 226 const IdentifierInfo &II, 227 SourceLocation NameLoc) { 228 // Lookup in the parent class template context, if any. 229 const CXXRecordDecl *RD = nullptr; 230 UnqualifiedTypeNameLookupResult FoundTypeDecl = 231 UnqualifiedTypeNameLookupResult::NotFound; 232 for (DeclContext *DC = S.CurContext; 233 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 234 DC = DC->getParent()) { 235 // Look for type decls in dependent base classes that have known primary 236 // templates. 237 RD = dyn_cast<CXXRecordDecl>(DC); 238 if (RD && RD->getDescribedClassTemplate()) 239 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 240 } 241 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 242 return nullptr; 243 244 // We found some types in dependent base classes. Recover as if the user 245 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 246 // lookup during template instantiation. 247 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 248 249 ASTContext &Context = S.Context; 250 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 251 cast<Type>(Context.getRecordType(RD))); 252 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 253 254 CXXScopeSpec SS; 255 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 256 257 TypeLocBuilder Builder; 258 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 259 DepTL.setNameLoc(NameLoc); 260 DepTL.setElaboratedKeywordLoc(SourceLocation()); 261 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 262 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 263 } 264 265 /// \brief If the identifier refers to a type name within this scope, 266 /// return the declaration of that type. 267 /// 268 /// This routine performs ordinary name lookup of the identifier II 269 /// within the given scope, with optional C++ scope specifier SS, to 270 /// determine whether the name refers to a type. If so, returns an 271 /// opaque pointer (actually a QualType) corresponding to that 272 /// type. Otherwise, returns NULL. 273 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 274 Scope *S, CXXScopeSpec *SS, 275 bool isClassName, bool HasTrailingDot, 276 ParsedType ObjectTypePtr, 277 bool IsCtorOrDtorName, 278 bool WantNontrivialTypeSourceInfo, 279 bool IsClassTemplateDeductionContext, 280 IdentifierInfo **CorrectedII) { 281 // FIXME: Consider allowing this outside C++1z mode as an extension. 282 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 283 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName && 284 !isClassName && !HasTrailingDot; 285 286 // Determine where we will perform name lookup. 287 DeclContext *LookupCtx = nullptr; 288 if (ObjectTypePtr) { 289 QualType ObjectType = ObjectTypePtr.get(); 290 if (ObjectType->isRecordType()) 291 LookupCtx = computeDeclContext(ObjectType); 292 } else if (SS && SS->isNotEmpty()) { 293 LookupCtx = computeDeclContext(*SS, false); 294 295 if (!LookupCtx) { 296 if (isDependentScopeSpecifier(*SS)) { 297 // C++ [temp.res]p3: 298 // A qualified-id that refers to a type and in which the 299 // nested-name-specifier depends on a template-parameter (14.6.2) 300 // shall be prefixed by the keyword typename to indicate that the 301 // qualified-id denotes a type, forming an 302 // elaborated-type-specifier (7.1.5.3). 303 // 304 // We therefore do not perform any name lookup if the result would 305 // refer to a member of an unknown specialization. 306 if (!isClassName && !IsCtorOrDtorName) 307 return nullptr; 308 309 // We know from the grammar that this name refers to a type, 310 // so build a dependent node to describe the type. 311 if (WantNontrivialTypeSourceInfo) 312 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 313 314 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 315 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 316 II, NameLoc); 317 return ParsedType::make(T); 318 } 319 320 return nullptr; 321 } 322 323 if (!LookupCtx->isDependentContext() && 324 RequireCompleteDeclContext(*SS, LookupCtx)) 325 return nullptr; 326 } 327 328 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 329 // lookup for class-names. 330 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 331 LookupOrdinaryName; 332 LookupResult Result(*this, &II, NameLoc, Kind); 333 if (LookupCtx) { 334 // Perform "qualified" name lookup into the declaration context we 335 // computed, which is either the type of the base of a member access 336 // expression or the declaration context associated with a prior 337 // nested-name-specifier. 338 LookupQualifiedName(Result, LookupCtx); 339 340 if (ObjectTypePtr && Result.empty()) { 341 // C++ [basic.lookup.classref]p3: 342 // If the unqualified-id is ~type-name, the type-name is looked up 343 // in the context of the entire postfix-expression. If the type T of 344 // the object expression is of a class type C, the type-name is also 345 // looked up in the scope of class C. At least one of the lookups shall 346 // find a name that refers to (possibly cv-qualified) T. 347 LookupName(Result, S); 348 } 349 } else { 350 // Perform unqualified name lookup. 351 LookupName(Result, S); 352 353 // For unqualified lookup in a class template in MSVC mode, look into 354 // dependent base classes where the primary class template is known. 355 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 356 if (ParsedType TypeInBase = 357 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 358 return TypeInBase; 359 } 360 } 361 362 NamedDecl *IIDecl = nullptr; 363 switch (Result.getResultKind()) { 364 case LookupResult::NotFound: 365 case LookupResult::NotFoundInCurrentInstantiation: 366 if (CorrectedII) { 367 TypoCorrection Correction = 368 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 369 llvm::make_unique<TypeNameValidatorCCC>( 370 true, isClassName, AllowDeducedTemplate), 371 CTK_ErrorRecovery); 372 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 373 TemplateTy Template; 374 bool MemberOfUnknownSpecialization; 375 UnqualifiedId TemplateName; 376 TemplateName.setIdentifier(NewII, NameLoc); 377 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 378 CXXScopeSpec NewSS, *NewSSPtr = SS; 379 if (SS && NNS) { 380 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 381 NewSSPtr = &NewSS; 382 } 383 if (Correction && (NNS || NewII != &II) && 384 // Ignore a correction to a template type as the to-be-corrected 385 // identifier is not a template (typo correction for template names 386 // is handled elsewhere). 387 !(getLangOpts().CPlusPlus && NewSSPtr && 388 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 389 Template, MemberOfUnknownSpecialization))) { 390 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 391 isClassName, HasTrailingDot, ObjectTypePtr, 392 IsCtorOrDtorName, 393 WantNontrivialTypeSourceInfo, 394 IsClassTemplateDeductionContext); 395 if (Ty) { 396 diagnoseTypo(Correction, 397 PDiag(diag::err_unknown_type_or_class_name_suggest) 398 << Result.getLookupName() << isClassName); 399 if (SS && NNS) 400 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 401 *CorrectedII = NewII; 402 return Ty; 403 } 404 } 405 } 406 // If typo correction failed or was not performed, fall through 407 case LookupResult::FoundOverloaded: 408 case LookupResult::FoundUnresolvedValue: 409 Result.suppressDiagnostics(); 410 return nullptr; 411 412 case LookupResult::Ambiguous: 413 // Recover from type-hiding ambiguities by hiding the type. We'll 414 // do the lookup again when looking for an object, and we can 415 // diagnose the error then. If we don't do this, then the error 416 // about hiding the type will be immediately followed by an error 417 // that only makes sense if the identifier was treated like a type. 418 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 419 Result.suppressDiagnostics(); 420 return nullptr; 421 } 422 423 // Look to see if we have a type anywhere in the list of results. 424 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 425 Res != ResEnd; ++Res) { 426 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 427 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 428 if (!IIDecl || 429 (*Res)->getLocation().getRawEncoding() < 430 IIDecl->getLocation().getRawEncoding()) 431 IIDecl = *Res; 432 } 433 } 434 435 if (!IIDecl) { 436 // None of the entities we found is a type, so there is no way 437 // to even assume that the result is a type. In this case, don't 438 // complain about the ambiguity. The parser will either try to 439 // perform this lookup again (e.g., as an object name), which 440 // will produce the ambiguity, or will complain that it expected 441 // a type name. 442 Result.suppressDiagnostics(); 443 return nullptr; 444 } 445 446 // We found a type within the ambiguous lookup; diagnose the 447 // ambiguity and then return that type. This might be the right 448 // answer, or it might not be, but it suppresses any attempt to 449 // perform the name lookup again. 450 break; 451 452 case LookupResult::Found: 453 IIDecl = Result.getFoundDecl(); 454 break; 455 } 456 457 assert(IIDecl && "Didn't find decl"); 458 459 QualType T; 460 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 461 // C++ [class.qual]p2: A lookup that would find the injected-class-name 462 // instead names the constructors of the class, except when naming a class. 463 // This is ill-formed when we're not actually forming a ctor or dtor name. 464 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 465 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 466 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 467 FoundRD->isInjectedClassName() && 468 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 469 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 470 << &II << /*Type*/1; 471 472 DiagnoseUseOfDecl(IIDecl, NameLoc); 473 474 T = Context.getTypeDeclType(TD); 475 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 476 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 477 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 478 if (!HasTrailingDot) 479 T = Context.getObjCInterfaceType(IDecl); 480 } else if (AllowDeducedTemplate) { 481 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 482 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 483 QualType(), false); 484 } 485 486 if (T.isNull()) { 487 // If it's not plausibly a type, suppress diagnostics. 488 Result.suppressDiagnostics(); 489 return nullptr; 490 } 491 492 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 493 // constructor or destructor name (in such a case, the scope specifier 494 // will be attached to the enclosing Expr or Decl node). 495 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 496 !isa<ObjCInterfaceDecl>(IIDecl)) { 497 if (WantNontrivialTypeSourceInfo) { 498 // Construct a type with type-source information. 499 TypeLocBuilder Builder; 500 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 501 502 T = getElaboratedType(ETK_None, *SS, T); 503 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 504 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 505 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 506 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 507 } else { 508 T = getElaboratedType(ETK_None, *SS, T); 509 } 510 } 511 512 return ParsedType::make(T); 513 } 514 515 // Builds a fake NNS for the given decl context. 516 static NestedNameSpecifier * 517 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 518 for (;; DC = DC->getLookupParent()) { 519 DC = DC->getPrimaryContext(); 520 auto *ND = dyn_cast<NamespaceDecl>(DC); 521 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 522 return NestedNameSpecifier::Create(Context, nullptr, ND); 523 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 524 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 525 RD->getTypeForDecl()); 526 else if (isa<TranslationUnitDecl>(DC)) 527 return NestedNameSpecifier::GlobalSpecifier(Context); 528 } 529 llvm_unreachable("something isn't in TU scope?"); 530 } 531 532 /// Find the parent class with dependent bases of the innermost enclosing method 533 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 534 /// up allowing unqualified dependent type names at class-level, which MSVC 535 /// correctly rejects. 536 static const CXXRecordDecl * 537 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 538 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 539 DC = DC->getPrimaryContext(); 540 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 541 if (MD->getParent()->hasAnyDependentBases()) 542 return MD->getParent(); 543 } 544 return nullptr; 545 } 546 547 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 548 SourceLocation NameLoc, 549 bool IsTemplateTypeArg) { 550 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 551 552 NestedNameSpecifier *NNS = nullptr; 553 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 554 // If we weren't able to parse a default template argument, delay lookup 555 // until instantiation time by making a non-dependent DependentTypeName. We 556 // pretend we saw a NestedNameSpecifier referring to the current scope, and 557 // lookup is retried. 558 // FIXME: This hurts our diagnostic quality, since we get errors like "no 559 // type named 'Foo' in 'current_namespace'" when the user didn't write any 560 // name specifiers. 561 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 562 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 563 } else if (const CXXRecordDecl *RD = 564 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 565 // Build a DependentNameType that will perform lookup into RD at 566 // instantiation time. 567 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 568 RD->getTypeForDecl()); 569 570 // Diagnose that this identifier was undeclared, and retry the lookup during 571 // template instantiation. 572 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 573 << RD; 574 } else { 575 // This is not a situation that we should recover from. 576 return ParsedType(); 577 } 578 579 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 580 581 // Build type location information. We synthesized the qualifier, so we have 582 // to build a fake NestedNameSpecifierLoc. 583 NestedNameSpecifierLocBuilder NNSLocBuilder; 584 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 585 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 586 587 TypeLocBuilder Builder; 588 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 589 DepTL.setNameLoc(NameLoc); 590 DepTL.setElaboratedKeywordLoc(SourceLocation()); 591 DepTL.setQualifierLoc(QualifierLoc); 592 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 593 } 594 595 /// isTagName() - This method is called *for error recovery purposes only* 596 /// to determine if the specified name is a valid tag name ("struct foo"). If 597 /// so, this returns the TST for the tag corresponding to it (TST_enum, 598 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 599 /// cases in C where the user forgot to specify the tag. 600 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 601 // Do a tag name lookup in this scope. 602 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 603 LookupName(R, S, false); 604 R.suppressDiagnostics(); 605 if (R.getResultKind() == LookupResult::Found) 606 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 607 switch (TD->getTagKind()) { 608 case TTK_Struct: return DeclSpec::TST_struct; 609 case TTK_Interface: return DeclSpec::TST_interface; 610 case TTK_Union: return DeclSpec::TST_union; 611 case TTK_Class: return DeclSpec::TST_class; 612 case TTK_Enum: return DeclSpec::TST_enum; 613 } 614 } 615 616 return DeclSpec::TST_unspecified; 617 } 618 619 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 620 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 621 /// then downgrade the missing typename error to a warning. 622 /// This is needed for MSVC compatibility; Example: 623 /// @code 624 /// template<class T> class A { 625 /// public: 626 /// typedef int TYPE; 627 /// }; 628 /// template<class T> class B : public A<T> { 629 /// public: 630 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 631 /// }; 632 /// @endcode 633 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 634 if (CurContext->isRecord()) { 635 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 636 return true; 637 638 const Type *Ty = SS->getScopeRep()->getAsType(); 639 640 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 641 for (const auto &Base : RD->bases()) 642 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 643 return true; 644 return S->isFunctionPrototypeScope(); 645 } 646 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 647 } 648 649 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 650 SourceLocation IILoc, 651 Scope *S, 652 CXXScopeSpec *SS, 653 ParsedType &SuggestedType, 654 bool IsTemplateName) { 655 // Don't report typename errors for editor placeholders. 656 if (II->isEditorPlaceholder()) 657 return; 658 // We don't have anything to suggest (yet). 659 SuggestedType = nullptr; 660 661 // There may have been a typo in the name of the type. Look up typo 662 // results, in case we have something that we can suggest. 663 if (TypoCorrection Corrected = 664 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 665 llvm::make_unique<TypeNameValidatorCCC>( 666 false, false, IsTemplateName, !IsTemplateName), 667 CTK_ErrorRecovery)) { 668 // FIXME: Support error recovery for the template-name case. 669 bool CanRecover = !IsTemplateName; 670 if (Corrected.isKeyword()) { 671 // We corrected to a keyword. 672 diagnoseTypo(Corrected, 673 PDiag(IsTemplateName ? diag::err_no_template_suggest 674 : diag::err_unknown_typename_suggest) 675 << II); 676 II = Corrected.getCorrectionAsIdentifierInfo(); 677 } else { 678 // We found a similarly-named type or interface; suggest that. 679 if (!SS || !SS->isSet()) { 680 diagnoseTypo(Corrected, 681 PDiag(IsTemplateName ? diag::err_no_template_suggest 682 : diag::err_unknown_typename_suggest) 683 << II, CanRecover); 684 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 685 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 686 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 687 II->getName().equals(CorrectedStr); 688 diagnoseTypo(Corrected, 689 PDiag(IsTemplateName 690 ? diag::err_no_member_template_suggest 691 : diag::err_unknown_nested_typename_suggest) 692 << II << DC << DroppedSpecifier << SS->getRange(), 693 CanRecover); 694 } else { 695 llvm_unreachable("could not have corrected a typo here"); 696 } 697 698 if (!CanRecover) 699 return; 700 701 CXXScopeSpec tmpSS; 702 if (Corrected.getCorrectionSpecifier()) 703 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 704 SourceRange(IILoc)); 705 // FIXME: Support class template argument deduction here. 706 SuggestedType = 707 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 708 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 709 /*IsCtorOrDtorName=*/false, 710 /*NonTrivialTypeSourceInfo=*/true); 711 } 712 return; 713 } 714 715 if (getLangOpts().CPlusPlus && !IsTemplateName) { 716 // See if II is a class template that the user forgot to pass arguments to. 717 UnqualifiedId Name; 718 Name.setIdentifier(II, IILoc); 719 CXXScopeSpec EmptySS; 720 TemplateTy TemplateResult; 721 bool MemberOfUnknownSpecialization; 722 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 723 Name, nullptr, true, TemplateResult, 724 MemberOfUnknownSpecialization) == TNK_Type_template) { 725 TemplateName TplName = TemplateResult.get(); 726 Diag(IILoc, diag::err_template_missing_args) 727 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 728 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 729 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 730 << TplDecl->getTemplateParameters()->getSourceRange(); 731 } 732 return; 733 } 734 } 735 736 // FIXME: Should we move the logic that tries to recover from a missing tag 737 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 738 739 if (!SS || (!SS->isSet() && !SS->isInvalid())) 740 Diag(IILoc, IsTemplateName ? diag::err_no_template 741 : diag::err_unknown_typename) 742 << II; 743 else if (DeclContext *DC = computeDeclContext(*SS, false)) 744 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 745 : diag::err_typename_nested_not_found) 746 << II << DC << SS->getRange(); 747 else if (isDependentScopeSpecifier(*SS)) { 748 unsigned DiagID = diag::err_typename_missing; 749 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 750 DiagID = diag::ext_typename_missing; 751 752 Diag(SS->getRange().getBegin(), DiagID) 753 << SS->getScopeRep() << II->getName() 754 << SourceRange(SS->getRange().getBegin(), IILoc) 755 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 756 SuggestedType = ActOnTypenameType(S, SourceLocation(), 757 *SS, *II, IILoc).get(); 758 } else { 759 assert(SS && SS->isInvalid() && 760 "Invalid scope specifier has already been diagnosed"); 761 } 762 } 763 764 /// \brief Determine whether the given result set contains either a type name 765 /// or 766 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 767 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 768 NextToken.is(tok::less); 769 770 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 771 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 772 return true; 773 774 if (CheckTemplate && isa<TemplateDecl>(*I)) 775 return true; 776 } 777 778 return false; 779 } 780 781 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 782 Scope *S, CXXScopeSpec &SS, 783 IdentifierInfo *&Name, 784 SourceLocation NameLoc) { 785 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 786 SemaRef.LookupParsedName(R, S, &SS); 787 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 788 StringRef FixItTagName; 789 switch (Tag->getTagKind()) { 790 case TTK_Class: 791 FixItTagName = "class "; 792 break; 793 794 case TTK_Enum: 795 FixItTagName = "enum "; 796 break; 797 798 case TTK_Struct: 799 FixItTagName = "struct "; 800 break; 801 802 case TTK_Interface: 803 FixItTagName = "__interface "; 804 break; 805 806 case TTK_Union: 807 FixItTagName = "union "; 808 break; 809 } 810 811 StringRef TagName = FixItTagName.drop_back(); 812 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 813 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 814 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 815 816 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 817 I != IEnd; ++I) 818 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 819 << Name << TagName; 820 821 // Replace lookup results with just the tag decl. 822 Result.clear(Sema::LookupTagName); 823 SemaRef.LookupParsedName(Result, S, &SS); 824 return true; 825 } 826 827 return false; 828 } 829 830 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 831 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 832 QualType T, SourceLocation NameLoc) { 833 ASTContext &Context = S.Context; 834 835 TypeLocBuilder Builder; 836 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 837 838 T = S.getElaboratedType(ETK_None, SS, T); 839 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 840 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 841 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 842 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 843 } 844 845 Sema::NameClassification 846 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 847 SourceLocation NameLoc, const Token &NextToken, 848 bool IsAddressOfOperand, 849 std::unique_ptr<CorrectionCandidateCallback> CCC) { 850 DeclarationNameInfo NameInfo(Name, NameLoc); 851 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 852 853 if (NextToken.is(tok::coloncolon)) { 854 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 855 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 856 } else if (getLangOpts().CPlusPlus && SS.isSet() && 857 isCurrentClassName(*Name, S, &SS)) { 858 // Per [class.qual]p2, this names the constructors of SS, not the 859 // injected-class-name. We don't have a classification for that. 860 // There's not much point caching this result, since the parser 861 // will reject it later. 862 return NameClassification::Unknown(); 863 } 864 865 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 866 LookupParsedName(Result, S, &SS, !CurMethod); 867 868 // For unqualified lookup in a class template in MSVC mode, look into 869 // dependent base classes where the primary class template is known. 870 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 871 if (ParsedType TypeInBase = 872 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 873 return TypeInBase; 874 } 875 876 // Perform lookup for Objective-C instance variables (including automatically 877 // synthesized instance variables), if we're in an Objective-C method. 878 // FIXME: This lookup really, really needs to be folded in to the normal 879 // unqualified lookup mechanism. 880 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 881 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 882 if (E.get() || E.isInvalid()) 883 return E; 884 } 885 886 bool SecondTry = false; 887 bool IsFilteredTemplateName = false; 888 889 Corrected: 890 switch (Result.getResultKind()) { 891 case LookupResult::NotFound: 892 // If an unqualified-id is followed by a '(', then we have a function 893 // call. 894 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 895 // In C++, this is an ADL-only call. 896 // FIXME: Reference? 897 if (getLangOpts().CPlusPlus) 898 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 899 900 // C90 6.3.2.2: 901 // If the expression that precedes the parenthesized argument list in a 902 // function call consists solely of an identifier, and if no 903 // declaration is visible for this identifier, the identifier is 904 // implicitly declared exactly as if, in the innermost block containing 905 // the function call, the declaration 906 // 907 // extern int identifier (); 908 // 909 // appeared. 910 // 911 // We also allow this in C99 as an extension. 912 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 913 Result.addDecl(D); 914 Result.resolveKind(); 915 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 916 } 917 } 918 919 // In C, we first see whether there is a tag type by the same name, in 920 // which case it's likely that the user just forgot to write "enum", 921 // "struct", or "union". 922 if (!getLangOpts().CPlusPlus && !SecondTry && 923 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 924 break; 925 } 926 927 // Perform typo correction to determine if there is another name that is 928 // close to this name. 929 if (!SecondTry && CCC) { 930 SecondTry = true; 931 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 932 Result.getLookupKind(), S, 933 &SS, std::move(CCC), 934 CTK_ErrorRecovery)) { 935 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 936 unsigned QualifiedDiag = diag::err_no_member_suggest; 937 938 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 939 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 940 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 941 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 942 UnqualifiedDiag = diag::err_no_template_suggest; 943 QualifiedDiag = diag::err_no_member_template_suggest; 944 } else if (UnderlyingFirstDecl && 945 (isa<TypeDecl>(UnderlyingFirstDecl) || 946 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 947 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 948 UnqualifiedDiag = diag::err_unknown_typename_suggest; 949 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 950 } 951 952 if (SS.isEmpty()) { 953 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 954 } else {// FIXME: is this even reachable? Test it. 955 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 956 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 957 Name->getName().equals(CorrectedStr); 958 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 959 << Name << computeDeclContext(SS, false) 960 << DroppedSpecifier << SS.getRange()); 961 } 962 963 // Update the name, so that the caller has the new name. 964 Name = Corrected.getCorrectionAsIdentifierInfo(); 965 966 // Typo correction corrected to a keyword. 967 if (Corrected.isKeyword()) 968 return Name; 969 970 // Also update the LookupResult... 971 // FIXME: This should probably go away at some point 972 Result.clear(); 973 Result.setLookupName(Corrected.getCorrection()); 974 if (FirstDecl) 975 Result.addDecl(FirstDecl); 976 977 // If we found an Objective-C instance variable, let 978 // LookupInObjCMethod build the appropriate expression to 979 // reference the ivar. 980 // FIXME: This is a gross hack. 981 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 982 Result.clear(); 983 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 984 return E; 985 } 986 987 goto Corrected; 988 } 989 } 990 991 // We failed to correct; just fall through and let the parser deal with it. 992 Result.suppressDiagnostics(); 993 return NameClassification::Unknown(); 994 995 case LookupResult::NotFoundInCurrentInstantiation: { 996 // We performed name lookup into the current instantiation, and there were 997 // dependent bases, so we treat this result the same way as any other 998 // dependent nested-name-specifier. 999 1000 // C++ [temp.res]p2: 1001 // A name used in a template declaration or definition and that is 1002 // dependent on a template-parameter is assumed not to name a type 1003 // unless the applicable name lookup finds a type name or the name is 1004 // qualified by the keyword typename. 1005 // 1006 // FIXME: If the next token is '<', we might want to ask the parser to 1007 // perform some heroics to see if we actually have a 1008 // template-argument-list, which would indicate a missing 'template' 1009 // keyword here. 1010 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1011 NameInfo, IsAddressOfOperand, 1012 /*TemplateArgs=*/nullptr); 1013 } 1014 1015 case LookupResult::Found: 1016 case LookupResult::FoundOverloaded: 1017 case LookupResult::FoundUnresolvedValue: 1018 break; 1019 1020 case LookupResult::Ambiguous: 1021 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1022 hasAnyAcceptableTemplateNames(Result)) { 1023 // C++ [temp.local]p3: 1024 // A lookup that finds an injected-class-name (10.2) can result in an 1025 // ambiguity in certain cases (for example, if it is found in more than 1026 // one base class). If all of the injected-class-names that are found 1027 // refer to specializations of the same class template, and if the name 1028 // is followed by a template-argument-list, the reference refers to the 1029 // class template itself and not a specialization thereof, and is not 1030 // ambiguous. 1031 // 1032 // This filtering can make an ambiguous result into an unambiguous one, 1033 // so try again after filtering out template names. 1034 FilterAcceptableTemplateNames(Result); 1035 if (!Result.isAmbiguous()) { 1036 IsFilteredTemplateName = true; 1037 break; 1038 } 1039 } 1040 1041 // Diagnose the ambiguity and return an error. 1042 return NameClassification::Error(); 1043 } 1044 1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1046 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1047 // C++ [temp.names]p3: 1048 // After name lookup (3.4) finds that a name is a template-name or that 1049 // an operator-function-id or a literal- operator-id refers to a set of 1050 // overloaded functions any member of which is a function template if 1051 // this is followed by a <, the < is always taken as the delimiter of a 1052 // template-argument-list and never as the less-than operator. 1053 if (!IsFilteredTemplateName) 1054 FilterAcceptableTemplateNames(Result); 1055 1056 if (!Result.empty()) { 1057 bool IsFunctionTemplate; 1058 bool IsVarTemplate; 1059 TemplateName Template; 1060 if (Result.end() - Result.begin() > 1) { 1061 IsFunctionTemplate = true; 1062 Template = Context.getOverloadedTemplateName(Result.begin(), 1063 Result.end()); 1064 } else { 1065 TemplateDecl *TD 1066 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1067 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1068 IsVarTemplate = isa<VarTemplateDecl>(TD); 1069 1070 if (SS.isSet() && !SS.isInvalid()) 1071 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1072 /*TemplateKeyword=*/false, 1073 TD); 1074 else 1075 Template = TemplateName(TD); 1076 } 1077 1078 if (IsFunctionTemplate) { 1079 // Function templates always go through overload resolution, at which 1080 // point we'll perform the various checks (e.g., accessibility) we need 1081 // to based on which function we selected. 1082 Result.suppressDiagnostics(); 1083 1084 return NameClassification::FunctionTemplate(Template); 1085 } 1086 1087 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1088 : NameClassification::TypeTemplate(Template); 1089 } 1090 } 1091 1092 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1093 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1094 DiagnoseUseOfDecl(Type, NameLoc); 1095 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1096 QualType T = Context.getTypeDeclType(Type); 1097 if (SS.isNotEmpty()) 1098 return buildNestedType(*this, SS, T, NameLoc); 1099 return ParsedType::make(T); 1100 } 1101 1102 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1103 if (!Class) { 1104 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1105 if (ObjCCompatibleAliasDecl *Alias = 1106 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1107 Class = Alias->getClassInterface(); 1108 } 1109 1110 if (Class) { 1111 DiagnoseUseOfDecl(Class, NameLoc); 1112 1113 if (NextToken.is(tok::period)) { 1114 // Interface. <something> is parsed as a property reference expression. 1115 // Just return "unknown" as a fall-through for now. 1116 Result.suppressDiagnostics(); 1117 return NameClassification::Unknown(); 1118 } 1119 1120 QualType T = Context.getObjCInterfaceType(Class); 1121 return ParsedType::make(T); 1122 } 1123 1124 // We can have a type template here if we're classifying a template argument. 1125 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1126 !isa<VarTemplateDecl>(FirstDecl)) 1127 return NameClassification::TypeTemplate( 1128 TemplateName(cast<TemplateDecl>(FirstDecl))); 1129 1130 // Check for a tag type hidden by a non-type decl in a few cases where it 1131 // seems likely a type is wanted instead of the non-type that was found. 1132 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1133 if ((NextToken.is(tok::identifier) || 1134 (NextIsOp && 1135 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1136 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1137 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1138 DiagnoseUseOfDecl(Type, NameLoc); 1139 QualType T = Context.getTypeDeclType(Type); 1140 if (SS.isNotEmpty()) 1141 return buildNestedType(*this, SS, T, NameLoc); 1142 return ParsedType::make(T); 1143 } 1144 1145 if (FirstDecl->isCXXClassMember()) 1146 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1147 nullptr, S); 1148 1149 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1150 return BuildDeclarationNameExpr(SS, Result, ADL); 1151 } 1152 1153 Sema::TemplateNameKindForDiagnostics 1154 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1155 auto *TD = Name.getAsTemplateDecl(); 1156 if (!TD) 1157 return TemplateNameKindForDiagnostics::DependentTemplate; 1158 if (isa<ClassTemplateDecl>(TD)) 1159 return TemplateNameKindForDiagnostics::ClassTemplate; 1160 if (isa<FunctionTemplateDecl>(TD)) 1161 return TemplateNameKindForDiagnostics::FunctionTemplate; 1162 if (isa<VarTemplateDecl>(TD)) 1163 return TemplateNameKindForDiagnostics::VarTemplate; 1164 if (isa<TypeAliasTemplateDecl>(TD)) 1165 return TemplateNameKindForDiagnostics::AliasTemplate; 1166 if (isa<TemplateTemplateParmDecl>(TD)) 1167 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1168 return TemplateNameKindForDiagnostics::DependentTemplate; 1169 } 1170 1171 // Determines the context to return to after temporarily entering a 1172 // context. This depends in an unnecessarily complicated way on the 1173 // exact ordering of callbacks from the parser. 1174 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1175 1176 // Functions defined inline within classes aren't parsed until we've 1177 // finished parsing the top-level class, so the top-level class is 1178 // the context we'll need to return to. 1179 // A Lambda call operator whose parent is a class must not be treated 1180 // as an inline member function. A Lambda can be used legally 1181 // either as an in-class member initializer or a default argument. These 1182 // are parsed once the class has been marked complete and so the containing 1183 // context would be the nested class (when the lambda is defined in one); 1184 // If the class is not complete, then the lambda is being used in an 1185 // ill-formed fashion (such as to specify the width of a bit-field, or 1186 // in an array-bound) - in which case we still want to return the 1187 // lexically containing DC (which could be a nested class). 1188 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1189 DC = DC->getLexicalParent(); 1190 1191 // A function not defined within a class will always return to its 1192 // lexical context. 1193 if (!isa<CXXRecordDecl>(DC)) 1194 return DC; 1195 1196 // A C++ inline method/friend is parsed *after* the topmost class 1197 // it was declared in is fully parsed ("complete"); the topmost 1198 // class is the context we need to return to. 1199 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1200 DC = RD; 1201 1202 // Return the declaration context of the topmost class the inline method is 1203 // declared in. 1204 return DC; 1205 } 1206 1207 return DC->getLexicalParent(); 1208 } 1209 1210 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1211 assert(getContainingDC(DC) == CurContext && 1212 "The next DeclContext should be lexically contained in the current one."); 1213 CurContext = DC; 1214 S->setEntity(DC); 1215 } 1216 1217 void Sema::PopDeclContext() { 1218 assert(CurContext && "DeclContext imbalance!"); 1219 1220 CurContext = getContainingDC(CurContext); 1221 assert(CurContext && "Popped translation unit!"); 1222 } 1223 1224 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1225 Decl *D) { 1226 // Unlike PushDeclContext, the context to which we return is not necessarily 1227 // the containing DC of TD, because the new context will be some pre-existing 1228 // TagDecl definition instead of a fresh one. 1229 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1230 CurContext = cast<TagDecl>(D)->getDefinition(); 1231 assert(CurContext && "skipping definition of undefined tag"); 1232 // Start lookups from the parent of the current context; we don't want to look 1233 // into the pre-existing complete definition. 1234 S->setEntity(CurContext->getLookupParent()); 1235 return Result; 1236 } 1237 1238 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1239 CurContext = static_cast<decltype(CurContext)>(Context); 1240 } 1241 1242 /// EnterDeclaratorContext - Used when we must lookup names in the context 1243 /// of a declarator's nested name specifier. 1244 /// 1245 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1246 // C++0x [basic.lookup.unqual]p13: 1247 // A name used in the definition of a static data member of class 1248 // X (after the qualified-id of the static member) is looked up as 1249 // if the name was used in a member function of X. 1250 // C++0x [basic.lookup.unqual]p14: 1251 // If a variable member of a namespace is defined outside of the 1252 // scope of its namespace then any name used in the definition of 1253 // the variable member (after the declarator-id) is looked up as 1254 // if the definition of the variable member occurred in its 1255 // namespace. 1256 // Both of these imply that we should push a scope whose context 1257 // is the semantic context of the declaration. We can't use 1258 // PushDeclContext here because that context is not necessarily 1259 // lexically contained in the current context. Fortunately, 1260 // the containing scope should have the appropriate information. 1261 1262 assert(!S->getEntity() && "scope already has entity"); 1263 1264 #ifndef NDEBUG 1265 Scope *Ancestor = S->getParent(); 1266 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1267 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1268 #endif 1269 1270 CurContext = DC; 1271 S->setEntity(DC); 1272 } 1273 1274 void Sema::ExitDeclaratorContext(Scope *S) { 1275 assert(S->getEntity() == CurContext && "Context imbalance!"); 1276 1277 // Switch back to the lexical context. The safety of this is 1278 // enforced by an assert in EnterDeclaratorContext. 1279 Scope *Ancestor = S->getParent(); 1280 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1281 CurContext = Ancestor->getEntity(); 1282 1283 // We don't need to do anything with the scope, which is going to 1284 // disappear. 1285 } 1286 1287 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1288 // We assume that the caller has already called 1289 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1290 FunctionDecl *FD = D->getAsFunction(); 1291 if (!FD) 1292 return; 1293 1294 // Same implementation as PushDeclContext, but enters the context 1295 // from the lexical parent, rather than the top-level class. 1296 assert(CurContext == FD->getLexicalParent() && 1297 "The next DeclContext should be lexically contained in the current one."); 1298 CurContext = FD; 1299 S->setEntity(CurContext); 1300 1301 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1302 ParmVarDecl *Param = FD->getParamDecl(P); 1303 // If the parameter has an identifier, then add it to the scope 1304 if (Param->getIdentifier()) { 1305 S->AddDecl(Param); 1306 IdResolver.AddDecl(Param); 1307 } 1308 } 1309 } 1310 1311 void Sema::ActOnExitFunctionContext() { 1312 // Same implementation as PopDeclContext, but returns to the lexical parent, 1313 // rather than the top-level class. 1314 assert(CurContext && "DeclContext imbalance!"); 1315 CurContext = CurContext->getLexicalParent(); 1316 assert(CurContext && "Popped translation unit!"); 1317 } 1318 1319 /// \brief Determine whether we allow overloading of the function 1320 /// PrevDecl with another declaration. 1321 /// 1322 /// This routine determines whether overloading is possible, not 1323 /// whether some new function is actually an overload. It will return 1324 /// true in C++ (where we can always provide overloads) or, as an 1325 /// extension, in C when the previous function is already an 1326 /// overloaded function declaration or has the "overloadable" 1327 /// attribute. 1328 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1329 ASTContext &Context) { 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 } 1339 1340 /// Add this decl to the scope shadowed decl chains. 1341 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1342 // Move up the scope chain until we find the nearest enclosing 1343 // non-transparent context. The declaration will be introduced into this 1344 // scope. 1345 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1346 S = S->getParent(); 1347 1348 // Add scoped declarations into their context, so that they can be 1349 // found later. Declarations without a context won't be inserted 1350 // into any context. 1351 if (AddToContext) 1352 CurContext->addDecl(D); 1353 1354 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1355 // are function-local declarations. 1356 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1357 !D->getDeclContext()->getRedeclContext()->Equals( 1358 D->getLexicalDeclContext()->getRedeclContext()) && 1359 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1360 return; 1361 1362 // Template instantiations should also not be pushed into scope. 1363 if (isa<FunctionDecl>(D) && 1364 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1365 return; 1366 1367 // If this replaces anything in the current scope, 1368 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1369 IEnd = IdResolver.end(); 1370 for (; I != IEnd; ++I) { 1371 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1372 S->RemoveDecl(*I); 1373 IdResolver.RemoveDecl(*I); 1374 1375 // Should only need to replace one decl. 1376 break; 1377 } 1378 } 1379 1380 S->AddDecl(D); 1381 1382 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1383 // Implicitly-generated labels may end up getting generated in an order that 1384 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1385 // the label at the appropriate place in the identifier chain. 1386 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1387 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1388 if (IDC == CurContext) { 1389 if (!S->isDeclScope(*I)) 1390 continue; 1391 } else if (IDC->Encloses(CurContext)) 1392 break; 1393 } 1394 1395 IdResolver.InsertDeclAfter(I, D); 1396 } else { 1397 IdResolver.AddDecl(D); 1398 } 1399 } 1400 1401 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1402 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1403 TUScope->AddDecl(D); 1404 } 1405 1406 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1407 bool AllowInlineNamespace) { 1408 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1409 } 1410 1411 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1412 DeclContext *TargetDC = DC->getPrimaryContext(); 1413 do { 1414 if (DeclContext *ScopeDC = S->getEntity()) 1415 if (ScopeDC->getPrimaryContext() == TargetDC) 1416 return S; 1417 } while ((S = S->getParent())); 1418 1419 return nullptr; 1420 } 1421 1422 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1423 DeclContext*, 1424 ASTContext&); 1425 1426 /// Filters out lookup results that don't fall within the given scope 1427 /// as determined by isDeclInScope. 1428 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1429 bool ConsiderLinkage, 1430 bool AllowInlineNamespace) { 1431 LookupResult::Filter F = R.makeFilter(); 1432 while (F.hasNext()) { 1433 NamedDecl *D = F.next(); 1434 1435 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1436 continue; 1437 1438 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1439 continue; 1440 1441 F.erase(); 1442 } 1443 1444 F.done(); 1445 } 1446 1447 static bool isUsingDecl(NamedDecl *D) { 1448 return isa<UsingShadowDecl>(D) || 1449 isa<UnresolvedUsingTypenameDecl>(D) || 1450 isa<UnresolvedUsingValueDecl>(D); 1451 } 1452 1453 /// Removes using shadow declarations from the lookup results. 1454 static void RemoveUsingDecls(LookupResult &R) { 1455 LookupResult::Filter F = R.makeFilter(); 1456 while (F.hasNext()) 1457 if (isUsingDecl(F.next())) 1458 F.erase(); 1459 1460 F.done(); 1461 } 1462 1463 /// \brief Check for this common pattern: 1464 /// @code 1465 /// class S { 1466 /// S(const S&); // DO NOT IMPLEMENT 1467 /// void operator=(const S&); // DO NOT IMPLEMENT 1468 /// }; 1469 /// @endcode 1470 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1471 // FIXME: Should check for private access too but access is set after we get 1472 // the decl here. 1473 if (D->doesThisDeclarationHaveABody()) 1474 return false; 1475 1476 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1477 return CD->isCopyConstructor(); 1478 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1479 return Method->isCopyAssignmentOperator(); 1480 return false; 1481 } 1482 1483 // We need this to handle 1484 // 1485 // typedef struct { 1486 // void *foo() { return 0; } 1487 // } A; 1488 // 1489 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1490 // for example. If 'A', foo will have external linkage. If we have '*A', 1491 // foo will have no linkage. Since we can't know until we get to the end 1492 // of the typedef, this function finds out if D might have non-external linkage. 1493 // Callers should verify at the end of the TU if it D has external linkage or 1494 // not. 1495 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1496 const DeclContext *DC = D->getDeclContext(); 1497 while (!DC->isTranslationUnit()) { 1498 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1499 if (!RD->hasNameForLinkage()) 1500 return true; 1501 } 1502 DC = DC->getParent(); 1503 } 1504 1505 return !D->isExternallyVisible(); 1506 } 1507 1508 // FIXME: This needs to be refactored; some other isInMainFile users want 1509 // these semantics. 1510 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1511 if (S.TUKind != TU_Complete) 1512 return false; 1513 return S.SourceMgr.isInMainFile(Loc); 1514 } 1515 1516 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1517 assert(D); 1518 1519 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1520 return false; 1521 1522 // Ignore all entities declared within templates, and out-of-line definitions 1523 // of members of class templates. 1524 if (D->getDeclContext()->isDependentContext() || 1525 D->getLexicalDeclContext()->isDependentContext()) 1526 return false; 1527 1528 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1529 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1530 return false; 1531 // A non-out-of-line declaration of a member specialization was implicitly 1532 // instantiated; it's the out-of-line declaration that we're interested in. 1533 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1534 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1535 return false; 1536 1537 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1538 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1539 return false; 1540 } else { 1541 // 'static inline' functions are defined in headers; don't warn. 1542 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1543 return false; 1544 } 1545 1546 if (FD->doesThisDeclarationHaveABody() && 1547 Context.DeclMustBeEmitted(FD)) 1548 return false; 1549 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1550 // Constants and utility variables are defined in headers with internal 1551 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1552 // like "inline".) 1553 if (!isMainFileLoc(*this, VD->getLocation())) 1554 return false; 1555 1556 if (Context.DeclMustBeEmitted(VD)) 1557 return false; 1558 1559 if (VD->isStaticDataMember() && 1560 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1561 return false; 1562 if (VD->isStaticDataMember() && 1563 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1564 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1565 return false; 1566 1567 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1568 return false; 1569 } else { 1570 return false; 1571 } 1572 1573 // Only warn for unused decls internal to the translation unit. 1574 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1575 // for inline functions defined in the main source file, for instance. 1576 return mightHaveNonExternalLinkage(D); 1577 } 1578 1579 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1580 if (!D) 1581 return; 1582 1583 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1584 const FunctionDecl *First = FD->getFirstDecl(); 1585 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1586 return; // First should already be in the vector. 1587 } 1588 1589 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1590 const VarDecl *First = VD->getFirstDecl(); 1591 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1592 return; // First should already be in the vector. 1593 } 1594 1595 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1596 UnusedFileScopedDecls.push_back(D); 1597 } 1598 1599 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1600 if (D->isInvalidDecl()) 1601 return false; 1602 1603 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1604 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1605 return false; 1606 1607 if (isa<LabelDecl>(D)) 1608 return true; 1609 1610 // Except for labels, we only care about unused decls that are local to 1611 // functions. 1612 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1613 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1614 // For dependent types, the diagnostic is deferred. 1615 WithinFunction = 1616 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1617 if (!WithinFunction) 1618 return false; 1619 1620 if (isa<TypedefNameDecl>(D)) 1621 return true; 1622 1623 // White-list anything that isn't a local variable. 1624 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1625 return false; 1626 1627 // Types of valid local variables should be complete, so this should succeed. 1628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1629 1630 // White-list anything with an __attribute__((unused)) type. 1631 const auto *Ty = VD->getType().getTypePtr(); 1632 1633 // Only look at the outermost level of typedef. 1634 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1635 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1636 return false; 1637 } 1638 1639 // If we failed to complete the type for some reason, or if the type is 1640 // dependent, don't diagnose the variable. 1641 if (Ty->isIncompleteType() || Ty->isDependentType()) 1642 return false; 1643 1644 // Look at the element type to ensure that the warning behaviour is 1645 // consistent for both scalars and arrays. 1646 Ty = Ty->getBaseElementTypeUnsafe(); 1647 1648 if (const TagType *TT = Ty->getAs<TagType>()) { 1649 const TagDecl *Tag = TT->getDecl(); 1650 if (Tag->hasAttr<UnusedAttr>()) 1651 return false; 1652 1653 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1654 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1655 return false; 1656 1657 if (const Expr *Init = VD->getInit()) { 1658 if (const ExprWithCleanups *Cleanups = 1659 dyn_cast<ExprWithCleanups>(Init)) 1660 Init = Cleanups->getSubExpr(); 1661 const CXXConstructExpr *Construct = 1662 dyn_cast<CXXConstructExpr>(Init); 1663 if (Construct && !Construct->isElidable()) { 1664 CXXConstructorDecl *CD = Construct->getConstructor(); 1665 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1666 return false; 1667 } 1668 } 1669 } 1670 } 1671 1672 // TODO: __attribute__((unused)) templates? 1673 } 1674 1675 return true; 1676 } 1677 1678 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1679 FixItHint &Hint) { 1680 if (isa<LabelDecl>(D)) { 1681 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1682 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1683 if (AfterColon.isInvalid()) 1684 return; 1685 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1686 getCharRange(D->getLocStart(), AfterColon)); 1687 } 1688 } 1689 1690 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1691 if (D->getTypeForDecl()->isDependentType()) 1692 return; 1693 1694 for (auto *TmpD : D->decls()) { 1695 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1696 DiagnoseUnusedDecl(T); 1697 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1698 DiagnoseUnusedNestedTypedefs(R); 1699 } 1700 } 1701 1702 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1703 /// unless they are marked attr(unused). 1704 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1705 if (!ShouldDiagnoseUnusedDecl(D)) 1706 return; 1707 1708 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1709 // typedefs can be referenced later on, so the diagnostics are emitted 1710 // at end-of-translation-unit. 1711 UnusedLocalTypedefNameCandidates.insert(TD); 1712 return; 1713 } 1714 1715 FixItHint Hint; 1716 GenerateFixForUnusedDecl(D, Context, Hint); 1717 1718 unsigned DiagID; 1719 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1720 DiagID = diag::warn_unused_exception_param; 1721 else if (isa<LabelDecl>(D)) 1722 DiagID = diag::warn_unused_label; 1723 else 1724 DiagID = diag::warn_unused_variable; 1725 1726 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1727 } 1728 1729 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1730 // Verify that we have no forward references left. If so, there was a goto 1731 // or address of a label taken, but no definition of it. Label fwd 1732 // definitions are indicated with a null substmt which is also not a resolved 1733 // MS inline assembly label name. 1734 bool Diagnose = false; 1735 if (L->isMSAsmLabel()) 1736 Diagnose = !L->isResolvedMSAsmLabel(); 1737 else 1738 Diagnose = L->getStmt() == nullptr; 1739 if (Diagnose) 1740 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1741 } 1742 1743 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1744 S->mergeNRVOIntoParent(); 1745 1746 if (S->decl_empty()) return; 1747 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1748 "Scope shouldn't contain decls!"); 1749 1750 for (auto *TmpD : S->decls()) { 1751 assert(TmpD && "This decl didn't get pushed??"); 1752 1753 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1754 NamedDecl *D = cast<NamedDecl>(TmpD); 1755 1756 if (!D->getDeclName()) continue; 1757 1758 // Diagnose unused variables in this scope. 1759 if (!S->hasUnrecoverableErrorOccurred()) { 1760 DiagnoseUnusedDecl(D); 1761 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1762 DiagnoseUnusedNestedTypedefs(RD); 1763 } 1764 1765 // If this was a forward reference to a label, verify it was defined. 1766 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1767 CheckPoppedLabel(LD, *this); 1768 1769 // Remove this name from our lexical scope, and warn on it if we haven't 1770 // already. 1771 IdResolver.RemoveDecl(D); 1772 auto ShadowI = ShadowingDecls.find(D); 1773 if (ShadowI != ShadowingDecls.end()) { 1774 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1775 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1776 << D << FD << FD->getParent(); 1777 Diag(FD->getLocation(), diag::note_previous_declaration); 1778 } 1779 ShadowingDecls.erase(ShadowI); 1780 } 1781 } 1782 } 1783 1784 /// \brief Look for an Objective-C class in the translation unit. 1785 /// 1786 /// \param Id The name of the Objective-C class we're looking for. If 1787 /// typo-correction fixes this name, the Id will be updated 1788 /// to the fixed name. 1789 /// 1790 /// \param IdLoc The location of the name in the translation unit. 1791 /// 1792 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1793 /// if there is no class with the given name. 1794 /// 1795 /// \returns The declaration of the named Objective-C class, or NULL if the 1796 /// class could not be found. 1797 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1798 SourceLocation IdLoc, 1799 bool DoTypoCorrection) { 1800 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1801 // creation from this context. 1802 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1803 1804 if (!IDecl && DoTypoCorrection) { 1805 // Perform typo correction at the given location, but only if we 1806 // find an Objective-C class name. 1807 if (TypoCorrection C = CorrectTypo( 1808 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1809 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1810 CTK_ErrorRecovery)) { 1811 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1812 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1813 Id = IDecl->getIdentifier(); 1814 } 1815 } 1816 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1817 // This routine must always return a class definition, if any. 1818 if (Def && Def->getDefinition()) 1819 Def = Def->getDefinition(); 1820 return Def; 1821 } 1822 1823 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1824 /// from S, where a non-field would be declared. This routine copes 1825 /// with the difference between C and C++ scoping rules in structs and 1826 /// unions. For example, the following code is well-formed in C but 1827 /// ill-formed in C++: 1828 /// @code 1829 /// struct S6 { 1830 /// enum { BAR } e; 1831 /// }; 1832 /// 1833 /// void test_S6() { 1834 /// struct S6 a; 1835 /// a.e = BAR; 1836 /// } 1837 /// @endcode 1838 /// For the declaration of BAR, this routine will return a different 1839 /// scope. The scope S will be the scope of the unnamed enumeration 1840 /// within S6. In C++, this routine will return the scope associated 1841 /// with S6, because the enumeration's scope is a transparent 1842 /// context but structures can contain non-field names. In C, this 1843 /// routine will return the translation unit scope, since the 1844 /// enumeration's scope is a transparent context and structures cannot 1845 /// contain non-field names. 1846 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1847 while (((S->getFlags() & Scope::DeclScope) == 0) || 1848 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1849 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1850 S = S->getParent(); 1851 return S; 1852 } 1853 1854 /// \brief Looks up the declaration of "struct objc_super" and 1855 /// saves it for later use in building builtin declaration of 1856 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1857 /// pre-existing declaration exists no action takes place. 1858 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1859 IdentifierInfo *II) { 1860 if (!II->isStr("objc_msgSendSuper")) 1861 return; 1862 ASTContext &Context = ThisSema.Context; 1863 1864 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1865 SourceLocation(), Sema::LookupTagName); 1866 ThisSema.LookupName(Result, S); 1867 if (Result.getResultKind() == LookupResult::Found) 1868 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1869 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1870 } 1871 1872 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1873 switch (Error) { 1874 case ASTContext::GE_None: 1875 return ""; 1876 case ASTContext::GE_Missing_stdio: 1877 return "stdio.h"; 1878 case ASTContext::GE_Missing_setjmp: 1879 return "setjmp.h"; 1880 case ASTContext::GE_Missing_ucontext: 1881 return "ucontext.h"; 1882 } 1883 llvm_unreachable("unhandled error kind"); 1884 } 1885 1886 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1887 /// file scope. lazily create a decl for it. ForRedeclaration is true 1888 /// if we're creating this built-in in anticipation of redeclaring the 1889 /// built-in. 1890 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1891 Scope *S, bool ForRedeclaration, 1892 SourceLocation Loc) { 1893 LookupPredefedObjCSuperType(*this, S, II); 1894 1895 ASTContext::GetBuiltinTypeError Error; 1896 QualType R = Context.GetBuiltinType(ID, Error); 1897 if (Error) { 1898 if (ForRedeclaration) 1899 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1900 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1901 return nullptr; 1902 } 1903 1904 if (!ForRedeclaration && 1905 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1906 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1907 Diag(Loc, diag::ext_implicit_lib_function_decl) 1908 << Context.BuiltinInfo.getName(ID) << R; 1909 if (Context.BuiltinInfo.getHeaderName(ID) && 1910 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1911 Diag(Loc, diag::note_include_header_or_declare) 1912 << Context.BuiltinInfo.getHeaderName(ID) 1913 << Context.BuiltinInfo.getName(ID); 1914 } 1915 1916 if (R.isNull()) 1917 return nullptr; 1918 1919 DeclContext *Parent = Context.getTranslationUnitDecl(); 1920 if (getLangOpts().CPlusPlus) { 1921 LinkageSpecDecl *CLinkageDecl = 1922 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1923 LinkageSpecDecl::lang_c, false); 1924 CLinkageDecl->setImplicit(); 1925 Parent->addDecl(CLinkageDecl); 1926 Parent = CLinkageDecl; 1927 } 1928 1929 FunctionDecl *New = FunctionDecl::Create(Context, 1930 Parent, 1931 Loc, Loc, II, R, /*TInfo=*/nullptr, 1932 SC_Extern, 1933 false, 1934 R->isFunctionProtoType()); 1935 New->setImplicit(); 1936 1937 // Create Decl objects for each parameter, adding them to the 1938 // FunctionDecl. 1939 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1940 SmallVector<ParmVarDecl*, 16> Params; 1941 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1942 ParmVarDecl *parm = 1943 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1944 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1945 SC_None, nullptr); 1946 parm->setScopeInfo(0, i); 1947 Params.push_back(parm); 1948 } 1949 New->setParams(Params); 1950 } 1951 1952 AddKnownFunctionAttributes(New); 1953 RegisterLocallyScopedExternCDecl(New, S); 1954 1955 // TUScope is the translation-unit scope to insert this function into. 1956 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1957 // relate Scopes to DeclContexts, and probably eliminate CurContext 1958 // entirely, but we're not there yet. 1959 DeclContext *SavedContext = CurContext; 1960 CurContext = Parent; 1961 PushOnScopeChains(New, TUScope); 1962 CurContext = SavedContext; 1963 return New; 1964 } 1965 1966 /// Typedef declarations don't have linkage, but they still denote the same 1967 /// entity if their types are the same. 1968 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1969 /// isSameEntity. 1970 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1971 TypedefNameDecl *Decl, 1972 LookupResult &Previous) { 1973 // This is only interesting when modules are enabled. 1974 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1975 return; 1976 1977 // Empty sets are uninteresting. 1978 if (Previous.empty()) 1979 return; 1980 1981 LookupResult::Filter Filter = Previous.makeFilter(); 1982 while (Filter.hasNext()) { 1983 NamedDecl *Old = Filter.next(); 1984 1985 // Non-hidden declarations are never ignored. 1986 if (S.isVisible(Old)) 1987 continue; 1988 1989 // Declarations of the same entity are not ignored, even if they have 1990 // different linkages. 1991 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1992 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1993 Decl->getUnderlyingType())) 1994 continue; 1995 1996 // If both declarations give a tag declaration a typedef name for linkage 1997 // purposes, then they declare the same entity. 1998 if (S.getLangOpts().CPlusPlus && 1999 OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2000 Decl->getAnonDeclWithTypedefName()) 2001 continue; 2002 } 2003 2004 Filter.erase(); 2005 } 2006 2007 Filter.done(); 2008 } 2009 2010 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2011 QualType OldType; 2012 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2013 OldType = OldTypedef->getUnderlyingType(); 2014 else 2015 OldType = Context.getTypeDeclType(Old); 2016 QualType NewType = New->getUnderlyingType(); 2017 2018 if (NewType->isVariablyModifiedType()) { 2019 // Must not redefine a typedef with a variably-modified type. 2020 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2021 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2022 << Kind << NewType; 2023 if (Old->getLocation().isValid()) 2024 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2025 New->setInvalidDecl(); 2026 return true; 2027 } 2028 2029 if (OldType != NewType && 2030 !OldType->isDependentType() && 2031 !NewType->isDependentType() && 2032 !Context.hasSameType(OldType, NewType)) { 2033 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2034 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2035 << Kind << NewType << OldType; 2036 if (Old->getLocation().isValid()) 2037 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2038 New->setInvalidDecl(); 2039 return true; 2040 } 2041 return false; 2042 } 2043 2044 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2045 /// same name and scope as a previous declaration 'Old'. Figure out 2046 /// how to resolve this situation, merging decls or emitting 2047 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2048 /// 2049 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2050 LookupResult &OldDecls) { 2051 // If the new decl is known invalid already, don't bother doing any 2052 // merging checks. 2053 if (New->isInvalidDecl()) return; 2054 2055 // Allow multiple definitions for ObjC built-in typedefs. 2056 // FIXME: Verify the underlying types are equivalent! 2057 if (getLangOpts().ObjC1) { 2058 const IdentifierInfo *TypeID = New->getIdentifier(); 2059 switch (TypeID->getLength()) { 2060 default: break; 2061 case 2: 2062 { 2063 if (!TypeID->isStr("id")) 2064 break; 2065 QualType T = New->getUnderlyingType(); 2066 if (!T->isPointerType()) 2067 break; 2068 if (!T->isVoidPointerType()) { 2069 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2070 if (!PT->isStructureType()) 2071 break; 2072 } 2073 Context.setObjCIdRedefinitionType(T); 2074 // Install the built-in type for 'id', ignoring the current definition. 2075 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2076 return; 2077 } 2078 case 5: 2079 if (!TypeID->isStr("Class")) 2080 break; 2081 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2082 // Install the built-in type for 'Class', ignoring the current definition. 2083 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2084 return; 2085 case 3: 2086 if (!TypeID->isStr("SEL")) 2087 break; 2088 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2089 // Install the built-in type for 'SEL', ignoring the current definition. 2090 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2091 return; 2092 } 2093 // Fall through - the typedef name was not a builtin type. 2094 } 2095 2096 // Verify the old decl was also a type. 2097 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2098 if (!Old) { 2099 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2100 << New->getDeclName(); 2101 2102 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2103 if (OldD->getLocation().isValid()) 2104 notePreviousDefinition(OldD->getLocation(), New->getLocation()); 2105 2106 return New->setInvalidDecl(); 2107 } 2108 2109 // If the old declaration is invalid, just give up here. 2110 if (Old->isInvalidDecl()) 2111 return New->setInvalidDecl(); 2112 2113 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2114 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2115 auto *NewTag = New->getAnonDeclWithTypedefName(); 2116 NamedDecl *Hidden = nullptr; 2117 if (getLangOpts().CPlusPlus && OldTag && NewTag && 2118 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2119 !hasVisibleDefinition(OldTag, &Hidden)) { 2120 // There is a definition of this tag, but it is not visible. Use it 2121 // instead of our tag. 2122 New->setTypeForDecl(OldTD->getTypeForDecl()); 2123 if (OldTD->isModed()) 2124 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2125 OldTD->getUnderlyingType()); 2126 else 2127 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2128 2129 // Make the old tag definition visible. 2130 makeMergedDefinitionVisible(Hidden); 2131 2132 // If this was an unscoped enumeration, yank all of its enumerators 2133 // out of the scope. 2134 if (isa<EnumDecl>(NewTag)) { 2135 Scope *EnumScope = getNonFieldDeclScope(S); 2136 for (auto *D : NewTag->decls()) { 2137 auto *ED = cast<EnumConstantDecl>(D); 2138 assert(EnumScope->isDeclScope(ED)); 2139 EnumScope->RemoveDecl(ED); 2140 IdResolver.RemoveDecl(ED); 2141 ED->getLexicalDeclContext()->removeDecl(ED); 2142 } 2143 } 2144 } 2145 } 2146 2147 // If the typedef types are not identical, reject them in all languages and 2148 // with any extensions enabled. 2149 if (isIncompatibleTypedef(Old, New)) 2150 return; 2151 2152 // The types match. Link up the redeclaration chain and merge attributes if 2153 // the old declaration was a typedef. 2154 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2155 New->setPreviousDecl(Typedef); 2156 mergeDeclAttributes(New, Old); 2157 } 2158 2159 if (getLangOpts().MicrosoftExt) 2160 return; 2161 2162 if (getLangOpts().CPlusPlus) { 2163 // C++ [dcl.typedef]p2: 2164 // In a given non-class scope, a typedef specifier can be used to 2165 // redefine the name of any type declared in that scope to refer 2166 // to the type to which it already refers. 2167 if (!isa<CXXRecordDecl>(CurContext)) 2168 return; 2169 2170 // C++0x [dcl.typedef]p4: 2171 // In a given class scope, a typedef specifier can be used to redefine 2172 // any class-name declared in that scope that is not also a typedef-name 2173 // to refer to the type to which it already refers. 2174 // 2175 // This wording came in via DR424, which was a correction to the 2176 // wording in DR56, which accidentally banned code like: 2177 // 2178 // struct S { 2179 // typedef struct A { } A; 2180 // }; 2181 // 2182 // in the C++03 standard. We implement the C++0x semantics, which 2183 // allow the above but disallow 2184 // 2185 // struct S { 2186 // typedef int I; 2187 // typedef int I; 2188 // }; 2189 // 2190 // since that was the intent of DR56. 2191 if (!isa<TypedefNameDecl>(Old)) 2192 return; 2193 2194 Diag(New->getLocation(), diag::err_redefinition) 2195 << New->getDeclName(); 2196 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2197 return New->setInvalidDecl(); 2198 } 2199 2200 // Modules always permit redefinition of typedefs, as does C11. 2201 if (getLangOpts().Modules || getLangOpts().C11) 2202 return; 2203 2204 // If we have a redefinition of a typedef in C, emit a warning. This warning 2205 // is normally mapped to an error, but can be controlled with 2206 // -Wtypedef-redefinition. If either the original or the redefinition is 2207 // in a system header, don't emit this for compatibility with GCC. 2208 if (getDiagnostics().getSuppressSystemWarnings() && 2209 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2210 (Old->isImplicit() || 2211 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2212 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2213 return; 2214 2215 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2216 << New->getDeclName(); 2217 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2218 } 2219 2220 /// DeclhasAttr - returns true if decl Declaration already has the target 2221 /// attribute. 2222 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2223 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2224 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2225 for (const auto *i : D->attrs()) 2226 if (i->getKind() == A->getKind()) { 2227 if (Ann) { 2228 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2229 return true; 2230 continue; 2231 } 2232 // FIXME: Don't hardcode this check 2233 if (OA && isa<OwnershipAttr>(i)) 2234 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2235 return true; 2236 } 2237 2238 return false; 2239 } 2240 2241 static bool isAttributeTargetADefinition(Decl *D) { 2242 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2243 return VD->isThisDeclarationADefinition(); 2244 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2245 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2246 return true; 2247 } 2248 2249 /// Merge alignment attributes from \p Old to \p New, taking into account the 2250 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2251 /// 2252 /// \return \c true if any attributes were added to \p New. 2253 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2254 // Look for alignas attributes on Old, and pick out whichever attribute 2255 // specifies the strictest alignment requirement. 2256 AlignedAttr *OldAlignasAttr = nullptr; 2257 AlignedAttr *OldStrictestAlignAttr = nullptr; 2258 unsigned OldAlign = 0; 2259 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2260 // FIXME: We have no way of representing inherited dependent alignments 2261 // in a case like: 2262 // template<int A, int B> struct alignas(A) X; 2263 // template<int A, int B> struct alignas(B) X {}; 2264 // For now, we just ignore any alignas attributes which are not on the 2265 // definition in such a case. 2266 if (I->isAlignmentDependent()) 2267 return false; 2268 2269 if (I->isAlignas()) 2270 OldAlignasAttr = I; 2271 2272 unsigned Align = I->getAlignment(S.Context); 2273 if (Align > OldAlign) { 2274 OldAlign = Align; 2275 OldStrictestAlignAttr = I; 2276 } 2277 } 2278 2279 // Look for alignas attributes on New. 2280 AlignedAttr *NewAlignasAttr = nullptr; 2281 unsigned NewAlign = 0; 2282 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2283 if (I->isAlignmentDependent()) 2284 return false; 2285 2286 if (I->isAlignas()) 2287 NewAlignasAttr = I; 2288 2289 unsigned Align = I->getAlignment(S.Context); 2290 if (Align > NewAlign) 2291 NewAlign = Align; 2292 } 2293 2294 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2295 // Both declarations have 'alignas' attributes. We require them to match. 2296 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2297 // fall short. (If two declarations both have alignas, they must both match 2298 // every definition, and so must match each other if there is a definition.) 2299 2300 // If either declaration only contains 'alignas(0)' specifiers, then it 2301 // specifies the natural alignment for the type. 2302 if (OldAlign == 0 || NewAlign == 0) { 2303 QualType Ty; 2304 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2305 Ty = VD->getType(); 2306 else 2307 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2308 2309 if (OldAlign == 0) 2310 OldAlign = S.Context.getTypeAlign(Ty); 2311 if (NewAlign == 0) 2312 NewAlign = S.Context.getTypeAlign(Ty); 2313 } 2314 2315 if (OldAlign != NewAlign) { 2316 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2317 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2318 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2319 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2320 } 2321 } 2322 2323 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2324 // C++11 [dcl.align]p6: 2325 // if any declaration of an entity has an alignment-specifier, 2326 // every defining declaration of that entity shall specify an 2327 // equivalent alignment. 2328 // C11 6.7.5/7: 2329 // If the definition of an object does not have an alignment 2330 // specifier, any other declaration of that object shall also 2331 // have no alignment specifier. 2332 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2333 << OldAlignasAttr; 2334 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2335 << OldAlignasAttr; 2336 } 2337 2338 bool AnyAdded = false; 2339 2340 // Ensure we have an attribute representing the strictest alignment. 2341 if (OldAlign > NewAlign) { 2342 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2343 Clone->setInherited(true); 2344 New->addAttr(Clone); 2345 AnyAdded = true; 2346 } 2347 2348 // Ensure we have an alignas attribute if the old declaration had one. 2349 if (OldAlignasAttr && !NewAlignasAttr && 2350 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2351 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2352 Clone->setInherited(true); 2353 New->addAttr(Clone); 2354 AnyAdded = true; 2355 } 2356 2357 return AnyAdded; 2358 } 2359 2360 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2361 const InheritableAttr *Attr, 2362 Sema::AvailabilityMergeKind AMK) { 2363 // This function copies an attribute Attr from a previous declaration to the 2364 // new declaration D if the new declaration doesn't itself have that attribute 2365 // yet or if that attribute allows duplicates. 2366 // If you're adding a new attribute that requires logic different from 2367 // "use explicit attribute on decl if present, else use attribute from 2368 // previous decl", for example if the attribute needs to be consistent 2369 // between redeclarations, you need to call a custom merge function here. 2370 InheritableAttr *NewAttr = nullptr; 2371 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2372 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2373 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2374 AA->isImplicit(), AA->getIntroduced(), 2375 AA->getDeprecated(), 2376 AA->getObsoleted(), AA->getUnavailable(), 2377 AA->getMessage(), AA->getStrict(), 2378 AA->getReplacement(), AMK, 2379 AttrSpellingListIndex); 2380 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2381 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2382 AttrSpellingListIndex); 2383 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2384 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2385 AttrSpellingListIndex); 2386 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2387 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2388 AttrSpellingListIndex); 2389 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2390 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2391 AttrSpellingListIndex); 2392 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2393 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2394 FA->getFormatIdx(), FA->getFirstArg(), 2395 AttrSpellingListIndex); 2396 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2397 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2398 AttrSpellingListIndex); 2399 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2400 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2401 AttrSpellingListIndex, 2402 IA->getSemanticSpelling()); 2403 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2404 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2405 &S.Context.Idents.get(AA->getSpelling()), 2406 AttrSpellingListIndex); 2407 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2408 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2409 isa<CUDAGlobalAttr>(Attr))) { 2410 // CUDA target attributes are part of function signature for 2411 // overloading purposes and must not be merged. 2412 return false; 2413 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2414 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2415 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2416 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2417 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2418 NewAttr = S.mergeInternalLinkageAttr( 2419 D, InternalLinkageA->getRange(), 2420 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2421 AttrSpellingListIndex); 2422 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2423 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2424 &S.Context.Idents.get(CommonA->getSpelling()), 2425 AttrSpellingListIndex); 2426 else if (isa<AlignedAttr>(Attr)) 2427 // AlignedAttrs are handled separately, because we need to handle all 2428 // such attributes on a declaration at the same time. 2429 NewAttr = nullptr; 2430 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2431 (AMK == Sema::AMK_Override || 2432 AMK == Sema::AMK_ProtocolImplementation)) 2433 NewAttr = nullptr; 2434 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2435 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2436 UA->getGuid()); 2437 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2438 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2439 2440 if (NewAttr) { 2441 NewAttr->setInherited(true); 2442 D->addAttr(NewAttr); 2443 if (isa<MSInheritanceAttr>(NewAttr)) 2444 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2445 return true; 2446 } 2447 2448 return false; 2449 } 2450 2451 static const Decl *getDefinition(const Decl *D) { 2452 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2453 return TD->getDefinition(); 2454 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2455 const VarDecl *Def = VD->getDefinition(); 2456 if (Def) 2457 return Def; 2458 return VD->getActingDefinition(); 2459 } 2460 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2461 return FD->getDefinition(); 2462 return nullptr; 2463 } 2464 2465 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2466 for (const auto *Attribute : D->attrs()) 2467 if (Attribute->getKind() == Kind) 2468 return true; 2469 return false; 2470 } 2471 2472 /// checkNewAttributesAfterDef - If we already have a definition, check that 2473 /// there are no new attributes in this declaration. 2474 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2475 if (!New->hasAttrs()) 2476 return; 2477 2478 const Decl *Def = getDefinition(Old); 2479 if (!Def || Def == New) 2480 return; 2481 2482 AttrVec &NewAttributes = New->getAttrs(); 2483 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2484 const Attr *NewAttribute = NewAttributes[I]; 2485 2486 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2487 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2488 Sema::SkipBodyInfo SkipBody; 2489 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2490 2491 // If we're skipping this definition, drop the "alias" attribute. 2492 if (SkipBody.ShouldSkip) { 2493 NewAttributes.erase(NewAttributes.begin() + I); 2494 --E; 2495 continue; 2496 } 2497 } else { 2498 VarDecl *VD = cast<VarDecl>(New); 2499 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2500 VarDecl::TentativeDefinition 2501 ? diag::err_alias_after_tentative 2502 : diag::err_redefinition; 2503 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2504 if (Diag == diag::err_redefinition) 2505 S.notePreviousDefinition(Def->getLocation(), VD->getLocation()); 2506 else 2507 S.Diag(Def->getLocation(), diag::note_previous_definition); 2508 VD->setInvalidDecl(); 2509 } 2510 ++I; 2511 continue; 2512 } 2513 2514 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2515 // Tentative definitions are only interesting for the alias check above. 2516 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2517 ++I; 2518 continue; 2519 } 2520 } 2521 2522 if (hasAttribute(Def, NewAttribute->getKind())) { 2523 ++I; 2524 continue; // regular attr merging will take care of validating this. 2525 } 2526 2527 if (isa<C11NoReturnAttr>(NewAttribute)) { 2528 // C's _Noreturn is allowed to be added to a function after it is defined. 2529 ++I; 2530 continue; 2531 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2532 if (AA->isAlignas()) { 2533 // C++11 [dcl.align]p6: 2534 // if any declaration of an entity has an alignment-specifier, 2535 // every defining declaration of that entity shall specify an 2536 // equivalent alignment. 2537 // C11 6.7.5/7: 2538 // If the definition of an object does not have an alignment 2539 // specifier, any other declaration of that object shall also 2540 // have no alignment specifier. 2541 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2542 << AA; 2543 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2544 << AA; 2545 NewAttributes.erase(NewAttributes.begin() + I); 2546 --E; 2547 continue; 2548 } 2549 } 2550 2551 S.Diag(NewAttribute->getLocation(), 2552 diag::warn_attribute_precede_definition); 2553 S.Diag(Def->getLocation(), diag::note_previous_definition); 2554 NewAttributes.erase(NewAttributes.begin() + I); 2555 --E; 2556 } 2557 } 2558 2559 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2560 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2561 AvailabilityMergeKind AMK) { 2562 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2563 UsedAttr *NewAttr = OldAttr->clone(Context); 2564 NewAttr->setInherited(true); 2565 New->addAttr(NewAttr); 2566 } 2567 2568 if (!Old->hasAttrs() && !New->hasAttrs()) 2569 return; 2570 2571 // Attributes declared post-definition are currently ignored. 2572 checkNewAttributesAfterDef(*this, New, Old); 2573 2574 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2575 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2576 if (OldA->getLabel() != NewA->getLabel()) { 2577 // This redeclaration changes __asm__ label. 2578 Diag(New->getLocation(), diag::err_different_asm_label); 2579 Diag(OldA->getLocation(), diag::note_previous_declaration); 2580 } 2581 } else if (Old->isUsed()) { 2582 // This redeclaration adds an __asm__ label to a declaration that has 2583 // already been ODR-used. 2584 Diag(New->getLocation(), diag::err_late_asm_label_name) 2585 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2586 } 2587 } 2588 2589 // Re-declaration cannot add abi_tag's. 2590 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2591 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2592 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2593 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2594 NewTag) == OldAbiTagAttr->tags_end()) { 2595 Diag(NewAbiTagAttr->getLocation(), 2596 diag::err_new_abi_tag_on_redeclaration) 2597 << NewTag; 2598 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2599 } 2600 } 2601 } else { 2602 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2603 Diag(Old->getLocation(), diag::note_previous_declaration); 2604 } 2605 } 2606 2607 if (!Old->hasAttrs()) 2608 return; 2609 2610 bool foundAny = New->hasAttrs(); 2611 2612 // Ensure that any moving of objects within the allocated map is done before 2613 // we process them. 2614 if (!foundAny) New->setAttrs(AttrVec()); 2615 2616 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2617 // Ignore deprecated/unavailable/availability attributes if requested. 2618 AvailabilityMergeKind LocalAMK = AMK_None; 2619 if (isa<DeprecatedAttr>(I) || 2620 isa<UnavailableAttr>(I) || 2621 isa<AvailabilityAttr>(I)) { 2622 switch (AMK) { 2623 case AMK_None: 2624 continue; 2625 2626 case AMK_Redeclaration: 2627 case AMK_Override: 2628 case AMK_ProtocolImplementation: 2629 LocalAMK = AMK; 2630 break; 2631 } 2632 } 2633 2634 // Already handled. 2635 if (isa<UsedAttr>(I)) 2636 continue; 2637 2638 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2639 foundAny = true; 2640 } 2641 2642 if (mergeAlignedAttrs(*this, New, Old)) 2643 foundAny = true; 2644 2645 if (!foundAny) New->dropAttrs(); 2646 } 2647 2648 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2649 /// to the new one. 2650 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2651 const ParmVarDecl *oldDecl, 2652 Sema &S) { 2653 // C++11 [dcl.attr.depend]p2: 2654 // The first declaration of a function shall specify the 2655 // carries_dependency attribute for its declarator-id if any declaration 2656 // of the function specifies the carries_dependency attribute. 2657 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2658 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2659 S.Diag(CDA->getLocation(), 2660 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2661 // Find the first declaration of the parameter. 2662 // FIXME: Should we build redeclaration chains for function parameters? 2663 const FunctionDecl *FirstFD = 2664 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2665 const ParmVarDecl *FirstVD = 2666 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2667 S.Diag(FirstVD->getLocation(), 2668 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2669 } 2670 2671 if (!oldDecl->hasAttrs()) 2672 return; 2673 2674 bool foundAny = newDecl->hasAttrs(); 2675 2676 // Ensure that any moving of objects within the allocated map is 2677 // done before we process them. 2678 if (!foundAny) newDecl->setAttrs(AttrVec()); 2679 2680 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2681 if (!DeclHasAttr(newDecl, I)) { 2682 InheritableAttr *newAttr = 2683 cast<InheritableParamAttr>(I->clone(S.Context)); 2684 newAttr->setInherited(true); 2685 newDecl->addAttr(newAttr); 2686 foundAny = true; 2687 } 2688 } 2689 2690 if (!foundAny) newDecl->dropAttrs(); 2691 } 2692 2693 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2694 const ParmVarDecl *OldParam, 2695 Sema &S) { 2696 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2697 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2698 if (*Oldnullability != *Newnullability) { 2699 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2700 << DiagNullabilityKind( 2701 *Newnullability, 2702 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2703 != 0)) 2704 << DiagNullabilityKind( 2705 *Oldnullability, 2706 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2707 != 0)); 2708 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2709 } 2710 } else { 2711 QualType NewT = NewParam->getType(); 2712 NewT = S.Context.getAttributedType( 2713 AttributedType::getNullabilityAttrKind(*Oldnullability), 2714 NewT, NewT); 2715 NewParam->setType(NewT); 2716 } 2717 } 2718 } 2719 2720 namespace { 2721 2722 /// Used in MergeFunctionDecl to keep track of function parameters in 2723 /// C. 2724 struct GNUCompatibleParamWarning { 2725 ParmVarDecl *OldParm; 2726 ParmVarDecl *NewParm; 2727 QualType PromotedType; 2728 }; 2729 2730 } // end anonymous namespace 2731 2732 /// getSpecialMember - get the special member enum for a method. 2733 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2734 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2735 if (Ctor->isDefaultConstructor()) 2736 return Sema::CXXDefaultConstructor; 2737 2738 if (Ctor->isCopyConstructor()) 2739 return Sema::CXXCopyConstructor; 2740 2741 if (Ctor->isMoveConstructor()) 2742 return Sema::CXXMoveConstructor; 2743 } else if (isa<CXXDestructorDecl>(MD)) { 2744 return Sema::CXXDestructor; 2745 } else if (MD->isCopyAssignmentOperator()) { 2746 return Sema::CXXCopyAssignment; 2747 } else if (MD->isMoveAssignmentOperator()) { 2748 return Sema::CXXMoveAssignment; 2749 } 2750 2751 return Sema::CXXInvalid; 2752 } 2753 2754 // Determine whether the previous declaration was a definition, implicit 2755 // declaration, or a declaration. 2756 template <typename T> 2757 static std::pair<diag::kind, SourceLocation> 2758 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2759 diag::kind PrevDiag; 2760 SourceLocation OldLocation = Old->getLocation(); 2761 if (Old->isThisDeclarationADefinition()) 2762 PrevDiag = diag::note_previous_definition; 2763 else if (Old->isImplicit()) { 2764 PrevDiag = diag::note_previous_implicit_declaration; 2765 if (OldLocation.isInvalid()) 2766 OldLocation = New->getLocation(); 2767 } else 2768 PrevDiag = diag::note_previous_declaration; 2769 return std::make_pair(PrevDiag, OldLocation); 2770 } 2771 2772 /// canRedefineFunction - checks if a function can be redefined. Currently, 2773 /// only extern inline functions can be redefined, and even then only in 2774 /// GNU89 mode. 2775 static bool canRedefineFunction(const FunctionDecl *FD, 2776 const LangOptions& LangOpts) { 2777 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2778 !LangOpts.CPlusPlus && 2779 FD->isInlineSpecified() && 2780 FD->getStorageClass() == SC_Extern); 2781 } 2782 2783 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2784 const AttributedType *AT = T->getAs<AttributedType>(); 2785 while (AT && !AT->isCallingConv()) 2786 AT = AT->getModifiedType()->getAs<AttributedType>(); 2787 return AT; 2788 } 2789 2790 template <typename T> 2791 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2792 const DeclContext *DC = Old->getDeclContext(); 2793 if (DC->isRecord()) 2794 return false; 2795 2796 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2797 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2798 return true; 2799 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2800 return true; 2801 return false; 2802 } 2803 2804 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2805 static bool isExternC(VarTemplateDecl *) { return false; } 2806 2807 /// \brief Check whether a redeclaration of an entity introduced by a 2808 /// using-declaration is valid, given that we know it's not an overload 2809 /// (nor a hidden tag declaration). 2810 template<typename ExpectedDecl> 2811 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2812 ExpectedDecl *New) { 2813 // C++11 [basic.scope.declarative]p4: 2814 // Given a set of declarations in a single declarative region, each of 2815 // which specifies the same unqualified name, 2816 // -- they shall all refer to the same entity, or all refer to functions 2817 // and function templates; or 2818 // -- exactly one declaration shall declare a class name or enumeration 2819 // name that is not a typedef name and the other declarations shall all 2820 // refer to the same variable or enumerator, or all refer to functions 2821 // and function templates; in this case the class name or enumeration 2822 // name is hidden (3.3.10). 2823 2824 // C++11 [namespace.udecl]p14: 2825 // If a function declaration in namespace scope or block scope has the 2826 // same name and the same parameter-type-list as a function introduced 2827 // by a using-declaration, and the declarations do not declare the same 2828 // function, the program is ill-formed. 2829 2830 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2831 if (Old && 2832 !Old->getDeclContext()->getRedeclContext()->Equals( 2833 New->getDeclContext()->getRedeclContext()) && 2834 !(isExternC(Old) && isExternC(New))) 2835 Old = nullptr; 2836 2837 if (!Old) { 2838 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2839 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2840 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2841 return true; 2842 } 2843 return false; 2844 } 2845 2846 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2847 const FunctionDecl *B) { 2848 assert(A->getNumParams() == B->getNumParams()); 2849 2850 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2851 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2852 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2853 if (AttrA == AttrB) 2854 return true; 2855 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2856 }; 2857 2858 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2859 } 2860 2861 /// MergeFunctionDecl - We just parsed a function 'New' from 2862 /// declarator D which has the same name and scope as a previous 2863 /// declaration 'Old'. Figure out how to resolve this situation, 2864 /// merging decls or emitting diagnostics as appropriate. 2865 /// 2866 /// In C++, New and Old must be declarations that are not 2867 /// overloaded. Use IsOverload to determine whether New and Old are 2868 /// overloaded, and to select the Old declaration that New should be 2869 /// merged with. 2870 /// 2871 /// Returns true if there was an error, false otherwise. 2872 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2873 Scope *S, bool MergeTypeWithOld) { 2874 // Verify the old decl was also a function. 2875 FunctionDecl *Old = OldD->getAsFunction(); 2876 if (!Old) { 2877 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2878 if (New->getFriendObjectKind()) { 2879 Diag(New->getLocation(), diag::err_using_decl_friend); 2880 Diag(Shadow->getTargetDecl()->getLocation(), 2881 diag::note_using_decl_target); 2882 Diag(Shadow->getUsingDecl()->getLocation(), 2883 diag::note_using_decl) << 0; 2884 return true; 2885 } 2886 2887 // Check whether the two declarations might declare the same function. 2888 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2889 return true; 2890 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2891 } else { 2892 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2893 << New->getDeclName(); 2894 notePreviousDefinition(OldD->getLocation(), New->getLocation()); 2895 return true; 2896 } 2897 } 2898 2899 // If the old declaration is invalid, just give up here. 2900 if (Old->isInvalidDecl()) 2901 return true; 2902 2903 diag::kind PrevDiag; 2904 SourceLocation OldLocation; 2905 std::tie(PrevDiag, OldLocation) = 2906 getNoteDiagForInvalidRedeclaration(Old, New); 2907 2908 // Don't complain about this if we're in GNU89 mode and the old function 2909 // is an extern inline function. 2910 // Don't complain about specializations. They are not supposed to have 2911 // storage classes. 2912 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2913 New->getStorageClass() == SC_Static && 2914 Old->hasExternalFormalLinkage() && 2915 !New->getTemplateSpecializationInfo() && 2916 !canRedefineFunction(Old, getLangOpts())) { 2917 if (getLangOpts().MicrosoftExt) { 2918 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2919 Diag(OldLocation, PrevDiag); 2920 } else { 2921 Diag(New->getLocation(), diag::err_static_non_static) << New; 2922 Diag(OldLocation, PrevDiag); 2923 return true; 2924 } 2925 } 2926 2927 if (New->hasAttr<InternalLinkageAttr>() && 2928 !Old->hasAttr<InternalLinkageAttr>()) { 2929 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2930 << New->getDeclName(); 2931 notePreviousDefinition(Old->getLocation(), New->getLocation()); 2932 New->dropAttr<InternalLinkageAttr>(); 2933 } 2934 2935 // If a function is first declared with a calling convention, but is later 2936 // declared or defined without one, all following decls assume the calling 2937 // convention of the first. 2938 // 2939 // It's OK if a function is first declared without a calling convention, 2940 // but is later declared or defined with the default calling convention. 2941 // 2942 // To test if either decl has an explicit calling convention, we look for 2943 // AttributedType sugar nodes on the type as written. If they are missing or 2944 // were canonicalized away, we assume the calling convention was implicit. 2945 // 2946 // Note also that we DO NOT return at this point, because we still have 2947 // other tests to run. 2948 QualType OldQType = Context.getCanonicalType(Old->getType()); 2949 QualType NewQType = Context.getCanonicalType(New->getType()); 2950 const FunctionType *OldType = cast<FunctionType>(OldQType); 2951 const FunctionType *NewType = cast<FunctionType>(NewQType); 2952 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2953 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2954 bool RequiresAdjustment = false; 2955 2956 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2957 FunctionDecl *First = Old->getFirstDecl(); 2958 const FunctionType *FT = 2959 First->getType().getCanonicalType()->castAs<FunctionType>(); 2960 FunctionType::ExtInfo FI = FT->getExtInfo(); 2961 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2962 if (!NewCCExplicit) { 2963 // Inherit the CC from the previous declaration if it was specified 2964 // there but not here. 2965 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2966 RequiresAdjustment = true; 2967 } else { 2968 // Calling conventions aren't compatible, so complain. 2969 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2970 Diag(New->getLocation(), diag::err_cconv_change) 2971 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2972 << !FirstCCExplicit 2973 << (!FirstCCExplicit ? "" : 2974 FunctionType::getNameForCallConv(FI.getCC())); 2975 2976 // Put the note on the first decl, since it is the one that matters. 2977 Diag(First->getLocation(), diag::note_previous_declaration); 2978 return true; 2979 } 2980 } 2981 2982 // FIXME: diagnose the other way around? 2983 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2984 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2985 RequiresAdjustment = true; 2986 } 2987 2988 // Merge regparm attribute. 2989 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2990 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2991 if (NewTypeInfo.getHasRegParm()) { 2992 Diag(New->getLocation(), diag::err_regparm_mismatch) 2993 << NewType->getRegParmType() 2994 << OldType->getRegParmType(); 2995 Diag(OldLocation, diag::note_previous_declaration); 2996 return true; 2997 } 2998 2999 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3000 RequiresAdjustment = true; 3001 } 3002 3003 // Merge ns_returns_retained attribute. 3004 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3005 if (NewTypeInfo.getProducesResult()) { 3006 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3007 << "'ns_returns_retained'"; 3008 Diag(OldLocation, diag::note_previous_declaration); 3009 return true; 3010 } 3011 3012 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3013 RequiresAdjustment = true; 3014 } 3015 3016 if (OldTypeInfo.getNoCallerSavedRegs() != 3017 NewTypeInfo.getNoCallerSavedRegs()) { 3018 if (NewTypeInfo.getNoCallerSavedRegs()) { 3019 AnyX86NoCallerSavedRegistersAttr *Attr = 3020 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3021 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3022 Diag(OldLocation, diag::note_previous_declaration); 3023 return true; 3024 } 3025 3026 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3027 RequiresAdjustment = true; 3028 } 3029 3030 if (RequiresAdjustment) { 3031 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3032 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3033 New->setType(QualType(AdjustedType, 0)); 3034 NewQType = Context.getCanonicalType(New->getType()); 3035 NewType = cast<FunctionType>(NewQType); 3036 } 3037 3038 // If this redeclaration makes the function inline, we may need to add it to 3039 // UndefinedButUsed. 3040 if (!Old->isInlined() && New->isInlined() && 3041 !New->hasAttr<GNUInlineAttr>() && 3042 !getLangOpts().GNUInline && 3043 Old->isUsed(false) && 3044 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3045 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3046 SourceLocation())); 3047 3048 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3049 // about it. 3050 if (New->hasAttr<GNUInlineAttr>() && 3051 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3052 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3053 } 3054 3055 // If pass_object_size params don't match up perfectly, this isn't a valid 3056 // redeclaration. 3057 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3058 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3059 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3060 << New->getDeclName(); 3061 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3062 return true; 3063 } 3064 3065 if (getLangOpts().CPlusPlus) { 3066 // C++1z [over.load]p2 3067 // Certain function declarations cannot be overloaded: 3068 // -- Function declarations that differ only in the return type, 3069 // the exception specification, or both cannot be overloaded. 3070 3071 // Check the exception specifications match. This may recompute the type of 3072 // both Old and New if it resolved exception specifications, so grab the 3073 // types again after this. Because this updates the type, we do this before 3074 // any of the other checks below, which may update the "de facto" NewQType 3075 // but do not necessarily update the type of New. 3076 if (CheckEquivalentExceptionSpec(Old, New)) 3077 return true; 3078 OldQType = Context.getCanonicalType(Old->getType()); 3079 NewQType = Context.getCanonicalType(New->getType()); 3080 3081 // Go back to the type source info to compare the declared return types, 3082 // per C++1y [dcl.type.auto]p13: 3083 // Redeclarations or specializations of a function or function template 3084 // with a declared return type that uses a placeholder type shall also 3085 // use that placeholder, not a deduced type. 3086 QualType OldDeclaredReturnType = 3087 (Old->getTypeSourceInfo() 3088 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3089 : OldType)->getReturnType(); 3090 QualType NewDeclaredReturnType = 3091 (New->getTypeSourceInfo() 3092 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3093 : NewType)->getReturnType(); 3094 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3095 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3096 New->isLocalExternDecl())) { 3097 QualType ResQT; 3098 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3099 OldDeclaredReturnType->isObjCObjectPointerType()) 3100 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3101 if (ResQT.isNull()) { 3102 if (New->isCXXClassMember() && New->isOutOfLine()) 3103 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3104 << New << New->getReturnTypeSourceRange(); 3105 else 3106 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3107 << New->getReturnTypeSourceRange(); 3108 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3109 << Old->getReturnTypeSourceRange(); 3110 return true; 3111 } 3112 else 3113 NewQType = ResQT; 3114 } 3115 3116 QualType OldReturnType = OldType->getReturnType(); 3117 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3118 if (OldReturnType != NewReturnType) { 3119 // If this function has a deduced return type and has already been 3120 // defined, copy the deduced value from the old declaration. 3121 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3122 if (OldAT && OldAT->isDeduced()) { 3123 New->setType( 3124 SubstAutoType(New->getType(), 3125 OldAT->isDependentType() ? Context.DependentTy 3126 : OldAT->getDeducedType())); 3127 NewQType = Context.getCanonicalType( 3128 SubstAutoType(NewQType, 3129 OldAT->isDependentType() ? Context.DependentTy 3130 : OldAT->getDeducedType())); 3131 } 3132 } 3133 3134 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3135 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3136 if (OldMethod && NewMethod) { 3137 // Preserve triviality. 3138 NewMethod->setTrivial(OldMethod->isTrivial()); 3139 3140 // MSVC allows explicit template specialization at class scope: 3141 // 2 CXXMethodDecls referring to the same function will be injected. 3142 // We don't want a redeclaration error. 3143 bool IsClassScopeExplicitSpecialization = 3144 OldMethod->isFunctionTemplateSpecialization() && 3145 NewMethod->isFunctionTemplateSpecialization(); 3146 bool isFriend = NewMethod->getFriendObjectKind(); 3147 3148 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3149 !IsClassScopeExplicitSpecialization) { 3150 // -- Member function declarations with the same name and the 3151 // same parameter types cannot be overloaded if any of them 3152 // is a static member function declaration. 3153 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3154 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3155 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3156 return true; 3157 } 3158 3159 // C++ [class.mem]p1: 3160 // [...] A member shall not be declared twice in the 3161 // member-specification, except that a nested class or member 3162 // class template can be declared and then later defined. 3163 if (!inTemplateInstantiation()) { 3164 unsigned NewDiag; 3165 if (isa<CXXConstructorDecl>(OldMethod)) 3166 NewDiag = diag::err_constructor_redeclared; 3167 else if (isa<CXXDestructorDecl>(NewMethod)) 3168 NewDiag = diag::err_destructor_redeclared; 3169 else if (isa<CXXConversionDecl>(NewMethod)) 3170 NewDiag = diag::err_conv_function_redeclared; 3171 else 3172 NewDiag = diag::err_member_redeclared; 3173 3174 Diag(New->getLocation(), NewDiag); 3175 } else { 3176 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3177 << New << New->getType(); 3178 } 3179 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3180 return true; 3181 3182 // Complain if this is an explicit declaration of a special 3183 // member that was initially declared implicitly. 3184 // 3185 // As an exception, it's okay to befriend such methods in order 3186 // to permit the implicit constructor/destructor/operator calls. 3187 } else if (OldMethod->isImplicit()) { 3188 if (isFriend) { 3189 NewMethod->setImplicit(); 3190 } else { 3191 Diag(NewMethod->getLocation(), 3192 diag::err_definition_of_implicitly_declared_member) 3193 << New << getSpecialMember(OldMethod); 3194 return true; 3195 } 3196 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3197 Diag(NewMethod->getLocation(), 3198 diag::err_definition_of_explicitly_defaulted_member) 3199 << getSpecialMember(OldMethod); 3200 return true; 3201 } 3202 } 3203 3204 // C++11 [dcl.attr.noreturn]p1: 3205 // The first declaration of a function shall specify the noreturn 3206 // attribute if any declaration of that function specifies the noreturn 3207 // attribute. 3208 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3209 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3210 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3211 Diag(Old->getFirstDecl()->getLocation(), 3212 diag::note_noreturn_missing_first_decl); 3213 } 3214 3215 // C++11 [dcl.attr.depend]p2: 3216 // The first declaration of a function shall specify the 3217 // carries_dependency attribute for its declarator-id if any declaration 3218 // of the function specifies the carries_dependency attribute. 3219 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3220 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3221 Diag(CDA->getLocation(), 3222 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3223 Diag(Old->getFirstDecl()->getLocation(), 3224 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3225 } 3226 3227 // (C++98 8.3.5p3): 3228 // All declarations for a function shall agree exactly in both the 3229 // return type and the parameter-type-list. 3230 // We also want to respect all the extended bits except noreturn. 3231 3232 // noreturn should now match unless the old type info didn't have it. 3233 QualType OldQTypeForComparison = OldQType; 3234 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3235 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3236 const FunctionType *OldTypeForComparison 3237 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3238 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3239 assert(OldQTypeForComparison.isCanonical()); 3240 } 3241 3242 if (haveIncompatibleLanguageLinkages(Old, New)) { 3243 // As a special case, retain the language linkage from previous 3244 // declarations of a friend function as an extension. 3245 // 3246 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3247 // and is useful because there's otherwise no way to specify language 3248 // linkage within class scope. 3249 // 3250 // Check cautiously as the friend object kind isn't yet complete. 3251 if (New->getFriendObjectKind() != Decl::FOK_None) { 3252 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3253 Diag(OldLocation, PrevDiag); 3254 } else { 3255 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3256 Diag(OldLocation, PrevDiag); 3257 return true; 3258 } 3259 } 3260 3261 if (OldQTypeForComparison == NewQType) 3262 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3263 3264 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3265 New->isLocalExternDecl()) { 3266 // It's OK if we couldn't merge types for a local function declaraton 3267 // if either the old or new type is dependent. We'll merge the types 3268 // when we instantiate the function. 3269 return false; 3270 } 3271 3272 // Fall through for conflicting redeclarations and redefinitions. 3273 } 3274 3275 // C: Function types need to be compatible, not identical. This handles 3276 // duplicate function decls like "void f(int); void f(enum X);" properly. 3277 if (!getLangOpts().CPlusPlus && 3278 Context.typesAreCompatible(OldQType, NewQType)) { 3279 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3280 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3281 const FunctionProtoType *OldProto = nullptr; 3282 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3283 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3284 // The old declaration provided a function prototype, but the 3285 // new declaration does not. Merge in the prototype. 3286 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3287 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3288 NewQType = 3289 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3290 OldProto->getExtProtoInfo()); 3291 New->setType(NewQType); 3292 New->setHasInheritedPrototype(); 3293 3294 // Synthesize parameters with the same types. 3295 SmallVector<ParmVarDecl*, 16> Params; 3296 for (const auto &ParamType : OldProto->param_types()) { 3297 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3298 SourceLocation(), nullptr, 3299 ParamType, /*TInfo=*/nullptr, 3300 SC_None, nullptr); 3301 Param->setScopeInfo(0, Params.size()); 3302 Param->setImplicit(); 3303 Params.push_back(Param); 3304 } 3305 3306 New->setParams(Params); 3307 } 3308 3309 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3310 } 3311 3312 // GNU C permits a K&R definition to follow a prototype declaration 3313 // if the declared types of the parameters in the K&R definition 3314 // match the types in the prototype declaration, even when the 3315 // promoted types of the parameters from the K&R definition differ 3316 // from the types in the prototype. GCC then keeps the types from 3317 // the prototype. 3318 // 3319 // If a variadic prototype is followed by a non-variadic K&R definition, 3320 // the K&R definition becomes variadic. This is sort of an edge case, but 3321 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3322 // C99 6.9.1p8. 3323 if (!getLangOpts().CPlusPlus && 3324 Old->hasPrototype() && !New->hasPrototype() && 3325 New->getType()->getAs<FunctionProtoType>() && 3326 Old->getNumParams() == New->getNumParams()) { 3327 SmallVector<QualType, 16> ArgTypes; 3328 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3329 const FunctionProtoType *OldProto 3330 = Old->getType()->getAs<FunctionProtoType>(); 3331 const FunctionProtoType *NewProto 3332 = New->getType()->getAs<FunctionProtoType>(); 3333 3334 // Determine whether this is the GNU C extension. 3335 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3336 NewProto->getReturnType()); 3337 bool LooseCompatible = !MergedReturn.isNull(); 3338 for (unsigned Idx = 0, End = Old->getNumParams(); 3339 LooseCompatible && Idx != End; ++Idx) { 3340 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3341 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3342 if (Context.typesAreCompatible(OldParm->getType(), 3343 NewProto->getParamType(Idx))) { 3344 ArgTypes.push_back(NewParm->getType()); 3345 } else if (Context.typesAreCompatible(OldParm->getType(), 3346 NewParm->getType(), 3347 /*CompareUnqualified=*/true)) { 3348 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3349 NewProto->getParamType(Idx) }; 3350 Warnings.push_back(Warn); 3351 ArgTypes.push_back(NewParm->getType()); 3352 } else 3353 LooseCompatible = false; 3354 } 3355 3356 if (LooseCompatible) { 3357 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3358 Diag(Warnings[Warn].NewParm->getLocation(), 3359 diag::ext_param_promoted_not_compatible_with_prototype) 3360 << Warnings[Warn].PromotedType 3361 << Warnings[Warn].OldParm->getType(); 3362 if (Warnings[Warn].OldParm->getLocation().isValid()) 3363 Diag(Warnings[Warn].OldParm->getLocation(), 3364 diag::note_previous_declaration); 3365 } 3366 3367 if (MergeTypeWithOld) 3368 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3369 OldProto->getExtProtoInfo())); 3370 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3371 } 3372 3373 // Fall through to diagnose conflicting types. 3374 } 3375 3376 // A function that has already been declared has been redeclared or 3377 // defined with a different type; show an appropriate diagnostic. 3378 3379 // If the previous declaration was an implicitly-generated builtin 3380 // declaration, then at the very least we should use a specialized note. 3381 unsigned BuiltinID; 3382 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3383 // If it's actually a library-defined builtin function like 'malloc' 3384 // or 'printf', just warn about the incompatible redeclaration. 3385 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3386 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3387 Diag(OldLocation, diag::note_previous_builtin_declaration) 3388 << Old << Old->getType(); 3389 3390 // If this is a global redeclaration, just forget hereafter 3391 // about the "builtin-ness" of the function. 3392 // 3393 // Doing this for local extern declarations is problematic. If 3394 // the builtin declaration remains visible, a second invalid 3395 // local declaration will produce a hard error; if it doesn't 3396 // remain visible, a single bogus local redeclaration (which is 3397 // actually only a warning) could break all the downstream code. 3398 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3399 New->getIdentifier()->revertBuiltin(); 3400 3401 return false; 3402 } 3403 3404 PrevDiag = diag::note_previous_builtin_declaration; 3405 } 3406 3407 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3408 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3409 return true; 3410 } 3411 3412 /// \brief Completes the merge of two function declarations that are 3413 /// known to be compatible. 3414 /// 3415 /// This routine handles the merging of attributes and other 3416 /// properties of function declarations from the old declaration to 3417 /// the new declaration, once we know that New is in fact a 3418 /// redeclaration of Old. 3419 /// 3420 /// \returns false 3421 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3422 Scope *S, bool MergeTypeWithOld) { 3423 // Merge the attributes 3424 mergeDeclAttributes(New, Old); 3425 3426 // Merge "pure" flag. 3427 if (Old->isPure()) 3428 New->setPure(); 3429 3430 // Merge "used" flag. 3431 if (Old->getMostRecentDecl()->isUsed(false)) 3432 New->setIsUsed(); 3433 3434 // Merge attributes from the parameters. These can mismatch with K&R 3435 // declarations. 3436 if (New->getNumParams() == Old->getNumParams()) 3437 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3438 ParmVarDecl *NewParam = New->getParamDecl(i); 3439 ParmVarDecl *OldParam = Old->getParamDecl(i); 3440 mergeParamDeclAttributes(NewParam, OldParam, *this); 3441 mergeParamDeclTypes(NewParam, OldParam, *this); 3442 } 3443 3444 if (getLangOpts().CPlusPlus) 3445 return MergeCXXFunctionDecl(New, Old, S); 3446 3447 // Merge the function types so the we get the composite types for the return 3448 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3449 // was visible. 3450 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3451 if (!Merged.isNull() && MergeTypeWithOld) 3452 New->setType(Merged); 3453 3454 return false; 3455 } 3456 3457 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3458 ObjCMethodDecl *oldMethod) { 3459 // Merge the attributes, including deprecated/unavailable 3460 AvailabilityMergeKind MergeKind = 3461 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3462 ? AMK_ProtocolImplementation 3463 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3464 : AMK_Override; 3465 3466 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3467 3468 // Merge attributes from the parameters. 3469 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3470 oe = oldMethod->param_end(); 3471 for (ObjCMethodDecl::param_iterator 3472 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3473 ni != ne && oi != oe; ++ni, ++oi) 3474 mergeParamDeclAttributes(*ni, *oi, *this); 3475 3476 CheckObjCMethodOverride(newMethod, oldMethod); 3477 } 3478 3479 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3480 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3481 3482 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3483 ? diag::err_redefinition_different_type 3484 : diag::err_redeclaration_different_type) 3485 << New->getDeclName() << New->getType() << Old->getType(); 3486 3487 diag::kind PrevDiag; 3488 SourceLocation OldLocation; 3489 std::tie(PrevDiag, OldLocation) 3490 = getNoteDiagForInvalidRedeclaration(Old, New); 3491 S.Diag(OldLocation, PrevDiag); 3492 New->setInvalidDecl(); 3493 } 3494 3495 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3496 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3497 /// emitting diagnostics as appropriate. 3498 /// 3499 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3500 /// to here in AddInitializerToDecl. We can't check them before the initializer 3501 /// is attached. 3502 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3503 bool MergeTypeWithOld) { 3504 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3505 return; 3506 3507 QualType MergedT; 3508 if (getLangOpts().CPlusPlus) { 3509 if (New->getType()->isUndeducedType()) { 3510 // We don't know what the new type is until the initializer is attached. 3511 return; 3512 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3513 // These could still be something that needs exception specs checked. 3514 return MergeVarDeclExceptionSpecs(New, Old); 3515 } 3516 // C++ [basic.link]p10: 3517 // [...] the types specified by all declarations referring to a given 3518 // object or function shall be identical, except that declarations for an 3519 // array object can specify array types that differ by the presence or 3520 // absence of a major array bound (8.3.4). 3521 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3522 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3523 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3524 3525 // We are merging a variable declaration New into Old. If it has an array 3526 // bound, and that bound differs from Old's bound, we should diagnose the 3527 // mismatch. 3528 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3529 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3530 PrevVD = PrevVD->getPreviousDecl()) { 3531 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3532 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3533 continue; 3534 3535 if (!Context.hasSameType(NewArray, PrevVDTy)) 3536 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3537 } 3538 } 3539 3540 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3541 if (Context.hasSameType(OldArray->getElementType(), 3542 NewArray->getElementType())) 3543 MergedT = New->getType(); 3544 } 3545 // FIXME: Check visibility. New is hidden but has a complete type. If New 3546 // has no array bound, it should not inherit one from Old, if Old is not 3547 // visible. 3548 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3549 if (Context.hasSameType(OldArray->getElementType(), 3550 NewArray->getElementType())) 3551 MergedT = Old->getType(); 3552 } 3553 } 3554 else if (New->getType()->isObjCObjectPointerType() && 3555 Old->getType()->isObjCObjectPointerType()) { 3556 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3557 Old->getType()); 3558 } 3559 } else { 3560 // C 6.2.7p2: 3561 // All declarations that refer to the same object or function shall have 3562 // compatible type. 3563 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3564 } 3565 if (MergedT.isNull()) { 3566 // It's OK if we couldn't merge types if either type is dependent, for a 3567 // block-scope variable. In other cases (static data members of class 3568 // templates, variable templates, ...), we require the types to be 3569 // equivalent. 3570 // FIXME: The C++ standard doesn't say anything about this. 3571 if ((New->getType()->isDependentType() || 3572 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3573 // If the old type was dependent, we can't merge with it, so the new type 3574 // becomes dependent for now. We'll reproduce the original type when we 3575 // instantiate the TypeSourceInfo for the variable. 3576 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3577 New->setType(Context.DependentTy); 3578 return; 3579 } 3580 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3581 } 3582 3583 // Don't actually update the type on the new declaration if the old 3584 // declaration was an extern declaration in a different scope. 3585 if (MergeTypeWithOld) 3586 New->setType(MergedT); 3587 } 3588 3589 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3590 LookupResult &Previous) { 3591 // C11 6.2.7p4: 3592 // For an identifier with internal or external linkage declared 3593 // in a scope in which a prior declaration of that identifier is 3594 // visible, if the prior declaration specifies internal or 3595 // external linkage, the type of the identifier at the later 3596 // declaration becomes the composite type. 3597 // 3598 // If the variable isn't visible, we do not merge with its type. 3599 if (Previous.isShadowed()) 3600 return false; 3601 3602 if (S.getLangOpts().CPlusPlus) { 3603 // C++11 [dcl.array]p3: 3604 // If there is a preceding declaration of the entity in the same 3605 // scope in which the bound was specified, an omitted array bound 3606 // is taken to be the same as in that earlier declaration. 3607 return NewVD->isPreviousDeclInSameBlockScope() || 3608 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3609 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3610 } else { 3611 // If the old declaration was function-local, don't merge with its 3612 // type unless we're in the same function. 3613 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3614 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3615 } 3616 } 3617 3618 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3619 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3620 /// situation, merging decls or emitting diagnostics as appropriate. 3621 /// 3622 /// Tentative definition rules (C99 6.9.2p2) are checked by 3623 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3624 /// definitions here, since the initializer hasn't been attached. 3625 /// 3626 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3627 // If the new decl is already invalid, don't do any other checking. 3628 if (New->isInvalidDecl()) 3629 return; 3630 3631 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3632 return; 3633 3634 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3635 3636 // Verify the old decl was also a variable or variable template. 3637 VarDecl *Old = nullptr; 3638 VarTemplateDecl *OldTemplate = nullptr; 3639 if (Previous.isSingleResult()) { 3640 if (NewTemplate) { 3641 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3642 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3643 3644 if (auto *Shadow = 3645 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3646 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3647 return New->setInvalidDecl(); 3648 } else { 3649 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3650 3651 if (auto *Shadow = 3652 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3653 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3654 return New->setInvalidDecl(); 3655 } 3656 } 3657 if (!Old) { 3658 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3659 << New->getDeclName(); 3660 notePreviousDefinition(Previous.getRepresentativeDecl()->getLocation(), 3661 New->getLocation()); 3662 return New->setInvalidDecl(); 3663 } 3664 3665 // Ensure the template parameters are compatible. 3666 if (NewTemplate && 3667 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3668 OldTemplate->getTemplateParameters(), 3669 /*Complain=*/true, TPL_TemplateMatch)) 3670 return New->setInvalidDecl(); 3671 3672 // C++ [class.mem]p1: 3673 // A member shall not be declared twice in the member-specification [...] 3674 // 3675 // Here, we need only consider static data members. 3676 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3677 Diag(New->getLocation(), diag::err_duplicate_member) 3678 << New->getIdentifier(); 3679 Diag(Old->getLocation(), diag::note_previous_declaration); 3680 New->setInvalidDecl(); 3681 } 3682 3683 mergeDeclAttributes(New, Old); 3684 // Warn if an already-declared variable is made a weak_import in a subsequent 3685 // declaration 3686 if (New->hasAttr<WeakImportAttr>() && 3687 Old->getStorageClass() == SC_None && 3688 !Old->hasAttr<WeakImportAttr>()) { 3689 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3690 notePreviousDefinition(Old->getLocation(), New->getLocation()); 3691 // Remove weak_import attribute on new declaration. 3692 New->dropAttr<WeakImportAttr>(); 3693 } 3694 3695 if (New->hasAttr<InternalLinkageAttr>() && 3696 !Old->hasAttr<InternalLinkageAttr>()) { 3697 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3698 << New->getDeclName(); 3699 notePreviousDefinition(Old->getLocation(), New->getLocation()); 3700 New->dropAttr<InternalLinkageAttr>(); 3701 } 3702 3703 // Merge the types. 3704 VarDecl *MostRecent = Old->getMostRecentDecl(); 3705 if (MostRecent != Old) { 3706 MergeVarDeclTypes(New, MostRecent, 3707 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3708 if (New->isInvalidDecl()) 3709 return; 3710 } 3711 3712 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3713 if (New->isInvalidDecl()) 3714 return; 3715 3716 diag::kind PrevDiag; 3717 SourceLocation OldLocation; 3718 std::tie(PrevDiag, OldLocation) = 3719 getNoteDiagForInvalidRedeclaration(Old, New); 3720 3721 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3722 if (New->getStorageClass() == SC_Static && 3723 !New->isStaticDataMember() && 3724 Old->hasExternalFormalLinkage()) { 3725 if (getLangOpts().MicrosoftExt) { 3726 Diag(New->getLocation(), diag::ext_static_non_static) 3727 << New->getDeclName(); 3728 Diag(OldLocation, PrevDiag); 3729 } else { 3730 Diag(New->getLocation(), diag::err_static_non_static) 3731 << New->getDeclName(); 3732 Diag(OldLocation, PrevDiag); 3733 return New->setInvalidDecl(); 3734 } 3735 } 3736 // C99 6.2.2p4: 3737 // For an identifier declared with the storage-class specifier 3738 // extern in a scope in which a prior declaration of that 3739 // identifier is visible,23) if the prior declaration specifies 3740 // internal or external linkage, the linkage of the identifier at 3741 // the later declaration is the same as the linkage specified at 3742 // the prior declaration. If no prior declaration is visible, or 3743 // if the prior declaration specifies no linkage, then the 3744 // identifier has external linkage. 3745 if (New->hasExternalStorage() && Old->hasLinkage()) 3746 /* Okay */; 3747 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3748 !New->isStaticDataMember() && 3749 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3750 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3751 Diag(OldLocation, PrevDiag); 3752 return New->setInvalidDecl(); 3753 } 3754 3755 // Check if extern is followed by non-extern and vice-versa. 3756 if (New->hasExternalStorage() && 3757 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3758 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3759 Diag(OldLocation, PrevDiag); 3760 return New->setInvalidDecl(); 3761 } 3762 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3763 !New->hasExternalStorage()) { 3764 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3765 Diag(OldLocation, PrevDiag); 3766 return New->setInvalidDecl(); 3767 } 3768 3769 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3770 3771 // FIXME: The test for external storage here seems wrong? We still 3772 // need to check for mismatches. 3773 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3774 // Don't complain about out-of-line definitions of static members. 3775 !(Old->getLexicalDeclContext()->isRecord() && 3776 !New->getLexicalDeclContext()->isRecord())) { 3777 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3778 Diag(OldLocation, PrevDiag); 3779 return New->setInvalidDecl(); 3780 } 3781 3782 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3783 if (VarDecl *Def = Old->getDefinition()) { 3784 // C++1z [dcl.fcn.spec]p4: 3785 // If the definition of a variable appears in a translation unit before 3786 // its first declaration as inline, the program is ill-formed. 3787 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3788 Diag(Def->getLocation(), diag::note_previous_definition); 3789 } 3790 } 3791 3792 // If this redeclaration makes the function inline, we may need to add it to 3793 // UndefinedButUsed. 3794 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3795 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3796 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3797 SourceLocation())); 3798 3799 if (New->getTLSKind() != Old->getTLSKind()) { 3800 if (!Old->getTLSKind()) { 3801 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3802 Diag(OldLocation, PrevDiag); 3803 } else if (!New->getTLSKind()) { 3804 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3805 Diag(OldLocation, PrevDiag); 3806 } else { 3807 // Do not allow redeclaration to change the variable between requiring 3808 // static and dynamic initialization. 3809 // FIXME: GCC allows this, but uses the TLS keyword on the first 3810 // declaration to determine the kind. Do we need to be compatible here? 3811 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3812 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3813 Diag(OldLocation, PrevDiag); 3814 } 3815 } 3816 3817 // C++ doesn't have tentative definitions, so go right ahead and check here. 3818 if (getLangOpts().CPlusPlus && 3819 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3820 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3821 Old->getCanonicalDecl()->isConstexpr()) { 3822 // This definition won't be a definition any more once it's been merged. 3823 Diag(New->getLocation(), 3824 diag::warn_deprecated_redundant_constexpr_static_def); 3825 } else if (VarDecl *Def = Old->getDefinition()) { 3826 if (checkVarDeclRedefinition(Def, New)) 3827 return; 3828 } 3829 } 3830 3831 if (haveIncompatibleLanguageLinkages(Old, New)) { 3832 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3833 Diag(OldLocation, PrevDiag); 3834 New->setInvalidDecl(); 3835 return; 3836 } 3837 3838 // Merge "used" flag. 3839 if (Old->getMostRecentDecl()->isUsed(false)) 3840 New->setIsUsed(); 3841 3842 // Keep a chain of previous declarations. 3843 New->setPreviousDecl(Old); 3844 if (NewTemplate) 3845 NewTemplate->setPreviousDecl(OldTemplate); 3846 3847 // Inherit access appropriately. 3848 New->setAccess(Old->getAccess()); 3849 if (NewTemplate) 3850 NewTemplate->setAccess(New->getAccess()); 3851 3852 if (Old->isInline()) 3853 New->setImplicitlyInline(); 3854 } 3855 3856 void Sema::notePreviousDefinition(SourceLocation Old, SourceLocation New) { 3857 SourceManager &SrcMgr = getSourceManager(); 3858 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 3859 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old); 3860 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 3861 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 3862 auto &HSI = PP.getHeaderSearchInfo(); 3863 StringRef HdrFilename = SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old)); 3864 3865 auto noteFromModuleOrInclude = [&](SourceLocation &Loc, 3866 SourceLocation &IncLoc) -> bool { 3867 Module *Mod = nullptr; 3868 // Redefinition errors with modules are common with non modular mapped 3869 // headers, example: a non-modular header H in module A that also gets 3870 // included directly in a TU. Pointing twice to the same header/definition 3871 // is confusing, try to get better diagnostics when modules is on. 3872 if (getLangOpts().Modules) { 3873 auto ModLoc = SrcMgr.getModuleImportLoc(Old); 3874 if (!ModLoc.first.isInvalid()) 3875 Mod = HSI.getModuleMap().inferModuleFromLocation( 3876 FullSourceLoc(Loc, SrcMgr)); 3877 } 3878 3879 if (IncLoc.isValid()) { 3880 if (Mod) { 3881 Diag(IncLoc, diag::note_redefinition_modules_same_file) 3882 << HdrFilename.str() << Mod->getFullModuleName(); 3883 if (!Mod->DefinitionLoc.isInvalid()) 3884 Diag(Mod->DefinitionLoc, diag::note_defined_here) 3885 << Mod->getFullModuleName(); 3886 } else { 3887 Diag(IncLoc, diag::note_redefinition_include_same_file) 3888 << HdrFilename.str(); 3889 } 3890 return true; 3891 } 3892 3893 return false; 3894 }; 3895 3896 // Is it the same file and same offset? Provide more information on why 3897 // this leads to a redefinition error. 3898 bool EmittedDiag = false; 3899 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 3900 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 3901 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 3902 EmittedDiag = noteFromModuleOrInclude(Old, OldIncLoc); 3903 EmittedDiag |= noteFromModuleOrInclude(New, NewIncLoc); 3904 3905 // If the header has no guards, emit a note suggesting one. 3906 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 3907 Diag(Old, diag::note_use_ifdef_guards); 3908 3909 if (EmittedDiag) 3910 return; 3911 } 3912 3913 // Redefinition coming from different files or couldn't do better above. 3914 Diag(Old, diag::note_previous_definition); 3915 } 3916 3917 /// We've just determined that \p Old and \p New both appear to be definitions 3918 /// of the same variable. Either diagnose or fix the problem. 3919 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 3920 if (!hasVisibleDefinition(Old) && 3921 (New->getFormalLinkage() == InternalLinkage || 3922 New->isInline() || 3923 New->getDescribedVarTemplate() || 3924 New->getNumTemplateParameterLists() || 3925 New->getDeclContext()->isDependentContext())) { 3926 // The previous definition is hidden, and multiple definitions are 3927 // permitted (in separate TUs). Demote this to a declaration. 3928 New->demoteThisDefinitionToDeclaration(); 3929 3930 // Make the canonical definition visible. 3931 if (auto *OldTD = Old->getDescribedVarTemplate()) 3932 makeMergedDefinitionVisible(OldTD); 3933 makeMergedDefinitionVisible(Old); 3934 return false; 3935 } else { 3936 Diag(New->getLocation(), diag::err_redefinition) << New; 3937 notePreviousDefinition(Old->getLocation(), New->getLocation()); 3938 New->setInvalidDecl(); 3939 return true; 3940 } 3941 } 3942 3943 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3944 /// no declarator (e.g. "struct foo;") is parsed. 3945 Decl * 3946 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 3947 RecordDecl *&AnonRecord) { 3948 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 3949 AnonRecord); 3950 } 3951 3952 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3953 // disambiguate entities defined in different scopes. 3954 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3955 // compatibility. 3956 // We will pick our mangling number depending on which version of MSVC is being 3957 // targeted. 3958 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3959 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3960 ? S->getMSCurManglingNumber() 3961 : S->getMSLastManglingNumber(); 3962 } 3963 3964 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3965 if (!Context.getLangOpts().CPlusPlus) 3966 return; 3967 3968 if (isa<CXXRecordDecl>(Tag->getParent())) { 3969 // If this tag is the direct child of a class, number it if 3970 // it is anonymous. 3971 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3972 return; 3973 MangleNumberingContext &MCtx = 3974 Context.getManglingNumberContext(Tag->getParent()); 3975 Context.setManglingNumber( 3976 Tag, MCtx.getManglingNumber( 3977 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3978 return; 3979 } 3980 3981 // If this tag isn't a direct child of a class, number it if it is local. 3982 Decl *ManglingContextDecl; 3983 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3984 Tag->getDeclContext(), ManglingContextDecl)) { 3985 Context.setManglingNumber( 3986 Tag, MCtx->getManglingNumber( 3987 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3988 } 3989 } 3990 3991 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3992 TypedefNameDecl *NewTD) { 3993 if (TagFromDeclSpec->isInvalidDecl()) 3994 return; 3995 3996 // Do nothing if the tag already has a name for linkage purposes. 3997 if (TagFromDeclSpec->hasNameForLinkage()) 3998 return; 3999 4000 // A well-formed anonymous tag must always be a TUK_Definition. 4001 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4002 4003 // The type must match the tag exactly; no qualifiers allowed. 4004 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4005 Context.getTagDeclType(TagFromDeclSpec))) { 4006 if (getLangOpts().CPlusPlus) 4007 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4008 return; 4009 } 4010 4011 // If we've already computed linkage for the anonymous tag, then 4012 // adding a typedef name for the anonymous decl can change that 4013 // linkage, which might be a serious problem. Diagnose this as 4014 // unsupported and ignore the typedef name. TODO: we should 4015 // pursue this as a language defect and establish a formal rule 4016 // for how to handle it. 4017 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4018 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4019 4020 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4021 tagLoc = getLocForEndOfToken(tagLoc); 4022 4023 llvm::SmallString<40> textToInsert; 4024 textToInsert += ' '; 4025 textToInsert += NewTD->getIdentifier()->getName(); 4026 Diag(tagLoc, diag::note_typedef_changes_linkage) 4027 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4028 return; 4029 } 4030 4031 // Otherwise, set this is the anon-decl typedef for the tag. 4032 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4033 } 4034 4035 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4036 switch (T) { 4037 case DeclSpec::TST_class: 4038 return 0; 4039 case DeclSpec::TST_struct: 4040 return 1; 4041 case DeclSpec::TST_interface: 4042 return 2; 4043 case DeclSpec::TST_union: 4044 return 3; 4045 case DeclSpec::TST_enum: 4046 return 4; 4047 default: 4048 llvm_unreachable("unexpected type specifier"); 4049 } 4050 } 4051 4052 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4053 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4054 /// parameters to cope with template friend declarations. 4055 Decl * 4056 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4057 MultiTemplateParamsArg TemplateParams, 4058 bool IsExplicitInstantiation, 4059 RecordDecl *&AnonRecord) { 4060 Decl *TagD = nullptr; 4061 TagDecl *Tag = nullptr; 4062 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4063 DS.getTypeSpecType() == DeclSpec::TST_struct || 4064 DS.getTypeSpecType() == DeclSpec::TST_interface || 4065 DS.getTypeSpecType() == DeclSpec::TST_union || 4066 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4067 TagD = DS.getRepAsDecl(); 4068 4069 if (!TagD) // We probably had an error 4070 return nullptr; 4071 4072 // Note that the above type specs guarantee that the 4073 // type rep is a Decl, whereas in many of the others 4074 // it's a Type. 4075 if (isa<TagDecl>(TagD)) 4076 Tag = cast<TagDecl>(TagD); 4077 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4078 Tag = CTD->getTemplatedDecl(); 4079 } 4080 4081 if (Tag) { 4082 handleTagNumbering(Tag, S); 4083 Tag->setFreeStanding(); 4084 if (Tag->isInvalidDecl()) 4085 return Tag; 4086 } 4087 4088 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4089 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4090 // or incomplete types shall not be restrict-qualified." 4091 if (TypeQuals & DeclSpec::TQ_restrict) 4092 Diag(DS.getRestrictSpecLoc(), 4093 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4094 << DS.getSourceRange(); 4095 } 4096 4097 if (DS.isInlineSpecified()) 4098 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4099 << getLangOpts().CPlusPlus1z; 4100 4101 if (DS.isConstexprSpecified()) { 4102 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4103 // and definitions of functions and variables. 4104 if (Tag) 4105 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4106 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4107 else 4108 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4109 // Don't emit warnings after this error. 4110 return TagD; 4111 } 4112 4113 if (DS.isConceptSpecified()) { 4114 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 4115 // either a function concept and its definition or a variable concept and 4116 // its initializer. 4117 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 4118 return TagD; 4119 } 4120 4121 DiagnoseFunctionSpecifiers(DS); 4122 4123 if (DS.isFriendSpecified()) { 4124 // If we're dealing with a decl but not a TagDecl, assume that 4125 // whatever routines created it handled the friendship aspect. 4126 if (TagD && !Tag) 4127 return nullptr; 4128 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4129 } 4130 4131 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4132 bool IsExplicitSpecialization = 4133 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4134 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4135 !IsExplicitInstantiation && !IsExplicitSpecialization && 4136 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4137 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4138 // nested-name-specifier unless it is an explicit instantiation 4139 // or an explicit specialization. 4140 // 4141 // FIXME: We allow class template partial specializations here too, per the 4142 // obvious intent of DR1819. 4143 // 4144 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4145 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4146 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4147 return nullptr; 4148 } 4149 4150 // Track whether this decl-specifier declares anything. 4151 bool DeclaresAnything = true; 4152 4153 // Handle anonymous struct definitions. 4154 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4155 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4156 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4157 if (getLangOpts().CPlusPlus || 4158 Record->getDeclContext()->isRecord()) { 4159 // If CurContext is a DeclContext that can contain statements, 4160 // RecursiveASTVisitor won't visit the decls that 4161 // BuildAnonymousStructOrUnion() will put into CurContext. 4162 // Also store them here so that they can be part of the 4163 // DeclStmt that gets created in this case. 4164 // FIXME: Also return the IndirectFieldDecls created by 4165 // BuildAnonymousStructOr union, for the same reason? 4166 if (CurContext->isFunctionOrMethod()) 4167 AnonRecord = Record; 4168 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4169 Context.getPrintingPolicy()); 4170 } 4171 4172 DeclaresAnything = false; 4173 } 4174 } 4175 4176 // C11 6.7.2.1p2: 4177 // A struct-declaration that does not declare an anonymous structure or 4178 // anonymous union shall contain a struct-declarator-list. 4179 // 4180 // This rule also existed in C89 and C99; the grammar for struct-declaration 4181 // did not permit a struct-declaration without a struct-declarator-list. 4182 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4183 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4184 // Check for Microsoft C extension: anonymous struct/union member. 4185 // Handle 2 kinds of anonymous struct/union: 4186 // struct STRUCT; 4187 // union UNION; 4188 // and 4189 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4190 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4191 if ((Tag && Tag->getDeclName()) || 4192 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4193 RecordDecl *Record = nullptr; 4194 if (Tag) 4195 Record = dyn_cast<RecordDecl>(Tag); 4196 else if (const RecordType *RT = 4197 DS.getRepAsType().get()->getAsStructureType()) 4198 Record = RT->getDecl(); 4199 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4200 Record = UT->getDecl(); 4201 4202 if (Record && getLangOpts().MicrosoftExt) { 4203 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4204 << Record->isUnion() << DS.getSourceRange(); 4205 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4206 } 4207 4208 DeclaresAnything = false; 4209 } 4210 } 4211 4212 // Skip all the checks below if we have a type error. 4213 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4214 (TagD && TagD->isInvalidDecl())) 4215 return TagD; 4216 4217 if (getLangOpts().CPlusPlus && 4218 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4219 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4220 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4221 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4222 DeclaresAnything = false; 4223 4224 if (!DS.isMissingDeclaratorOk()) { 4225 // Customize diagnostic for a typedef missing a name. 4226 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4227 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4228 << DS.getSourceRange(); 4229 else 4230 DeclaresAnything = false; 4231 } 4232 4233 if (DS.isModulePrivateSpecified() && 4234 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4235 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4236 << Tag->getTagKind() 4237 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4238 4239 ActOnDocumentableDecl(TagD); 4240 4241 // C 6.7/2: 4242 // A declaration [...] shall declare at least a declarator [...], a tag, 4243 // or the members of an enumeration. 4244 // C++ [dcl.dcl]p3: 4245 // [If there are no declarators], and except for the declaration of an 4246 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4247 // names into the program, or shall redeclare a name introduced by a 4248 // previous declaration. 4249 if (!DeclaresAnything) { 4250 // In C, we allow this as a (popular) extension / bug. Don't bother 4251 // producing further diagnostics for redundant qualifiers after this. 4252 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4253 return TagD; 4254 } 4255 4256 // C++ [dcl.stc]p1: 4257 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4258 // init-declarator-list of the declaration shall not be empty. 4259 // C++ [dcl.fct.spec]p1: 4260 // If a cv-qualifier appears in a decl-specifier-seq, the 4261 // init-declarator-list of the declaration shall not be empty. 4262 // 4263 // Spurious qualifiers here appear to be valid in C. 4264 unsigned DiagID = diag::warn_standalone_specifier; 4265 if (getLangOpts().CPlusPlus) 4266 DiagID = diag::ext_standalone_specifier; 4267 4268 // Note that a linkage-specification sets a storage class, but 4269 // 'extern "C" struct foo;' is actually valid and not theoretically 4270 // useless. 4271 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4272 if (SCS == DeclSpec::SCS_mutable) 4273 // Since mutable is not a viable storage class specifier in C, there is 4274 // no reason to treat it as an extension. Instead, diagnose as an error. 4275 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4276 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4277 Diag(DS.getStorageClassSpecLoc(), DiagID) 4278 << DeclSpec::getSpecifierName(SCS); 4279 } 4280 4281 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4282 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4283 << DeclSpec::getSpecifierName(TSCS); 4284 if (DS.getTypeQualifiers()) { 4285 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4286 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4287 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4288 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4289 // Restrict is covered above. 4290 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4291 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4292 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4293 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4294 } 4295 4296 // Warn about ignored type attributes, for example: 4297 // __attribute__((aligned)) struct A; 4298 // Attributes should be placed after tag to apply to type declaration. 4299 if (!DS.getAttributes().empty()) { 4300 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4301 if (TypeSpecType == DeclSpec::TST_class || 4302 TypeSpecType == DeclSpec::TST_struct || 4303 TypeSpecType == DeclSpec::TST_interface || 4304 TypeSpecType == DeclSpec::TST_union || 4305 TypeSpecType == DeclSpec::TST_enum) { 4306 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4307 attrs = attrs->getNext()) 4308 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4309 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4310 } 4311 } 4312 4313 return TagD; 4314 } 4315 4316 /// We are trying to inject an anonymous member into the given scope; 4317 /// check if there's an existing declaration that can't be overloaded. 4318 /// 4319 /// \return true if this is a forbidden redeclaration 4320 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4321 Scope *S, 4322 DeclContext *Owner, 4323 DeclarationName Name, 4324 SourceLocation NameLoc, 4325 bool IsUnion) { 4326 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4327 Sema::ForRedeclaration); 4328 if (!SemaRef.LookupName(R, S)) return false; 4329 4330 // Pick a representative declaration. 4331 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4332 assert(PrevDecl && "Expected a non-null Decl"); 4333 4334 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4335 return false; 4336 4337 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4338 << IsUnion << Name; 4339 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4340 4341 return true; 4342 } 4343 4344 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4345 /// anonymous struct or union AnonRecord into the owning context Owner 4346 /// and scope S. This routine will be invoked just after we realize 4347 /// that an unnamed union or struct is actually an anonymous union or 4348 /// struct, e.g., 4349 /// 4350 /// @code 4351 /// union { 4352 /// int i; 4353 /// float f; 4354 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4355 /// // f into the surrounding scope.x 4356 /// @endcode 4357 /// 4358 /// This routine is recursive, injecting the names of nested anonymous 4359 /// structs/unions into the owning context and scope as well. 4360 static bool 4361 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4362 RecordDecl *AnonRecord, AccessSpecifier AS, 4363 SmallVectorImpl<NamedDecl *> &Chaining) { 4364 bool Invalid = false; 4365 4366 // Look every FieldDecl and IndirectFieldDecl with a name. 4367 for (auto *D : AnonRecord->decls()) { 4368 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4369 cast<NamedDecl>(D)->getDeclName()) { 4370 ValueDecl *VD = cast<ValueDecl>(D); 4371 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4372 VD->getLocation(), 4373 AnonRecord->isUnion())) { 4374 // C++ [class.union]p2: 4375 // The names of the members of an anonymous union shall be 4376 // distinct from the names of any other entity in the 4377 // scope in which the anonymous union is declared. 4378 Invalid = true; 4379 } else { 4380 // C++ [class.union]p2: 4381 // For the purpose of name lookup, after the anonymous union 4382 // definition, the members of the anonymous union are 4383 // considered to have been defined in the scope in which the 4384 // anonymous union is declared. 4385 unsigned OldChainingSize = Chaining.size(); 4386 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4387 Chaining.append(IF->chain_begin(), IF->chain_end()); 4388 else 4389 Chaining.push_back(VD); 4390 4391 assert(Chaining.size() >= 2); 4392 NamedDecl **NamedChain = 4393 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4394 for (unsigned i = 0; i < Chaining.size(); i++) 4395 NamedChain[i] = Chaining[i]; 4396 4397 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4398 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4399 VD->getType(), {NamedChain, Chaining.size()}); 4400 4401 for (const auto *Attr : VD->attrs()) 4402 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4403 4404 IndirectField->setAccess(AS); 4405 IndirectField->setImplicit(); 4406 SemaRef.PushOnScopeChains(IndirectField, S); 4407 4408 // That includes picking up the appropriate access specifier. 4409 if (AS != AS_none) IndirectField->setAccess(AS); 4410 4411 Chaining.resize(OldChainingSize); 4412 } 4413 } 4414 } 4415 4416 return Invalid; 4417 } 4418 4419 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4420 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4421 /// illegal input values are mapped to SC_None. 4422 static StorageClass 4423 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4424 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4425 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4426 "Parser allowed 'typedef' as storage class VarDecl."); 4427 switch (StorageClassSpec) { 4428 case DeclSpec::SCS_unspecified: return SC_None; 4429 case DeclSpec::SCS_extern: 4430 if (DS.isExternInLinkageSpec()) 4431 return SC_None; 4432 return SC_Extern; 4433 case DeclSpec::SCS_static: return SC_Static; 4434 case DeclSpec::SCS_auto: return SC_Auto; 4435 case DeclSpec::SCS_register: return SC_Register; 4436 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4437 // Illegal SCSs map to None: error reporting is up to the caller. 4438 case DeclSpec::SCS_mutable: // Fall through. 4439 case DeclSpec::SCS_typedef: return SC_None; 4440 } 4441 llvm_unreachable("unknown storage class specifier"); 4442 } 4443 4444 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4445 assert(Record->hasInClassInitializer()); 4446 4447 for (const auto *I : Record->decls()) { 4448 const auto *FD = dyn_cast<FieldDecl>(I); 4449 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4450 FD = IFD->getAnonField(); 4451 if (FD && FD->hasInClassInitializer()) 4452 return FD->getLocation(); 4453 } 4454 4455 llvm_unreachable("couldn't find in-class initializer"); 4456 } 4457 4458 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4459 SourceLocation DefaultInitLoc) { 4460 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4461 return; 4462 4463 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4464 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4465 } 4466 4467 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4468 CXXRecordDecl *AnonUnion) { 4469 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4470 return; 4471 4472 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4473 } 4474 4475 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4476 /// anonymous structure or union. Anonymous unions are a C++ feature 4477 /// (C++ [class.union]) and a C11 feature; anonymous structures 4478 /// are a C11 feature and GNU C++ extension. 4479 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4480 AccessSpecifier AS, 4481 RecordDecl *Record, 4482 const PrintingPolicy &Policy) { 4483 DeclContext *Owner = Record->getDeclContext(); 4484 4485 // Diagnose whether this anonymous struct/union is an extension. 4486 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4487 Diag(Record->getLocation(), diag::ext_anonymous_union); 4488 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4489 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4490 else if (!Record->isUnion() && !getLangOpts().C11) 4491 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4492 4493 // C and C++ require different kinds of checks for anonymous 4494 // structs/unions. 4495 bool Invalid = false; 4496 if (getLangOpts().CPlusPlus) { 4497 const char *PrevSpec = nullptr; 4498 unsigned DiagID; 4499 if (Record->isUnion()) { 4500 // C++ [class.union]p6: 4501 // Anonymous unions declared in a named namespace or in the 4502 // global namespace shall be declared static. 4503 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4504 (isa<TranslationUnitDecl>(Owner) || 4505 (isa<NamespaceDecl>(Owner) && 4506 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4507 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4508 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4509 4510 // Recover by adding 'static'. 4511 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4512 PrevSpec, DiagID, Policy); 4513 } 4514 // C++ [class.union]p6: 4515 // A storage class is not allowed in a declaration of an 4516 // anonymous union in a class scope. 4517 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4518 isa<RecordDecl>(Owner)) { 4519 Diag(DS.getStorageClassSpecLoc(), 4520 diag::err_anonymous_union_with_storage_spec) 4521 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4522 4523 // Recover by removing the storage specifier. 4524 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4525 SourceLocation(), 4526 PrevSpec, DiagID, Context.getPrintingPolicy()); 4527 } 4528 } 4529 4530 // Ignore const/volatile/restrict qualifiers. 4531 if (DS.getTypeQualifiers()) { 4532 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4533 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4534 << Record->isUnion() << "const" 4535 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4536 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4537 Diag(DS.getVolatileSpecLoc(), 4538 diag::ext_anonymous_struct_union_qualified) 4539 << Record->isUnion() << "volatile" 4540 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4541 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4542 Diag(DS.getRestrictSpecLoc(), 4543 diag::ext_anonymous_struct_union_qualified) 4544 << Record->isUnion() << "restrict" 4545 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4546 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4547 Diag(DS.getAtomicSpecLoc(), 4548 diag::ext_anonymous_struct_union_qualified) 4549 << Record->isUnion() << "_Atomic" 4550 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4551 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4552 Diag(DS.getUnalignedSpecLoc(), 4553 diag::ext_anonymous_struct_union_qualified) 4554 << Record->isUnion() << "__unaligned" 4555 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4556 4557 DS.ClearTypeQualifiers(); 4558 } 4559 4560 // C++ [class.union]p2: 4561 // The member-specification of an anonymous union shall only 4562 // define non-static data members. [Note: nested types and 4563 // functions cannot be declared within an anonymous union. ] 4564 for (auto *Mem : Record->decls()) { 4565 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4566 // C++ [class.union]p3: 4567 // An anonymous union shall not have private or protected 4568 // members (clause 11). 4569 assert(FD->getAccess() != AS_none); 4570 if (FD->getAccess() != AS_public) { 4571 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4572 << Record->isUnion() << (FD->getAccess() == AS_protected); 4573 Invalid = true; 4574 } 4575 4576 // C++ [class.union]p1 4577 // An object of a class with a non-trivial constructor, a non-trivial 4578 // copy constructor, a non-trivial destructor, or a non-trivial copy 4579 // assignment operator cannot be a member of a union, nor can an 4580 // array of such objects. 4581 if (CheckNontrivialField(FD)) 4582 Invalid = true; 4583 } else if (Mem->isImplicit()) { 4584 // Any implicit members are fine. 4585 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4586 // This is a type that showed up in an 4587 // elaborated-type-specifier inside the anonymous struct or 4588 // union, but which actually declares a type outside of the 4589 // anonymous struct or union. It's okay. 4590 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4591 if (!MemRecord->isAnonymousStructOrUnion() && 4592 MemRecord->getDeclName()) { 4593 // Visual C++ allows type definition in anonymous struct or union. 4594 if (getLangOpts().MicrosoftExt) 4595 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4596 << Record->isUnion(); 4597 else { 4598 // This is a nested type declaration. 4599 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4600 << Record->isUnion(); 4601 Invalid = true; 4602 } 4603 } else { 4604 // This is an anonymous type definition within another anonymous type. 4605 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4606 // not part of standard C++. 4607 Diag(MemRecord->getLocation(), 4608 diag::ext_anonymous_record_with_anonymous_type) 4609 << Record->isUnion(); 4610 } 4611 } else if (isa<AccessSpecDecl>(Mem)) { 4612 // Any access specifier is fine. 4613 } else if (isa<StaticAssertDecl>(Mem)) { 4614 // In C++1z, static_assert declarations are also fine. 4615 } else { 4616 // We have something that isn't a non-static data 4617 // member. Complain about it. 4618 unsigned DK = diag::err_anonymous_record_bad_member; 4619 if (isa<TypeDecl>(Mem)) 4620 DK = diag::err_anonymous_record_with_type; 4621 else if (isa<FunctionDecl>(Mem)) 4622 DK = diag::err_anonymous_record_with_function; 4623 else if (isa<VarDecl>(Mem)) 4624 DK = diag::err_anonymous_record_with_static; 4625 4626 // Visual C++ allows type definition in anonymous struct or union. 4627 if (getLangOpts().MicrosoftExt && 4628 DK == diag::err_anonymous_record_with_type) 4629 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4630 << Record->isUnion(); 4631 else { 4632 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4633 Invalid = true; 4634 } 4635 } 4636 } 4637 4638 // C++11 [class.union]p8 (DR1460): 4639 // At most one variant member of a union may have a 4640 // brace-or-equal-initializer. 4641 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4642 Owner->isRecord()) 4643 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4644 cast<CXXRecordDecl>(Record)); 4645 } 4646 4647 if (!Record->isUnion() && !Owner->isRecord()) { 4648 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4649 << getLangOpts().CPlusPlus; 4650 Invalid = true; 4651 } 4652 4653 // Mock up a declarator. 4654 Declarator Dc(DS, Declarator::MemberContext); 4655 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4656 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4657 4658 // Create a declaration for this anonymous struct/union. 4659 NamedDecl *Anon = nullptr; 4660 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4661 Anon = FieldDecl::Create(Context, OwningClass, 4662 DS.getLocStart(), 4663 Record->getLocation(), 4664 /*IdentifierInfo=*/nullptr, 4665 Context.getTypeDeclType(Record), 4666 TInfo, 4667 /*BitWidth=*/nullptr, /*Mutable=*/false, 4668 /*InitStyle=*/ICIS_NoInit); 4669 Anon->setAccess(AS); 4670 if (getLangOpts().CPlusPlus) 4671 FieldCollector->Add(cast<FieldDecl>(Anon)); 4672 } else { 4673 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4674 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4675 if (SCSpec == DeclSpec::SCS_mutable) { 4676 // mutable can only appear on non-static class members, so it's always 4677 // an error here 4678 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4679 Invalid = true; 4680 SC = SC_None; 4681 } 4682 4683 Anon = VarDecl::Create(Context, Owner, 4684 DS.getLocStart(), 4685 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4686 Context.getTypeDeclType(Record), 4687 TInfo, SC); 4688 4689 // Default-initialize the implicit variable. This initialization will be 4690 // trivial in almost all cases, except if a union member has an in-class 4691 // initializer: 4692 // union { int n = 0; }; 4693 ActOnUninitializedDecl(Anon); 4694 } 4695 Anon->setImplicit(); 4696 4697 // Mark this as an anonymous struct/union type. 4698 Record->setAnonymousStructOrUnion(true); 4699 4700 // Add the anonymous struct/union object to the current 4701 // context. We'll be referencing this object when we refer to one of 4702 // its members. 4703 Owner->addDecl(Anon); 4704 4705 // Inject the members of the anonymous struct/union into the owning 4706 // context and into the identifier resolver chain for name lookup 4707 // purposes. 4708 SmallVector<NamedDecl*, 2> Chain; 4709 Chain.push_back(Anon); 4710 4711 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4712 Invalid = true; 4713 4714 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4715 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4716 Decl *ManglingContextDecl; 4717 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4718 NewVD->getDeclContext(), ManglingContextDecl)) { 4719 Context.setManglingNumber( 4720 NewVD, MCtx->getManglingNumber( 4721 NewVD, getMSManglingNumber(getLangOpts(), S))); 4722 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4723 } 4724 } 4725 } 4726 4727 if (Invalid) 4728 Anon->setInvalidDecl(); 4729 4730 return Anon; 4731 } 4732 4733 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4734 /// Microsoft C anonymous structure. 4735 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4736 /// Example: 4737 /// 4738 /// struct A { int a; }; 4739 /// struct B { struct A; int b; }; 4740 /// 4741 /// void foo() { 4742 /// B var; 4743 /// var.a = 3; 4744 /// } 4745 /// 4746 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4747 RecordDecl *Record) { 4748 assert(Record && "expected a record!"); 4749 4750 // Mock up a declarator. 4751 Declarator Dc(DS, Declarator::TypeNameContext); 4752 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4753 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4754 4755 auto *ParentDecl = cast<RecordDecl>(CurContext); 4756 QualType RecTy = Context.getTypeDeclType(Record); 4757 4758 // Create a declaration for this anonymous struct. 4759 NamedDecl *Anon = FieldDecl::Create(Context, 4760 ParentDecl, 4761 DS.getLocStart(), 4762 DS.getLocStart(), 4763 /*IdentifierInfo=*/nullptr, 4764 RecTy, 4765 TInfo, 4766 /*BitWidth=*/nullptr, /*Mutable=*/false, 4767 /*InitStyle=*/ICIS_NoInit); 4768 Anon->setImplicit(); 4769 4770 // Add the anonymous struct object to the current context. 4771 CurContext->addDecl(Anon); 4772 4773 // Inject the members of the anonymous struct into the current 4774 // context and into the identifier resolver chain for name lookup 4775 // purposes. 4776 SmallVector<NamedDecl*, 2> Chain; 4777 Chain.push_back(Anon); 4778 4779 RecordDecl *RecordDef = Record->getDefinition(); 4780 if (RequireCompleteType(Anon->getLocation(), RecTy, 4781 diag::err_field_incomplete) || 4782 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4783 AS_none, Chain)) { 4784 Anon->setInvalidDecl(); 4785 ParentDecl->setInvalidDecl(); 4786 } 4787 4788 return Anon; 4789 } 4790 4791 /// GetNameForDeclarator - Determine the full declaration name for the 4792 /// given Declarator. 4793 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4794 return GetNameFromUnqualifiedId(D.getName()); 4795 } 4796 4797 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4798 DeclarationNameInfo 4799 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4800 DeclarationNameInfo NameInfo; 4801 NameInfo.setLoc(Name.StartLocation); 4802 4803 switch (Name.getKind()) { 4804 4805 case UnqualifiedId::IK_ImplicitSelfParam: 4806 case UnqualifiedId::IK_Identifier: 4807 NameInfo.setName(Name.Identifier); 4808 NameInfo.setLoc(Name.StartLocation); 4809 return NameInfo; 4810 4811 case UnqualifiedId::IK_DeductionGuideName: { 4812 // C++ [temp.deduct.guide]p3: 4813 // The simple-template-id shall name a class template specialization. 4814 // The template-name shall be the same identifier as the template-name 4815 // of the simple-template-id. 4816 // These together intend to imply that the template-name shall name a 4817 // class template. 4818 // FIXME: template<typename T> struct X {}; 4819 // template<typename T> using Y = X<T>; 4820 // Y(int) -> Y<int>; 4821 // satisfies these rules but does not name a class template. 4822 TemplateName TN = Name.TemplateName.get().get(); 4823 auto *Template = TN.getAsTemplateDecl(); 4824 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4825 Diag(Name.StartLocation, 4826 diag::err_deduction_guide_name_not_class_template) 4827 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4828 if (Template) 4829 Diag(Template->getLocation(), diag::note_template_decl_here); 4830 return DeclarationNameInfo(); 4831 } 4832 4833 NameInfo.setName( 4834 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4835 NameInfo.setLoc(Name.StartLocation); 4836 return NameInfo; 4837 } 4838 4839 case UnqualifiedId::IK_OperatorFunctionId: 4840 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4841 Name.OperatorFunctionId.Operator)); 4842 NameInfo.setLoc(Name.StartLocation); 4843 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4844 = Name.OperatorFunctionId.SymbolLocations[0]; 4845 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4846 = Name.EndLocation.getRawEncoding(); 4847 return NameInfo; 4848 4849 case UnqualifiedId::IK_LiteralOperatorId: 4850 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4851 Name.Identifier)); 4852 NameInfo.setLoc(Name.StartLocation); 4853 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4854 return NameInfo; 4855 4856 case UnqualifiedId::IK_ConversionFunctionId: { 4857 TypeSourceInfo *TInfo; 4858 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4859 if (Ty.isNull()) 4860 return DeclarationNameInfo(); 4861 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4862 Context.getCanonicalType(Ty))); 4863 NameInfo.setLoc(Name.StartLocation); 4864 NameInfo.setNamedTypeInfo(TInfo); 4865 return NameInfo; 4866 } 4867 4868 case UnqualifiedId::IK_ConstructorName: { 4869 TypeSourceInfo *TInfo; 4870 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4871 if (Ty.isNull()) 4872 return DeclarationNameInfo(); 4873 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4874 Context.getCanonicalType(Ty))); 4875 NameInfo.setLoc(Name.StartLocation); 4876 NameInfo.setNamedTypeInfo(TInfo); 4877 return NameInfo; 4878 } 4879 4880 case UnqualifiedId::IK_ConstructorTemplateId: { 4881 // In well-formed code, we can only have a constructor 4882 // template-id that refers to the current context, so go there 4883 // to find the actual type being constructed. 4884 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4885 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4886 return DeclarationNameInfo(); 4887 4888 // Determine the type of the class being constructed. 4889 QualType CurClassType = Context.getTypeDeclType(CurClass); 4890 4891 // FIXME: Check two things: that the template-id names the same type as 4892 // CurClassType, and that the template-id does not occur when the name 4893 // was qualified. 4894 4895 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4896 Context.getCanonicalType(CurClassType))); 4897 NameInfo.setLoc(Name.StartLocation); 4898 // FIXME: should we retrieve TypeSourceInfo? 4899 NameInfo.setNamedTypeInfo(nullptr); 4900 return NameInfo; 4901 } 4902 4903 case UnqualifiedId::IK_DestructorName: { 4904 TypeSourceInfo *TInfo; 4905 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4906 if (Ty.isNull()) 4907 return DeclarationNameInfo(); 4908 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4909 Context.getCanonicalType(Ty))); 4910 NameInfo.setLoc(Name.StartLocation); 4911 NameInfo.setNamedTypeInfo(TInfo); 4912 return NameInfo; 4913 } 4914 4915 case UnqualifiedId::IK_TemplateId: { 4916 TemplateName TName = Name.TemplateId->Template.get(); 4917 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4918 return Context.getNameForTemplate(TName, TNameLoc); 4919 } 4920 4921 } // switch (Name.getKind()) 4922 4923 llvm_unreachable("Unknown name kind"); 4924 } 4925 4926 static QualType getCoreType(QualType Ty) { 4927 do { 4928 if (Ty->isPointerType() || Ty->isReferenceType()) 4929 Ty = Ty->getPointeeType(); 4930 else if (Ty->isArrayType()) 4931 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4932 else 4933 return Ty.withoutLocalFastQualifiers(); 4934 } while (true); 4935 } 4936 4937 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4938 /// and Definition have "nearly" matching parameters. This heuristic is 4939 /// used to improve diagnostics in the case where an out-of-line function 4940 /// definition doesn't match any declaration within the class or namespace. 4941 /// Also sets Params to the list of indices to the parameters that differ 4942 /// between the declaration and the definition. If hasSimilarParameters 4943 /// returns true and Params is empty, then all of the parameters match. 4944 static bool hasSimilarParameters(ASTContext &Context, 4945 FunctionDecl *Declaration, 4946 FunctionDecl *Definition, 4947 SmallVectorImpl<unsigned> &Params) { 4948 Params.clear(); 4949 if (Declaration->param_size() != Definition->param_size()) 4950 return false; 4951 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4952 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4953 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4954 4955 // The parameter types are identical 4956 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4957 continue; 4958 4959 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4960 QualType DefParamBaseTy = getCoreType(DefParamTy); 4961 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4962 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4963 4964 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4965 (DeclTyName && DeclTyName == DefTyName)) 4966 Params.push_back(Idx); 4967 else // The two parameters aren't even close 4968 return false; 4969 } 4970 4971 return true; 4972 } 4973 4974 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4975 /// declarator needs to be rebuilt in the current instantiation. 4976 /// Any bits of declarator which appear before the name are valid for 4977 /// consideration here. That's specifically the type in the decl spec 4978 /// and the base type in any member-pointer chunks. 4979 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4980 DeclarationName Name) { 4981 // The types we specifically need to rebuild are: 4982 // - typenames, typeofs, and decltypes 4983 // - types which will become injected class names 4984 // Of course, we also need to rebuild any type referencing such a 4985 // type. It's safest to just say "dependent", but we call out a 4986 // few cases here. 4987 4988 DeclSpec &DS = D.getMutableDeclSpec(); 4989 switch (DS.getTypeSpecType()) { 4990 case DeclSpec::TST_typename: 4991 case DeclSpec::TST_typeofType: 4992 case DeclSpec::TST_underlyingType: 4993 case DeclSpec::TST_atomic: { 4994 // Grab the type from the parser. 4995 TypeSourceInfo *TSI = nullptr; 4996 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4997 if (T.isNull() || !T->isDependentType()) break; 4998 4999 // Make sure there's a type source info. This isn't really much 5000 // of a waste; most dependent types should have type source info 5001 // attached already. 5002 if (!TSI) 5003 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5004 5005 // Rebuild the type in the current instantiation. 5006 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5007 if (!TSI) return true; 5008 5009 // Store the new type back in the decl spec. 5010 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5011 DS.UpdateTypeRep(LocType); 5012 break; 5013 } 5014 5015 case DeclSpec::TST_decltype: 5016 case DeclSpec::TST_typeofExpr: { 5017 Expr *E = DS.getRepAsExpr(); 5018 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5019 if (Result.isInvalid()) return true; 5020 DS.UpdateExprRep(Result.get()); 5021 break; 5022 } 5023 5024 default: 5025 // Nothing to do for these decl specs. 5026 break; 5027 } 5028 5029 // It doesn't matter what order we do this in. 5030 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5031 DeclaratorChunk &Chunk = D.getTypeObject(I); 5032 5033 // The only type information in the declarator which can come 5034 // before the declaration name is the base type of a member 5035 // pointer. 5036 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5037 continue; 5038 5039 // Rebuild the scope specifier in-place. 5040 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5041 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5042 return true; 5043 } 5044 5045 return false; 5046 } 5047 5048 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5049 D.setFunctionDefinitionKind(FDK_Declaration); 5050 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5051 5052 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5053 Dcl && Dcl->getDeclContext()->isFileContext()) 5054 Dcl->setTopLevelDeclInObjCContainer(); 5055 5056 if (getLangOpts().OpenCL) 5057 setCurrentOpenCLExtensionForDecl(Dcl); 5058 5059 return Dcl; 5060 } 5061 5062 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5063 /// If T is the name of a class, then each of the following shall have a 5064 /// name different from T: 5065 /// - every static data member of class T; 5066 /// - every member function of class T 5067 /// - every member of class T that is itself a type; 5068 /// \returns true if the declaration name violates these rules. 5069 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5070 DeclarationNameInfo NameInfo) { 5071 DeclarationName Name = NameInfo.getName(); 5072 5073 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5074 while (Record && Record->isAnonymousStructOrUnion()) 5075 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5076 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5077 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5078 return true; 5079 } 5080 5081 return false; 5082 } 5083 5084 /// \brief Diagnose a declaration whose declarator-id has the given 5085 /// nested-name-specifier. 5086 /// 5087 /// \param SS The nested-name-specifier of the declarator-id. 5088 /// 5089 /// \param DC The declaration context to which the nested-name-specifier 5090 /// resolves. 5091 /// 5092 /// \param Name The name of the entity being declared. 5093 /// 5094 /// \param Loc The location of the name of the entity being declared. 5095 /// 5096 /// \returns true if we cannot safely recover from this error, false otherwise. 5097 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5098 DeclarationName Name, 5099 SourceLocation Loc) { 5100 DeclContext *Cur = CurContext; 5101 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5102 Cur = Cur->getParent(); 5103 5104 // If the user provided a superfluous scope specifier that refers back to the 5105 // class in which the entity is already declared, diagnose and ignore it. 5106 // 5107 // class X { 5108 // void X::f(); 5109 // }; 5110 // 5111 // Note, it was once ill-formed to give redundant qualification in all 5112 // contexts, but that rule was removed by DR482. 5113 if (Cur->Equals(DC)) { 5114 if (Cur->isRecord()) { 5115 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5116 : diag::err_member_extra_qualification) 5117 << Name << FixItHint::CreateRemoval(SS.getRange()); 5118 SS.clear(); 5119 } else { 5120 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5121 } 5122 return false; 5123 } 5124 5125 // Check whether the qualifying scope encloses the scope of the original 5126 // declaration. 5127 if (!Cur->Encloses(DC)) { 5128 if (Cur->isRecord()) 5129 Diag(Loc, diag::err_member_qualification) 5130 << Name << SS.getRange(); 5131 else if (isa<TranslationUnitDecl>(DC)) 5132 Diag(Loc, diag::err_invalid_declarator_global_scope) 5133 << Name << SS.getRange(); 5134 else if (isa<FunctionDecl>(Cur)) 5135 Diag(Loc, diag::err_invalid_declarator_in_function) 5136 << Name << SS.getRange(); 5137 else if (isa<BlockDecl>(Cur)) 5138 Diag(Loc, diag::err_invalid_declarator_in_block) 5139 << Name << SS.getRange(); 5140 else 5141 Diag(Loc, diag::err_invalid_declarator_scope) 5142 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5143 5144 return true; 5145 } 5146 5147 if (Cur->isRecord()) { 5148 // Cannot qualify members within a class. 5149 Diag(Loc, diag::err_member_qualification) 5150 << Name << SS.getRange(); 5151 SS.clear(); 5152 5153 // C++ constructors and destructors with incorrect scopes can break 5154 // our AST invariants by having the wrong underlying types. If 5155 // that's the case, then drop this declaration entirely. 5156 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5157 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5158 !Context.hasSameType(Name.getCXXNameType(), 5159 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5160 return true; 5161 5162 return false; 5163 } 5164 5165 // C++11 [dcl.meaning]p1: 5166 // [...] "The nested-name-specifier of the qualified declarator-id shall 5167 // not begin with a decltype-specifer" 5168 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5169 while (SpecLoc.getPrefix()) 5170 SpecLoc = SpecLoc.getPrefix(); 5171 if (dyn_cast_or_null<DecltypeType>( 5172 SpecLoc.getNestedNameSpecifier()->getAsType())) 5173 Diag(Loc, diag::err_decltype_in_declarator) 5174 << SpecLoc.getTypeLoc().getSourceRange(); 5175 5176 return false; 5177 } 5178 5179 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5180 MultiTemplateParamsArg TemplateParamLists) { 5181 // TODO: consider using NameInfo for diagnostic. 5182 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5183 DeclarationName Name = NameInfo.getName(); 5184 5185 // All of these full declarators require an identifier. If it doesn't have 5186 // one, the ParsedFreeStandingDeclSpec action should be used. 5187 if (D.isDecompositionDeclarator()) { 5188 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5189 } else if (!Name) { 5190 if (!D.isInvalidType()) // Reject this if we think it is valid. 5191 Diag(D.getDeclSpec().getLocStart(), 5192 diag::err_declarator_need_ident) 5193 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5194 return nullptr; 5195 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5196 return nullptr; 5197 5198 // The scope passed in may not be a decl scope. Zip up the scope tree until 5199 // we find one that is. 5200 while ((S->getFlags() & Scope::DeclScope) == 0 || 5201 (S->getFlags() & Scope::TemplateParamScope) != 0) 5202 S = S->getParent(); 5203 5204 DeclContext *DC = CurContext; 5205 if (D.getCXXScopeSpec().isInvalid()) 5206 D.setInvalidType(); 5207 else if (D.getCXXScopeSpec().isSet()) { 5208 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5209 UPPC_DeclarationQualifier)) 5210 return nullptr; 5211 5212 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5213 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5214 if (!DC || isa<EnumDecl>(DC)) { 5215 // If we could not compute the declaration context, it's because the 5216 // declaration context is dependent but does not refer to a class, 5217 // class template, or class template partial specialization. Complain 5218 // and return early, to avoid the coming semantic disaster. 5219 Diag(D.getIdentifierLoc(), 5220 diag::err_template_qualified_declarator_no_match) 5221 << D.getCXXScopeSpec().getScopeRep() 5222 << D.getCXXScopeSpec().getRange(); 5223 return nullptr; 5224 } 5225 bool IsDependentContext = DC->isDependentContext(); 5226 5227 if (!IsDependentContext && 5228 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5229 return nullptr; 5230 5231 // If a class is incomplete, do not parse entities inside it. 5232 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5233 Diag(D.getIdentifierLoc(), 5234 diag::err_member_def_undefined_record) 5235 << Name << DC << D.getCXXScopeSpec().getRange(); 5236 return nullptr; 5237 } 5238 if (!D.getDeclSpec().isFriendSpecified()) { 5239 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5240 Name, D.getIdentifierLoc())) { 5241 if (DC->isRecord()) 5242 return nullptr; 5243 5244 D.setInvalidType(); 5245 } 5246 } 5247 5248 // Check whether we need to rebuild the type of the given 5249 // declaration in the current instantiation. 5250 if (EnteringContext && IsDependentContext && 5251 TemplateParamLists.size() != 0) { 5252 ContextRAII SavedContext(*this, DC); 5253 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5254 D.setInvalidType(); 5255 } 5256 } 5257 5258 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5259 QualType R = TInfo->getType(); 5260 5261 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5262 // If this is a typedef, we'll end up spewing multiple diagnostics. 5263 // Just return early; it's safer. If this is a function, let the 5264 // "constructor cannot have a return type" diagnostic handle it. 5265 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5266 return nullptr; 5267 5268 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5269 UPPC_DeclarationType)) 5270 D.setInvalidType(); 5271 5272 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5273 ForRedeclaration); 5274 5275 // See if this is a redefinition of a variable in the same scope. 5276 if (!D.getCXXScopeSpec().isSet()) { 5277 bool IsLinkageLookup = false; 5278 bool CreateBuiltins = false; 5279 5280 // If the declaration we're planning to build will be a function 5281 // or object with linkage, then look for another declaration with 5282 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5283 // 5284 // If the declaration we're planning to build will be declared with 5285 // external linkage in the translation unit, create any builtin with 5286 // the same name. 5287 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5288 /* Do nothing*/; 5289 else if (CurContext->isFunctionOrMethod() && 5290 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5291 R->isFunctionType())) { 5292 IsLinkageLookup = true; 5293 CreateBuiltins = 5294 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5295 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5296 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5297 CreateBuiltins = true; 5298 5299 if (IsLinkageLookup) 5300 Previous.clear(LookupRedeclarationWithLinkage); 5301 5302 LookupName(Previous, S, CreateBuiltins); 5303 } else { // Something like "int foo::x;" 5304 LookupQualifiedName(Previous, DC); 5305 5306 // C++ [dcl.meaning]p1: 5307 // When the declarator-id is qualified, the declaration shall refer to a 5308 // previously declared member of the class or namespace to which the 5309 // qualifier refers (or, in the case of a namespace, of an element of the 5310 // inline namespace set of that namespace (7.3.1)) or to a specialization 5311 // thereof; [...] 5312 // 5313 // Note that we already checked the context above, and that we do not have 5314 // enough information to make sure that Previous contains the declaration 5315 // we want to match. For example, given: 5316 // 5317 // class X { 5318 // void f(); 5319 // void f(float); 5320 // }; 5321 // 5322 // void X::f(int) { } // ill-formed 5323 // 5324 // In this case, Previous will point to the overload set 5325 // containing the two f's declared in X, but neither of them 5326 // matches. 5327 5328 // C++ [dcl.meaning]p1: 5329 // [...] the member shall not merely have been introduced by a 5330 // using-declaration in the scope of the class or namespace nominated by 5331 // the nested-name-specifier of the declarator-id. 5332 RemoveUsingDecls(Previous); 5333 } 5334 5335 if (Previous.isSingleResult() && 5336 Previous.getFoundDecl()->isTemplateParameter()) { 5337 // Maybe we will complain about the shadowed template parameter. 5338 if (!D.isInvalidType()) 5339 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5340 Previous.getFoundDecl()); 5341 5342 // Just pretend that we didn't see the previous declaration. 5343 Previous.clear(); 5344 } 5345 5346 // In C++, the previous declaration we find might be a tag type 5347 // (class or enum). In this case, the new declaration will hide the 5348 // tag type. Note that this does does not apply if we're declaring a 5349 // typedef (C++ [dcl.typedef]p4). 5350 if (Previous.isSingleTagDecl() && 5351 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 5352 Previous.clear(); 5353 5354 // Check that there are no default arguments other than in the parameters 5355 // of a function declaration (C++ only). 5356 if (getLangOpts().CPlusPlus) 5357 CheckExtraCXXDefaultArguments(D); 5358 5359 if (D.getDeclSpec().isConceptSpecified()) { 5360 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5361 // applied only to the definition of a function template or variable 5362 // template, declared in namespace scope 5363 if (!TemplateParamLists.size()) { 5364 Diag(D.getDeclSpec().getConceptSpecLoc(), 5365 diag:: err_concept_wrong_decl_kind); 5366 return nullptr; 5367 } 5368 5369 if (!DC->getRedeclContext()->isFileContext()) { 5370 Diag(D.getIdentifierLoc(), 5371 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5372 return nullptr; 5373 } 5374 } 5375 5376 NamedDecl *New; 5377 5378 bool AddToScope = true; 5379 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5380 if (TemplateParamLists.size()) { 5381 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5382 return nullptr; 5383 } 5384 5385 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5386 } else if (R->isFunctionType()) { 5387 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5388 TemplateParamLists, 5389 AddToScope); 5390 } else { 5391 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5392 AddToScope); 5393 } 5394 5395 if (!New) 5396 return nullptr; 5397 5398 // If this has an identifier and is not a function template specialization, 5399 // add it to the scope stack. 5400 if (New->getDeclName() && AddToScope) { 5401 // Only make a locally-scoped extern declaration visible if it is the first 5402 // declaration of this entity. Qualified lookup for such an entity should 5403 // only find this declaration if there is no visible declaration of it. 5404 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5405 PushOnScopeChains(New, S, AddToContext); 5406 if (!AddToContext) 5407 CurContext->addHiddenDecl(New); 5408 } 5409 5410 if (isInOpenMPDeclareTargetContext()) 5411 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5412 5413 return New; 5414 } 5415 5416 /// Helper method to turn variable array types into constant array 5417 /// types in certain situations which would otherwise be errors (for 5418 /// GCC compatibility). 5419 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5420 ASTContext &Context, 5421 bool &SizeIsNegative, 5422 llvm::APSInt &Oversized) { 5423 // This method tries to turn a variable array into a constant 5424 // array even when the size isn't an ICE. This is necessary 5425 // for compatibility with code that depends on gcc's buggy 5426 // constant expression folding, like struct {char x[(int)(char*)2];} 5427 SizeIsNegative = false; 5428 Oversized = 0; 5429 5430 if (T->isDependentType()) 5431 return QualType(); 5432 5433 QualifierCollector Qs; 5434 const Type *Ty = Qs.strip(T); 5435 5436 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5437 QualType Pointee = PTy->getPointeeType(); 5438 QualType FixedType = 5439 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5440 Oversized); 5441 if (FixedType.isNull()) return FixedType; 5442 FixedType = Context.getPointerType(FixedType); 5443 return Qs.apply(Context, FixedType); 5444 } 5445 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5446 QualType Inner = PTy->getInnerType(); 5447 QualType FixedType = 5448 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5449 Oversized); 5450 if (FixedType.isNull()) return FixedType; 5451 FixedType = Context.getParenType(FixedType); 5452 return Qs.apply(Context, FixedType); 5453 } 5454 5455 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5456 if (!VLATy) 5457 return QualType(); 5458 // FIXME: We should probably handle this case 5459 if (VLATy->getElementType()->isVariablyModifiedType()) 5460 return QualType(); 5461 5462 llvm::APSInt Res; 5463 if (!VLATy->getSizeExpr() || 5464 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5465 return QualType(); 5466 5467 // Check whether the array size is negative. 5468 if (Res.isSigned() && Res.isNegative()) { 5469 SizeIsNegative = true; 5470 return QualType(); 5471 } 5472 5473 // Check whether the array is too large to be addressed. 5474 unsigned ActiveSizeBits 5475 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5476 Res); 5477 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5478 Oversized = Res; 5479 return QualType(); 5480 } 5481 5482 return Context.getConstantArrayType(VLATy->getElementType(), 5483 Res, ArrayType::Normal, 0); 5484 } 5485 5486 static void 5487 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5488 SrcTL = SrcTL.getUnqualifiedLoc(); 5489 DstTL = DstTL.getUnqualifiedLoc(); 5490 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5491 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5492 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5493 DstPTL.getPointeeLoc()); 5494 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5495 return; 5496 } 5497 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5498 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5499 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5500 DstPTL.getInnerLoc()); 5501 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5502 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5503 return; 5504 } 5505 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5506 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5507 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5508 TypeLoc DstElemTL = DstATL.getElementLoc(); 5509 DstElemTL.initializeFullCopy(SrcElemTL); 5510 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5511 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5512 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5513 } 5514 5515 /// Helper method to turn variable array types into constant array 5516 /// types in certain situations which would otherwise be errors (for 5517 /// GCC compatibility). 5518 static TypeSourceInfo* 5519 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5520 ASTContext &Context, 5521 bool &SizeIsNegative, 5522 llvm::APSInt &Oversized) { 5523 QualType FixedTy 5524 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5525 SizeIsNegative, Oversized); 5526 if (FixedTy.isNull()) 5527 return nullptr; 5528 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5529 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5530 FixedTInfo->getTypeLoc()); 5531 return FixedTInfo; 5532 } 5533 5534 /// \brief Register the given locally-scoped extern "C" declaration so 5535 /// that it can be found later for redeclarations. We include any extern "C" 5536 /// declaration that is not visible in the translation unit here, not just 5537 /// function-scope declarations. 5538 void 5539 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5540 if (!getLangOpts().CPlusPlus && 5541 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5542 // Don't need to track declarations in the TU in C. 5543 return; 5544 5545 // Note that we have a locally-scoped external with this name. 5546 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5547 } 5548 5549 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5550 // FIXME: We can have multiple results via __attribute__((overloadable)). 5551 auto Result = Context.getExternCContextDecl()->lookup(Name); 5552 return Result.empty() ? nullptr : *Result.begin(); 5553 } 5554 5555 /// \brief Diagnose function specifiers on a declaration of an identifier that 5556 /// does not identify a function. 5557 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5558 // FIXME: We should probably indicate the identifier in question to avoid 5559 // confusion for constructs like "virtual int a(), b;" 5560 if (DS.isVirtualSpecified()) 5561 Diag(DS.getVirtualSpecLoc(), 5562 diag::err_virtual_non_function); 5563 5564 if (DS.isExplicitSpecified()) 5565 Diag(DS.getExplicitSpecLoc(), 5566 diag::err_explicit_non_function); 5567 5568 if (DS.isNoreturnSpecified()) 5569 Diag(DS.getNoreturnSpecLoc(), 5570 diag::err_noreturn_non_function); 5571 } 5572 5573 NamedDecl* 5574 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5575 TypeSourceInfo *TInfo, LookupResult &Previous) { 5576 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5577 if (D.getCXXScopeSpec().isSet()) { 5578 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5579 << D.getCXXScopeSpec().getRange(); 5580 D.setInvalidType(); 5581 // Pretend we didn't see the scope specifier. 5582 DC = CurContext; 5583 Previous.clear(); 5584 } 5585 5586 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5587 5588 if (D.getDeclSpec().isInlineSpecified()) 5589 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5590 << getLangOpts().CPlusPlus1z; 5591 if (D.getDeclSpec().isConstexprSpecified()) 5592 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5593 << 1; 5594 if (D.getDeclSpec().isConceptSpecified()) 5595 Diag(D.getDeclSpec().getConceptSpecLoc(), 5596 diag::err_concept_wrong_decl_kind); 5597 5598 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5599 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName) 5600 Diag(D.getName().StartLocation, 5601 diag::err_deduction_guide_invalid_specifier) 5602 << "typedef"; 5603 else 5604 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5605 << D.getName().getSourceRange(); 5606 return nullptr; 5607 } 5608 5609 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5610 if (!NewTD) return nullptr; 5611 5612 // Handle attributes prior to checking for duplicates in MergeVarDecl 5613 ProcessDeclAttributes(S, NewTD, D); 5614 5615 CheckTypedefForVariablyModifiedType(S, NewTD); 5616 5617 bool Redeclaration = D.isRedeclaration(); 5618 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5619 D.setRedeclaration(Redeclaration); 5620 return ND; 5621 } 5622 5623 void 5624 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5625 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5626 // then it shall have block scope. 5627 // Note that variably modified types must be fixed before merging the decl so 5628 // that redeclarations will match. 5629 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5630 QualType T = TInfo->getType(); 5631 if (T->isVariablyModifiedType()) { 5632 getCurFunction()->setHasBranchProtectedScope(); 5633 5634 if (S->getFnParent() == nullptr) { 5635 bool SizeIsNegative; 5636 llvm::APSInt Oversized; 5637 TypeSourceInfo *FixedTInfo = 5638 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5639 SizeIsNegative, 5640 Oversized); 5641 if (FixedTInfo) { 5642 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5643 NewTD->setTypeSourceInfo(FixedTInfo); 5644 } else { 5645 if (SizeIsNegative) 5646 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5647 else if (T->isVariableArrayType()) 5648 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5649 else if (Oversized.getBoolValue()) 5650 Diag(NewTD->getLocation(), diag::err_array_too_large) 5651 << Oversized.toString(10); 5652 else 5653 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5654 NewTD->setInvalidDecl(); 5655 } 5656 } 5657 } 5658 } 5659 5660 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5661 /// declares a typedef-name, either using the 'typedef' type specifier or via 5662 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5663 NamedDecl* 5664 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5665 LookupResult &Previous, bool &Redeclaration) { 5666 5667 // Find the shadowed declaration before filtering for scope. 5668 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5669 5670 // Merge the decl with the existing one if appropriate. If the decl is 5671 // in an outer scope, it isn't the same thing. 5672 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5673 /*AllowInlineNamespace*/false); 5674 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5675 if (!Previous.empty()) { 5676 Redeclaration = true; 5677 MergeTypedefNameDecl(S, NewTD, Previous); 5678 } 5679 5680 if (ShadowedDecl && !Redeclaration) 5681 CheckShadow(NewTD, ShadowedDecl, Previous); 5682 5683 // If this is the C FILE type, notify the AST context. 5684 if (IdentifierInfo *II = NewTD->getIdentifier()) 5685 if (!NewTD->isInvalidDecl() && 5686 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5687 if (II->isStr("FILE")) 5688 Context.setFILEDecl(NewTD); 5689 else if (II->isStr("jmp_buf")) 5690 Context.setjmp_bufDecl(NewTD); 5691 else if (II->isStr("sigjmp_buf")) 5692 Context.setsigjmp_bufDecl(NewTD); 5693 else if (II->isStr("ucontext_t")) 5694 Context.setucontext_tDecl(NewTD); 5695 } 5696 5697 return NewTD; 5698 } 5699 5700 /// \brief Determines whether the given declaration is an out-of-scope 5701 /// previous declaration. 5702 /// 5703 /// This routine should be invoked when name lookup has found a 5704 /// previous declaration (PrevDecl) that is not in the scope where a 5705 /// new declaration by the same name is being introduced. If the new 5706 /// declaration occurs in a local scope, previous declarations with 5707 /// linkage may still be considered previous declarations (C99 5708 /// 6.2.2p4-5, C++ [basic.link]p6). 5709 /// 5710 /// \param PrevDecl the previous declaration found by name 5711 /// lookup 5712 /// 5713 /// \param DC the context in which the new declaration is being 5714 /// declared. 5715 /// 5716 /// \returns true if PrevDecl is an out-of-scope previous declaration 5717 /// for a new delcaration with the same name. 5718 static bool 5719 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5720 ASTContext &Context) { 5721 if (!PrevDecl) 5722 return false; 5723 5724 if (!PrevDecl->hasLinkage()) 5725 return false; 5726 5727 if (Context.getLangOpts().CPlusPlus) { 5728 // C++ [basic.link]p6: 5729 // If there is a visible declaration of an entity with linkage 5730 // having the same name and type, ignoring entities declared 5731 // outside the innermost enclosing namespace scope, the block 5732 // scope declaration declares that same entity and receives the 5733 // linkage of the previous declaration. 5734 DeclContext *OuterContext = DC->getRedeclContext(); 5735 if (!OuterContext->isFunctionOrMethod()) 5736 // This rule only applies to block-scope declarations. 5737 return false; 5738 5739 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5740 if (PrevOuterContext->isRecord()) 5741 // We found a member function: ignore it. 5742 return false; 5743 5744 // Find the innermost enclosing namespace for the new and 5745 // previous declarations. 5746 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5747 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5748 5749 // The previous declaration is in a different namespace, so it 5750 // isn't the same function. 5751 if (!OuterContext->Equals(PrevOuterContext)) 5752 return false; 5753 } 5754 5755 return true; 5756 } 5757 5758 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5759 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5760 if (!SS.isSet()) return; 5761 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5762 } 5763 5764 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5765 QualType type = decl->getType(); 5766 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5767 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5768 // Various kinds of declaration aren't allowed to be __autoreleasing. 5769 unsigned kind = -1U; 5770 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5771 if (var->hasAttr<BlocksAttr>()) 5772 kind = 0; // __block 5773 else if (!var->hasLocalStorage()) 5774 kind = 1; // global 5775 } else if (isa<ObjCIvarDecl>(decl)) { 5776 kind = 3; // ivar 5777 } else if (isa<FieldDecl>(decl)) { 5778 kind = 2; // field 5779 } 5780 5781 if (kind != -1U) { 5782 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5783 << kind; 5784 } 5785 } else if (lifetime == Qualifiers::OCL_None) { 5786 // Try to infer lifetime. 5787 if (!type->isObjCLifetimeType()) 5788 return false; 5789 5790 lifetime = type->getObjCARCImplicitLifetime(); 5791 type = Context.getLifetimeQualifiedType(type, lifetime); 5792 decl->setType(type); 5793 } 5794 5795 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5796 // Thread-local variables cannot have lifetime. 5797 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5798 var->getTLSKind()) { 5799 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5800 << var->getType(); 5801 return true; 5802 } 5803 } 5804 5805 return false; 5806 } 5807 5808 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5809 // Ensure that an auto decl is deduced otherwise the checks below might cache 5810 // the wrong linkage. 5811 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5812 5813 // 'weak' only applies to declarations with external linkage. 5814 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5815 if (!ND.isExternallyVisible()) { 5816 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5817 ND.dropAttr<WeakAttr>(); 5818 } 5819 } 5820 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5821 if (ND.isExternallyVisible()) { 5822 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5823 ND.dropAttr<WeakRefAttr>(); 5824 ND.dropAttr<AliasAttr>(); 5825 } 5826 } 5827 5828 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5829 if (VD->hasInit()) { 5830 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5831 assert(VD->isThisDeclarationADefinition() && 5832 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5833 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5834 VD->dropAttr<AliasAttr>(); 5835 } 5836 } 5837 } 5838 5839 // 'selectany' only applies to externally visible variable declarations. 5840 // It does not apply to functions. 5841 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5842 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5843 S.Diag(Attr->getLocation(), 5844 diag::err_attribute_selectany_non_extern_data); 5845 ND.dropAttr<SelectAnyAttr>(); 5846 } 5847 } 5848 5849 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5850 // dll attributes require external linkage. Static locals may have external 5851 // linkage but still cannot be explicitly imported or exported. 5852 auto *VD = dyn_cast<VarDecl>(&ND); 5853 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5854 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5855 << &ND << Attr; 5856 ND.setInvalidDecl(); 5857 } 5858 } 5859 5860 // Virtual functions cannot be marked as 'notail'. 5861 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5862 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5863 if (MD->isVirtual()) { 5864 S.Diag(ND.getLocation(), 5865 diag::err_invalid_attribute_on_virtual_function) 5866 << Attr; 5867 ND.dropAttr<NotTailCalledAttr>(); 5868 } 5869 } 5870 5871 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5872 NamedDecl *NewDecl, 5873 bool IsSpecialization, 5874 bool IsDefinition) { 5875 if (OldDecl->isInvalidDecl()) 5876 return; 5877 5878 bool IsTemplate = false; 5879 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5880 OldDecl = OldTD->getTemplatedDecl(); 5881 IsTemplate = true; 5882 if (!IsSpecialization) 5883 IsDefinition = false; 5884 } 5885 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5886 NewDecl = NewTD->getTemplatedDecl(); 5887 IsTemplate = true; 5888 } 5889 5890 if (!OldDecl || !NewDecl) 5891 return; 5892 5893 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5894 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5895 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5896 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5897 5898 // dllimport and dllexport are inheritable attributes so we have to exclude 5899 // inherited attribute instances. 5900 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5901 (NewExportAttr && !NewExportAttr->isInherited()); 5902 5903 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5904 // the only exception being explicit specializations. 5905 // Implicitly generated declarations are also excluded for now because there 5906 // is no other way to switch these to use dllimport or dllexport. 5907 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5908 5909 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5910 // Allow with a warning for free functions and global variables. 5911 bool JustWarn = false; 5912 if (!OldDecl->isCXXClassMember()) { 5913 auto *VD = dyn_cast<VarDecl>(OldDecl); 5914 if (VD && !VD->getDescribedVarTemplate()) 5915 JustWarn = true; 5916 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5917 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5918 JustWarn = true; 5919 } 5920 5921 // We cannot change a declaration that's been used because IR has already 5922 // been emitted. Dllimported functions will still work though (modulo 5923 // address equality) as they can use the thunk. 5924 if (OldDecl->isUsed()) 5925 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5926 JustWarn = false; 5927 5928 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5929 : diag::err_attribute_dll_redeclaration; 5930 S.Diag(NewDecl->getLocation(), DiagID) 5931 << NewDecl 5932 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5933 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5934 if (!JustWarn) { 5935 NewDecl->setInvalidDecl(); 5936 return; 5937 } 5938 } 5939 5940 // A redeclaration is not allowed to drop a dllimport attribute, the only 5941 // exceptions being inline function definitions (except for function 5942 // templates), local extern declarations, qualified friend declarations or 5943 // special MSVC extension: in the last case, the declaration is treated as if 5944 // it were marked dllexport. 5945 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5946 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 5947 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 5948 // Ignore static data because out-of-line definitions are diagnosed 5949 // separately. 5950 IsStaticDataMember = VD->isStaticDataMember(); 5951 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 5952 VarDecl::DeclarationOnly; 5953 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5954 IsInline = FD->isInlined(); 5955 IsQualifiedFriend = FD->getQualifier() && 5956 FD->getFriendObjectKind() == Decl::FOK_Declared; 5957 } 5958 5959 if (OldImportAttr && !HasNewAttr && 5960 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 5961 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5962 if (IsMicrosoft && IsDefinition) { 5963 S.Diag(NewDecl->getLocation(), 5964 diag::warn_redeclaration_without_import_attribute) 5965 << NewDecl; 5966 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5967 NewDecl->dropAttr<DLLImportAttr>(); 5968 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 5969 NewImportAttr->getRange(), S.Context, 5970 NewImportAttr->getSpellingListIndex())); 5971 } else { 5972 S.Diag(NewDecl->getLocation(), 5973 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5974 << NewDecl << OldImportAttr; 5975 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5976 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5977 OldDecl->dropAttr<DLLImportAttr>(); 5978 NewDecl->dropAttr<DLLImportAttr>(); 5979 } 5980 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 5981 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5982 OldDecl->dropAttr<DLLImportAttr>(); 5983 NewDecl->dropAttr<DLLImportAttr>(); 5984 S.Diag(NewDecl->getLocation(), 5985 diag::warn_dllimport_dropped_from_inline_function) 5986 << NewDecl << OldImportAttr; 5987 } 5988 } 5989 5990 /// Given that we are within the definition of the given function, 5991 /// will that definition behave like C99's 'inline', where the 5992 /// definition is discarded except for optimization purposes? 5993 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5994 // Try to avoid calling GetGVALinkageForFunction. 5995 5996 // All cases of this require the 'inline' keyword. 5997 if (!FD->isInlined()) return false; 5998 5999 // This is only possible in C++ with the gnu_inline attribute. 6000 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6001 return false; 6002 6003 // Okay, go ahead and call the relatively-more-expensive function. 6004 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6005 } 6006 6007 /// Determine whether a variable is extern "C" prior to attaching 6008 /// an initializer. We can't just call isExternC() here, because that 6009 /// will also compute and cache whether the declaration is externally 6010 /// visible, which might change when we attach the initializer. 6011 /// 6012 /// This can only be used if the declaration is known to not be a 6013 /// redeclaration of an internal linkage declaration. 6014 /// 6015 /// For instance: 6016 /// 6017 /// auto x = []{}; 6018 /// 6019 /// Attaching the initializer here makes this declaration not externally 6020 /// visible, because its type has internal linkage. 6021 /// 6022 /// FIXME: This is a hack. 6023 template<typename T> 6024 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6025 if (S.getLangOpts().CPlusPlus) { 6026 // In C++, the overloadable attribute negates the effects of extern "C". 6027 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6028 return false; 6029 6030 // So do CUDA's host/device attributes. 6031 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6032 D->template hasAttr<CUDAHostAttr>())) 6033 return false; 6034 } 6035 return D->isExternC(); 6036 } 6037 6038 static bool shouldConsiderLinkage(const VarDecl *VD) { 6039 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6040 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6041 return VD->hasExternalStorage(); 6042 if (DC->isFileContext()) 6043 return true; 6044 if (DC->isRecord()) 6045 return false; 6046 llvm_unreachable("Unexpected context"); 6047 } 6048 6049 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6050 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6051 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6052 isa<OMPDeclareReductionDecl>(DC)) 6053 return true; 6054 if (DC->isRecord()) 6055 return false; 6056 llvm_unreachable("Unexpected context"); 6057 } 6058 6059 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6060 AttributeList::Kind Kind) { 6061 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6062 if (L->getKind() == Kind) 6063 return true; 6064 return false; 6065 } 6066 6067 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6068 AttributeList::Kind Kind) { 6069 // Check decl attributes on the DeclSpec. 6070 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6071 return true; 6072 6073 // Walk the declarator structure, checking decl attributes that were in a type 6074 // position to the decl itself. 6075 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6076 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6077 return true; 6078 } 6079 6080 // Finally, check attributes on the decl itself. 6081 return hasParsedAttr(S, PD.getAttributes(), Kind); 6082 } 6083 6084 /// Adjust the \c DeclContext for a function or variable that might be a 6085 /// function-local external declaration. 6086 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6087 if (!DC->isFunctionOrMethod()) 6088 return false; 6089 6090 // If this is a local extern function or variable declared within a function 6091 // template, don't add it into the enclosing namespace scope until it is 6092 // instantiated; it might have a dependent type right now. 6093 if (DC->isDependentContext()) 6094 return true; 6095 6096 // C++11 [basic.link]p7: 6097 // When a block scope declaration of an entity with linkage is not found to 6098 // refer to some other declaration, then that entity is a member of the 6099 // innermost enclosing namespace. 6100 // 6101 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6102 // semantically-enclosing namespace, not a lexically-enclosing one. 6103 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6104 DC = DC->getParent(); 6105 return true; 6106 } 6107 6108 /// \brief Returns true if given declaration has external C language linkage. 6109 static bool isDeclExternC(const Decl *D) { 6110 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6111 return FD->isExternC(); 6112 if (const auto *VD = dyn_cast<VarDecl>(D)) 6113 return VD->isExternC(); 6114 6115 llvm_unreachable("Unknown type of decl!"); 6116 } 6117 6118 NamedDecl *Sema::ActOnVariableDeclarator( 6119 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6120 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6121 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6122 QualType R = TInfo->getType(); 6123 DeclarationName Name = GetNameForDeclarator(D).getName(); 6124 6125 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6126 6127 if (D.isDecompositionDeclarator()) { 6128 AddToScope = false; 6129 // Take the name of the first declarator as our name for diagnostic 6130 // purposes. 6131 auto &Decomp = D.getDecompositionDeclarator(); 6132 if (!Decomp.bindings().empty()) { 6133 II = Decomp.bindings()[0].Name; 6134 Name = II; 6135 } 6136 } else if (!II) { 6137 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6138 return nullptr; 6139 } 6140 6141 if (getLangOpts().OpenCL) { 6142 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6143 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6144 // argument. 6145 if (R->isImageType() || R->isPipeType()) { 6146 Diag(D.getIdentifierLoc(), 6147 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6148 << R; 6149 D.setInvalidType(); 6150 return nullptr; 6151 } 6152 6153 // OpenCL v1.2 s6.9.r: 6154 // The event type cannot be used to declare a program scope variable. 6155 // OpenCL v2.0 s6.9.q: 6156 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6157 if (NULL == S->getParent()) { 6158 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6159 Diag(D.getIdentifierLoc(), 6160 diag::err_invalid_type_for_program_scope_var) << R; 6161 D.setInvalidType(); 6162 return nullptr; 6163 } 6164 } 6165 6166 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6167 QualType NR = R; 6168 while (NR->isPointerType()) { 6169 if (NR->isFunctionPointerType()) { 6170 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 6171 D.setInvalidType(); 6172 break; 6173 } 6174 NR = NR->getPointeeType(); 6175 } 6176 6177 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6178 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6179 // half array type (unless the cl_khr_fp16 extension is enabled). 6180 if (Context.getBaseElementType(R)->isHalfType()) { 6181 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6182 D.setInvalidType(); 6183 } 6184 } 6185 6186 if (R->isSamplerT()) { 6187 // OpenCL v1.2 s6.9.b p4: 6188 // The sampler type cannot be used with the __local and __global address 6189 // space qualifiers. 6190 if (R.getAddressSpace() == LangAS::opencl_local || 6191 R.getAddressSpace() == LangAS::opencl_global) { 6192 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6193 } 6194 6195 // OpenCL v1.2 s6.12.14.1: 6196 // A global sampler must be declared with either the constant address 6197 // space qualifier or with the const qualifier. 6198 if (DC->isTranslationUnit() && 6199 !(R.getAddressSpace() == LangAS::opencl_constant || 6200 R.isConstQualified())) { 6201 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6202 D.setInvalidType(); 6203 } 6204 } 6205 6206 // OpenCL v1.2 s6.9.r: 6207 // The event type cannot be used with the __local, __constant and __global 6208 // address space qualifiers. 6209 if (R->isEventT()) { 6210 if (R.getAddressSpace()) { 6211 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6212 D.setInvalidType(); 6213 } 6214 } 6215 } 6216 6217 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6218 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6219 6220 // dllimport globals without explicit storage class are treated as extern. We 6221 // have to change the storage class this early to get the right DeclContext. 6222 if (SC == SC_None && !DC->isRecord() && 6223 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6224 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6225 SC = SC_Extern; 6226 6227 DeclContext *OriginalDC = DC; 6228 bool IsLocalExternDecl = SC == SC_Extern && 6229 adjustContextForLocalExternDecl(DC); 6230 6231 if (SCSpec == DeclSpec::SCS_mutable) { 6232 // mutable can only appear on non-static class members, so it's always 6233 // an error here 6234 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6235 D.setInvalidType(); 6236 SC = SC_None; 6237 } 6238 6239 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6240 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6241 D.getDeclSpec().getStorageClassSpecLoc())) { 6242 // In C++11, the 'register' storage class specifier is deprecated. 6243 // Suppress the warning in system macros, it's used in macros in some 6244 // popular C system headers, such as in glibc's htonl() macro. 6245 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6246 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6247 : diag::warn_deprecated_register) 6248 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6249 } 6250 6251 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6252 6253 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6254 // C99 6.9p2: The storage-class specifiers auto and register shall not 6255 // appear in the declaration specifiers in an external declaration. 6256 // Global Register+Asm is a GNU extension we support. 6257 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6258 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6259 D.setInvalidType(); 6260 } 6261 } 6262 6263 bool IsMemberSpecialization = false; 6264 bool IsVariableTemplateSpecialization = false; 6265 bool IsPartialSpecialization = false; 6266 bool IsVariableTemplate = false; 6267 VarDecl *NewVD = nullptr; 6268 VarTemplateDecl *NewTemplate = nullptr; 6269 TemplateParameterList *TemplateParams = nullptr; 6270 if (!getLangOpts().CPlusPlus) { 6271 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6272 D.getIdentifierLoc(), II, 6273 R, TInfo, SC); 6274 6275 if (R->getContainedDeducedType()) 6276 ParsingInitForAutoVars.insert(NewVD); 6277 6278 if (D.isInvalidType()) 6279 NewVD->setInvalidDecl(); 6280 } else { 6281 bool Invalid = false; 6282 6283 if (DC->isRecord() && !CurContext->isRecord()) { 6284 // This is an out-of-line definition of a static data member. 6285 switch (SC) { 6286 case SC_None: 6287 break; 6288 case SC_Static: 6289 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6290 diag::err_static_out_of_line) 6291 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6292 break; 6293 case SC_Auto: 6294 case SC_Register: 6295 case SC_Extern: 6296 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6297 // to names of variables declared in a block or to function parameters. 6298 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6299 // of class members 6300 6301 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6302 diag::err_storage_class_for_static_member) 6303 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6304 break; 6305 case SC_PrivateExtern: 6306 llvm_unreachable("C storage class in c++!"); 6307 } 6308 } 6309 6310 if (SC == SC_Static && CurContext->isRecord()) { 6311 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6312 if (RD->isLocalClass()) 6313 Diag(D.getIdentifierLoc(), 6314 diag::err_static_data_member_not_allowed_in_local_class) 6315 << Name << RD->getDeclName(); 6316 6317 // C++98 [class.union]p1: If a union contains a static data member, 6318 // the program is ill-formed. C++11 drops this restriction. 6319 if (RD->isUnion()) 6320 Diag(D.getIdentifierLoc(), 6321 getLangOpts().CPlusPlus11 6322 ? diag::warn_cxx98_compat_static_data_member_in_union 6323 : diag::ext_static_data_member_in_union) << Name; 6324 // We conservatively disallow static data members in anonymous structs. 6325 else if (!RD->getDeclName()) 6326 Diag(D.getIdentifierLoc(), 6327 diag::err_static_data_member_not_allowed_in_anon_struct) 6328 << Name << RD->isUnion(); 6329 } 6330 } 6331 6332 // Match up the template parameter lists with the scope specifier, then 6333 // determine whether we have a template or a template specialization. 6334 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6335 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6336 D.getCXXScopeSpec(), 6337 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6338 ? D.getName().TemplateId 6339 : nullptr, 6340 TemplateParamLists, 6341 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6342 6343 if (TemplateParams) { 6344 if (!TemplateParams->size() && 6345 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6346 // There is an extraneous 'template<>' for this variable. Complain 6347 // about it, but allow the declaration of the variable. 6348 Diag(TemplateParams->getTemplateLoc(), 6349 diag::err_template_variable_noparams) 6350 << II 6351 << SourceRange(TemplateParams->getTemplateLoc(), 6352 TemplateParams->getRAngleLoc()); 6353 TemplateParams = nullptr; 6354 } else { 6355 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6356 // This is an explicit specialization or a partial specialization. 6357 // FIXME: Check that we can declare a specialization here. 6358 IsVariableTemplateSpecialization = true; 6359 IsPartialSpecialization = TemplateParams->size() > 0; 6360 } else { // if (TemplateParams->size() > 0) 6361 // This is a template declaration. 6362 IsVariableTemplate = true; 6363 6364 // Check that we can declare a template here. 6365 if (CheckTemplateDeclScope(S, TemplateParams)) 6366 return nullptr; 6367 6368 // Only C++1y supports variable templates (N3651). 6369 Diag(D.getIdentifierLoc(), 6370 getLangOpts().CPlusPlus14 6371 ? diag::warn_cxx11_compat_variable_template 6372 : diag::ext_variable_template); 6373 } 6374 } 6375 } else { 6376 assert( 6377 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6378 "should have a 'template<>' for this decl"); 6379 } 6380 6381 if (IsVariableTemplateSpecialization) { 6382 SourceLocation TemplateKWLoc = 6383 TemplateParamLists.size() > 0 6384 ? TemplateParamLists[0]->getTemplateLoc() 6385 : SourceLocation(); 6386 DeclResult Res = ActOnVarTemplateSpecialization( 6387 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6388 IsPartialSpecialization); 6389 if (Res.isInvalid()) 6390 return nullptr; 6391 NewVD = cast<VarDecl>(Res.get()); 6392 AddToScope = false; 6393 } else if (D.isDecompositionDeclarator()) { 6394 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6395 D.getIdentifierLoc(), R, TInfo, SC, 6396 Bindings); 6397 } else 6398 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6399 D.getIdentifierLoc(), II, R, TInfo, SC); 6400 6401 // If this is supposed to be a variable template, create it as such. 6402 if (IsVariableTemplate) { 6403 NewTemplate = 6404 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6405 TemplateParams, NewVD); 6406 NewVD->setDescribedVarTemplate(NewTemplate); 6407 } 6408 6409 // If this decl has an auto type in need of deduction, make a note of the 6410 // Decl so we can diagnose uses of it in its own initializer. 6411 if (R->getContainedDeducedType()) 6412 ParsingInitForAutoVars.insert(NewVD); 6413 6414 if (D.isInvalidType() || Invalid) { 6415 NewVD->setInvalidDecl(); 6416 if (NewTemplate) 6417 NewTemplate->setInvalidDecl(); 6418 } 6419 6420 SetNestedNameSpecifier(NewVD, D); 6421 6422 // If we have any template parameter lists that don't directly belong to 6423 // the variable (matching the scope specifier), store them. 6424 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6425 if (TemplateParamLists.size() > VDTemplateParamLists) 6426 NewVD->setTemplateParameterListsInfo( 6427 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6428 6429 if (D.getDeclSpec().isConstexprSpecified()) { 6430 NewVD->setConstexpr(true); 6431 // C++1z [dcl.spec.constexpr]p1: 6432 // A static data member declared with the constexpr specifier is 6433 // implicitly an inline variable. 6434 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6435 NewVD->setImplicitlyInline(); 6436 } 6437 6438 if (D.getDeclSpec().isConceptSpecified()) { 6439 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6440 VTD->setConcept(); 6441 6442 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6443 // be declared with the thread_local, inline, friend, or constexpr 6444 // specifiers, [...] 6445 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6446 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6447 diag::err_concept_decl_invalid_specifiers) 6448 << 0 << 0; 6449 NewVD->setInvalidDecl(true); 6450 } 6451 6452 if (D.getDeclSpec().isConstexprSpecified()) { 6453 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6454 diag::err_concept_decl_invalid_specifiers) 6455 << 0 << 3; 6456 NewVD->setInvalidDecl(true); 6457 } 6458 6459 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6460 // applied only to the definition of a function template or variable 6461 // template, declared in namespace scope. 6462 if (IsVariableTemplateSpecialization) { 6463 Diag(D.getDeclSpec().getConceptSpecLoc(), 6464 diag::err_concept_specified_specialization) 6465 << (IsPartialSpecialization ? 2 : 1); 6466 } 6467 6468 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6469 // following restrictions: 6470 // - The declared type shall have the type bool. 6471 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6472 !NewVD->isInvalidDecl()) { 6473 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6474 NewVD->setInvalidDecl(true); 6475 } 6476 } 6477 } 6478 6479 if (D.getDeclSpec().isInlineSpecified()) { 6480 if (!getLangOpts().CPlusPlus) { 6481 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6482 << 0; 6483 } else if (CurContext->isFunctionOrMethod()) { 6484 // 'inline' is not allowed on block scope variable declaration. 6485 Diag(D.getDeclSpec().getInlineSpecLoc(), 6486 diag::err_inline_declaration_block_scope) << Name 6487 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6488 } else { 6489 Diag(D.getDeclSpec().getInlineSpecLoc(), 6490 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6491 : diag::ext_inline_variable); 6492 NewVD->setInlineSpecified(); 6493 } 6494 } 6495 6496 // Set the lexical context. If the declarator has a C++ scope specifier, the 6497 // lexical context will be different from the semantic context. 6498 NewVD->setLexicalDeclContext(CurContext); 6499 if (NewTemplate) 6500 NewTemplate->setLexicalDeclContext(CurContext); 6501 6502 if (IsLocalExternDecl) { 6503 if (D.isDecompositionDeclarator()) 6504 for (auto *B : Bindings) 6505 B->setLocalExternDecl(); 6506 else 6507 NewVD->setLocalExternDecl(); 6508 } 6509 6510 bool EmitTLSUnsupportedError = false; 6511 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6512 // C++11 [dcl.stc]p4: 6513 // When thread_local is applied to a variable of block scope the 6514 // storage-class-specifier static is implied if it does not appear 6515 // explicitly. 6516 // Core issue: 'static' is not implied if the variable is declared 6517 // 'extern'. 6518 if (NewVD->hasLocalStorage() && 6519 (SCSpec != DeclSpec::SCS_unspecified || 6520 TSCS != DeclSpec::TSCS_thread_local || 6521 !DC->isFunctionOrMethod())) 6522 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6523 diag::err_thread_non_global) 6524 << DeclSpec::getSpecifierName(TSCS); 6525 else if (!Context.getTargetInfo().isTLSSupported()) { 6526 if (getLangOpts().CUDA) { 6527 // Postpone error emission until we've collected attributes required to 6528 // figure out whether it's a host or device variable and whether the 6529 // error should be ignored. 6530 EmitTLSUnsupportedError = true; 6531 // We still need to mark the variable as TLS so it shows up in AST with 6532 // proper storage class for other tools to use even if we're not going 6533 // to emit any code for it. 6534 NewVD->setTSCSpec(TSCS); 6535 } else 6536 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6537 diag::err_thread_unsupported); 6538 } else 6539 NewVD->setTSCSpec(TSCS); 6540 } 6541 6542 // C99 6.7.4p3 6543 // An inline definition of a function with external linkage shall 6544 // not contain a definition of a modifiable object with static or 6545 // thread storage duration... 6546 // We only apply this when the function is required to be defined 6547 // elsewhere, i.e. when the function is not 'extern inline'. Note 6548 // that a local variable with thread storage duration still has to 6549 // be marked 'static'. Also note that it's possible to get these 6550 // semantics in C++ using __attribute__((gnu_inline)). 6551 if (SC == SC_Static && S->getFnParent() != nullptr && 6552 !NewVD->getType().isConstQualified()) { 6553 FunctionDecl *CurFD = getCurFunctionDecl(); 6554 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6555 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6556 diag::warn_static_local_in_extern_inline); 6557 MaybeSuggestAddingStaticToDecl(CurFD); 6558 } 6559 } 6560 6561 if (D.getDeclSpec().isModulePrivateSpecified()) { 6562 if (IsVariableTemplateSpecialization) 6563 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6564 << (IsPartialSpecialization ? 1 : 0) 6565 << FixItHint::CreateRemoval( 6566 D.getDeclSpec().getModulePrivateSpecLoc()); 6567 else if (IsMemberSpecialization) 6568 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6569 << 2 6570 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6571 else if (NewVD->hasLocalStorage()) 6572 Diag(NewVD->getLocation(), diag::err_module_private_local) 6573 << 0 << NewVD->getDeclName() 6574 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6575 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6576 else { 6577 NewVD->setModulePrivate(); 6578 if (NewTemplate) 6579 NewTemplate->setModulePrivate(); 6580 for (auto *B : Bindings) 6581 B->setModulePrivate(); 6582 } 6583 } 6584 6585 // Handle attributes prior to checking for duplicates in MergeVarDecl 6586 ProcessDeclAttributes(S, NewVD, D); 6587 6588 if (getLangOpts().CUDA) { 6589 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6590 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6591 diag::err_thread_unsupported); 6592 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6593 // storage [duration]." 6594 if (SC == SC_None && S->getFnParent() != nullptr && 6595 (NewVD->hasAttr<CUDASharedAttr>() || 6596 NewVD->hasAttr<CUDAConstantAttr>())) { 6597 NewVD->setStorageClass(SC_Static); 6598 } 6599 } 6600 6601 // Ensure that dllimport globals without explicit storage class are treated as 6602 // extern. The storage class is set above using parsed attributes. Now we can 6603 // check the VarDecl itself. 6604 assert(!NewVD->hasAttr<DLLImportAttr>() || 6605 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6606 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6607 6608 // In auto-retain/release, infer strong retension for variables of 6609 // retainable type. 6610 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6611 NewVD->setInvalidDecl(); 6612 6613 // Handle GNU asm-label extension (encoded as an attribute). 6614 if (Expr *E = (Expr*)D.getAsmLabel()) { 6615 // The parser guarantees this is a string. 6616 StringLiteral *SE = cast<StringLiteral>(E); 6617 StringRef Label = SE->getString(); 6618 if (S->getFnParent() != nullptr) { 6619 switch (SC) { 6620 case SC_None: 6621 case SC_Auto: 6622 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6623 break; 6624 case SC_Register: 6625 // Local Named register 6626 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6627 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6628 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6629 break; 6630 case SC_Static: 6631 case SC_Extern: 6632 case SC_PrivateExtern: 6633 break; 6634 } 6635 } else if (SC == SC_Register) { 6636 // Global Named register 6637 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6638 const auto &TI = Context.getTargetInfo(); 6639 bool HasSizeMismatch; 6640 6641 if (!TI.isValidGCCRegisterName(Label)) 6642 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6643 else if (!TI.validateGlobalRegisterVariable(Label, 6644 Context.getTypeSize(R), 6645 HasSizeMismatch)) 6646 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6647 else if (HasSizeMismatch) 6648 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6649 } 6650 6651 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6652 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6653 NewVD->setInvalidDecl(true); 6654 } 6655 } 6656 6657 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6658 Context, Label, 0)); 6659 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6660 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6661 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6662 if (I != ExtnameUndeclaredIdentifiers.end()) { 6663 if (isDeclExternC(NewVD)) { 6664 NewVD->addAttr(I->second); 6665 ExtnameUndeclaredIdentifiers.erase(I); 6666 } else 6667 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6668 << /*Variable*/1 << NewVD; 6669 } 6670 } 6671 6672 // Find the shadowed declaration before filtering for scope. 6673 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6674 ? getShadowedDeclaration(NewVD, Previous) 6675 : nullptr; 6676 6677 // Don't consider existing declarations that are in a different 6678 // scope and are out-of-semantic-context declarations (if the new 6679 // declaration has linkage). 6680 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6681 D.getCXXScopeSpec().isNotEmpty() || 6682 IsMemberSpecialization || 6683 IsVariableTemplateSpecialization); 6684 6685 // Check whether the previous declaration is in the same block scope. This 6686 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6687 if (getLangOpts().CPlusPlus && 6688 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6689 NewVD->setPreviousDeclInSameBlockScope( 6690 Previous.isSingleResult() && !Previous.isShadowed() && 6691 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6692 6693 if (!getLangOpts().CPlusPlus) { 6694 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6695 } else { 6696 // If this is an explicit specialization of a static data member, check it. 6697 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6698 CheckMemberSpecialization(NewVD, Previous)) 6699 NewVD->setInvalidDecl(); 6700 6701 // Merge the decl with the existing one if appropriate. 6702 if (!Previous.empty()) { 6703 if (Previous.isSingleResult() && 6704 isa<FieldDecl>(Previous.getFoundDecl()) && 6705 D.getCXXScopeSpec().isSet()) { 6706 // The user tried to define a non-static data member 6707 // out-of-line (C++ [dcl.meaning]p1). 6708 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6709 << D.getCXXScopeSpec().getRange(); 6710 Previous.clear(); 6711 NewVD->setInvalidDecl(); 6712 } 6713 } else if (D.getCXXScopeSpec().isSet()) { 6714 // No previous declaration in the qualifying scope. 6715 Diag(D.getIdentifierLoc(), diag::err_no_member) 6716 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6717 << D.getCXXScopeSpec().getRange(); 6718 NewVD->setInvalidDecl(); 6719 } 6720 6721 if (!IsVariableTemplateSpecialization) 6722 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6723 6724 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6725 // an explicit specialization (14.8.3) or a partial specialization of a 6726 // concept definition. 6727 if (IsVariableTemplateSpecialization && 6728 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6729 Previous.isSingleResult()) { 6730 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6731 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6732 if (VarTmpl->isConcept()) { 6733 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6734 << 1 /*variable*/ 6735 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6736 : 1 /*explicitly specialized*/); 6737 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6738 NewVD->setInvalidDecl(); 6739 } 6740 } 6741 } 6742 6743 if (NewTemplate) { 6744 VarTemplateDecl *PrevVarTemplate = 6745 NewVD->getPreviousDecl() 6746 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6747 : nullptr; 6748 6749 // Check the template parameter list of this declaration, possibly 6750 // merging in the template parameter list from the previous variable 6751 // template declaration. 6752 if (CheckTemplateParameterList( 6753 TemplateParams, 6754 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6755 : nullptr, 6756 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6757 DC->isDependentContext()) 6758 ? TPC_ClassTemplateMember 6759 : TPC_VarTemplate)) 6760 NewVD->setInvalidDecl(); 6761 6762 // If we are providing an explicit specialization of a static variable 6763 // template, make a note of that. 6764 if (PrevVarTemplate && 6765 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6766 PrevVarTemplate->setMemberSpecialization(); 6767 } 6768 } 6769 6770 // Diagnose shadowed variables iff this isn't a redeclaration. 6771 if (ShadowedDecl && !D.isRedeclaration()) 6772 CheckShadow(NewVD, ShadowedDecl, Previous); 6773 6774 ProcessPragmaWeak(S, NewVD); 6775 6776 // If this is the first declaration of an extern C variable, update 6777 // the map of such variables. 6778 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6779 isIncompleteDeclExternC(*this, NewVD)) 6780 RegisterLocallyScopedExternCDecl(NewVD, S); 6781 6782 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6783 Decl *ManglingContextDecl; 6784 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6785 NewVD->getDeclContext(), ManglingContextDecl)) { 6786 Context.setManglingNumber( 6787 NewVD, MCtx->getManglingNumber( 6788 NewVD, getMSManglingNumber(getLangOpts(), S))); 6789 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6790 } 6791 } 6792 6793 // Special handling of variable named 'main'. 6794 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6795 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6796 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6797 6798 // C++ [basic.start.main]p3 6799 // A program that declares a variable main at global scope is ill-formed. 6800 if (getLangOpts().CPlusPlus) 6801 Diag(D.getLocStart(), diag::err_main_global_variable); 6802 6803 // In C, and external-linkage variable named main results in undefined 6804 // behavior. 6805 else if (NewVD->hasExternalFormalLinkage()) 6806 Diag(D.getLocStart(), diag::warn_main_redefined); 6807 } 6808 6809 if (D.isRedeclaration() && !Previous.empty()) { 6810 checkDLLAttributeRedeclaration( 6811 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6812 IsMemberSpecialization, D.isFunctionDefinition()); 6813 } 6814 6815 if (NewTemplate) { 6816 if (NewVD->isInvalidDecl()) 6817 NewTemplate->setInvalidDecl(); 6818 ActOnDocumentableDecl(NewTemplate); 6819 return NewTemplate; 6820 } 6821 6822 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6823 CompleteMemberSpecialization(NewVD, Previous); 6824 6825 return NewVD; 6826 } 6827 6828 /// Enum describing the %select options in diag::warn_decl_shadow. 6829 enum ShadowedDeclKind { 6830 SDK_Local, 6831 SDK_Global, 6832 SDK_StaticMember, 6833 SDK_Field, 6834 SDK_Typedef, 6835 SDK_Using 6836 }; 6837 6838 /// Determine what kind of declaration we're shadowing. 6839 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6840 const DeclContext *OldDC) { 6841 if (isa<TypeAliasDecl>(ShadowedDecl)) 6842 return SDK_Using; 6843 else if (isa<TypedefDecl>(ShadowedDecl)) 6844 return SDK_Typedef; 6845 else if (isa<RecordDecl>(OldDC)) 6846 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6847 6848 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6849 } 6850 6851 /// Return the location of the capture if the given lambda captures the given 6852 /// variable \p VD, or an invalid source location otherwise. 6853 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6854 const VarDecl *VD) { 6855 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6856 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6857 return Capture.getLocation(); 6858 } 6859 return SourceLocation(); 6860 } 6861 6862 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6863 const LookupResult &R) { 6864 // Only diagnose if we're shadowing an unambiguous field or variable. 6865 if (R.getResultKind() != LookupResult::Found) 6866 return false; 6867 6868 // Return false if warning is ignored. 6869 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6870 } 6871 6872 /// \brief Return the declaration shadowed by the given variable \p D, or null 6873 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6874 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6875 const LookupResult &R) { 6876 if (!shouldWarnIfShadowedDecl(Diags, R)) 6877 return nullptr; 6878 6879 // Don't diagnose declarations at file scope. 6880 if (D->hasGlobalStorage()) 6881 return nullptr; 6882 6883 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6884 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6885 ? ShadowedDecl 6886 : nullptr; 6887 } 6888 6889 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6890 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6891 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6892 const LookupResult &R) { 6893 // Don't warn if typedef declaration is part of a class 6894 if (D->getDeclContext()->isRecord()) 6895 return nullptr; 6896 6897 if (!shouldWarnIfShadowedDecl(Diags, R)) 6898 return nullptr; 6899 6900 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6901 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6902 } 6903 6904 /// \brief Diagnose variable or built-in function shadowing. Implements 6905 /// -Wshadow. 6906 /// 6907 /// This method is called whenever a VarDecl is added to a "useful" 6908 /// scope. 6909 /// 6910 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6911 /// \param R the lookup of the name 6912 /// 6913 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 6914 const LookupResult &R) { 6915 DeclContext *NewDC = D->getDeclContext(); 6916 6917 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 6918 // Fields are not shadowed by variables in C++ static methods. 6919 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6920 if (MD->isStatic()) 6921 return; 6922 6923 // Fields shadowed by constructor parameters are a special case. Usually 6924 // the constructor initializes the field with the parameter. 6925 if (isa<CXXConstructorDecl>(NewDC)) 6926 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 6927 // Remember that this was shadowed so we can either warn about its 6928 // modification or its existence depending on warning settings. 6929 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 6930 return; 6931 } 6932 } 6933 6934 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6935 if (shadowedVar->isExternC()) { 6936 // For shadowing external vars, make sure that we point to the global 6937 // declaration, not a locally scoped extern declaration. 6938 for (auto I : shadowedVar->redecls()) 6939 if (I->isFileVarDecl()) { 6940 ShadowedDecl = I; 6941 break; 6942 } 6943 } 6944 6945 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6946 6947 unsigned WarningDiag = diag::warn_decl_shadow; 6948 SourceLocation CaptureLoc; 6949 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 6950 isa<CXXMethodDecl>(NewDC)) { 6951 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 6952 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 6953 if (RD->getLambdaCaptureDefault() == LCD_None) { 6954 // Try to avoid warnings for lambdas with an explicit capture list. 6955 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 6956 // Warn only when the lambda captures the shadowed decl explicitly. 6957 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 6958 if (CaptureLoc.isInvalid()) 6959 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 6960 } else { 6961 // Remember that this was shadowed so we can avoid the warning if the 6962 // shadowed decl isn't captured and the warning settings allow it. 6963 cast<LambdaScopeInfo>(getCurFunction()) 6964 ->ShadowingDecls.push_back( 6965 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 6966 return; 6967 } 6968 } 6969 } 6970 } 6971 6972 // Only warn about certain kinds of shadowing for class members. 6973 if (NewDC && NewDC->isRecord()) { 6974 // In particular, don't warn about shadowing non-class members. 6975 if (!OldDC->isRecord()) 6976 return; 6977 6978 // TODO: should we warn about static data members shadowing 6979 // static data members from base classes? 6980 6981 // TODO: don't diagnose for inaccessible shadowed members. 6982 // This is hard to do perfectly because we might friend the 6983 // shadowing context, but that's just a false negative. 6984 } 6985 6986 6987 DeclarationName Name = R.getLookupName(); 6988 6989 // Emit warning and note. 6990 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6991 return; 6992 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 6993 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 6994 if (!CaptureLoc.isInvalid()) 6995 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 6996 << Name << /*explicitly*/ 1; 6997 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6998 } 6999 7000 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7001 /// when these variables are captured by the lambda. 7002 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7003 for (const auto &Shadow : LSI->ShadowingDecls) { 7004 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7005 // Try to avoid the warning when the shadowed decl isn't captured. 7006 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7007 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7008 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7009 ? diag::warn_decl_shadow_uncaptured_local 7010 : diag::warn_decl_shadow) 7011 << Shadow.VD->getDeclName() 7012 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7013 if (!CaptureLoc.isInvalid()) 7014 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7015 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7016 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7017 } 7018 } 7019 7020 /// \brief Check -Wshadow without the advantage of a previous lookup. 7021 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7022 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7023 return; 7024 7025 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7026 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 7027 LookupName(R, S); 7028 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7029 CheckShadow(D, ShadowedDecl, R); 7030 } 7031 7032 /// Check if 'E', which is an expression that is about to be modified, refers 7033 /// to a constructor parameter that shadows a field. 7034 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7035 // Quickly ignore expressions that can't be shadowing ctor parameters. 7036 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7037 return; 7038 E = E->IgnoreParenImpCasts(); 7039 auto *DRE = dyn_cast<DeclRefExpr>(E); 7040 if (!DRE) 7041 return; 7042 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7043 auto I = ShadowingDecls.find(D); 7044 if (I == ShadowingDecls.end()) 7045 return; 7046 const NamedDecl *ShadowedDecl = I->second; 7047 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7048 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7049 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7050 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7051 7052 // Avoid issuing multiple warnings about the same decl. 7053 ShadowingDecls.erase(I); 7054 } 7055 7056 /// Check for conflict between this global or extern "C" declaration and 7057 /// previous global or extern "C" declarations. This is only used in C++. 7058 template<typename T> 7059 static bool checkGlobalOrExternCConflict( 7060 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7061 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7062 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7063 7064 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7065 // The common case: this global doesn't conflict with any extern "C" 7066 // declaration. 7067 return false; 7068 } 7069 7070 if (Prev) { 7071 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7072 // Both the old and new declarations have C language linkage. This is a 7073 // redeclaration. 7074 Previous.clear(); 7075 Previous.addDecl(Prev); 7076 return true; 7077 } 7078 7079 // This is a global, non-extern "C" declaration, and there is a previous 7080 // non-global extern "C" declaration. Diagnose if this is a variable 7081 // declaration. 7082 if (!isa<VarDecl>(ND)) 7083 return false; 7084 } else { 7085 // The declaration is extern "C". Check for any declaration in the 7086 // translation unit which might conflict. 7087 if (IsGlobal) { 7088 // We have already performed the lookup into the translation unit. 7089 IsGlobal = false; 7090 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7091 I != E; ++I) { 7092 if (isa<VarDecl>(*I)) { 7093 Prev = *I; 7094 break; 7095 } 7096 } 7097 } else { 7098 DeclContext::lookup_result R = 7099 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7100 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7101 I != E; ++I) { 7102 if (isa<VarDecl>(*I)) { 7103 Prev = *I; 7104 break; 7105 } 7106 // FIXME: If we have any other entity with this name in global scope, 7107 // the declaration is ill-formed, but that is a defect: it breaks the 7108 // 'stat' hack, for instance. Only variables can have mangled name 7109 // clashes with extern "C" declarations, so only they deserve a 7110 // diagnostic. 7111 } 7112 } 7113 7114 if (!Prev) 7115 return false; 7116 } 7117 7118 // Use the first declaration's location to ensure we point at something which 7119 // is lexically inside an extern "C" linkage-spec. 7120 assert(Prev && "should have found a previous declaration to diagnose"); 7121 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7122 Prev = FD->getFirstDecl(); 7123 else 7124 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7125 7126 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7127 << IsGlobal << ND; 7128 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7129 << IsGlobal; 7130 return false; 7131 } 7132 7133 /// Apply special rules for handling extern "C" declarations. Returns \c true 7134 /// if we have found that this is a redeclaration of some prior entity. 7135 /// 7136 /// Per C++ [dcl.link]p6: 7137 /// Two declarations [for a function or variable] with C language linkage 7138 /// with the same name that appear in different scopes refer to the same 7139 /// [entity]. An entity with C language linkage shall not be declared with 7140 /// the same name as an entity in global scope. 7141 template<typename T> 7142 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7143 LookupResult &Previous) { 7144 if (!S.getLangOpts().CPlusPlus) { 7145 // In C, when declaring a global variable, look for a corresponding 'extern' 7146 // variable declared in function scope. We don't need this in C++, because 7147 // we find local extern decls in the surrounding file-scope DeclContext. 7148 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7149 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7150 Previous.clear(); 7151 Previous.addDecl(Prev); 7152 return true; 7153 } 7154 } 7155 return false; 7156 } 7157 7158 // A declaration in the translation unit can conflict with an extern "C" 7159 // declaration. 7160 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7161 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7162 7163 // An extern "C" declaration can conflict with a declaration in the 7164 // translation unit or can be a redeclaration of an extern "C" declaration 7165 // in another scope. 7166 if (isIncompleteDeclExternC(S,ND)) 7167 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7168 7169 // Neither global nor extern "C": nothing to do. 7170 return false; 7171 } 7172 7173 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7174 // If the decl is already known invalid, don't check it. 7175 if (NewVD->isInvalidDecl()) 7176 return; 7177 7178 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7179 QualType T = TInfo->getType(); 7180 7181 // Defer checking an 'auto' type until its initializer is attached. 7182 if (T->isUndeducedType()) 7183 return; 7184 7185 if (NewVD->hasAttrs()) 7186 CheckAlignasUnderalignment(NewVD); 7187 7188 if (T->isObjCObjectType()) { 7189 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7190 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7191 T = Context.getObjCObjectPointerType(T); 7192 NewVD->setType(T); 7193 } 7194 7195 // Emit an error if an address space was applied to decl with local storage. 7196 // This includes arrays of objects with address space qualifiers, but not 7197 // automatic variables that point to other address spaces. 7198 // ISO/IEC TR 18037 S5.1.2 7199 if (!getLangOpts().OpenCL 7200 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 7201 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 7202 NewVD->setInvalidDecl(); 7203 return; 7204 } 7205 7206 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7207 // scope. 7208 if (getLangOpts().OpenCLVersion == 120 && 7209 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7210 NewVD->isStaticLocal()) { 7211 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7212 NewVD->setInvalidDecl(); 7213 return; 7214 } 7215 7216 if (getLangOpts().OpenCL) { 7217 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7218 if (NewVD->hasAttr<BlocksAttr>()) { 7219 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7220 return; 7221 } 7222 7223 if (T->isBlockPointerType()) { 7224 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7225 // can't use 'extern' storage class. 7226 if (!T.isConstQualified()) { 7227 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7228 << 0 /*const*/; 7229 NewVD->setInvalidDecl(); 7230 return; 7231 } 7232 if (NewVD->hasExternalStorage()) { 7233 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7234 NewVD->setInvalidDecl(); 7235 return; 7236 } 7237 } 7238 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7239 // __constant address space. 7240 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7241 // variables inside a function can also be declared in the global 7242 // address space. 7243 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7244 NewVD->hasExternalStorage()) { 7245 if (!T->isSamplerT() && 7246 !(T.getAddressSpace() == LangAS::opencl_constant || 7247 (T.getAddressSpace() == LangAS::opencl_global && 7248 getLangOpts().OpenCLVersion == 200))) { 7249 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7250 if (getLangOpts().OpenCLVersion == 200) 7251 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7252 << Scope << "global or constant"; 7253 else 7254 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7255 << Scope << "constant"; 7256 NewVD->setInvalidDecl(); 7257 return; 7258 } 7259 } else { 7260 if (T.getAddressSpace() == LangAS::opencl_global) { 7261 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7262 << 1 /*is any function*/ << "global"; 7263 NewVD->setInvalidDecl(); 7264 return; 7265 } 7266 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 7267 // in functions. 7268 if (T.getAddressSpace() == LangAS::opencl_constant || 7269 T.getAddressSpace() == LangAS::opencl_local) { 7270 FunctionDecl *FD = getCurFunctionDecl(); 7271 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7272 if (T.getAddressSpace() == LangAS::opencl_constant) 7273 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7274 << 0 /*non-kernel only*/ << "constant"; 7275 else 7276 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7277 << 0 /*non-kernel only*/ << "local"; 7278 NewVD->setInvalidDecl(); 7279 return; 7280 } 7281 } 7282 } 7283 } 7284 7285 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7286 && !NewVD->hasAttr<BlocksAttr>()) { 7287 if (getLangOpts().getGC() != LangOptions::NonGC) 7288 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7289 else { 7290 assert(!getLangOpts().ObjCAutoRefCount); 7291 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7292 } 7293 } 7294 7295 bool isVM = T->isVariablyModifiedType(); 7296 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7297 NewVD->hasAttr<BlocksAttr>()) 7298 getCurFunction()->setHasBranchProtectedScope(); 7299 7300 if ((isVM && NewVD->hasLinkage()) || 7301 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7302 bool SizeIsNegative; 7303 llvm::APSInt Oversized; 7304 TypeSourceInfo *FixedTInfo = 7305 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7306 SizeIsNegative, Oversized); 7307 if (!FixedTInfo && T->isVariableArrayType()) { 7308 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7309 // FIXME: This won't give the correct result for 7310 // int a[10][n]; 7311 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7312 7313 if (NewVD->isFileVarDecl()) 7314 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7315 << SizeRange; 7316 else if (NewVD->isStaticLocal()) 7317 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7318 << SizeRange; 7319 else 7320 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7321 << SizeRange; 7322 NewVD->setInvalidDecl(); 7323 return; 7324 } 7325 7326 if (!FixedTInfo) { 7327 if (NewVD->isFileVarDecl()) 7328 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7329 else 7330 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7331 NewVD->setInvalidDecl(); 7332 return; 7333 } 7334 7335 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7336 NewVD->setType(FixedTInfo->getType()); 7337 NewVD->setTypeSourceInfo(FixedTInfo); 7338 } 7339 7340 if (T->isVoidType()) { 7341 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7342 // of objects and functions. 7343 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7344 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7345 << T; 7346 NewVD->setInvalidDecl(); 7347 return; 7348 } 7349 } 7350 7351 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7352 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7353 NewVD->setInvalidDecl(); 7354 return; 7355 } 7356 7357 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7358 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7359 NewVD->setInvalidDecl(); 7360 return; 7361 } 7362 7363 if (NewVD->isConstexpr() && !T->isDependentType() && 7364 RequireLiteralType(NewVD->getLocation(), T, 7365 diag::err_constexpr_var_non_literal)) { 7366 NewVD->setInvalidDecl(); 7367 return; 7368 } 7369 } 7370 7371 /// \brief Perform semantic checking on a newly-created variable 7372 /// declaration. 7373 /// 7374 /// This routine performs all of the type-checking required for a 7375 /// variable declaration once it has been built. It is used both to 7376 /// check variables after they have been parsed and their declarators 7377 /// have been translated into a declaration, and to check variables 7378 /// that have been instantiated from a template. 7379 /// 7380 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7381 /// 7382 /// Returns true if the variable declaration is a redeclaration. 7383 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7384 CheckVariableDeclarationType(NewVD); 7385 7386 // If the decl is already known invalid, don't check it. 7387 if (NewVD->isInvalidDecl()) 7388 return false; 7389 7390 // If we did not find anything by this name, look for a non-visible 7391 // extern "C" declaration with the same name. 7392 if (Previous.empty() && 7393 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7394 Previous.setShadowed(); 7395 7396 if (!Previous.empty()) { 7397 MergeVarDecl(NewVD, Previous); 7398 return true; 7399 } 7400 return false; 7401 } 7402 7403 namespace { 7404 struct FindOverriddenMethod { 7405 Sema *S; 7406 CXXMethodDecl *Method; 7407 7408 /// Member lookup function that determines whether a given C++ 7409 /// method overrides a method in a base class, to be used with 7410 /// CXXRecordDecl::lookupInBases(). 7411 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7412 RecordDecl *BaseRecord = 7413 Specifier->getType()->getAs<RecordType>()->getDecl(); 7414 7415 DeclarationName Name = Method->getDeclName(); 7416 7417 // FIXME: Do we care about other names here too? 7418 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7419 // We really want to find the base class destructor here. 7420 QualType T = S->Context.getTypeDeclType(BaseRecord); 7421 CanQualType CT = S->Context.getCanonicalType(T); 7422 7423 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7424 } 7425 7426 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7427 Path.Decls = Path.Decls.slice(1)) { 7428 NamedDecl *D = Path.Decls.front(); 7429 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7430 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7431 return true; 7432 } 7433 } 7434 7435 return false; 7436 } 7437 }; 7438 7439 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7440 } // end anonymous namespace 7441 7442 /// \brief Report an error regarding overriding, along with any relevant 7443 /// overriden methods. 7444 /// 7445 /// \param DiagID the primary error to report. 7446 /// \param MD the overriding method. 7447 /// \param OEK which overrides to include as notes. 7448 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7449 OverrideErrorKind OEK = OEK_All) { 7450 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7451 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7452 E = MD->end_overridden_methods(); 7453 I != E; ++I) { 7454 // This check (& the OEK parameter) could be replaced by a predicate, but 7455 // without lambdas that would be overkill. This is still nicer than writing 7456 // out the diag loop 3 times. 7457 if ((OEK == OEK_All) || 7458 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7459 (OEK == OEK_Deleted && (*I)->isDeleted())) 7460 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7461 } 7462 } 7463 7464 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7465 /// and if so, check that it's a valid override and remember it. 7466 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7467 // Look for methods in base classes that this method might override. 7468 CXXBasePaths Paths; 7469 FindOverriddenMethod FOM; 7470 FOM.Method = MD; 7471 FOM.S = this; 7472 bool hasDeletedOverridenMethods = false; 7473 bool hasNonDeletedOverridenMethods = false; 7474 bool AddedAny = false; 7475 if (DC->lookupInBases(FOM, Paths)) { 7476 for (auto *I : Paths.found_decls()) { 7477 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7478 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7479 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7480 !CheckOverridingFunctionAttributes(MD, OldMD) && 7481 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7482 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7483 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7484 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7485 AddedAny = true; 7486 } 7487 } 7488 } 7489 } 7490 7491 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7492 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7493 } 7494 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7495 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7496 } 7497 7498 return AddedAny; 7499 } 7500 7501 namespace { 7502 // Struct for holding all of the extra arguments needed by 7503 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7504 struct ActOnFDArgs { 7505 Scope *S; 7506 Declarator &D; 7507 MultiTemplateParamsArg TemplateParamLists; 7508 bool AddToScope; 7509 }; 7510 } // end anonymous namespace 7511 7512 namespace { 7513 7514 // Callback to only accept typo corrections that have a non-zero edit distance. 7515 // Also only accept corrections that have the same parent decl. 7516 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7517 public: 7518 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7519 CXXRecordDecl *Parent) 7520 : Context(Context), OriginalFD(TypoFD), 7521 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7522 7523 bool ValidateCandidate(const TypoCorrection &candidate) override { 7524 if (candidate.getEditDistance() == 0) 7525 return false; 7526 7527 SmallVector<unsigned, 1> MismatchedParams; 7528 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7529 CDeclEnd = candidate.end(); 7530 CDecl != CDeclEnd; ++CDecl) { 7531 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7532 7533 if (FD && !FD->hasBody() && 7534 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7535 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7536 CXXRecordDecl *Parent = MD->getParent(); 7537 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7538 return true; 7539 } else if (!ExpectedParent) { 7540 return true; 7541 } 7542 } 7543 } 7544 7545 return false; 7546 } 7547 7548 private: 7549 ASTContext &Context; 7550 FunctionDecl *OriginalFD; 7551 CXXRecordDecl *ExpectedParent; 7552 }; 7553 7554 } // end anonymous namespace 7555 7556 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7557 TypoCorrectedFunctionDefinitions.insert(F); 7558 } 7559 7560 /// \brief Generate diagnostics for an invalid function redeclaration. 7561 /// 7562 /// This routine handles generating the diagnostic messages for an invalid 7563 /// function redeclaration, including finding possible similar declarations 7564 /// or performing typo correction if there are no previous declarations with 7565 /// the same name. 7566 /// 7567 /// Returns a NamedDecl iff typo correction was performed and substituting in 7568 /// the new declaration name does not cause new errors. 7569 static NamedDecl *DiagnoseInvalidRedeclaration( 7570 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7571 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7572 DeclarationName Name = NewFD->getDeclName(); 7573 DeclContext *NewDC = NewFD->getDeclContext(); 7574 SmallVector<unsigned, 1> MismatchedParams; 7575 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7576 TypoCorrection Correction; 7577 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7578 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7579 : diag::err_member_decl_does_not_match; 7580 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7581 IsLocalFriend ? Sema::LookupLocalFriendName 7582 : Sema::LookupOrdinaryName, 7583 Sema::ForRedeclaration); 7584 7585 NewFD->setInvalidDecl(); 7586 if (IsLocalFriend) 7587 SemaRef.LookupName(Prev, S); 7588 else 7589 SemaRef.LookupQualifiedName(Prev, NewDC); 7590 assert(!Prev.isAmbiguous() && 7591 "Cannot have an ambiguity in previous-declaration lookup"); 7592 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7593 if (!Prev.empty()) { 7594 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7595 Func != FuncEnd; ++Func) { 7596 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7597 if (FD && 7598 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7599 // Add 1 to the index so that 0 can mean the mismatch didn't 7600 // involve a parameter 7601 unsigned ParamNum = 7602 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7603 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7604 } 7605 } 7606 // If the qualified name lookup yielded nothing, try typo correction 7607 } else if ((Correction = SemaRef.CorrectTypo( 7608 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7609 &ExtraArgs.D.getCXXScopeSpec(), 7610 llvm::make_unique<DifferentNameValidatorCCC>( 7611 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7612 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7613 // Set up everything for the call to ActOnFunctionDeclarator 7614 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7615 ExtraArgs.D.getIdentifierLoc()); 7616 Previous.clear(); 7617 Previous.setLookupName(Correction.getCorrection()); 7618 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7619 CDeclEnd = Correction.end(); 7620 CDecl != CDeclEnd; ++CDecl) { 7621 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7622 if (FD && !FD->hasBody() && 7623 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7624 Previous.addDecl(FD); 7625 } 7626 } 7627 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7628 7629 NamedDecl *Result; 7630 // Retry building the function declaration with the new previous 7631 // declarations, and with errors suppressed. 7632 { 7633 // Trap errors. 7634 Sema::SFINAETrap Trap(SemaRef); 7635 7636 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7637 // pieces need to verify the typo-corrected C++ declaration and hopefully 7638 // eliminate the need for the parameter pack ExtraArgs. 7639 Result = SemaRef.ActOnFunctionDeclarator( 7640 ExtraArgs.S, ExtraArgs.D, 7641 Correction.getCorrectionDecl()->getDeclContext(), 7642 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7643 ExtraArgs.AddToScope); 7644 7645 if (Trap.hasErrorOccurred()) 7646 Result = nullptr; 7647 } 7648 7649 if (Result) { 7650 // Determine which correction we picked. 7651 Decl *Canonical = Result->getCanonicalDecl(); 7652 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7653 I != E; ++I) 7654 if ((*I)->getCanonicalDecl() == Canonical) 7655 Correction.setCorrectionDecl(*I); 7656 7657 // Let Sema know about the correction. 7658 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7659 SemaRef.diagnoseTypo( 7660 Correction, 7661 SemaRef.PDiag(IsLocalFriend 7662 ? diag::err_no_matching_local_friend_suggest 7663 : diag::err_member_decl_does_not_match_suggest) 7664 << Name << NewDC << IsDefinition); 7665 return Result; 7666 } 7667 7668 // Pretend the typo correction never occurred 7669 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7670 ExtraArgs.D.getIdentifierLoc()); 7671 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7672 Previous.clear(); 7673 Previous.setLookupName(Name); 7674 } 7675 7676 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7677 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7678 7679 bool NewFDisConst = false; 7680 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7681 NewFDisConst = NewMD->isConst(); 7682 7683 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7684 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7685 NearMatch != NearMatchEnd; ++NearMatch) { 7686 FunctionDecl *FD = NearMatch->first; 7687 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7688 bool FDisConst = MD && MD->isConst(); 7689 bool IsMember = MD || !IsLocalFriend; 7690 7691 // FIXME: These notes are poorly worded for the local friend case. 7692 if (unsigned Idx = NearMatch->second) { 7693 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7694 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7695 if (Loc.isInvalid()) Loc = FD->getLocation(); 7696 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7697 : diag::note_local_decl_close_param_match) 7698 << Idx << FDParam->getType() 7699 << NewFD->getParamDecl(Idx - 1)->getType(); 7700 } else if (FDisConst != NewFDisConst) { 7701 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7702 << NewFDisConst << FD->getSourceRange().getEnd(); 7703 } else 7704 SemaRef.Diag(FD->getLocation(), 7705 IsMember ? diag::note_member_def_close_match 7706 : diag::note_local_decl_close_match); 7707 } 7708 return nullptr; 7709 } 7710 7711 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7712 switch (D.getDeclSpec().getStorageClassSpec()) { 7713 default: llvm_unreachable("Unknown storage class!"); 7714 case DeclSpec::SCS_auto: 7715 case DeclSpec::SCS_register: 7716 case DeclSpec::SCS_mutable: 7717 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7718 diag::err_typecheck_sclass_func); 7719 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7720 D.setInvalidType(); 7721 break; 7722 case DeclSpec::SCS_unspecified: break; 7723 case DeclSpec::SCS_extern: 7724 if (D.getDeclSpec().isExternInLinkageSpec()) 7725 return SC_None; 7726 return SC_Extern; 7727 case DeclSpec::SCS_static: { 7728 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7729 // C99 6.7.1p5: 7730 // The declaration of an identifier for a function that has 7731 // block scope shall have no explicit storage-class specifier 7732 // other than extern 7733 // See also (C++ [dcl.stc]p4). 7734 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7735 diag::err_static_block_func); 7736 break; 7737 } else 7738 return SC_Static; 7739 } 7740 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7741 } 7742 7743 // No explicit storage class has already been returned 7744 return SC_None; 7745 } 7746 7747 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7748 DeclContext *DC, QualType &R, 7749 TypeSourceInfo *TInfo, 7750 StorageClass SC, 7751 bool &IsVirtualOkay) { 7752 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7753 DeclarationName Name = NameInfo.getName(); 7754 7755 FunctionDecl *NewFD = nullptr; 7756 bool isInline = D.getDeclSpec().isInlineSpecified(); 7757 7758 if (!SemaRef.getLangOpts().CPlusPlus) { 7759 // Determine whether the function was written with a 7760 // prototype. This true when: 7761 // - there is a prototype in the declarator, or 7762 // - the type R of the function is some kind of typedef or other non- 7763 // attributed reference to a type name (which eventually refers to a 7764 // function type). 7765 bool HasPrototype = 7766 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7767 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7768 7769 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7770 D.getLocStart(), NameInfo, R, 7771 TInfo, SC, isInline, 7772 HasPrototype, false); 7773 if (D.isInvalidType()) 7774 NewFD->setInvalidDecl(); 7775 7776 return NewFD; 7777 } 7778 7779 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7780 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7781 7782 // Check that the return type is not an abstract class type. 7783 // For record types, this is done by the AbstractClassUsageDiagnoser once 7784 // the class has been completely parsed. 7785 if (!DC->isRecord() && 7786 SemaRef.RequireNonAbstractType( 7787 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7788 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7789 D.setInvalidType(); 7790 7791 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7792 // This is a C++ constructor declaration. 7793 assert(DC->isRecord() && 7794 "Constructors can only be declared in a member context"); 7795 7796 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7797 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7798 D.getLocStart(), NameInfo, 7799 R, TInfo, isExplicit, isInline, 7800 /*isImplicitlyDeclared=*/false, 7801 isConstexpr); 7802 7803 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7804 // This is a C++ destructor declaration. 7805 if (DC->isRecord()) { 7806 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7807 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7808 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7809 SemaRef.Context, Record, 7810 D.getLocStart(), 7811 NameInfo, R, TInfo, isInline, 7812 /*isImplicitlyDeclared=*/false); 7813 7814 // If the class is complete, then we now create the implicit exception 7815 // specification. If the class is incomplete or dependent, we can't do 7816 // it yet. 7817 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7818 Record->getDefinition() && !Record->isBeingDefined() && 7819 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7820 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7821 } 7822 7823 IsVirtualOkay = true; 7824 return NewDD; 7825 7826 } else { 7827 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7828 D.setInvalidType(); 7829 7830 // Create a FunctionDecl to satisfy the function definition parsing 7831 // code path. 7832 return FunctionDecl::Create(SemaRef.Context, DC, 7833 D.getLocStart(), 7834 D.getIdentifierLoc(), Name, R, TInfo, 7835 SC, isInline, 7836 /*hasPrototype=*/true, isConstexpr); 7837 } 7838 7839 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7840 if (!DC->isRecord()) { 7841 SemaRef.Diag(D.getIdentifierLoc(), 7842 diag::err_conv_function_not_member); 7843 return nullptr; 7844 } 7845 7846 SemaRef.CheckConversionDeclarator(D, R, SC); 7847 IsVirtualOkay = true; 7848 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7849 D.getLocStart(), NameInfo, 7850 R, TInfo, isInline, isExplicit, 7851 isConstexpr, SourceLocation()); 7852 7853 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7854 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7855 7856 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7857 isExplicit, NameInfo, R, TInfo, 7858 D.getLocEnd()); 7859 } else if (DC->isRecord()) { 7860 // If the name of the function is the same as the name of the record, 7861 // then this must be an invalid constructor that has a return type. 7862 // (The parser checks for a return type and makes the declarator a 7863 // constructor if it has no return type). 7864 if (Name.getAsIdentifierInfo() && 7865 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7866 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7867 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7868 << SourceRange(D.getIdentifierLoc()); 7869 return nullptr; 7870 } 7871 7872 // This is a C++ method declaration. 7873 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7874 cast<CXXRecordDecl>(DC), 7875 D.getLocStart(), NameInfo, R, 7876 TInfo, SC, isInline, 7877 isConstexpr, SourceLocation()); 7878 IsVirtualOkay = !Ret->isStatic(); 7879 return Ret; 7880 } else { 7881 bool isFriend = 7882 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7883 if (!isFriend && SemaRef.CurContext->isRecord()) 7884 return nullptr; 7885 7886 // Determine whether the function was written with a 7887 // prototype. This true when: 7888 // - we're in C++ (where every function has a prototype), 7889 return FunctionDecl::Create(SemaRef.Context, DC, 7890 D.getLocStart(), 7891 NameInfo, R, TInfo, SC, isInline, 7892 true/*HasPrototype*/, isConstexpr); 7893 } 7894 } 7895 7896 enum OpenCLParamType { 7897 ValidKernelParam, 7898 PtrPtrKernelParam, 7899 PtrKernelParam, 7900 InvalidAddrSpacePtrKernelParam, 7901 InvalidKernelParam, 7902 RecordKernelParam 7903 }; 7904 7905 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 7906 if (PT->isPointerType()) { 7907 QualType PointeeType = PT->getPointeeType(); 7908 if (PointeeType->isPointerType()) 7909 return PtrPtrKernelParam; 7910 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 7911 PointeeType.getAddressSpace() == 0) 7912 return InvalidAddrSpacePtrKernelParam; 7913 return PtrKernelParam; 7914 } 7915 7916 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7917 // be used as builtin types. 7918 7919 if (PT->isImageType()) 7920 return PtrKernelParam; 7921 7922 if (PT->isBooleanType()) 7923 return InvalidKernelParam; 7924 7925 if (PT->isEventT()) 7926 return InvalidKernelParam; 7927 7928 // OpenCL extension spec v1.2 s9.5: 7929 // This extension adds support for half scalar and vector types as built-in 7930 // types that can be used for arithmetic operations, conversions etc. 7931 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 7932 return InvalidKernelParam; 7933 7934 if (PT->isRecordType()) 7935 return RecordKernelParam; 7936 7937 return ValidKernelParam; 7938 } 7939 7940 static void checkIsValidOpenCLKernelParameter( 7941 Sema &S, 7942 Declarator &D, 7943 ParmVarDecl *Param, 7944 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7945 QualType PT = Param->getType(); 7946 7947 // Cache the valid types we encounter to avoid rechecking structs that are 7948 // used again 7949 if (ValidTypes.count(PT.getTypePtr())) 7950 return; 7951 7952 switch (getOpenCLKernelParameterType(S, PT)) { 7953 case PtrPtrKernelParam: 7954 // OpenCL v1.2 s6.9.a: 7955 // A kernel function argument cannot be declared as a 7956 // pointer to a pointer type. 7957 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7958 D.setInvalidType(); 7959 return; 7960 7961 case InvalidAddrSpacePtrKernelParam: 7962 // OpenCL v1.0 s6.5: 7963 // __kernel function arguments declared to be a pointer of a type can point 7964 // to one of the following address spaces only : __global, __local or 7965 // __constant. 7966 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 7967 D.setInvalidType(); 7968 return; 7969 7970 // OpenCL v1.2 s6.9.k: 7971 // Arguments to kernel functions in a program cannot be declared with the 7972 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7973 // uintptr_t or a struct and/or union that contain fields declared to be 7974 // one of these built-in scalar types. 7975 7976 case InvalidKernelParam: 7977 // OpenCL v1.2 s6.8 n: 7978 // A kernel function argument cannot be declared 7979 // of event_t type. 7980 // Do not diagnose half type since it is diagnosed as invalid argument 7981 // type for any function elsewhere. 7982 if (!PT->isHalfType()) 7983 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7984 D.setInvalidType(); 7985 return; 7986 7987 case PtrKernelParam: 7988 case ValidKernelParam: 7989 ValidTypes.insert(PT.getTypePtr()); 7990 return; 7991 7992 case RecordKernelParam: 7993 break; 7994 } 7995 7996 // Track nested structs we will inspect 7997 SmallVector<const Decl *, 4> VisitStack; 7998 7999 // Track where we are in the nested structs. Items will migrate from 8000 // VisitStack to HistoryStack as we do the DFS for bad field. 8001 SmallVector<const FieldDecl *, 4> HistoryStack; 8002 HistoryStack.push_back(nullptr); 8003 8004 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8005 VisitStack.push_back(PD); 8006 8007 assert(VisitStack.back() && "First decl null?"); 8008 8009 do { 8010 const Decl *Next = VisitStack.pop_back_val(); 8011 if (!Next) { 8012 assert(!HistoryStack.empty()); 8013 // Found a marker, we have gone up a level 8014 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8015 ValidTypes.insert(Hist->getType().getTypePtr()); 8016 8017 continue; 8018 } 8019 8020 // Adds everything except the original parameter declaration (which is not a 8021 // field itself) to the history stack. 8022 const RecordDecl *RD; 8023 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8024 HistoryStack.push_back(Field); 8025 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8026 } else { 8027 RD = cast<RecordDecl>(Next); 8028 } 8029 8030 // Add a null marker so we know when we've gone back up a level 8031 VisitStack.push_back(nullptr); 8032 8033 for (const auto *FD : RD->fields()) { 8034 QualType QT = FD->getType(); 8035 8036 if (ValidTypes.count(QT.getTypePtr())) 8037 continue; 8038 8039 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8040 if (ParamType == ValidKernelParam) 8041 continue; 8042 8043 if (ParamType == RecordKernelParam) { 8044 VisitStack.push_back(FD); 8045 continue; 8046 } 8047 8048 // OpenCL v1.2 s6.9.p: 8049 // Arguments to kernel functions that are declared to be a struct or union 8050 // do not allow OpenCL objects to be passed as elements of the struct or 8051 // union. 8052 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8053 ParamType == InvalidAddrSpacePtrKernelParam) { 8054 S.Diag(Param->getLocation(), 8055 diag::err_record_with_pointers_kernel_param) 8056 << PT->isUnionType() 8057 << PT; 8058 } else { 8059 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8060 } 8061 8062 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8063 << PD->getDeclName(); 8064 8065 // We have an error, now let's go back up through history and show where 8066 // the offending field came from 8067 for (ArrayRef<const FieldDecl *>::const_iterator 8068 I = HistoryStack.begin() + 1, 8069 E = HistoryStack.end(); 8070 I != E; ++I) { 8071 const FieldDecl *OuterField = *I; 8072 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8073 << OuterField->getType(); 8074 } 8075 8076 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8077 << QT->isPointerType() 8078 << QT; 8079 D.setInvalidType(); 8080 return; 8081 } 8082 } while (!VisitStack.empty()); 8083 } 8084 8085 /// Find the DeclContext in which a tag is implicitly declared if we see an 8086 /// elaborated type specifier in the specified context, and lookup finds 8087 /// nothing. 8088 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8089 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8090 DC = DC->getParent(); 8091 return DC; 8092 } 8093 8094 /// Find the Scope in which a tag is implicitly declared if we see an 8095 /// elaborated type specifier in the specified context, and lookup finds 8096 /// nothing. 8097 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8098 while (S->isClassScope() || 8099 (LangOpts.CPlusPlus && 8100 S->isFunctionPrototypeScope()) || 8101 ((S->getFlags() & Scope::DeclScope) == 0) || 8102 (S->getEntity() && S->getEntity()->isTransparentContext())) 8103 S = S->getParent(); 8104 return S; 8105 } 8106 8107 NamedDecl* 8108 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8109 TypeSourceInfo *TInfo, LookupResult &Previous, 8110 MultiTemplateParamsArg TemplateParamLists, 8111 bool &AddToScope) { 8112 QualType R = TInfo->getType(); 8113 8114 assert(R.getTypePtr()->isFunctionType()); 8115 8116 // TODO: consider using NameInfo for diagnostic. 8117 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8118 DeclarationName Name = NameInfo.getName(); 8119 StorageClass SC = getFunctionStorageClass(*this, D); 8120 8121 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8122 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8123 diag::err_invalid_thread) 8124 << DeclSpec::getSpecifierName(TSCS); 8125 8126 if (D.isFirstDeclarationOfMember()) 8127 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8128 D.getIdentifierLoc()); 8129 8130 bool isFriend = false; 8131 FunctionTemplateDecl *FunctionTemplate = nullptr; 8132 bool isMemberSpecialization = false; 8133 bool isFunctionTemplateSpecialization = false; 8134 8135 bool isDependentClassScopeExplicitSpecialization = false; 8136 bool HasExplicitTemplateArgs = false; 8137 TemplateArgumentListInfo TemplateArgs; 8138 8139 bool isVirtualOkay = false; 8140 8141 DeclContext *OriginalDC = DC; 8142 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8143 8144 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8145 isVirtualOkay); 8146 if (!NewFD) return nullptr; 8147 8148 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8149 NewFD->setTopLevelDeclInObjCContainer(); 8150 8151 // Set the lexical context. If this is a function-scope declaration, or has a 8152 // C++ scope specifier, or is the object of a friend declaration, the lexical 8153 // context will be different from the semantic context. 8154 NewFD->setLexicalDeclContext(CurContext); 8155 8156 if (IsLocalExternDecl) 8157 NewFD->setLocalExternDecl(); 8158 8159 if (getLangOpts().CPlusPlus) { 8160 bool isInline = D.getDeclSpec().isInlineSpecified(); 8161 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8162 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8163 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8164 bool isConcept = D.getDeclSpec().isConceptSpecified(); 8165 isFriend = D.getDeclSpec().isFriendSpecified(); 8166 if (isFriend && !isInline && D.isFunctionDefinition()) { 8167 // C++ [class.friend]p5 8168 // A function can be defined in a friend declaration of a 8169 // class . . . . Such a function is implicitly inline. 8170 NewFD->setImplicitlyInline(); 8171 } 8172 8173 // If this is a method defined in an __interface, and is not a constructor 8174 // or an overloaded operator, then set the pure flag (isVirtual will already 8175 // return true). 8176 if (const CXXRecordDecl *Parent = 8177 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8178 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8179 NewFD->setPure(true); 8180 8181 // C++ [class.union]p2 8182 // A union can have member functions, but not virtual functions. 8183 if (isVirtual && Parent->isUnion()) 8184 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8185 } 8186 8187 SetNestedNameSpecifier(NewFD, D); 8188 isMemberSpecialization = false; 8189 isFunctionTemplateSpecialization = false; 8190 if (D.isInvalidType()) 8191 NewFD->setInvalidDecl(); 8192 8193 // Match up the template parameter lists with the scope specifier, then 8194 // determine whether we have a template or a template specialization. 8195 bool Invalid = false; 8196 if (TemplateParameterList *TemplateParams = 8197 MatchTemplateParametersToScopeSpecifier( 8198 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8199 D.getCXXScopeSpec(), 8200 D.getName().getKind() == UnqualifiedId::IK_TemplateId 8201 ? D.getName().TemplateId 8202 : nullptr, 8203 TemplateParamLists, isFriend, isMemberSpecialization, 8204 Invalid)) { 8205 if (TemplateParams->size() > 0) { 8206 // This is a function template 8207 8208 // Check that we can declare a template here. 8209 if (CheckTemplateDeclScope(S, TemplateParams)) 8210 NewFD->setInvalidDecl(); 8211 8212 // A destructor cannot be a template. 8213 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8214 Diag(NewFD->getLocation(), diag::err_destructor_template); 8215 NewFD->setInvalidDecl(); 8216 } 8217 8218 // If we're adding a template to a dependent context, we may need to 8219 // rebuilding some of the types used within the template parameter list, 8220 // now that we know what the current instantiation is. 8221 if (DC->isDependentContext()) { 8222 ContextRAII SavedContext(*this, DC); 8223 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8224 Invalid = true; 8225 } 8226 8227 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8228 NewFD->getLocation(), 8229 Name, TemplateParams, 8230 NewFD); 8231 FunctionTemplate->setLexicalDeclContext(CurContext); 8232 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8233 8234 // For source fidelity, store the other template param lists. 8235 if (TemplateParamLists.size() > 1) { 8236 NewFD->setTemplateParameterListsInfo(Context, 8237 TemplateParamLists.drop_back(1)); 8238 } 8239 } else { 8240 // This is a function template specialization. 8241 isFunctionTemplateSpecialization = true; 8242 // For source fidelity, store all the template param lists. 8243 if (TemplateParamLists.size() > 0) 8244 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8245 8246 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8247 if (isFriend) { 8248 // We want to remove the "template<>", found here. 8249 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8250 8251 // If we remove the template<> and the name is not a 8252 // template-id, we're actually silently creating a problem: 8253 // the friend declaration will refer to an untemplated decl, 8254 // and clearly the user wants a template specialization. So 8255 // we need to insert '<>' after the name. 8256 SourceLocation InsertLoc; 8257 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8258 InsertLoc = D.getName().getSourceRange().getEnd(); 8259 InsertLoc = getLocForEndOfToken(InsertLoc); 8260 } 8261 8262 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8263 << Name << RemoveRange 8264 << FixItHint::CreateRemoval(RemoveRange) 8265 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8266 } 8267 } 8268 } 8269 else { 8270 // All template param lists were matched against the scope specifier: 8271 // this is NOT (an explicit specialization of) a template. 8272 if (TemplateParamLists.size() > 0) 8273 // For source fidelity, store all the template param lists. 8274 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8275 } 8276 8277 if (Invalid) { 8278 NewFD->setInvalidDecl(); 8279 if (FunctionTemplate) 8280 FunctionTemplate->setInvalidDecl(); 8281 } 8282 8283 // C++ [dcl.fct.spec]p5: 8284 // The virtual specifier shall only be used in declarations of 8285 // nonstatic class member functions that appear within a 8286 // member-specification of a class declaration; see 10.3. 8287 // 8288 if (isVirtual && !NewFD->isInvalidDecl()) { 8289 if (!isVirtualOkay) { 8290 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8291 diag::err_virtual_non_function); 8292 } else if (!CurContext->isRecord()) { 8293 // 'virtual' was specified outside of the class. 8294 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8295 diag::err_virtual_out_of_class) 8296 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8297 } else if (NewFD->getDescribedFunctionTemplate()) { 8298 // C++ [temp.mem]p3: 8299 // A member function template shall not be virtual. 8300 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8301 diag::err_virtual_member_function_template) 8302 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8303 } else { 8304 // Okay: Add virtual to the method. 8305 NewFD->setVirtualAsWritten(true); 8306 } 8307 8308 if (getLangOpts().CPlusPlus14 && 8309 NewFD->getReturnType()->isUndeducedType()) 8310 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8311 } 8312 8313 if (getLangOpts().CPlusPlus14 && 8314 (NewFD->isDependentContext() || 8315 (isFriend && CurContext->isDependentContext())) && 8316 NewFD->getReturnType()->isUndeducedType()) { 8317 // If the function template is referenced directly (for instance, as a 8318 // member of the current instantiation), pretend it has a dependent type. 8319 // This is not really justified by the standard, but is the only sane 8320 // thing to do. 8321 // FIXME: For a friend function, we have not marked the function as being 8322 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8323 const FunctionProtoType *FPT = 8324 NewFD->getType()->castAs<FunctionProtoType>(); 8325 QualType Result = 8326 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8327 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8328 FPT->getExtProtoInfo())); 8329 } 8330 8331 // C++ [dcl.fct.spec]p3: 8332 // The inline specifier shall not appear on a block scope function 8333 // declaration. 8334 if (isInline && !NewFD->isInvalidDecl()) { 8335 if (CurContext->isFunctionOrMethod()) { 8336 // 'inline' is not allowed on block scope function declaration. 8337 Diag(D.getDeclSpec().getInlineSpecLoc(), 8338 diag::err_inline_declaration_block_scope) << Name 8339 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8340 } 8341 } 8342 8343 // C++ [dcl.fct.spec]p6: 8344 // The explicit specifier shall be used only in the declaration of a 8345 // constructor or conversion function within its class definition; 8346 // see 12.3.1 and 12.3.2. 8347 if (isExplicit && !NewFD->isInvalidDecl() && 8348 !isa<CXXDeductionGuideDecl>(NewFD)) { 8349 if (!CurContext->isRecord()) { 8350 // 'explicit' was specified outside of the class. 8351 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8352 diag::err_explicit_out_of_class) 8353 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8354 } else if (!isa<CXXConstructorDecl>(NewFD) && 8355 !isa<CXXConversionDecl>(NewFD)) { 8356 // 'explicit' was specified on a function that wasn't a constructor 8357 // or conversion function. 8358 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8359 diag::err_explicit_non_ctor_or_conv_function) 8360 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8361 } 8362 } 8363 8364 if (isConstexpr) { 8365 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8366 // are implicitly inline. 8367 NewFD->setImplicitlyInline(); 8368 8369 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8370 // be either constructors or to return a literal type. Therefore, 8371 // destructors cannot be declared constexpr. 8372 if (isa<CXXDestructorDecl>(NewFD)) 8373 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8374 } 8375 8376 if (isConcept) { 8377 // This is a function concept. 8378 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8379 FTD->setConcept(); 8380 8381 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8382 // applied only to the definition of a function template [...] 8383 if (!D.isFunctionDefinition()) { 8384 Diag(D.getDeclSpec().getConceptSpecLoc(), 8385 diag::err_function_concept_not_defined); 8386 NewFD->setInvalidDecl(); 8387 } 8388 8389 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8390 // have no exception-specification and is treated as if it were specified 8391 // with noexcept(true) (15.4). [...] 8392 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8393 if (FPT->hasExceptionSpec()) { 8394 SourceRange Range; 8395 if (D.isFunctionDeclarator()) 8396 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8397 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8398 << FixItHint::CreateRemoval(Range); 8399 NewFD->setInvalidDecl(); 8400 } else { 8401 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8402 } 8403 8404 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8405 // following restrictions: 8406 // - The declared return type shall have the type bool. 8407 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8408 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8409 NewFD->setInvalidDecl(); 8410 } 8411 8412 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8413 // following restrictions: 8414 // - The declaration's parameter list shall be equivalent to an empty 8415 // parameter list. 8416 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8417 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8418 } 8419 8420 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8421 // implicity defined to be a constexpr declaration (implicitly inline) 8422 NewFD->setImplicitlyInline(); 8423 8424 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8425 // be declared with the thread_local, inline, friend, or constexpr 8426 // specifiers, [...] 8427 if (isInline) { 8428 Diag(D.getDeclSpec().getInlineSpecLoc(), 8429 diag::err_concept_decl_invalid_specifiers) 8430 << 1 << 1; 8431 NewFD->setInvalidDecl(true); 8432 } 8433 8434 if (isFriend) { 8435 Diag(D.getDeclSpec().getFriendSpecLoc(), 8436 diag::err_concept_decl_invalid_specifiers) 8437 << 1 << 2; 8438 NewFD->setInvalidDecl(true); 8439 } 8440 8441 if (isConstexpr) { 8442 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8443 diag::err_concept_decl_invalid_specifiers) 8444 << 1 << 3; 8445 NewFD->setInvalidDecl(true); 8446 } 8447 8448 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8449 // applied only to the definition of a function template or variable 8450 // template, declared in namespace scope. 8451 if (isFunctionTemplateSpecialization) { 8452 Diag(D.getDeclSpec().getConceptSpecLoc(), 8453 diag::err_concept_specified_specialization) << 1; 8454 NewFD->setInvalidDecl(true); 8455 return NewFD; 8456 } 8457 } 8458 8459 // If __module_private__ was specified, mark the function accordingly. 8460 if (D.getDeclSpec().isModulePrivateSpecified()) { 8461 if (isFunctionTemplateSpecialization) { 8462 SourceLocation ModulePrivateLoc 8463 = D.getDeclSpec().getModulePrivateSpecLoc(); 8464 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8465 << 0 8466 << FixItHint::CreateRemoval(ModulePrivateLoc); 8467 } else { 8468 NewFD->setModulePrivate(); 8469 if (FunctionTemplate) 8470 FunctionTemplate->setModulePrivate(); 8471 } 8472 } 8473 8474 if (isFriend) { 8475 if (FunctionTemplate) { 8476 FunctionTemplate->setObjectOfFriendDecl(); 8477 FunctionTemplate->setAccess(AS_public); 8478 } 8479 NewFD->setObjectOfFriendDecl(); 8480 NewFD->setAccess(AS_public); 8481 } 8482 8483 // If a function is defined as defaulted or deleted, mark it as such now. 8484 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8485 // definition kind to FDK_Definition. 8486 switch (D.getFunctionDefinitionKind()) { 8487 case FDK_Declaration: 8488 case FDK_Definition: 8489 break; 8490 8491 case FDK_Defaulted: 8492 NewFD->setDefaulted(); 8493 break; 8494 8495 case FDK_Deleted: 8496 NewFD->setDeletedAsWritten(); 8497 break; 8498 } 8499 8500 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8501 D.isFunctionDefinition()) { 8502 // C++ [class.mfct]p2: 8503 // A member function may be defined (8.4) in its class definition, in 8504 // which case it is an inline member function (7.1.2) 8505 NewFD->setImplicitlyInline(); 8506 } 8507 8508 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8509 !CurContext->isRecord()) { 8510 // C++ [class.static]p1: 8511 // A data or function member of a class may be declared static 8512 // in a class definition, in which case it is a static member of 8513 // the class. 8514 8515 // Complain about the 'static' specifier if it's on an out-of-line 8516 // member function definition. 8517 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8518 diag::err_static_out_of_line) 8519 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8520 } 8521 8522 // C++11 [except.spec]p15: 8523 // A deallocation function with no exception-specification is treated 8524 // as if it were specified with noexcept(true). 8525 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8526 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8527 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8528 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8529 NewFD->setType(Context.getFunctionType( 8530 FPT->getReturnType(), FPT->getParamTypes(), 8531 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8532 } 8533 8534 // Filter out previous declarations that don't match the scope. 8535 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8536 D.getCXXScopeSpec().isNotEmpty() || 8537 isMemberSpecialization || 8538 isFunctionTemplateSpecialization); 8539 8540 // Handle GNU asm-label extension (encoded as an attribute). 8541 if (Expr *E = (Expr*) D.getAsmLabel()) { 8542 // The parser guarantees this is a string. 8543 StringLiteral *SE = cast<StringLiteral>(E); 8544 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8545 SE->getString(), 0)); 8546 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8547 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8548 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8549 if (I != ExtnameUndeclaredIdentifiers.end()) { 8550 if (isDeclExternC(NewFD)) { 8551 NewFD->addAttr(I->second); 8552 ExtnameUndeclaredIdentifiers.erase(I); 8553 } else 8554 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8555 << /*Variable*/0 << NewFD; 8556 } 8557 } 8558 8559 // Copy the parameter declarations from the declarator D to the function 8560 // declaration NewFD, if they are available. First scavenge them into Params. 8561 SmallVector<ParmVarDecl*, 16> Params; 8562 unsigned FTIIdx; 8563 if (D.isFunctionDeclarator(FTIIdx)) { 8564 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8565 8566 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8567 // function that takes no arguments, not a function that takes a 8568 // single void argument. 8569 // We let through "const void" here because Sema::GetTypeForDeclarator 8570 // already checks for that case. 8571 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8572 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8573 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8574 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8575 Param->setDeclContext(NewFD); 8576 Params.push_back(Param); 8577 8578 if (Param->isInvalidDecl()) 8579 NewFD->setInvalidDecl(); 8580 } 8581 } 8582 8583 if (!getLangOpts().CPlusPlus) { 8584 // In C, find all the tag declarations from the prototype and move them 8585 // into the function DeclContext. Remove them from the surrounding tag 8586 // injection context of the function, which is typically but not always 8587 // the TU. 8588 DeclContext *PrototypeTagContext = 8589 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8590 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8591 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8592 8593 // We don't want to reparent enumerators. Look at their parent enum 8594 // instead. 8595 if (!TD) { 8596 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8597 TD = cast<EnumDecl>(ECD->getDeclContext()); 8598 } 8599 if (!TD) 8600 continue; 8601 DeclContext *TagDC = TD->getLexicalDeclContext(); 8602 if (!TagDC->containsDecl(TD)) 8603 continue; 8604 TagDC->removeDecl(TD); 8605 TD->setDeclContext(NewFD); 8606 NewFD->addDecl(TD); 8607 8608 // Preserve the lexical DeclContext if it is not the surrounding tag 8609 // injection context of the FD. In this example, the semantic context of 8610 // E will be f and the lexical context will be S, while both the 8611 // semantic and lexical contexts of S will be f: 8612 // void f(struct S { enum E { a } f; } s); 8613 if (TagDC != PrototypeTagContext) 8614 TD->setLexicalDeclContext(TagDC); 8615 } 8616 } 8617 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8618 // When we're declaring a function with a typedef, typeof, etc as in the 8619 // following example, we'll need to synthesize (unnamed) 8620 // parameters for use in the declaration. 8621 // 8622 // @code 8623 // typedef void fn(int); 8624 // fn f; 8625 // @endcode 8626 8627 // Synthesize a parameter for each argument type. 8628 for (const auto &AI : FT->param_types()) { 8629 ParmVarDecl *Param = 8630 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8631 Param->setScopeInfo(0, Params.size()); 8632 Params.push_back(Param); 8633 } 8634 } else { 8635 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8636 "Should not need args for typedef of non-prototype fn"); 8637 } 8638 8639 // Finally, we know we have the right number of parameters, install them. 8640 NewFD->setParams(Params); 8641 8642 if (D.getDeclSpec().isNoreturnSpecified()) 8643 NewFD->addAttr( 8644 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8645 Context, 0)); 8646 8647 // Functions returning a variably modified type violate C99 6.7.5.2p2 8648 // because all functions have linkage. 8649 if (!NewFD->isInvalidDecl() && 8650 NewFD->getReturnType()->isVariablyModifiedType()) { 8651 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8652 NewFD->setInvalidDecl(); 8653 } 8654 8655 // Apply an implicit SectionAttr if #pragma code_seg is active. 8656 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8657 !NewFD->hasAttr<SectionAttr>()) { 8658 NewFD->addAttr( 8659 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8660 CodeSegStack.CurrentValue->getString(), 8661 CodeSegStack.CurrentPragmaLocation)); 8662 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8663 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8664 ASTContext::PSF_Read, 8665 NewFD)) 8666 NewFD->dropAttr<SectionAttr>(); 8667 } 8668 8669 // Handle attributes. 8670 ProcessDeclAttributes(S, NewFD, D); 8671 8672 if (getLangOpts().OpenCL) { 8673 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8674 // type declaration will generate a compilation error. 8675 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8676 if (AddressSpace == LangAS::opencl_local || 8677 AddressSpace == LangAS::opencl_global || 8678 AddressSpace == LangAS::opencl_constant) { 8679 Diag(NewFD->getLocation(), 8680 diag::err_opencl_return_value_with_address_space); 8681 NewFD->setInvalidDecl(); 8682 } 8683 } 8684 8685 if (!getLangOpts().CPlusPlus) { 8686 // Perform semantic checking on the function declaration. 8687 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8688 CheckMain(NewFD, D.getDeclSpec()); 8689 8690 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8691 CheckMSVCRTEntryPoint(NewFD); 8692 8693 if (!NewFD->isInvalidDecl()) 8694 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8695 isMemberSpecialization)); 8696 else if (!Previous.empty()) 8697 // Recover gracefully from an invalid redeclaration. 8698 D.setRedeclaration(true); 8699 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8700 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8701 "previous declaration set still overloaded"); 8702 8703 // Diagnose no-prototype function declarations with calling conventions that 8704 // don't support variadic calls. Only do this in C and do it after merging 8705 // possibly prototyped redeclarations. 8706 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8707 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8708 CallingConv CC = FT->getExtInfo().getCC(); 8709 if (!supportsVariadicCall(CC)) { 8710 // Windows system headers sometimes accidentally use stdcall without 8711 // (void) parameters, so we relax this to a warning. 8712 int DiagID = 8713 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8714 Diag(NewFD->getLocation(), DiagID) 8715 << FunctionType::getNameForCallConv(CC); 8716 } 8717 } 8718 } else { 8719 // C++11 [replacement.functions]p3: 8720 // The program's definitions shall not be specified as inline. 8721 // 8722 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8723 // 8724 // Suppress the diagnostic if the function is __attribute__((used)), since 8725 // that forces an external definition to be emitted. 8726 if (D.getDeclSpec().isInlineSpecified() && 8727 NewFD->isReplaceableGlobalAllocationFunction() && 8728 !NewFD->hasAttr<UsedAttr>()) 8729 Diag(D.getDeclSpec().getInlineSpecLoc(), 8730 diag::ext_operator_new_delete_declared_inline) 8731 << NewFD->getDeclName(); 8732 8733 // If the declarator is a template-id, translate the parser's template 8734 // argument list into our AST format. 8735 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8736 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8737 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8738 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8739 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8740 TemplateId->NumArgs); 8741 translateTemplateArguments(TemplateArgsPtr, 8742 TemplateArgs); 8743 8744 HasExplicitTemplateArgs = true; 8745 8746 if (NewFD->isInvalidDecl()) { 8747 HasExplicitTemplateArgs = false; 8748 } else if (FunctionTemplate) { 8749 // Function template with explicit template arguments. 8750 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8751 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8752 8753 HasExplicitTemplateArgs = false; 8754 } else { 8755 assert((isFunctionTemplateSpecialization || 8756 D.getDeclSpec().isFriendSpecified()) && 8757 "should have a 'template<>' for this decl"); 8758 // "friend void foo<>(int);" is an implicit specialization decl. 8759 isFunctionTemplateSpecialization = true; 8760 } 8761 } else if (isFriend && isFunctionTemplateSpecialization) { 8762 // This combination is only possible in a recovery case; the user 8763 // wrote something like: 8764 // template <> friend void foo(int); 8765 // which we're recovering from as if the user had written: 8766 // friend void foo<>(int); 8767 // Go ahead and fake up a template id. 8768 HasExplicitTemplateArgs = true; 8769 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8770 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8771 } 8772 8773 // We do not add HD attributes to specializations here because 8774 // they may have different constexpr-ness compared to their 8775 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8776 // may end up with different effective targets. Instead, a 8777 // specialization inherits its target attributes from its template 8778 // in the CheckFunctionTemplateSpecialization() call below. 8779 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8780 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8781 8782 // If it's a friend (and only if it's a friend), it's possible 8783 // that either the specialized function type or the specialized 8784 // template is dependent, and therefore matching will fail. In 8785 // this case, don't check the specialization yet. 8786 bool InstantiationDependent = false; 8787 if (isFunctionTemplateSpecialization && isFriend && 8788 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8789 TemplateSpecializationType::anyDependentTemplateArguments( 8790 TemplateArgs, 8791 InstantiationDependent))) { 8792 assert(HasExplicitTemplateArgs && 8793 "friend function specialization without template args"); 8794 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8795 Previous)) 8796 NewFD->setInvalidDecl(); 8797 } else if (isFunctionTemplateSpecialization) { 8798 if (CurContext->isDependentContext() && CurContext->isRecord() 8799 && !isFriend) { 8800 isDependentClassScopeExplicitSpecialization = true; 8801 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8802 diag::ext_function_specialization_in_class : 8803 diag::err_function_specialization_in_class) 8804 << NewFD->getDeclName(); 8805 } else if (CheckFunctionTemplateSpecialization(NewFD, 8806 (HasExplicitTemplateArgs ? &TemplateArgs 8807 : nullptr), 8808 Previous)) 8809 NewFD->setInvalidDecl(); 8810 8811 // C++ [dcl.stc]p1: 8812 // A storage-class-specifier shall not be specified in an explicit 8813 // specialization (14.7.3) 8814 FunctionTemplateSpecializationInfo *Info = 8815 NewFD->getTemplateSpecializationInfo(); 8816 if (Info && SC != SC_None) { 8817 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8818 Diag(NewFD->getLocation(), 8819 diag::err_explicit_specialization_inconsistent_storage_class) 8820 << SC 8821 << FixItHint::CreateRemoval( 8822 D.getDeclSpec().getStorageClassSpecLoc()); 8823 8824 else 8825 Diag(NewFD->getLocation(), 8826 diag::ext_explicit_specialization_storage_class) 8827 << FixItHint::CreateRemoval( 8828 D.getDeclSpec().getStorageClassSpecLoc()); 8829 } 8830 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8831 if (CheckMemberSpecialization(NewFD, Previous)) 8832 NewFD->setInvalidDecl(); 8833 } 8834 8835 // Perform semantic checking on the function declaration. 8836 if (!isDependentClassScopeExplicitSpecialization) { 8837 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8838 CheckMain(NewFD, D.getDeclSpec()); 8839 8840 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8841 CheckMSVCRTEntryPoint(NewFD); 8842 8843 if (!NewFD->isInvalidDecl()) 8844 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8845 isMemberSpecialization)); 8846 else if (!Previous.empty()) 8847 // Recover gracefully from an invalid redeclaration. 8848 D.setRedeclaration(true); 8849 } 8850 8851 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8852 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8853 "previous declaration set still overloaded"); 8854 8855 NamedDecl *PrincipalDecl = (FunctionTemplate 8856 ? cast<NamedDecl>(FunctionTemplate) 8857 : NewFD); 8858 8859 if (isFriend && NewFD->getPreviousDecl()) { 8860 AccessSpecifier Access = AS_public; 8861 if (!NewFD->isInvalidDecl()) 8862 Access = NewFD->getPreviousDecl()->getAccess(); 8863 8864 NewFD->setAccess(Access); 8865 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8866 } 8867 8868 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8869 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8870 PrincipalDecl->setNonMemberOperator(); 8871 8872 // If we have a function template, check the template parameter 8873 // list. This will check and merge default template arguments. 8874 if (FunctionTemplate) { 8875 FunctionTemplateDecl *PrevTemplate = 8876 FunctionTemplate->getPreviousDecl(); 8877 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8878 PrevTemplate ? PrevTemplate->getTemplateParameters() 8879 : nullptr, 8880 D.getDeclSpec().isFriendSpecified() 8881 ? (D.isFunctionDefinition() 8882 ? TPC_FriendFunctionTemplateDefinition 8883 : TPC_FriendFunctionTemplate) 8884 : (D.getCXXScopeSpec().isSet() && 8885 DC && DC->isRecord() && 8886 DC->isDependentContext()) 8887 ? TPC_ClassTemplateMember 8888 : TPC_FunctionTemplate); 8889 } 8890 8891 if (NewFD->isInvalidDecl()) { 8892 // Ignore all the rest of this. 8893 } else if (!D.isRedeclaration()) { 8894 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8895 AddToScope }; 8896 // Fake up an access specifier if it's supposed to be a class member. 8897 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8898 NewFD->setAccess(AS_public); 8899 8900 // Qualified decls generally require a previous declaration. 8901 if (D.getCXXScopeSpec().isSet()) { 8902 // ...with the major exception of templated-scope or 8903 // dependent-scope friend declarations. 8904 8905 // TODO: we currently also suppress this check in dependent 8906 // contexts because (1) the parameter depth will be off when 8907 // matching friend templates and (2) we might actually be 8908 // selecting a friend based on a dependent factor. But there 8909 // are situations where these conditions don't apply and we 8910 // can actually do this check immediately. 8911 if (isFriend && 8912 (TemplateParamLists.size() || 8913 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8914 CurContext->isDependentContext())) { 8915 // ignore these 8916 } else { 8917 // The user tried to provide an out-of-line definition for a 8918 // function that is a member of a class or namespace, but there 8919 // was no such member function declared (C++ [class.mfct]p2, 8920 // C++ [namespace.memdef]p2). For example: 8921 // 8922 // class X { 8923 // void f() const; 8924 // }; 8925 // 8926 // void X::f() { } // ill-formed 8927 // 8928 // Complain about this problem, and attempt to suggest close 8929 // matches (e.g., those that differ only in cv-qualifiers and 8930 // whether the parameter types are references). 8931 8932 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8933 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8934 AddToScope = ExtraArgs.AddToScope; 8935 return Result; 8936 } 8937 } 8938 8939 // Unqualified local friend declarations are required to resolve 8940 // to something. 8941 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8942 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8943 *this, Previous, NewFD, ExtraArgs, true, S)) { 8944 AddToScope = ExtraArgs.AddToScope; 8945 return Result; 8946 } 8947 } 8948 } else if (!D.isFunctionDefinition() && 8949 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8950 !isFriend && !isFunctionTemplateSpecialization && 8951 !isMemberSpecialization) { 8952 // An out-of-line member function declaration must also be a 8953 // definition (C++ [class.mfct]p2). 8954 // Note that this is not the case for explicit specializations of 8955 // function templates or member functions of class templates, per 8956 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8957 // extension for compatibility with old SWIG code which likes to 8958 // generate them. 8959 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8960 << D.getCXXScopeSpec().getRange(); 8961 } 8962 } 8963 8964 ProcessPragmaWeak(S, NewFD); 8965 checkAttributesAfterMerging(*this, *NewFD); 8966 8967 AddKnownFunctionAttributes(NewFD); 8968 8969 if (NewFD->hasAttr<OverloadableAttr>() && 8970 !NewFD->getType()->getAs<FunctionProtoType>()) { 8971 Diag(NewFD->getLocation(), 8972 diag::err_attribute_overloadable_no_prototype) 8973 << NewFD; 8974 8975 // Turn this into a variadic function with no parameters. 8976 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8977 FunctionProtoType::ExtProtoInfo EPI( 8978 Context.getDefaultCallingConvention(true, false)); 8979 EPI.Variadic = true; 8980 EPI.ExtInfo = FT->getExtInfo(); 8981 8982 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8983 NewFD->setType(R); 8984 } 8985 8986 // If there's a #pragma GCC visibility in scope, and this isn't a class 8987 // member, set the visibility of this function. 8988 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8989 AddPushedVisibilityAttribute(NewFD); 8990 8991 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8992 // marking the function. 8993 AddCFAuditedAttribute(NewFD); 8994 8995 // If this is a function definition, check if we have to apply optnone due to 8996 // a pragma. 8997 if(D.isFunctionDefinition()) 8998 AddRangeBasedOptnone(NewFD); 8999 9000 // If this is the first declaration of an extern C variable, update 9001 // the map of such variables. 9002 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9003 isIncompleteDeclExternC(*this, NewFD)) 9004 RegisterLocallyScopedExternCDecl(NewFD, S); 9005 9006 // Set this FunctionDecl's range up to the right paren. 9007 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9008 9009 if (D.isRedeclaration() && !Previous.empty()) { 9010 checkDLLAttributeRedeclaration( 9011 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 9012 isMemberSpecialization || isFunctionTemplateSpecialization, 9013 D.isFunctionDefinition()); 9014 } 9015 9016 if (getLangOpts().CUDA) { 9017 IdentifierInfo *II = NewFD->getIdentifier(); 9018 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 9019 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9020 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9021 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9022 9023 Context.setcudaConfigureCallDecl(NewFD); 9024 } 9025 9026 // Variadic functions, other than a *declaration* of printf, are not allowed 9027 // in device-side CUDA code, unless someone passed 9028 // -fcuda-allow-variadic-functions. 9029 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9030 (NewFD->hasAttr<CUDADeviceAttr>() || 9031 NewFD->hasAttr<CUDAGlobalAttr>()) && 9032 !(II && II->isStr("printf") && NewFD->isExternC() && 9033 !D.isFunctionDefinition())) { 9034 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9035 } 9036 } 9037 9038 MarkUnusedFileScopedDecl(NewFD); 9039 9040 if (getLangOpts().CPlusPlus) { 9041 if (FunctionTemplate) { 9042 if (NewFD->isInvalidDecl()) 9043 FunctionTemplate->setInvalidDecl(); 9044 return FunctionTemplate; 9045 } 9046 9047 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9048 CompleteMemberSpecialization(NewFD, Previous); 9049 } 9050 9051 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9052 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9053 if ((getLangOpts().OpenCLVersion >= 120) 9054 && (SC == SC_Static)) { 9055 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9056 D.setInvalidType(); 9057 } 9058 9059 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9060 if (!NewFD->getReturnType()->isVoidType()) { 9061 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9062 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9063 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9064 : FixItHint()); 9065 D.setInvalidType(); 9066 } 9067 9068 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9069 for (auto Param : NewFD->parameters()) 9070 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9071 } 9072 for (const ParmVarDecl *Param : NewFD->parameters()) { 9073 QualType PT = Param->getType(); 9074 9075 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9076 // types. 9077 if (getLangOpts().OpenCLVersion >= 200) { 9078 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9079 QualType ElemTy = PipeTy->getElementType(); 9080 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9081 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9082 D.setInvalidType(); 9083 } 9084 } 9085 } 9086 } 9087 9088 // Here we have an function template explicit specialization at class scope. 9089 // The actually specialization will be postponed to template instatiation 9090 // time via the ClassScopeFunctionSpecializationDecl node. 9091 if (isDependentClassScopeExplicitSpecialization) { 9092 ClassScopeFunctionSpecializationDecl *NewSpec = 9093 ClassScopeFunctionSpecializationDecl::Create( 9094 Context, CurContext, SourceLocation(), 9095 cast<CXXMethodDecl>(NewFD), 9096 HasExplicitTemplateArgs, TemplateArgs); 9097 CurContext->addDecl(NewSpec); 9098 AddToScope = false; 9099 } 9100 9101 return NewFD; 9102 } 9103 9104 /// \brief Checks if the new declaration declared in dependent context must be 9105 /// put in the same redeclaration chain as the specified declaration. 9106 /// 9107 /// \param D Declaration that is checked. 9108 /// \param PrevDecl Previous declaration found with proper lookup method for the 9109 /// same declaration name. 9110 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9111 /// belongs to. 9112 /// 9113 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9114 // Any declarations should be put into redeclaration chains except for 9115 // friend declaration in a dependent context that names a function in 9116 // namespace scope. 9117 // 9118 // This allows to compile code like: 9119 // 9120 // void func(); 9121 // template<typename T> class C1 { friend void func() { } }; 9122 // template<typename T> class C2 { friend void func() { } }; 9123 // 9124 // This code snippet is a valid code unless both templates are instantiated. 9125 return !(D->getLexicalDeclContext()->isDependentContext() && 9126 D->getDeclContext()->isFileContext() && 9127 D->getFriendObjectKind() != Decl::FOK_None); 9128 } 9129 9130 /// \brief Perform semantic checking of a new function declaration. 9131 /// 9132 /// Performs semantic analysis of the new function declaration 9133 /// NewFD. This routine performs all semantic checking that does not 9134 /// require the actual declarator involved in the declaration, and is 9135 /// used both for the declaration of functions as they are parsed 9136 /// (called via ActOnDeclarator) and for the declaration of functions 9137 /// that have been instantiated via C++ template instantiation (called 9138 /// via InstantiateDecl). 9139 /// 9140 /// \param IsMemberSpecialization whether this new function declaration is 9141 /// a member specialization (that replaces any definition provided by the 9142 /// previous declaration). 9143 /// 9144 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9145 /// 9146 /// \returns true if the function declaration is a redeclaration. 9147 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9148 LookupResult &Previous, 9149 bool IsMemberSpecialization) { 9150 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9151 "Variably modified return types are not handled here"); 9152 9153 // Determine whether the type of this function should be merged with 9154 // a previous visible declaration. This never happens for functions in C++, 9155 // and always happens in C if the previous declaration was visible. 9156 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9157 !Previous.isShadowed(); 9158 9159 bool Redeclaration = false; 9160 NamedDecl *OldDecl = nullptr; 9161 9162 // Merge or overload the declaration with an existing declaration of 9163 // the same name, if appropriate. 9164 if (!Previous.empty()) { 9165 // Determine whether NewFD is an overload of PrevDecl or 9166 // a declaration that requires merging. If it's an overload, 9167 // there's no more work to do here; we'll just add the new 9168 // function to the scope. 9169 if (!AllowOverloadingOfFunction(Previous, Context)) { 9170 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9171 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9172 Redeclaration = true; 9173 OldDecl = Candidate; 9174 } 9175 } else { 9176 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9177 /*NewIsUsingDecl*/ false)) { 9178 case Ovl_Match: 9179 Redeclaration = true; 9180 break; 9181 9182 case Ovl_NonFunction: 9183 Redeclaration = true; 9184 break; 9185 9186 case Ovl_Overload: 9187 Redeclaration = false; 9188 break; 9189 } 9190 9191 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 9192 // If a function name is overloadable in C, then every function 9193 // with that name must be marked "overloadable". 9194 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 9195 << Redeclaration << NewFD; 9196 NamedDecl *OverloadedDecl = 9197 Redeclaration ? OldDecl : Previous.getRepresentativeDecl(); 9198 Diag(OverloadedDecl->getLocation(), 9199 diag::note_attribute_overloadable_prev_overload); 9200 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9201 } 9202 } 9203 } 9204 9205 // Check for a previous extern "C" declaration with this name. 9206 if (!Redeclaration && 9207 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9208 if (!Previous.empty()) { 9209 // This is an extern "C" declaration with the same name as a previous 9210 // declaration, and thus redeclares that entity... 9211 Redeclaration = true; 9212 OldDecl = Previous.getFoundDecl(); 9213 MergeTypeWithPrevious = false; 9214 9215 // ... except in the presence of __attribute__((overloadable)). 9216 if (OldDecl->hasAttr<OverloadableAttr>()) { 9217 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 9218 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 9219 << Redeclaration << NewFD; 9220 Diag(Previous.getFoundDecl()->getLocation(), 9221 diag::note_attribute_overloadable_prev_overload); 9222 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9223 } 9224 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9225 Redeclaration = false; 9226 OldDecl = nullptr; 9227 } 9228 } 9229 } 9230 } 9231 9232 // C++11 [dcl.constexpr]p8: 9233 // A constexpr specifier for a non-static member function that is not 9234 // a constructor declares that member function to be const. 9235 // 9236 // This needs to be delayed until we know whether this is an out-of-line 9237 // definition of a static member function. 9238 // 9239 // This rule is not present in C++1y, so we produce a backwards 9240 // compatibility warning whenever it happens in C++11. 9241 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9242 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9243 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9244 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9245 CXXMethodDecl *OldMD = nullptr; 9246 if (OldDecl) 9247 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9248 if (!OldMD || !OldMD->isStatic()) { 9249 const FunctionProtoType *FPT = 9250 MD->getType()->castAs<FunctionProtoType>(); 9251 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9252 EPI.TypeQuals |= Qualifiers::Const; 9253 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9254 FPT->getParamTypes(), EPI)); 9255 9256 // Warn that we did this, if we're not performing template instantiation. 9257 // In that case, we'll have warned already when the template was defined. 9258 if (!inTemplateInstantiation()) { 9259 SourceLocation AddConstLoc; 9260 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9261 .IgnoreParens().getAs<FunctionTypeLoc>()) 9262 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9263 9264 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9265 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9266 } 9267 } 9268 } 9269 9270 if (Redeclaration) { 9271 // NewFD and OldDecl represent declarations that need to be 9272 // merged. 9273 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9274 NewFD->setInvalidDecl(); 9275 return Redeclaration; 9276 } 9277 9278 Previous.clear(); 9279 Previous.addDecl(OldDecl); 9280 9281 if (FunctionTemplateDecl *OldTemplateDecl 9282 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9283 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9284 FunctionTemplateDecl *NewTemplateDecl 9285 = NewFD->getDescribedFunctionTemplate(); 9286 assert(NewTemplateDecl && "Template/non-template mismatch"); 9287 if (CXXMethodDecl *Method 9288 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9289 Method->setAccess(OldTemplateDecl->getAccess()); 9290 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9291 } 9292 9293 // If this is an explicit specialization of a member that is a function 9294 // template, mark it as a member specialization. 9295 if (IsMemberSpecialization && 9296 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9297 NewTemplateDecl->setMemberSpecialization(); 9298 assert(OldTemplateDecl->isMemberSpecialization()); 9299 // Explicit specializations of a member template do not inherit deleted 9300 // status from the parent member template that they are specializing. 9301 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9302 FunctionDecl *const OldTemplatedDecl = 9303 OldTemplateDecl->getTemplatedDecl(); 9304 // FIXME: This assert will not hold in the presence of modules. 9305 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9306 // FIXME: We need an update record for this AST mutation. 9307 OldTemplatedDecl->setDeletedAsWritten(false); 9308 } 9309 } 9310 9311 } else { 9312 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9313 // This needs to happen first so that 'inline' propagates. 9314 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9315 if (isa<CXXMethodDecl>(NewFD)) 9316 NewFD->setAccess(OldDecl->getAccess()); 9317 } 9318 } 9319 } 9320 9321 // Semantic checking for this function declaration (in isolation). 9322 9323 if (getLangOpts().CPlusPlus) { 9324 // C++-specific checks. 9325 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9326 CheckConstructor(Constructor); 9327 } else if (CXXDestructorDecl *Destructor = 9328 dyn_cast<CXXDestructorDecl>(NewFD)) { 9329 CXXRecordDecl *Record = Destructor->getParent(); 9330 QualType ClassType = Context.getTypeDeclType(Record); 9331 9332 // FIXME: Shouldn't we be able to perform this check even when the class 9333 // type is dependent? Both gcc and edg can handle that. 9334 if (!ClassType->isDependentType()) { 9335 DeclarationName Name 9336 = Context.DeclarationNames.getCXXDestructorName( 9337 Context.getCanonicalType(ClassType)); 9338 if (NewFD->getDeclName() != Name) { 9339 Diag(NewFD->getLocation(), diag::err_destructor_name); 9340 NewFD->setInvalidDecl(); 9341 return Redeclaration; 9342 } 9343 } 9344 } else if (CXXConversionDecl *Conversion 9345 = dyn_cast<CXXConversionDecl>(NewFD)) { 9346 ActOnConversionDeclarator(Conversion); 9347 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9348 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9349 CheckDeductionGuideTemplate(TD); 9350 9351 // A deduction guide is not on the list of entities that can be 9352 // explicitly specialized. 9353 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9354 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9355 << /*explicit specialization*/ 1; 9356 } 9357 9358 // Find any virtual functions that this function overrides. 9359 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9360 if (!Method->isFunctionTemplateSpecialization() && 9361 !Method->getDescribedFunctionTemplate() && 9362 Method->isCanonicalDecl()) { 9363 if (AddOverriddenMethods(Method->getParent(), Method)) { 9364 // If the function was marked as "static", we have a problem. 9365 if (NewFD->getStorageClass() == SC_Static) { 9366 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9367 } 9368 } 9369 } 9370 9371 if (Method->isStatic()) 9372 checkThisInStaticMemberFunctionType(Method); 9373 } 9374 9375 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9376 if (NewFD->isOverloadedOperator() && 9377 CheckOverloadedOperatorDeclaration(NewFD)) { 9378 NewFD->setInvalidDecl(); 9379 return Redeclaration; 9380 } 9381 9382 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9383 if (NewFD->getLiteralIdentifier() && 9384 CheckLiteralOperatorDeclaration(NewFD)) { 9385 NewFD->setInvalidDecl(); 9386 return Redeclaration; 9387 } 9388 9389 // In C++, check default arguments now that we have merged decls. Unless 9390 // the lexical context is the class, because in this case this is done 9391 // during delayed parsing anyway. 9392 if (!CurContext->isRecord()) 9393 CheckCXXDefaultArguments(NewFD); 9394 9395 // If this function declares a builtin function, check the type of this 9396 // declaration against the expected type for the builtin. 9397 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9398 ASTContext::GetBuiltinTypeError Error; 9399 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9400 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9401 // If the type of the builtin differs only in its exception 9402 // specification, that's OK. 9403 // FIXME: If the types do differ in this way, it would be better to 9404 // retain the 'noexcept' form of the type. 9405 if (!T.isNull() && 9406 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9407 NewFD->getType())) 9408 // The type of this function differs from the type of the builtin, 9409 // so forget about the builtin entirely. 9410 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9411 } 9412 9413 // If this function is declared as being extern "C", then check to see if 9414 // the function returns a UDT (class, struct, or union type) that is not C 9415 // compatible, and if it does, warn the user. 9416 // But, issue any diagnostic on the first declaration only. 9417 if (Previous.empty() && NewFD->isExternC()) { 9418 QualType R = NewFD->getReturnType(); 9419 if (R->isIncompleteType() && !R->isVoidType()) 9420 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9421 << NewFD << R; 9422 else if (!R.isPODType(Context) && !R->isVoidType() && 9423 !R->isObjCObjectPointerType()) 9424 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9425 } 9426 9427 // C++1z [dcl.fct]p6: 9428 // [...] whether the function has a non-throwing exception-specification 9429 // [is] part of the function type 9430 // 9431 // This results in an ABI break between C++14 and C++17 for functions whose 9432 // declared type includes an exception-specification in a parameter or 9433 // return type. (Exception specifications on the function itself are OK in 9434 // most cases, and exception specifications are not permitted in most other 9435 // contexts where they could make it into a mangling.) 9436 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9437 auto HasNoexcept = [&](QualType T) -> bool { 9438 // Strip off declarator chunks that could be between us and a function 9439 // type. We don't need to look far, exception specifications are very 9440 // restricted prior to C++17. 9441 if (auto *RT = T->getAs<ReferenceType>()) 9442 T = RT->getPointeeType(); 9443 else if (T->isAnyPointerType()) 9444 T = T->getPointeeType(); 9445 else if (auto *MPT = T->getAs<MemberPointerType>()) 9446 T = MPT->getPointeeType(); 9447 if (auto *FPT = T->getAs<FunctionProtoType>()) 9448 if (FPT->isNothrow(Context)) 9449 return true; 9450 return false; 9451 }; 9452 9453 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9454 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9455 for (QualType T : FPT->param_types()) 9456 AnyNoexcept |= HasNoexcept(T); 9457 if (AnyNoexcept) 9458 Diag(NewFD->getLocation(), 9459 diag::warn_cxx1z_compat_exception_spec_in_signature) 9460 << NewFD; 9461 } 9462 9463 if (!Redeclaration && LangOpts.CUDA) 9464 checkCUDATargetOverload(NewFD, Previous); 9465 } 9466 return Redeclaration; 9467 } 9468 9469 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9470 // C++11 [basic.start.main]p3: 9471 // A program that [...] declares main to be inline, static or 9472 // constexpr is ill-formed. 9473 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9474 // appear in a declaration of main. 9475 // static main is not an error under C99, but we should warn about it. 9476 // We accept _Noreturn main as an extension. 9477 if (FD->getStorageClass() == SC_Static) 9478 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9479 ? diag::err_static_main : diag::warn_static_main) 9480 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9481 if (FD->isInlineSpecified()) 9482 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9483 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9484 if (DS.isNoreturnSpecified()) { 9485 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9486 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9487 Diag(NoreturnLoc, diag::ext_noreturn_main); 9488 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9489 << FixItHint::CreateRemoval(NoreturnRange); 9490 } 9491 if (FD->isConstexpr()) { 9492 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9493 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9494 FD->setConstexpr(false); 9495 } 9496 9497 if (getLangOpts().OpenCL) { 9498 Diag(FD->getLocation(), diag::err_opencl_no_main) 9499 << FD->hasAttr<OpenCLKernelAttr>(); 9500 FD->setInvalidDecl(); 9501 return; 9502 } 9503 9504 QualType T = FD->getType(); 9505 assert(T->isFunctionType() && "function decl is not of function type"); 9506 const FunctionType* FT = T->castAs<FunctionType>(); 9507 9508 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9509 // In C with GNU extensions we allow main() to have non-integer return 9510 // type, but we should warn about the extension, and we disable the 9511 // implicit-return-zero rule. 9512 9513 // GCC in C mode accepts qualified 'int'. 9514 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9515 FD->setHasImplicitReturnZero(true); 9516 else { 9517 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9518 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9519 if (RTRange.isValid()) 9520 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9521 << FixItHint::CreateReplacement(RTRange, "int"); 9522 } 9523 } else { 9524 // In C and C++, main magically returns 0 if you fall off the end; 9525 // set the flag which tells us that. 9526 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9527 9528 // All the standards say that main() should return 'int'. 9529 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9530 FD->setHasImplicitReturnZero(true); 9531 else { 9532 // Otherwise, this is just a flat-out error. 9533 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9534 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9535 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9536 : FixItHint()); 9537 FD->setInvalidDecl(true); 9538 } 9539 } 9540 9541 // Treat protoless main() as nullary. 9542 if (isa<FunctionNoProtoType>(FT)) return; 9543 9544 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9545 unsigned nparams = FTP->getNumParams(); 9546 assert(FD->getNumParams() == nparams); 9547 9548 bool HasExtraParameters = (nparams > 3); 9549 9550 if (FTP->isVariadic()) { 9551 Diag(FD->getLocation(), diag::ext_variadic_main); 9552 // FIXME: if we had information about the location of the ellipsis, we 9553 // could add a FixIt hint to remove it as a parameter. 9554 } 9555 9556 // Darwin passes an undocumented fourth argument of type char**. If 9557 // other platforms start sprouting these, the logic below will start 9558 // getting shifty. 9559 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9560 HasExtraParameters = false; 9561 9562 if (HasExtraParameters) { 9563 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9564 FD->setInvalidDecl(true); 9565 nparams = 3; 9566 } 9567 9568 // FIXME: a lot of the following diagnostics would be improved 9569 // if we had some location information about types. 9570 9571 QualType CharPP = 9572 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9573 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9574 9575 for (unsigned i = 0; i < nparams; ++i) { 9576 QualType AT = FTP->getParamType(i); 9577 9578 bool mismatch = true; 9579 9580 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9581 mismatch = false; 9582 else if (Expected[i] == CharPP) { 9583 // As an extension, the following forms are okay: 9584 // char const ** 9585 // char const * const * 9586 // char * const * 9587 9588 QualifierCollector qs; 9589 const PointerType* PT; 9590 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9591 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9592 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9593 Context.CharTy)) { 9594 qs.removeConst(); 9595 mismatch = !qs.empty(); 9596 } 9597 } 9598 9599 if (mismatch) { 9600 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9601 // TODO: suggest replacing given type with expected type 9602 FD->setInvalidDecl(true); 9603 } 9604 } 9605 9606 if (nparams == 1 && !FD->isInvalidDecl()) { 9607 Diag(FD->getLocation(), diag::warn_main_one_arg); 9608 } 9609 9610 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9611 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9612 FD->setInvalidDecl(); 9613 } 9614 } 9615 9616 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9617 QualType T = FD->getType(); 9618 assert(T->isFunctionType() && "function decl is not of function type"); 9619 const FunctionType *FT = T->castAs<FunctionType>(); 9620 9621 // Set an implicit return of 'zero' if the function can return some integral, 9622 // enumeration, pointer or nullptr type. 9623 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9624 FT->getReturnType()->isAnyPointerType() || 9625 FT->getReturnType()->isNullPtrType()) 9626 // DllMain is exempt because a return value of zero means it failed. 9627 if (FD->getName() != "DllMain") 9628 FD->setHasImplicitReturnZero(true); 9629 9630 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9631 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9632 FD->setInvalidDecl(); 9633 } 9634 } 9635 9636 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9637 // FIXME: Need strict checking. In C89, we need to check for 9638 // any assignment, increment, decrement, function-calls, or 9639 // commas outside of a sizeof. In C99, it's the same list, 9640 // except that the aforementioned are allowed in unevaluated 9641 // expressions. Everything else falls under the 9642 // "may accept other forms of constant expressions" exception. 9643 // (We never end up here for C++, so the constant expression 9644 // rules there don't matter.) 9645 const Expr *Culprit; 9646 if (Init->isConstantInitializer(Context, false, &Culprit)) 9647 return false; 9648 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9649 << Culprit->getSourceRange(); 9650 return true; 9651 } 9652 9653 namespace { 9654 // Visits an initialization expression to see if OrigDecl is evaluated in 9655 // its own initialization and throws a warning if it does. 9656 class SelfReferenceChecker 9657 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9658 Sema &S; 9659 Decl *OrigDecl; 9660 bool isRecordType; 9661 bool isPODType; 9662 bool isReferenceType; 9663 9664 bool isInitList; 9665 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9666 9667 public: 9668 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9669 9670 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9671 S(S), OrigDecl(OrigDecl) { 9672 isPODType = false; 9673 isRecordType = false; 9674 isReferenceType = false; 9675 isInitList = false; 9676 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9677 isPODType = VD->getType().isPODType(S.Context); 9678 isRecordType = VD->getType()->isRecordType(); 9679 isReferenceType = VD->getType()->isReferenceType(); 9680 } 9681 } 9682 9683 // For most expressions, just call the visitor. For initializer lists, 9684 // track the index of the field being initialized since fields are 9685 // initialized in order allowing use of previously initialized fields. 9686 void CheckExpr(Expr *E) { 9687 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9688 if (!InitList) { 9689 Visit(E); 9690 return; 9691 } 9692 9693 // Track and increment the index here. 9694 isInitList = true; 9695 InitFieldIndex.push_back(0); 9696 for (auto Child : InitList->children()) { 9697 CheckExpr(cast<Expr>(Child)); 9698 ++InitFieldIndex.back(); 9699 } 9700 InitFieldIndex.pop_back(); 9701 } 9702 9703 // Returns true if MemberExpr is checked and no further checking is needed. 9704 // Returns false if additional checking is required. 9705 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9706 llvm::SmallVector<FieldDecl*, 4> Fields; 9707 Expr *Base = E; 9708 bool ReferenceField = false; 9709 9710 // Get the field memebers used. 9711 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9712 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9713 if (!FD) 9714 return false; 9715 Fields.push_back(FD); 9716 if (FD->getType()->isReferenceType()) 9717 ReferenceField = true; 9718 Base = ME->getBase()->IgnoreParenImpCasts(); 9719 } 9720 9721 // Keep checking only if the base Decl is the same. 9722 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9723 if (!DRE || DRE->getDecl() != OrigDecl) 9724 return false; 9725 9726 // A reference field can be bound to an unininitialized field. 9727 if (CheckReference && !ReferenceField) 9728 return true; 9729 9730 // Convert FieldDecls to their index number. 9731 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9732 for (const FieldDecl *I : llvm::reverse(Fields)) 9733 UsedFieldIndex.push_back(I->getFieldIndex()); 9734 9735 // See if a warning is needed by checking the first difference in index 9736 // numbers. If field being used has index less than the field being 9737 // initialized, then the use is safe. 9738 for (auto UsedIter = UsedFieldIndex.begin(), 9739 UsedEnd = UsedFieldIndex.end(), 9740 OrigIter = InitFieldIndex.begin(), 9741 OrigEnd = InitFieldIndex.end(); 9742 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9743 if (*UsedIter < *OrigIter) 9744 return true; 9745 if (*UsedIter > *OrigIter) 9746 break; 9747 } 9748 9749 // TODO: Add a different warning which will print the field names. 9750 HandleDeclRefExpr(DRE); 9751 return true; 9752 } 9753 9754 // For most expressions, the cast is directly above the DeclRefExpr. 9755 // For conditional operators, the cast can be outside the conditional 9756 // operator if both expressions are DeclRefExpr's. 9757 void HandleValue(Expr *E) { 9758 E = E->IgnoreParens(); 9759 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9760 HandleDeclRefExpr(DRE); 9761 return; 9762 } 9763 9764 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9765 Visit(CO->getCond()); 9766 HandleValue(CO->getTrueExpr()); 9767 HandleValue(CO->getFalseExpr()); 9768 return; 9769 } 9770 9771 if (BinaryConditionalOperator *BCO = 9772 dyn_cast<BinaryConditionalOperator>(E)) { 9773 Visit(BCO->getCond()); 9774 HandleValue(BCO->getFalseExpr()); 9775 return; 9776 } 9777 9778 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9779 HandleValue(OVE->getSourceExpr()); 9780 return; 9781 } 9782 9783 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9784 if (BO->getOpcode() == BO_Comma) { 9785 Visit(BO->getLHS()); 9786 HandleValue(BO->getRHS()); 9787 return; 9788 } 9789 } 9790 9791 if (isa<MemberExpr>(E)) { 9792 if (isInitList) { 9793 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9794 false /*CheckReference*/)) 9795 return; 9796 } 9797 9798 Expr *Base = E->IgnoreParenImpCasts(); 9799 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9800 // Check for static member variables and don't warn on them. 9801 if (!isa<FieldDecl>(ME->getMemberDecl())) 9802 return; 9803 Base = ME->getBase()->IgnoreParenImpCasts(); 9804 } 9805 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9806 HandleDeclRefExpr(DRE); 9807 return; 9808 } 9809 9810 Visit(E); 9811 } 9812 9813 // Reference types not handled in HandleValue are handled here since all 9814 // uses of references are bad, not just r-value uses. 9815 void VisitDeclRefExpr(DeclRefExpr *E) { 9816 if (isReferenceType) 9817 HandleDeclRefExpr(E); 9818 } 9819 9820 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9821 if (E->getCastKind() == CK_LValueToRValue) { 9822 HandleValue(E->getSubExpr()); 9823 return; 9824 } 9825 9826 Inherited::VisitImplicitCastExpr(E); 9827 } 9828 9829 void VisitMemberExpr(MemberExpr *E) { 9830 if (isInitList) { 9831 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9832 return; 9833 } 9834 9835 // Don't warn on arrays since they can be treated as pointers. 9836 if (E->getType()->canDecayToPointerType()) return; 9837 9838 // Warn when a non-static method call is followed by non-static member 9839 // field accesses, which is followed by a DeclRefExpr. 9840 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 9841 bool Warn = (MD && !MD->isStatic()); 9842 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 9843 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9844 if (!isa<FieldDecl>(ME->getMemberDecl())) 9845 Warn = false; 9846 Base = ME->getBase()->IgnoreParenImpCasts(); 9847 } 9848 9849 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 9850 if (Warn) 9851 HandleDeclRefExpr(DRE); 9852 return; 9853 } 9854 9855 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 9856 // Visit that expression. 9857 Visit(Base); 9858 } 9859 9860 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 9861 Expr *Callee = E->getCallee(); 9862 9863 if (isa<UnresolvedLookupExpr>(Callee)) 9864 return Inherited::VisitCXXOperatorCallExpr(E); 9865 9866 Visit(Callee); 9867 for (auto Arg: E->arguments()) 9868 HandleValue(Arg->IgnoreParenImpCasts()); 9869 } 9870 9871 void VisitUnaryOperator(UnaryOperator *E) { 9872 // For POD record types, addresses of its own members are well-defined. 9873 if (E->getOpcode() == UO_AddrOf && isRecordType && 9874 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 9875 if (!isPODType) 9876 HandleValue(E->getSubExpr()); 9877 return; 9878 } 9879 9880 if (E->isIncrementDecrementOp()) { 9881 HandleValue(E->getSubExpr()); 9882 return; 9883 } 9884 9885 Inherited::VisitUnaryOperator(E); 9886 } 9887 9888 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 9889 9890 void VisitCXXConstructExpr(CXXConstructExpr *E) { 9891 if (E->getConstructor()->isCopyConstructor()) { 9892 Expr *ArgExpr = E->getArg(0); 9893 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 9894 if (ILE->getNumInits() == 1) 9895 ArgExpr = ILE->getInit(0); 9896 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 9897 if (ICE->getCastKind() == CK_NoOp) 9898 ArgExpr = ICE->getSubExpr(); 9899 HandleValue(ArgExpr); 9900 return; 9901 } 9902 Inherited::VisitCXXConstructExpr(E); 9903 } 9904 9905 void VisitCallExpr(CallExpr *E) { 9906 // Treat std::move as a use. 9907 if (E->getNumArgs() == 1) { 9908 if (FunctionDecl *FD = E->getDirectCallee()) { 9909 if (FD->isInStdNamespace() && FD->getIdentifier() && 9910 FD->getIdentifier()->isStr("move")) { 9911 HandleValue(E->getArg(0)); 9912 return; 9913 } 9914 } 9915 } 9916 9917 Inherited::VisitCallExpr(E); 9918 } 9919 9920 void VisitBinaryOperator(BinaryOperator *E) { 9921 if (E->isCompoundAssignmentOp()) { 9922 HandleValue(E->getLHS()); 9923 Visit(E->getRHS()); 9924 return; 9925 } 9926 9927 Inherited::VisitBinaryOperator(E); 9928 } 9929 9930 // A custom visitor for BinaryConditionalOperator is needed because the 9931 // regular visitor would check the condition and true expression separately 9932 // but both point to the same place giving duplicate diagnostics. 9933 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 9934 Visit(E->getCond()); 9935 Visit(E->getFalseExpr()); 9936 } 9937 9938 void HandleDeclRefExpr(DeclRefExpr *DRE) { 9939 Decl* ReferenceDecl = DRE->getDecl(); 9940 if (OrigDecl != ReferenceDecl) return; 9941 unsigned diag; 9942 if (isReferenceType) { 9943 diag = diag::warn_uninit_self_reference_in_reference_init; 9944 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 9945 diag = diag::warn_static_self_reference_in_init; 9946 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 9947 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 9948 DRE->getDecl()->getType()->isRecordType()) { 9949 diag = diag::warn_uninit_self_reference_in_init; 9950 } else { 9951 // Local variables will be handled by the CFG analysis. 9952 return; 9953 } 9954 9955 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 9956 S.PDiag(diag) 9957 << DRE->getNameInfo().getName() 9958 << OrigDecl->getLocation() 9959 << DRE->getSourceRange()); 9960 } 9961 }; 9962 9963 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9964 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9965 bool DirectInit) { 9966 // Parameters arguments are occassionially constructed with itself, 9967 // for instance, in recursive functions. Skip them. 9968 if (isa<ParmVarDecl>(OrigDecl)) 9969 return; 9970 9971 E = E->IgnoreParens(); 9972 9973 // Skip checking T a = a where T is not a record or reference type. 9974 // Doing so is a way to silence uninitialized warnings. 9975 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9976 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9977 if (ICE->getCastKind() == CK_LValueToRValue) 9978 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9979 if (DRE->getDecl() == OrigDecl) 9980 return; 9981 9982 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9983 } 9984 } // end anonymous namespace 9985 9986 namespace { 9987 // Simple wrapper to add the name of a variable or (if no variable is 9988 // available) a DeclarationName into a diagnostic. 9989 struct VarDeclOrName { 9990 VarDecl *VDecl; 9991 DeclarationName Name; 9992 9993 friend const Sema::SemaDiagnosticBuilder & 9994 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 9995 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 9996 } 9997 }; 9998 } // end anonymous namespace 9999 10000 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10001 DeclarationName Name, QualType Type, 10002 TypeSourceInfo *TSI, 10003 SourceRange Range, bool DirectInit, 10004 Expr *Init) { 10005 bool IsInitCapture = !VDecl; 10006 assert((!VDecl || !VDecl->isInitCapture()) && 10007 "init captures are expected to be deduced prior to initialization"); 10008 10009 VarDeclOrName VN{VDecl, Name}; 10010 10011 DeducedType *Deduced = Type->getContainedDeducedType(); 10012 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10013 10014 // C++11 [dcl.spec.auto]p3 10015 if (!Init) { 10016 assert(VDecl && "no init for init capture deduction?"); 10017 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10018 << VDecl->getDeclName() << Type; 10019 return QualType(); 10020 } 10021 10022 ArrayRef<Expr*> DeduceInits = Init; 10023 if (DirectInit) { 10024 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10025 DeduceInits = PL->exprs(); 10026 } 10027 10028 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10029 assert(VDecl && "non-auto type for init capture deduction?"); 10030 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10031 InitializationKind Kind = InitializationKind::CreateForInit( 10032 VDecl->getLocation(), DirectInit, Init); 10033 // FIXME: Initialization should not be taking a mutable list of inits. 10034 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10035 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10036 InitsCopy); 10037 } 10038 10039 if (DirectInit) { 10040 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10041 DeduceInits = IL->inits(); 10042 } 10043 10044 // Deduction only works if we have exactly one source expression. 10045 if (DeduceInits.empty()) { 10046 // It isn't possible to write this directly, but it is possible to 10047 // end up in this situation with "auto x(some_pack...);" 10048 Diag(Init->getLocStart(), IsInitCapture 10049 ? diag::err_init_capture_no_expression 10050 : diag::err_auto_var_init_no_expression) 10051 << VN << Type << Range; 10052 return QualType(); 10053 } 10054 10055 if (DeduceInits.size() > 1) { 10056 Diag(DeduceInits[1]->getLocStart(), 10057 IsInitCapture ? diag::err_init_capture_multiple_expressions 10058 : diag::err_auto_var_init_multiple_expressions) 10059 << VN << Type << Range; 10060 return QualType(); 10061 } 10062 10063 Expr *DeduceInit = DeduceInits[0]; 10064 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10065 Diag(Init->getLocStart(), IsInitCapture 10066 ? diag::err_init_capture_paren_braces 10067 : diag::err_auto_var_init_paren_braces) 10068 << isa<InitListExpr>(Init) << VN << Type << Range; 10069 return QualType(); 10070 } 10071 10072 // Expressions default to 'id' when we're in a debugger. 10073 bool DefaultedAnyToId = false; 10074 if (getLangOpts().DebuggerCastResultToId && 10075 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10076 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10077 if (Result.isInvalid()) { 10078 return QualType(); 10079 } 10080 Init = Result.get(); 10081 DefaultedAnyToId = true; 10082 } 10083 10084 // C++ [dcl.decomp]p1: 10085 // If the assignment-expression [...] has array type A and no ref-qualifier 10086 // is present, e has type cv A 10087 if (VDecl && isa<DecompositionDecl>(VDecl) && 10088 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10089 DeduceInit->getType()->isConstantArrayType()) 10090 return Context.getQualifiedType(DeduceInit->getType(), 10091 Type.getQualifiers()); 10092 10093 QualType DeducedType; 10094 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10095 if (!IsInitCapture) 10096 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10097 else if (isa<InitListExpr>(Init)) 10098 Diag(Range.getBegin(), 10099 diag::err_init_capture_deduction_failure_from_init_list) 10100 << VN 10101 << (DeduceInit->getType().isNull() ? TSI->getType() 10102 : DeduceInit->getType()) 10103 << DeduceInit->getSourceRange(); 10104 else 10105 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10106 << VN << TSI->getType() 10107 << (DeduceInit->getType().isNull() ? TSI->getType() 10108 : DeduceInit->getType()) 10109 << DeduceInit->getSourceRange(); 10110 } 10111 10112 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10113 // 'id' instead of a specific object type prevents most of our usual 10114 // checks. 10115 // We only want to warn outside of template instantiations, though: 10116 // inside a template, the 'id' could have come from a parameter. 10117 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10118 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10119 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10120 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10121 } 10122 10123 return DeducedType; 10124 } 10125 10126 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10127 Expr *Init) { 10128 QualType DeducedType = deduceVarTypeFromInitializer( 10129 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10130 VDecl->getSourceRange(), DirectInit, Init); 10131 if (DeducedType.isNull()) { 10132 VDecl->setInvalidDecl(); 10133 return true; 10134 } 10135 10136 VDecl->setType(DeducedType); 10137 assert(VDecl->isLinkageValid()); 10138 10139 // In ARC, infer lifetime. 10140 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10141 VDecl->setInvalidDecl(); 10142 10143 // If this is a redeclaration, check that the type we just deduced matches 10144 // the previously declared type. 10145 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10146 // We never need to merge the type, because we cannot form an incomplete 10147 // array of auto, nor deduce such a type. 10148 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10149 } 10150 10151 // Check the deduced type is valid for a variable declaration. 10152 CheckVariableDeclarationType(VDecl); 10153 return VDecl->isInvalidDecl(); 10154 } 10155 10156 /// AddInitializerToDecl - Adds the initializer Init to the 10157 /// declaration dcl. If DirectInit is true, this is C++ direct 10158 /// initialization rather than copy initialization. 10159 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10160 // If there is no declaration, there was an error parsing it. Just ignore 10161 // the initializer. 10162 if (!RealDecl || RealDecl->isInvalidDecl()) { 10163 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10164 return; 10165 } 10166 10167 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10168 // Pure-specifiers are handled in ActOnPureSpecifier. 10169 Diag(Method->getLocation(), diag::err_member_function_initialization) 10170 << Method->getDeclName() << Init->getSourceRange(); 10171 Method->setInvalidDecl(); 10172 return; 10173 } 10174 10175 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10176 if (!VDecl) { 10177 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10178 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10179 RealDecl->setInvalidDecl(); 10180 return; 10181 } 10182 10183 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10184 if (VDecl->getType()->isUndeducedType()) { 10185 // Attempt typo correction early so that the type of the init expression can 10186 // be deduced based on the chosen correction if the original init contains a 10187 // TypoExpr. 10188 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10189 if (!Res.isUsable()) { 10190 RealDecl->setInvalidDecl(); 10191 return; 10192 } 10193 Init = Res.get(); 10194 10195 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10196 return; 10197 } 10198 10199 // dllimport cannot be used on variable definitions. 10200 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10201 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10202 VDecl->setInvalidDecl(); 10203 return; 10204 } 10205 10206 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10207 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10208 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10209 VDecl->setInvalidDecl(); 10210 return; 10211 } 10212 10213 if (!VDecl->getType()->isDependentType()) { 10214 // A definition must end up with a complete type, which means it must be 10215 // complete with the restriction that an array type might be completed by 10216 // the initializer; note that later code assumes this restriction. 10217 QualType BaseDeclType = VDecl->getType(); 10218 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10219 BaseDeclType = Array->getElementType(); 10220 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10221 diag::err_typecheck_decl_incomplete_type)) { 10222 RealDecl->setInvalidDecl(); 10223 return; 10224 } 10225 10226 // The variable can not have an abstract class type. 10227 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10228 diag::err_abstract_type_in_decl, 10229 AbstractVariableType)) 10230 VDecl->setInvalidDecl(); 10231 } 10232 10233 // If adding the initializer will turn this declaration into a definition, 10234 // and we already have a definition for this variable, diagnose or otherwise 10235 // handle the situation. 10236 VarDecl *Def; 10237 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10238 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10239 !VDecl->isThisDeclarationADemotedDefinition() && 10240 checkVarDeclRedefinition(Def, VDecl)) 10241 return; 10242 10243 if (getLangOpts().CPlusPlus) { 10244 // C++ [class.static.data]p4 10245 // If a static data member is of const integral or const 10246 // enumeration type, its declaration in the class definition can 10247 // specify a constant-initializer which shall be an integral 10248 // constant expression (5.19). In that case, the member can appear 10249 // in integral constant expressions. The member shall still be 10250 // defined in a namespace scope if it is used in the program and the 10251 // namespace scope definition shall not contain an initializer. 10252 // 10253 // We already performed a redefinition check above, but for static 10254 // data members we also need to check whether there was an in-class 10255 // declaration with an initializer. 10256 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10257 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10258 << VDecl->getDeclName(); 10259 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10260 diag::note_previous_initializer) 10261 << 0; 10262 return; 10263 } 10264 10265 if (VDecl->hasLocalStorage()) 10266 getCurFunction()->setHasBranchProtectedScope(); 10267 10268 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10269 VDecl->setInvalidDecl(); 10270 return; 10271 } 10272 } 10273 10274 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10275 // a kernel function cannot be initialized." 10276 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10277 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10278 VDecl->setInvalidDecl(); 10279 return; 10280 } 10281 10282 // Get the decls type and save a reference for later, since 10283 // CheckInitializerTypes may change it. 10284 QualType DclT = VDecl->getType(), SavT = DclT; 10285 10286 // Expressions default to 'id' when we're in a debugger 10287 // and we are assigning it to a variable of Objective-C pointer type. 10288 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10289 Init->getType() == Context.UnknownAnyTy) { 10290 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10291 if (Result.isInvalid()) { 10292 VDecl->setInvalidDecl(); 10293 return; 10294 } 10295 Init = Result.get(); 10296 } 10297 10298 // Perform the initialization. 10299 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10300 if (!VDecl->isInvalidDecl()) { 10301 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10302 InitializationKind Kind = InitializationKind::CreateForInit( 10303 VDecl->getLocation(), DirectInit, Init); 10304 10305 MultiExprArg Args = Init; 10306 if (CXXDirectInit) 10307 Args = MultiExprArg(CXXDirectInit->getExprs(), 10308 CXXDirectInit->getNumExprs()); 10309 10310 // Try to correct any TypoExprs in the initialization arguments. 10311 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10312 ExprResult Res = CorrectDelayedTyposInExpr( 10313 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10314 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10315 return Init.Failed() ? ExprError() : E; 10316 }); 10317 if (Res.isInvalid()) { 10318 VDecl->setInvalidDecl(); 10319 } else if (Res.get() != Args[Idx]) { 10320 Args[Idx] = Res.get(); 10321 } 10322 } 10323 if (VDecl->isInvalidDecl()) 10324 return; 10325 10326 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10327 /*TopLevelOfInitList=*/false, 10328 /*TreatUnavailableAsInvalid=*/false); 10329 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10330 if (Result.isInvalid()) { 10331 VDecl->setInvalidDecl(); 10332 return; 10333 } 10334 10335 Init = Result.getAs<Expr>(); 10336 } 10337 10338 // Check for self-references within variable initializers. 10339 // Variables declared within a function/method body (except for references) 10340 // are handled by a dataflow analysis. 10341 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10342 VDecl->getType()->isReferenceType()) { 10343 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10344 } 10345 10346 // If the type changed, it means we had an incomplete type that was 10347 // completed by the initializer. For example: 10348 // int ary[] = { 1, 3, 5 }; 10349 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10350 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10351 VDecl->setType(DclT); 10352 10353 if (!VDecl->isInvalidDecl()) { 10354 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10355 10356 if (VDecl->hasAttr<BlocksAttr>()) 10357 checkRetainCycles(VDecl, Init); 10358 10359 // It is safe to assign a weak reference into a strong variable. 10360 // Although this code can still have problems: 10361 // id x = self.weakProp; 10362 // id y = self.weakProp; 10363 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10364 // paths through the function. This should be revisited if 10365 // -Wrepeated-use-of-weak is made flow-sensitive. 10366 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10367 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10368 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10369 Init->getLocStart())) 10370 getCurFunction()->markSafeWeakUse(Init); 10371 } 10372 10373 // The initialization is usually a full-expression. 10374 // 10375 // FIXME: If this is a braced initialization of an aggregate, it is not 10376 // an expression, and each individual field initializer is a separate 10377 // full-expression. For instance, in: 10378 // 10379 // struct Temp { ~Temp(); }; 10380 // struct S { S(Temp); }; 10381 // struct T { S a, b; } t = { Temp(), Temp() } 10382 // 10383 // we should destroy the first Temp before constructing the second. 10384 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10385 false, 10386 VDecl->isConstexpr()); 10387 if (Result.isInvalid()) { 10388 VDecl->setInvalidDecl(); 10389 return; 10390 } 10391 Init = Result.get(); 10392 10393 // Attach the initializer to the decl. 10394 VDecl->setInit(Init); 10395 10396 if (VDecl->isLocalVarDecl()) { 10397 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10398 // static storage duration shall be constant expressions or string literals. 10399 // C++ does not have this restriction. 10400 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 10401 const Expr *Culprit; 10402 if (VDecl->getStorageClass() == SC_Static) 10403 CheckForConstantInitializer(Init, DclT); 10404 // C89 is stricter than C99 for non-static aggregate types. 10405 // C89 6.5.7p3: All the expressions [...] in an initializer list 10406 // for an object that has aggregate or union type shall be 10407 // constant expressions. 10408 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10409 isa<InitListExpr>(Init) && 10410 !Init->isConstantInitializer(Context, false, &Culprit)) 10411 Diag(Culprit->getExprLoc(), 10412 diag::ext_aggregate_init_not_constant) 10413 << Culprit->getSourceRange(); 10414 } 10415 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10416 VDecl->getLexicalDeclContext()->isRecord()) { 10417 // This is an in-class initialization for a static data member, e.g., 10418 // 10419 // struct S { 10420 // static const int value = 17; 10421 // }; 10422 10423 // C++ [class.mem]p4: 10424 // A member-declarator can contain a constant-initializer only 10425 // if it declares a static member (9.4) of const integral or 10426 // const enumeration type, see 9.4.2. 10427 // 10428 // C++11 [class.static.data]p3: 10429 // If a non-volatile non-inline const static data member is of integral 10430 // or enumeration type, its declaration in the class definition can 10431 // specify a brace-or-equal-initializer in which every initializer-clause 10432 // that is an assignment-expression is a constant expression. A static 10433 // data member of literal type can be declared in the class definition 10434 // with the constexpr specifier; if so, its declaration shall specify a 10435 // brace-or-equal-initializer in which every initializer-clause that is 10436 // an assignment-expression is a constant expression. 10437 10438 // Do nothing on dependent types. 10439 if (DclT->isDependentType()) { 10440 10441 // Allow any 'static constexpr' members, whether or not they are of literal 10442 // type. We separately check that every constexpr variable is of literal 10443 // type. 10444 } else if (VDecl->isConstexpr()) { 10445 10446 // Require constness. 10447 } else if (!DclT.isConstQualified()) { 10448 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10449 << Init->getSourceRange(); 10450 VDecl->setInvalidDecl(); 10451 10452 // We allow integer constant expressions in all cases. 10453 } else if (DclT->isIntegralOrEnumerationType()) { 10454 // Check whether the expression is a constant expression. 10455 SourceLocation Loc; 10456 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10457 // In C++11, a non-constexpr const static data member with an 10458 // in-class initializer cannot be volatile. 10459 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10460 else if (Init->isValueDependent()) 10461 ; // Nothing to check. 10462 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10463 ; // Ok, it's an ICE! 10464 else if (Init->isEvaluatable(Context)) { 10465 // If we can constant fold the initializer through heroics, accept it, 10466 // but report this as a use of an extension for -pedantic. 10467 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10468 << Init->getSourceRange(); 10469 } else { 10470 // Otherwise, this is some crazy unknown case. Report the issue at the 10471 // location provided by the isIntegerConstantExpr failed check. 10472 Diag(Loc, diag::err_in_class_initializer_non_constant) 10473 << Init->getSourceRange(); 10474 VDecl->setInvalidDecl(); 10475 } 10476 10477 // We allow foldable floating-point constants as an extension. 10478 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10479 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10480 // it anyway and provide a fixit to add the 'constexpr'. 10481 if (getLangOpts().CPlusPlus11) { 10482 Diag(VDecl->getLocation(), 10483 diag::ext_in_class_initializer_float_type_cxx11) 10484 << DclT << Init->getSourceRange(); 10485 Diag(VDecl->getLocStart(), 10486 diag::note_in_class_initializer_float_type_cxx11) 10487 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10488 } else { 10489 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10490 << DclT << Init->getSourceRange(); 10491 10492 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10493 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10494 << Init->getSourceRange(); 10495 VDecl->setInvalidDecl(); 10496 } 10497 } 10498 10499 // Suggest adding 'constexpr' in C++11 for literal types. 10500 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10501 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10502 << DclT << Init->getSourceRange() 10503 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10504 VDecl->setConstexpr(true); 10505 10506 } else { 10507 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10508 << DclT << Init->getSourceRange(); 10509 VDecl->setInvalidDecl(); 10510 } 10511 } else if (VDecl->isFileVarDecl()) { 10512 // In C, extern is typically used to avoid tentative definitions when 10513 // declaring variables in headers, but adding an intializer makes it a 10514 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10515 // In C++, extern is often used to give implictly static const variables 10516 // external linkage, so don't warn in that case. If selectany is present, 10517 // this might be header code intended for C and C++ inclusion, so apply the 10518 // C++ rules. 10519 if (VDecl->getStorageClass() == SC_Extern && 10520 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10521 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10522 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10523 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10524 Diag(VDecl->getLocation(), diag::warn_extern_init); 10525 10526 // C99 6.7.8p4. All file scoped initializers need to be constant. 10527 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10528 CheckForConstantInitializer(Init, DclT); 10529 } 10530 10531 // We will represent direct-initialization similarly to copy-initialization: 10532 // int x(1); -as-> int x = 1; 10533 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10534 // 10535 // Clients that want to distinguish between the two forms, can check for 10536 // direct initializer using VarDecl::getInitStyle(). 10537 // A major benefit is that clients that don't particularly care about which 10538 // exactly form was it (like the CodeGen) can handle both cases without 10539 // special case code. 10540 10541 // C++ 8.5p11: 10542 // The form of initialization (using parentheses or '=') is generally 10543 // insignificant, but does matter when the entity being initialized has a 10544 // class type. 10545 if (CXXDirectInit) { 10546 assert(DirectInit && "Call-style initializer must be direct init."); 10547 VDecl->setInitStyle(VarDecl::CallInit); 10548 } else if (DirectInit) { 10549 // This must be list-initialization. No other way is direct-initialization. 10550 VDecl->setInitStyle(VarDecl::ListInit); 10551 } 10552 10553 CheckCompleteVariableDeclaration(VDecl); 10554 } 10555 10556 /// ActOnInitializerError - Given that there was an error parsing an 10557 /// initializer for the given declaration, try to return to some form 10558 /// of sanity. 10559 void Sema::ActOnInitializerError(Decl *D) { 10560 // Our main concern here is re-establishing invariants like "a 10561 // variable's type is either dependent or complete". 10562 if (!D || D->isInvalidDecl()) return; 10563 10564 VarDecl *VD = dyn_cast<VarDecl>(D); 10565 if (!VD) return; 10566 10567 // Bindings are not usable if we can't make sense of the initializer. 10568 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10569 for (auto *BD : DD->bindings()) 10570 BD->setInvalidDecl(); 10571 10572 // Auto types are meaningless if we can't make sense of the initializer. 10573 if (ParsingInitForAutoVars.count(D)) { 10574 D->setInvalidDecl(); 10575 return; 10576 } 10577 10578 QualType Ty = VD->getType(); 10579 if (Ty->isDependentType()) return; 10580 10581 // Require a complete type. 10582 if (RequireCompleteType(VD->getLocation(), 10583 Context.getBaseElementType(Ty), 10584 diag::err_typecheck_decl_incomplete_type)) { 10585 VD->setInvalidDecl(); 10586 return; 10587 } 10588 10589 // Require a non-abstract type. 10590 if (RequireNonAbstractType(VD->getLocation(), Ty, 10591 diag::err_abstract_type_in_decl, 10592 AbstractVariableType)) { 10593 VD->setInvalidDecl(); 10594 return; 10595 } 10596 10597 // Don't bother complaining about constructors or destructors, 10598 // though. 10599 } 10600 10601 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10602 // If there is no declaration, there was an error parsing it. Just ignore it. 10603 if (!RealDecl) 10604 return; 10605 10606 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10607 QualType Type = Var->getType(); 10608 10609 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10610 if (isa<DecompositionDecl>(RealDecl)) { 10611 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10612 Var->setInvalidDecl(); 10613 return; 10614 } 10615 10616 if (Type->isUndeducedType() && 10617 DeduceVariableDeclarationType(Var, false, nullptr)) 10618 return; 10619 10620 // C++11 [class.static.data]p3: A static data member can be declared with 10621 // the constexpr specifier; if so, its declaration shall specify 10622 // a brace-or-equal-initializer. 10623 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10624 // the definition of a variable [...] or the declaration of a static data 10625 // member. 10626 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10627 !Var->isThisDeclarationADemotedDefinition()) { 10628 if (Var->isStaticDataMember()) { 10629 // C++1z removes the relevant rule; the in-class declaration is always 10630 // a definition there. 10631 if (!getLangOpts().CPlusPlus1z) { 10632 Diag(Var->getLocation(), 10633 diag::err_constexpr_static_mem_var_requires_init) 10634 << Var->getDeclName(); 10635 Var->setInvalidDecl(); 10636 return; 10637 } 10638 } else { 10639 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10640 Var->setInvalidDecl(); 10641 return; 10642 } 10643 } 10644 10645 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10646 // definition having the concept specifier is called a variable concept. A 10647 // concept definition refers to [...] a variable concept and its initializer. 10648 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10649 if (VTD->isConcept()) { 10650 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10651 Var->setInvalidDecl(); 10652 return; 10653 } 10654 } 10655 10656 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10657 // be initialized. 10658 if (!Var->isInvalidDecl() && 10659 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10660 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10661 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10662 Var->setInvalidDecl(); 10663 return; 10664 } 10665 10666 switch (Var->isThisDeclarationADefinition()) { 10667 case VarDecl::Definition: 10668 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10669 break; 10670 10671 // We have an out-of-line definition of a static data member 10672 // that has an in-class initializer, so we type-check this like 10673 // a declaration. 10674 // 10675 // Fall through 10676 10677 case VarDecl::DeclarationOnly: 10678 // It's only a declaration. 10679 10680 // Block scope. C99 6.7p7: If an identifier for an object is 10681 // declared with no linkage (C99 6.2.2p6), the type for the 10682 // object shall be complete. 10683 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10684 !Var->hasLinkage() && !Var->isInvalidDecl() && 10685 RequireCompleteType(Var->getLocation(), Type, 10686 diag::err_typecheck_decl_incomplete_type)) 10687 Var->setInvalidDecl(); 10688 10689 // Make sure that the type is not abstract. 10690 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10691 RequireNonAbstractType(Var->getLocation(), Type, 10692 diag::err_abstract_type_in_decl, 10693 AbstractVariableType)) 10694 Var->setInvalidDecl(); 10695 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10696 Var->getStorageClass() == SC_PrivateExtern) { 10697 Diag(Var->getLocation(), diag::warn_private_extern); 10698 Diag(Var->getLocation(), diag::note_private_extern); 10699 } 10700 10701 return; 10702 10703 case VarDecl::TentativeDefinition: 10704 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10705 // object that has file scope without an initializer, and without a 10706 // storage-class specifier or with the storage-class specifier "static", 10707 // constitutes a tentative definition. Note: A tentative definition with 10708 // external linkage is valid (C99 6.2.2p5). 10709 if (!Var->isInvalidDecl()) { 10710 if (const IncompleteArrayType *ArrayT 10711 = Context.getAsIncompleteArrayType(Type)) { 10712 if (RequireCompleteType(Var->getLocation(), 10713 ArrayT->getElementType(), 10714 diag::err_illegal_decl_array_incomplete_type)) 10715 Var->setInvalidDecl(); 10716 } else if (Var->getStorageClass() == SC_Static) { 10717 // C99 6.9.2p3: If the declaration of an identifier for an object is 10718 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10719 // declared type shall not be an incomplete type. 10720 // NOTE: code such as the following 10721 // static struct s; 10722 // struct s { int a; }; 10723 // is accepted by gcc. Hence here we issue a warning instead of 10724 // an error and we do not invalidate the static declaration. 10725 // NOTE: to avoid multiple warnings, only check the first declaration. 10726 if (Var->isFirstDecl()) 10727 RequireCompleteType(Var->getLocation(), Type, 10728 diag::ext_typecheck_decl_incomplete_type); 10729 } 10730 } 10731 10732 // Record the tentative definition; we're done. 10733 if (!Var->isInvalidDecl()) 10734 TentativeDefinitions.push_back(Var); 10735 return; 10736 } 10737 10738 // Provide a specific diagnostic for uninitialized variable 10739 // definitions with incomplete array type. 10740 if (Type->isIncompleteArrayType()) { 10741 Diag(Var->getLocation(), 10742 diag::err_typecheck_incomplete_array_needs_initializer); 10743 Var->setInvalidDecl(); 10744 return; 10745 } 10746 10747 // Provide a specific diagnostic for uninitialized variable 10748 // definitions with reference type. 10749 if (Type->isReferenceType()) { 10750 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10751 << Var->getDeclName() 10752 << SourceRange(Var->getLocation(), Var->getLocation()); 10753 Var->setInvalidDecl(); 10754 return; 10755 } 10756 10757 // Do not attempt to type-check the default initializer for a 10758 // variable with dependent type. 10759 if (Type->isDependentType()) 10760 return; 10761 10762 if (Var->isInvalidDecl()) 10763 return; 10764 10765 if (!Var->hasAttr<AliasAttr>()) { 10766 if (RequireCompleteType(Var->getLocation(), 10767 Context.getBaseElementType(Type), 10768 diag::err_typecheck_decl_incomplete_type)) { 10769 Var->setInvalidDecl(); 10770 return; 10771 } 10772 } else { 10773 return; 10774 } 10775 10776 // The variable can not have an abstract class type. 10777 if (RequireNonAbstractType(Var->getLocation(), Type, 10778 diag::err_abstract_type_in_decl, 10779 AbstractVariableType)) { 10780 Var->setInvalidDecl(); 10781 return; 10782 } 10783 10784 // Check for jumps past the implicit initializer. C++0x 10785 // clarifies that this applies to a "variable with automatic 10786 // storage duration", not a "local variable". 10787 // C++11 [stmt.dcl]p3 10788 // A program that jumps from a point where a variable with automatic 10789 // storage duration is not in scope to a point where it is in scope is 10790 // ill-formed unless the variable has scalar type, class type with a 10791 // trivial default constructor and a trivial destructor, a cv-qualified 10792 // version of one of these types, or an array of one of the preceding 10793 // types and is declared without an initializer. 10794 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10795 if (const RecordType *Record 10796 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10797 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10798 // Mark the function for further checking even if the looser rules of 10799 // C++11 do not require such checks, so that we can diagnose 10800 // incompatibilities with C++98. 10801 if (!CXXRecord->isPOD()) 10802 getCurFunction()->setHasBranchProtectedScope(); 10803 } 10804 } 10805 10806 // C++03 [dcl.init]p9: 10807 // If no initializer is specified for an object, and the 10808 // object is of (possibly cv-qualified) non-POD class type (or 10809 // array thereof), the object shall be default-initialized; if 10810 // the object is of const-qualified type, the underlying class 10811 // type shall have a user-declared default 10812 // constructor. Otherwise, if no initializer is specified for 10813 // a non- static object, the object and its subobjects, if 10814 // any, have an indeterminate initial value); if the object 10815 // or any of its subobjects are of const-qualified type, the 10816 // program is ill-formed. 10817 // C++0x [dcl.init]p11: 10818 // If no initializer is specified for an object, the object is 10819 // default-initialized; [...]. 10820 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10821 InitializationKind Kind 10822 = InitializationKind::CreateDefault(Var->getLocation()); 10823 10824 InitializationSequence InitSeq(*this, Entity, Kind, None); 10825 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 10826 if (Init.isInvalid()) 10827 Var->setInvalidDecl(); 10828 else if (Init.get()) { 10829 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 10830 // This is important for template substitution. 10831 Var->setInitStyle(VarDecl::CallInit); 10832 } 10833 10834 CheckCompleteVariableDeclaration(Var); 10835 } 10836 } 10837 10838 void Sema::ActOnCXXForRangeDecl(Decl *D) { 10839 // If there is no declaration, there was an error parsing it. Ignore it. 10840 if (!D) 10841 return; 10842 10843 VarDecl *VD = dyn_cast<VarDecl>(D); 10844 if (!VD) { 10845 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 10846 D->setInvalidDecl(); 10847 return; 10848 } 10849 10850 VD->setCXXForRangeDecl(true); 10851 10852 // for-range-declaration cannot be given a storage class specifier. 10853 int Error = -1; 10854 switch (VD->getStorageClass()) { 10855 case SC_None: 10856 break; 10857 case SC_Extern: 10858 Error = 0; 10859 break; 10860 case SC_Static: 10861 Error = 1; 10862 break; 10863 case SC_PrivateExtern: 10864 Error = 2; 10865 break; 10866 case SC_Auto: 10867 Error = 3; 10868 break; 10869 case SC_Register: 10870 Error = 4; 10871 break; 10872 } 10873 if (Error != -1) { 10874 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 10875 << VD->getDeclName() << Error; 10876 D->setInvalidDecl(); 10877 } 10878 } 10879 10880 StmtResult 10881 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 10882 IdentifierInfo *Ident, 10883 ParsedAttributes &Attrs, 10884 SourceLocation AttrEnd) { 10885 // C++1y [stmt.iter]p1: 10886 // A range-based for statement of the form 10887 // for ( for-range-identifier : for-range-initializer ) statement 10888 // is equivalent to 10889 // for ( auto&& for-range-identifier : for-range-initializer ) statement 10890 DeclSpec DS(Attrs.getPool().getFactory()); 10891 10892 const char *PrevSpec; 10893 unsigned DiagID; 10894 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 10895 getPrintingPolicy()); 10896 10897 Declarator D(DS, Declarator::ForContext); 10898 D.SetIdentifier(Ident, IdentLoc); 10899 D.takeAttributes(Attrs, AttrEnd); 10900 10901 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 10902 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 10903 EmptyAttrs, IdentLoc); 10904 Decl *Var = ActOnDeclarator(S, D); 10905 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 10906 FinalizeDeclaration(Var); 10907 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 10908 AttrEnd.isValid() ? AttrEnd : IdentLoc); 10909 } 10910 10911 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 10912 if (var->isInvalidDecl()) return; 10913 10914 if (getLangOpts().OpenCL) { 10915 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 10916 // initialiser 10917 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 10918 !var->hasInit()) { 10919 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 10920 << 1 /*Init*/; 10921 var->setInvalidDecl(); 10922 return; 10923 } 10924 } 10925 10926 // In Objective-C, don't allow jumps past the implicit initialization of a 10927 // local retaining variable. 10928 if (getLangOpts().ObjC1 && 10929 var->hasLocalStorage()) { 10930 switch (var->getType().getObjCLifetime()) { 10931 case Qualifiers::OCL_None: 10932 case Qualifiers::OCL_ExplicitNone: 10933 case Qualifiers::OCL_Autoreleasing: 10934 break; 10935 10936 case Qualifiers::OCL_Weak: 10937 case Qualifiers::OCL_Strong: 10938 getCurFunction()->setHasBranchProtectedScope(); 10939 break; 10940 } 10941 } 10942 10943 // Warn about externally-visible variables being defined without a 10944 // prior declaration. We only want to do this for global 10945 // declarations, but we also specifically need to avoid doing it for 10946 // class members because the linkage of an anonymous class can 10947 // change if it's later given a typedef name. 10948 if (var->isThisDeclarationADefinition() && 10949 var->getDeclContext()->getRedeclContext()->isFileContext() && 10950 var->isExternallyVisible() && var->hasLinkage() && 10951 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 10952 var->getLocation())) { 10953 // Find a previous declaration that's not a definition. 10954 VarDecl *prev = var->getPreviousDecl(); 10955 while (prev && prev->isThisDeclarationADefinition()) 10956 prev = prev->getPreviousDecl(); 10957 10958 if (!prev) 10959 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 10960 } 10961 10962 // Cache the result of checking for constant initialization. 10963 Optional<bool> CacheHasConstInit; 10964 const Expr *CacheCulprit; 10965 auto checkConstInit = [&]() mutable { 10966 if (!CacheHasConstInit) 10967 CacheHasConstInit = var->getInit()->isConstantInitializer( 10968 Context, var->getType()->isReferenceType(), &CacheCulprit); 10969 return *CacheHasConstInit; 10970 }; 10971 10972 if (var->getTLSKind() == VarDecl::TLS_Static) { 10973 if (var->getType().isDestructedType()) { 10974 // GNU C++98 edits for __thread, [basic.start.term]p3: 10975 // The type of an object with thread storage duration shall not 10976 // have a non-trivial destructor. 10977 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 10978 if (getLangOpts().CPlusPlus11) 10979 Diag(var->getLocation(), diag::note_use_thread_local); 10980 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 10981 if (!checkConstInit()) { 10982 // GNU C++98 edits for __thread, [basic.start.init]p4: 10983 // An object of thread storage duration shall not require dynamic 10984 // initialization. 10985 // FIXME: Need strict checking here. 10986 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 10987 << CacheCulprit->getSourceRange(); 10988 if (getLangOpts().CPlusPlus11) 10989 Diag(var->getLocation(), diag::note_use_thread_local); 10990 } 10991 } 10992 } 10993 10994 // Apply section attributes and pragmas to global variables. 10995 bool GlobalStorage = var->hasGlobalStorage(); 10996 if (GlobalStorage && var->isThisDeclarationADefinition() && 10997 !inTemplateInstantiation()) { 10998 PragmaStack<StringLiteral *> *Stack = nullptr; 10999 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11000 if (var->getType().isConstQualified()) 11001 Stack = &ConstSegStack; 11002 else if (!var->getInit()) { 11003 Stack = &BSSSegStack; 11004 SectionFlags |= ASTContext::PSF_Write; 11005 } else { 11006 Stack = &DataSegStack; 11007 SectionFlags |= ASTContext::PSF_Write; 11008 } 11009 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11010 var->addAttr(SectionAttr::CreateImplicit( 11011 Context, SectionAttr::Declspec_allocate, 11012 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11013 } 11014 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11015 if (UnifySection(SA->getName(), SectionFlags, var)) 11016 var->dropAttr<SectionAttr>(); 11017 11018 // Apply the init_seg attribute if this has an initializer. If the 11019 // initializer turns out to not be dynamic, we'll end up ignoring this 11020 // attribute. 11021 if (CurInitSeg && var->getInit()) 11022 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11023 CurInitSegLoc)); 11024 } 11025 11026 // All the following checks are C++ only. 11027 if (!getLangOpts().CPlusPlus) { 11028 // If this variable must be emitted, add it as an initializer for the 11029 // current module. 11030 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11031 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11032 return; 11033 } 11034 11035 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11036 CheckCompleteDecompositionDeclaration(DD); 11037 11038 QualType type = var->getType(); 11039 if (type->isDependentType()) return; 11040 11041 // __block variables might require us to capture a copy-initializer. 11042 if (var->hasAttr<BlocksAttr>()) { 11043 // It's currently invalid to ever have a __block variable with an 11044 // array type; should we diagnose that here? 11045 11046 // Regardless, we don't want to ignore array nesting when 11047 // constructing this copy. 11048 if (type->isStructureOrClassType()) { 11049 EnterExpressionEvaluationContext scope( 11050 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11051 SourceLocation poi = var->getLocation(); 11052 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11053 ExprResult result 11054 = PerformMoveOrCopyInitialization( 11055 InitializedEntity::InitializeBlock(poi, type, false), 11056 var, var->getType(), varRef, /*AllowNRVO=*/true); 11057 if (!result.isInvalid()) { 11058 result = MaybeCreateExprWithCleanups(result); 11059 Expr *init = result.getAs<Expr>(); 11060 Context.setBlockVarCopyInits(var, init); 11061 } 11062 } 11063 } 11064 11065 Expr *Init = var->getInit(); 11066 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11067 QualType baseType = Context.getBaseElementType(type); 11068 11069 if (!var->getDeclContext()->isDependentContext() && 11070 Init && !Init->isValueDependent()) { 11071 11072 if (var->isConstexpr()) { 11073 SmallVector<PartialDiagnosticAt, 8> Notes; 11074 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11075 SourceLocation DiagLoc = var->getLocation(); 11076 // If the note doesn't add any useful information other than a source 11077 // location, fold it into the primary diagnostic. 11078 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11079 diag::note_invalid_subexpr_in_const_expr) { 11080 DiagLoc = Notes[0].first; 11081 Notes.clear(); 11082 } 11083 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11084 << var << Init->getSourceRange(); 11085 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11086 Diag(Notes[I].first, Notes[I].second); 11087 } 11088 } else if (var->isUsableInConstantExpressions(Context)) { 11089 // Check whether the initializer of a const variable of integral or 11090 // enumeration type is an ICE now, since we can't tell whether it was 11091 // initialized by a constant expression if we check later. 11092 var->checkInitIsICE(); 11093 } 11094 11095 // Don't emit further diagnostics about constexpr globals since they 11096 // were just diagnosed. 11097 if (!var->isConstexpr() && GlobalStorage && 11098 var->hasAttr<RequireConstantInitAttr>()) { 11099 // FIXME: Need strict checking in C++03 here. 11100 bool DiagErr = getLangOpts().CPlusPlus11 11101 ? !var->checkInitIsICE() : !checkConstInit(); 11102 if (DiagErr) { 11103 auto attr = var->getAttr<RequireConstantInitAttr>(); 11104 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11105 << Init->getSourceRange(); 11106 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11107 << attr->getRange(); 11108 } 11109 } 11110 else if (!var->isConstexpr() && IsGlobal && 11111 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11112 var->getLocation())) { 11113 // Warn about globals which don't have a constant initializer. Don't 11114 // warn about globals with a non-trivial destructor because we already 11115 // warned about them. 11116 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11117 if (!(RD && !RD->hasTrivialDestructor())) { 11118 if (!checkConstInit()) 11119 Diag(var->getLocation(), diag::warn_global_constructor) 11120 << Init->getSourceRange(); 11121 } 11122 } 11123 } 11124 11125 // Require the destructor. 11126 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11127 FinalizeVarWithDestructor(var, recordType); 11128 11129 // If this variable must be emitted, add it as an initializer for the current 11130 // module. 11131 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11132 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11133 } 11134 11135 /// \brief Determines if a variable's alignment is dependent. 11136 static bool hasDependentAlignment(VarDecl *VD) { 11137 if (VD->getType()->isDependentType()) 11138 return true; 11139 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11140 if (I->isAlignmentDependent()) 11141 return true; 11142 return false; 11143 } 11144 11145 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11146 /// any semantic actions necessary after any initializer has been attached. 11147 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11148 // Note that we are no longer parsing the initializer for this declaration. 11149 ParsingInitForAutoVars.erase(ThisDecl); 11150 11151 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11152 if (!VD) 11153 return; 11154 11155 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11156 for (auto *BD : DD->bindings()) { 11157 FinalizeDeclaration(BD); 11158 } 11159 } 11160 11161 checkAttributesAfterMerging(*this, *VD); 11162 11163 // Perform TLS alignment check here after attributes attached to the variable 11164 // which may affect the alignment have been processed. Only perform the check 11165 // if the target has a maximum TLS alignment (zero means no constraints). 11166 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11167 // Protect the check so that it's not performed on dependent types and 11168 // dependent alignments (we can't determine the alignment in that case). 11169 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11170 !VD->isInvalidDecl()) { 11171 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11172 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11173 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11174 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11175 << (unsigned)MaxAlignChars.getQuantity(); 11176 } 11177 } 11178 } 11179 11180 if (VD->isStaticLocal()) { 11181 if (FunctionDecl *FD = 11182 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11183 // Static locals inherit dll attributes from their function. 11184 if (Attr *A = getDLLAttr(FD)) { 11185 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11186 NewAttr->setInherited(true); 11187 VD->addAttr(NewAttr); 11188 } 11189 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11190 // function, only __shared__ variables may be declared with 11191 // static storage class. 11192 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11193 CUDADiagIfDeviceCode(VD->getLocation(), 11194 diag::err_device_static_local_var) 11195 << CurrentCUDATarget()) 11196 VD->setInvalidDecl(); 11197 } 11198 } 11199 11200 // Perform check for initializers of device-side global variables. 11201 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11202 // 7.5). We must also apply the same checks to all __shared__ 11203 // variables whether they are local or not. CUDA also allows 11204 // constant initializers for __constant__ and __device__ variables. 11205 if (getLangOpts().CUDA) { 11206 const Expr *Init = VD->getInit(); 11207 if (Init && VD->hasGlobalStorage()) { 11208 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11209 VD->hasAttr<CUDASharedAttr>()) { 11210 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11211 bool AllowedInit = false; 11212 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11213 AllowedInit = 11214 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11215 // We'll allow constant initializers even if it's a non-empty 11216 // constructor according to CUDA rules. This deviates from NVCC, 11217 // but allows us to handle things like constexpr constructors. 11218 if (!AllowedInit && 11219 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11220 AllowedInit = VD->getInit()->isConstantInitializer( 11221 Context, VD->getType()->isReferenceType()); 11222 11223 // Also make sure that destructor, if there is one, is empty. 11224 if (AllowedInit) 11225 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11226 AllowedInit = 11227 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11228 11229 if (!AllowedInit) { 11230 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11231 ? diag::err_shared_var_init 11232 : diag::err_dynamic_var_init) 11233 << Init->getSourceRange(); 11234 VD->setInvalidDecl(); 11235 } 11236 } else { 11237 // This is a host-side global variable. Check that the initializer is 11238 // callable from the host side. 11239 const FunctionDecl *InitFn = nullptr; 11240 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11241 InitFn = CE->getConstructor(); 11242 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11243 InitFn = CE->getDirectCallee(); 11244 } 11245 if (InitFn) { 11246 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11247 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11248 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11249 << InitFnTarget << InitFn; 11250 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11251 VD->setInvalidDecl(); 11252 } 11253 } 11254 } 11255 } 11256 } 11257 11258 // Grab the dllimport or dllexport attribute off of the VarDecl. 11259 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11260 11261 // Imported static data members cannot be defined out-of-line. 11262 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11263 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11264 VD->isThisDeclarationADefinition()) { 11265 // We allow definitions of dllimport class template static data members 11266 // with a warning. 11267 CXXRecordDecl *Context = 11268 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11269 bool IsClassTemplateMember = 11270 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11271 Context->getDescribedClassTemplate(); 11272 11273 Diag(VD->getLocation(), 11274 IsClassTemplateMember 11275 ? diag::warn_attribute_dllimport_static_field_definition 11276 : diag::err_attribute_dllimport_static_field_definition); 11277 Diag(IA->getLocation(), diag::note_attribute); 11278 if (!IsClassTemplateMember) 11279 VD->setInvalidDecl(); 11280 } 11281 } 11282 11283 // dllimport/dllexport variables cannot be thread local, their TLS index 11284 // isn't exported with the variable. 11285 if (DLLAttr && VD->getTLSKind()) { 11286 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11287 if (F && getDLLAttr(F)) { 11288 assert(VD->isStaticLocal()); 11289 // But if this is a static local in a dlimport/dllexport function, the 11290 // function will never be inlined, which means the var would never be 11291 // imported, so having it marked import/export is safe. 11292 } else { 11293 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11294 << DLLAttr; 11295 VD->setInvalidDecl(); 11296 } 11297 } 11298 11299 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11300 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11301 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11302 VD->dropAttr<UsedAttr>(); 11303 } 11304 } 11305 11306 const DeclContext *DC = VD->getDeclContext(); 11307 // If there's a #pragma GCC visibility in scope, and this isn't a class 11308 // member, set the visibility of this variable. 11309 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11310 AddPushedVisibilityAttribute(VD); 11311 11312 // FIXME: Warn on unused var template partial specializations. 11313 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11314 MarkUnusedFileScopedDecl(VD); 11315 11316 // Now we have parsed the initializer and can update the table of magic 11317 // tag values. 11318 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11319 !VD->getType()->isIntegralOrEnumerationType()) 11320 return; 11321 11322 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11323 const Expr *MagicValueExpr = VD->getInit(); 11324 if (!MagicValueExpr) { 11325 continue; 11326 } 11327 llvm::APSInt MagicValueInt; 11328 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11329 Diag(I->getRange().getBegin(), 11330 diag::err_type_tag_for_datatype_not_ice) 11331 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11332 continue; 11333 } 11334 if (MagicValueInt.getActiveBits() > 64) { 11335 Diag(I->getRange().getBegin(), 11336 diag::err_type_tag_for_datatype_too_large) 11337 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11338 continue; 11339 } 11340 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11341 RegisterTypeTagForDatatype(I->getArgumentKind(), 11342 MagicValue, 11343 I->getMatchingCType(), 11344 I->getLayoutCompatible(), 11345 I->getMustBeNull()); 11346 } 11347 } 11348 11349 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11350 auto *VD = dyn_cast<VarDecl>(DD); 11351 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11352 } 11353 11354 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11355 ArrayRef<Decl *> Group) { 11356 SmallVector<Decl*, 8> Decls; 11357 11358 if (DS.isTypeSpecOwned()) 11359 Decls.push_back(DS.getRepAsDecl()); 11360 11361 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11362 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11363 bool DiagnosedMultipleDecomps = false; 11364 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11365 bool DiagnosedNonDeducedAuto = false; 11366 11367 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11368 if (Decl *D = Group[i]) { 11369 // For declarators, there are some additional syntactic-ish checks we need 11370 // to perform. 11371 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11372 if (!FirstDeclaratorInGroup) 11373 FirstDeclaratorInGroup = DD; 11374 if (!FirstDecompDeclaratorInGroup) 11375 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11376 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11377 !hasDeducedAuto(DD)) 11378 FirstNonDeducedAutoInGroup = DD; 11379 11380 if (FirstDeclaratorInGroup != DD) { 11381 // A decomposition declaration cannot be combined with any other 11382 // declaration in the same group. 11383 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11384 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11385 diag::err_decomp_decl_not_alone) 11386 << FirstDeclaratorInGroup->getSourceRange() 11387 << DD->getSourceRange(); 11388 DiagnosedMultipleDecomps = true; 11389 } 11390 11391 // A declarator that uses 'auto' in any way other than to declare a 11392 // variable with a deduced type cannot be combined with any other 11393 // declarator in the same group. 11394 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11395 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11396 diag::err_auto_non_deduced_not_alone) 11397 << FirstNonDeducedAutoInGroup->getType() 11398 ->hasAutoForTrailingReturnType() 11399 << FirstDeclaratorInGroup->getSourceRange() 11400 << DD->getSourceRange(); 11401 DiagnosedNonDeducedAuto = true; 11402 } 11403 } 11404 } 11405 11406 Decls.push_back(D); 11407 } 11408 } 11409 11410 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11411 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11412 handleTagNumbering(Tag, S); 11413 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11414 getLangOpts().CPlusPlus) 11415 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11416 } 11417 } 11418 11419 return BuildDeclaratorGroup(Decls); 11420 } 11421 11422 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11423 /// group, performing any necessary semantic checking. 11424 Sema::DeclGroupPtrTy 11425 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11426 // C++14 [dcl.spec.auto]p7: (DR1347) 11427 // If the type that replaces the placeholder type is not the same in each 11428 // deduction, the program is ill-formed. 11429 if (Group.size() > 1) { 11430 QualType Deduced; 11431 VarDecl *DeducedDecl = nullptr; 11432 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11433 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11434 if (!D || D->isInvalidDecl()) 11435 break; 11436 DeducedType *DT = D->getType()->getContainedDeducedType(); 11437 if (!DT || DT->getDeducedType().isNull()) 11438 continue; 11439 if (Deduced.isNull()) { 11440 Deduced = DT->getDeducedType(); 11441 DeducedDecl = D; 11442 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11443 auto *AT = dyn_cast<AutoType>(DT); 11444 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11445 diag::err_auto_different_deductions) 11446 << (AT ? (unsigned)AT->getKeyword() : 3) 11447 << Deduced << DeducedDecl->getDeclName() 11448 << DT->getDeducedType() << D->getDeclName() 11449 << DeducedDecl->getInit()->getSourceRange() 11450 << D->getInit()->getSourceRange(); 11451 D->setInvalidDecl(); 11452 break; 11453 } 11454 } 11455 } 11456 11457 ActOnDocumentableDecls(Group); 11458 11459 return DeclGroupPtrTy::make( 11460 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11461 } 11462 11463 void Sema::ActOnDocumentableDecl(Decl *D) { 11464 ActOnDocumentableDecls(D); 11465 } 11466 11467 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11468 // Don't parse the comment if Doxygen diagnostics are ignored. 11469 if (Group.empty() || !Group[0]) 11470 return; 11471 11472 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11473 Group[0]->getLocation()) && 11474 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11475 Group[0]->getLocation())) 11476 return; 11477 11478 if (Group.size() >= 2) { 11479 // This is a decl group. Normally it will contain only declarations 11480 // produced from declarator list. But in case we have any definitions or 11481 // additional declaration references: 11482 // 'typedef struct S {} S;' 11483 // 'typedef struct S *S;' 11484 // 'struct S *pS;' 11485 // FinalizeDeclaratorGroup adds these as separate declarations. 11486 Decl *MaybeTagDecl = Group[0]; 11487 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11488 Group = Group.slice(1); 11489 } 11490 } 11491 11492 // See if there are any new comments that are not attached to a decl. 11493 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11494 if (!Comments.empty() && 11495 !Comments.back()->isAttached()) { 11496 // There is at least one comment that not attached to a decl. 11497 // Maybe it should be attached to one of these decls? 11498 // 11499 // Note that this way we pick up not only comments that precede the 11500 // declaration, but also comments that *follow* the declaration -- thanks to 11501 // the lookahead in the lexer: we've consumed the semicolon and looked 11502 // ahead through comments. 11503 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11504 Context.getCommentForDecl(Group[i], &PP); 11505 } 11506 } 11507 11508 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11509 /// to introduce parameters into function prototype scope. 11510 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11511 const DeclSpec &DS = D.getDeclSpec(); 11512 11513 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11514 11515 // C++03 [dcl.stc]p2 also permits 'auto'. 11516 StorageClass SC = SC_None; 11517 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11518 SC = SC_Register; 11519 } else if (getLangOpts().CPlusPlus && 11520 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11521 SC = SC_Auto; 11522 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11523 Diag(DS.getStorageClassSpecLoc(), 11524 diag::err_invalid_storage_class_in_func_decl); 11525 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11526 } 11527 11528 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11529 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11530 << DeclSpec::getSpecifierName(TSCS); 11531 if (DS.isInlineSpecified()) 11532 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11533 << getLangOpts().CPlusPlus1z; 11534 if (DS.isConstexprSpecified()) 11535 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11536 << 0; 11537 if (DS.isConceptSpecified()) 11538 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11539 11540 DiagnoseFunctionSpecifiers(DS); 11541 11542 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11543 QualType parmDeclType = TInfo->getType(); 11544 11545 if (getLangOpts().CPlusPlus) { 11546 // Check that there are no default arguments inside the type of this 11547 // parameter. 11548 CheckExtraCXXDefaultArguments(D); 11549 11550 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11551 if (D.getCXXScopeSpec().isSet()) { 11552 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11553 << D.getCXXScopeSpec().getRange(); 11554 D.getCXXScopeSpec().clear(); 11555 } 11556 } 11557 11558 // Ensure we have a valid name 11559 IdentifierInfo *II = nullptr; 11560 if (D.hasName()) { 11561 II = D.getIdentifier(); 11562 if (!II) { 11563 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11564 << GetNameForDeclarator(D).getName(); 11565 D.setInvalidType(true); 11566 } 11567 } 11568 11569 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11570 if (II) { 11571 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11572 ForRedeclaration); 11573 LookupName(R, S); 11574 if (R.isSingleResult()) { 11575 NamedDecl *PrevDecl = R.getFoundDecl(); 11576 if (PrevDecl->isTemplateParameter()) { 11577 // Maybe we will complain about the shadowed template parameter. 11578 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11579 // Just pretend that we didn't see the previous declaration. 11580 PrevDecl = nullptr; 11581 } else if (S->isDeclScope(PrevDecl)) { 11582 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11583 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11584 11585 // Recover by removing the name 11586 II = nullptr; 11587 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11588 D.setInvalidType(true); 11589 } 11590 } 11591 } 11592 11593 // Temporarily put parameter variables in the translation unit, not 11594 // the enclosing context. This prevents them from accidentally 11595 // looking like class members in C++. 11596 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11597 D.getLocStart(), 11598 D.getIdentifierLoc(), II, 11599 parmDeclType, TInfo, 11600 SC); 11601 11602 if (D.isInvalidType()) 11603 New->setInvalidDecl(); 11604 11605 assert(S->isFunctionPrototypeScope()); 11606 assert(S->getFunctionPrototypeDepth() >= 1); 11607 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11608 S->getNextFunctionPrototypeIndex()); 11609 11610 // Add the parameter declaration into this scope. 11611 S->AddDecl(New); 11612 if (II) 11613 IdResolver.AddDecl(New); 11614 11615 ProcessDeclAttributes(S, New, D); 11616 11617 if (D.getDeclSpec().isModulePrivateSpecified()) 11618 Diag(New->getLocation(), diag::err_module_private_local) 11619 << 1 << New->getDeclName() 11620 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11621 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11622 11623 if (New->hasAttr<BlocksAttr>()) { 11624 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11625 } 11626 return New; 11627 } 11628 11629 /// \brief Synthesizes a variable for a parameter arising from a 11630 /// typedef. 11631 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11632 SourceLocation Loc, 11633 QualType T) { 11634 /* FIXME: setting StartLoc == Loc. 11635 Would it be worth to modify callers so as to provide proper source 11636 location for the unnamed parameters, embedding the parameter's type? */ 11637 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11638 T, Context.getTrivialTypeSourceInfo(T, Loc), 11639 SC_None, nullptr); 11640 Param->setImplicit(); 11641 return Param; 11642 } 11643 11644 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11645 // Don't diagnose unused-parameter errors in template instantiations; we 11646 // will already have done so in the template itself. 11647 if (inTemplateInstantiation()) 11648 return; 11649 11650 for (const ParmVarDecl *Parameter : Parameters) { 11651 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11652 !Parameter->hasAttr<UnusedAttr>()) { 11653 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11654 << Parameter->getDeclName(); 11655 } 11656 } 11657 } 11658 11659 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11660 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11661 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11662 return; 11663 11664 // Warn if the return value is pass-by-value and larger than the specified 11665 // threshold. 11666 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11667 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11668 if (Size > LangOpts.NumLargeByValueCopy) 11669 Diag(D->getLocation(), diag::warn_return_value_size) 11670 << D->getDeclName() << Size; 11671 } 11672 11673 // Warn if any parameter is pass-by-value and larger than the specified 11674 // threshold. 11675 for (const ParmVarDecl *Parameter : Parameters) { 11676 QualType T = Parameter->getType(); 11677 if (T->isDependentType() || !T.isPODType(Context)) 11678 continue; 11679 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11680 if (Size > LangOpts.NumLargeByValueCopy) 11681 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11682 << Parameter->getDeclName() << Size; 11683 } 11684 } 11685 11686 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11687 SourceLocation NameLoc, IdentifierInfo *Name, 11688 QualType T, TypeSourceInfo *TSInfo, 11689 StorageClass SC) { 11690 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11691 if (getLangOpts().ObjCAutoRefCount && 11692 T.getObjCLifetime() == Qualifiers::OCL_None && 11693 T->isObjCLifetimeType()) { 11694 11695 Qualifiers::ObjCLifetime lifetime; 11696 11697 // Special cases for arrays: 11698 // - if it's const, use __unsafe_unretained 11699 // - otherwise, it's an error 11700 if (T->isArrayType()) { 11701 if (!T.isConstQualified()) { 11702 DelayedDiagnostics.add( 11703 sema::DelayedDiagnostic::makeForbiddenType( 11704 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11705 } 11706 lifetime = Qualifiers::OCL_ExplicitNone; 11707 } else { 11708 lifetime = T->getObjCARCImplicitLifetime(); 11709 } 11710 T = Context.getLifetimeQualifiedType(T, lifetime); 11711 } 11712 11713 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11714 Context.getAdjustedParameterType(T), 11715 TSInfo, SC, nullptr); 11716 11717 // Parameters can not be abstract class types. 11718 // For record types, this is done by the AbstractClassUsageDiagnoser once 11719 // the class has been completely parsed. 11720 if (!CurContext->isRecord() && 11721 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11722 AbstractParamType)) 11723 New->setInvalidDecl(); 11724 11725 // Parameter declarators cannot be interface types. All ObjC objects are 11726 // passed by reference. 11727 if (T->isObjCObjectType()) { 11728 SourceLocation TypeEndLoc = 11729 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11730 Diag(NameLoc, 11731 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11732 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11733 T = Context.getObjCObjectPointerType(T); 11734 New->setType(T); 11735 } 11736 11737 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11738 // duration shall not be qualified by an address-space qualifier." 11739 // Since all parameters have automatic store duration, they can not have 11740 // an address space. 11741 if (T.getAddressSpace() != 0) { 11742 // OpenCL allows function arguments declared to be an array of a type 11743 // to be qualified with an address space. 11744 if (!(getLangOpts().OpenCL && T->isArrayType())) { 11745 Diag(NameLoc, diag::err_arg_with_address_space); 11746 New->setInvalidDecl(); 11747 } 11748 } 11749 11750 return New; 11751 } 11752 11753 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11754 SourceLocation LocAfterDecls) { 11755 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11756 11757 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11758 // for a K&R function. 11759 if (!FTI.hasPrototype) { 11760 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11761 --i; 11762 if (FTI.Params[i].Param == nullptr) { 11763 SmallString<256> Code; 11764 llvm::raw_svector_ostream(Code) 11765 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11766 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11767 << FTI.Params[i].Ident 11768 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11769 11770 // Implicitly declare the argument as type 'int' for lack of a better 11771 // type. 11772 AttributeFactory attrs; 11773 DeclSpec DS(attrs); 11774 const char* PrevSpec; // unused 11775 unsigned DiagID; // unused 11776 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11777 DiagID, Context.getPrintingPolicy()); 11778 // Use the identifier location for the type source range. 11779 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11780 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11781 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11782 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11783 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11784 } 11785 } 11786 } 11787 } 11788 11789 Decl * 11790 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11791 MultiTemplateParamsArg TemplateParameterLists, 11792 SkipBodyInfo *SkipBody) { 11793 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11794 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11795 Scope *ParentScope = FnBodyScope->getParent(); 11796 11797 D.setFunctionDefinitionKind(FDK_Definition); 11798 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11799 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 11800 } 11801 11802 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 11803 Consumer.HandleInlineFunctionDefinition(D); 11804 } 11805 11806 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 11807 const FunctionDecl*& PossibleZeroParamPrototype) { 11808 // Don't warn about invalid declarations. 11809 if (FD->isInvalidDecl()) 11810 return false; 11811 11812 // Or declarations that aren't global. 11813 if (!FD->isGlobal()) 11814 return false; 11815 11816 // Don't warn about C++ member functions. 11817 if (isa<CXXMethodDecl>(FD)) 11818 return false; 11819 11820 // Don't warn about 'main'. 11821 if (FD->isMain()) 11822 return false; 11823 11824 // Don't warn about inline functions. 11825 if (FD->isInlined()) 11826 return false; 11827 11828 // Don't warn about function templates. 11829 if (FD->getDescribedFunctionTemplate()) 11830 return false; 11831 11832 // Don't warn about function template specializations. 11833 if (FD->isFunctionTemplateSpecialization()) 11834 return false; 11835 11836 // Don't warn for OpenCL kernels. 11837 if (FD->hasAttr<OpenCLKernelAttr>()) 11838 return false; 11839 11840 // Don't warn on explicitly deleted functions. 11841 if (FD->isDeleted()) 11842 return false; 11843 11844 bool MissingPrototype = true; 11845 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 11846 Prev; Prev = Prev->getPreviousDecl()) { 11847 // Ignore any declarations that occur in function or method 11848 // scope, because they aren't visible from the header. 11849 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 11850 continue; 11851 11852 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 11853 if (FD->getNumParams() == 0) 11854 PossibleZeroParamPrototype = Prev; 11855 break; 11856 } 11857 11858 return MissingPrototype; 11859 } 11860 11861 void 11862 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 11863 const FunctionDecl *EffectiveDefinition, 11864 SkipBodyInfo *SkipBody) { 11865 const FunctionDecl *Definition = EffectiveDefinition; 11866 if (!Definition) 11867 if (!FD->isDefined(Definition)) 11868 return; 11869 11870 if (canRedefineFunction(Definition, getLangOpts())) 11871 return; 11872 11873 // Don't emit an error when this is redifinition of a typo-corrected 11874 // definition. 11875 if (TypoCorrectedFunctionDefinitions.count(Definition)) 11876 return; 11877 11878 // If we don't have a visible definition of the function, and it's inline or 11879 // a template, skip the new definition. 11880 if (SkipBody && !hasVisibleDefinition(Definition) && 11881 (Definition->getFormalLinkage() == InternalLinkage || 11882 Definition->isInlined() || 11883 Definition->getDescribedFunctionTemplate() || 11884 Definition->getNumTemplateParameterLists())) { 11885 SkipBody->ShouldSkip = true; 11886 if (auto *TD = Definition->getDescribedFunctionTemplate()) 11887 makeMergedDefinitionVisible(TD); 11888 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 11889 return; 11890 } 11891 11892 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 11893 Definition->getStorageClass() == SC_Extern) 11894 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 11895 << FD->getDeclName() << getLangOpts().CPlusPlus; 11896 else 11897 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 11898 11899 Diag(Definition->getLocation(), diag::note_previous_definition); 11900 FD->setInvalidDecl(); 11901 } 11902 11903 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 11904 Sema &S) { 11905 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 11906 11907 LambdaScopeInfo *LSI = S.PushLambdaScope(); 11908 LSI->CallOperator = CallOperator; 11909 LSI->Lambda = LambdaClass; 11910 LSI->ReturnType = CallOperator->getReturnType(); 11911 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 11912 11913 if (LCD == LCD_None) 11914 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 11915 else if (LCD == LCD_ByCopy) 11916 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 11917 else if (LCD == LCD_ByRef) 11918 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 11919 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 11920 11921 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 11922 LSI->Mutable = !CallOperator->isConst(); 11923 11924 // Add the captures to the LSI so they can be noted as already 11925 // captured within tryCaptureVar. 11926 auto I = LambdaClass->field_begin(); 11927 for (const auto &C : LambdaClass->captures()) { 11928 if (C.capturesVariable()) { 11929 VarDecl *VD = C.getCapturedVar(); 11930 if (VD->isInitCapture()) 11931 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 11932 QualType CaptureType = VD->getType(); 11933 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 11934 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 11935 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 11936 /*EllipsisLoc*/C.isPackExpansion() 11937 ? C.getEllipsisLoc() : SourceLocation(), 11938 CaptureType, /*Expr*/ nullptr); 11939 11940 } else if (C.capturesThis()) { 11941 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 11942 /*Expr*/ nullptr, 11943 C.getCaptureKind() == LCK_StarThis); 11944 } else { 11945 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 11946 } 11947 ++I; 11948 } 11949 } 11950 11951 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 11952 SkipBodyInfo *SkipBody) { 11953 if (!D) 11954 return D; 11955 FunctionDecl *FD = nullptr; 11956 11957 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 11958 FD = FunTmpl->getTemplatedDecl(); 11959 else 11960 FD = cast<FunctionDecl>(D); 11961 11962 // Check for defining attributes before the check for redefinition. 11963 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 11964 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 11965 FD->dropAttr<AliasAttr>(); 11966 FD->setInvalidDecl(); 11967 } 11968 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 11969 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 11970 FD->dropAttr<IFuncAttr>(); 11971 FD->setInvalidDecl(); 11972 } 11973 11974 // See if this is a redefinition. 11975 if (!FD->isLateTemplateParsed()) { 11976 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 11977 11978 // If we're skipping the body, we're done. Don't enter the scope. 11979 if (SkipBody && SkipBody->ShouldSkip) 11980 return D; 11981 } 11982 11983 // Mark this function as "will have a body eventually". This lets users to 11984 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 11985 // this function. 11986 FD->setWillHaveBody(); 11987 11988 // If we are instantiating a generic lambda call operator, push 11989 // a LambdaScopeInfo onto the function stack. But use the information 11990 // that's already been calculated (ActOnLambdaExpr) to prime the current 11991 // LambdaScopeInfo. 11992 // When the template operator is being specialized, the LambdaScopeInfo, 11993 // has to be properly restored so that tryCaptureVariable doesn't try 11994 // and capture any new variables. In addition when calculating potential 11995 // captures during transformation of nested lambdas, it is necessary to 11996 // have the LSI properly restored. 11997 if (isGenericLambdaCallOperatorSpecialization(FD)) { 11998 assert(inTemplateInstantiation() && 11999 "There should be an active template instantiation on the stack " 12000 "when instantiating a generic lambda!"); 12001 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12002 } else { 12003 // Enter a new function scope 12004 PushFunctionScope(); 12005 } 12006 12007 // Builtin functions cannot be defined. 12008 if (unsigned BuiltinID = FD->getBuiltinID()) { 12009 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12010 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12011 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12012 FD->setInvalidDecl(); 12013 } 12014 } 12015 12016 // The return type of a function definition must be complete 12017 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12018 QualType ResultType = FD->getReturnType(); 12019 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12020 !FD->isInvalidDecl() && 12021 RequireCompleteType(FD->getLocation(), ResultType, 12022 diag::err_func_def_incomplete_result)) 12023 FD->setInvalidDecl(); 12024 12025 if (FnBodyScope) 12026 PushDeclContext(FnBodyScope, FD); 12027 12028 // Check the validity of our function parameters 12029 CheckParmsForFunctionDef(FD->parameters(), 12030 /*CheckParameterNames=*/true); 12031 12032 // Add non-parameter declarations already in the function to the current 12033 // scope. 12034 if (FnBodyScope) { 12035 for (Decl *NPD : FD->decls()) { 12036 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12037 if (!NonParmDecl) 12038 continue; 12039 assert(!isa<ParmVarDecl>(NonParmDecl) && 12040 "parameters should not be in newly created FD yet"); 12041 12042 // If the decl has a name, make it accessible in the current scope. 12043 if (NonParmDecl->getDeclName()) 12044 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12045 12046 // Similarly, dive into enums and fish their constants out, making them 12047 // accessible in this scope. 12048 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12049 for (auto *EI : ED->enumerators()) 12050 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12051 } 12052 } 12053 } 12054 12055 // Introduce our parameters into the function scope 12056 for (auto Param : FD->parameters()) { 12057 Param->setOwningFunction(FD); 12058 12059 // If this has an identifier, add it to the scope stack. 12060 if (Param->getIdentifier() && FnBodyScope) { 12061 CheckShadow(FnBodyScope, Param); 12062 12063 PushOnScopeChains(Param, FnBodyScope); 12064 } 12065 } 12066 12067 // Ensure that the function's exception specification is instantiated. 12068 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12069 ResolveExceptionSpec(D->getLocation(), FPT); 12070 12071 // dllimport cannot be applied to non-inline function definitions. 12072 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12073 !FD->isTemplateInstantiation()) { 12074 assert(!FD->hasAttr<DLLExportAttr>()); 12075 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12076 FD->setInvalidDecl(); 12077 return D; 12078 } 12079 // We want to attach documentation to original Decl (which might be 12080 // a function template). 12081 ActOnDocumentableDecl(D); 12082 if (getCurLexicalContext()->isObjCContainer() && 12083 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12084 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12085 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12086 12087 return D; 12088 } 12089 12090 /// \brief Given the set of return statements within a function body, 12091 /// compute the variables that are subject to the named return value 12092 /// optimization. 12093 /// 12094 /// Each of the variables that is subject to the named return value 12095 /// optimization will be marked as NRVO variables in the AST, and any 12096 /// return statement that has a marked NRVO variable as its NRVO candidate can 12097 /// use the named return value optimization. 12098 /// 12099 /// This function applies a very simplistic algorithm for NRVO: if every return 12100 /// statement in the scope of a variable has the same NRVO candidate, that 12101 /// candidate is an NRVO variable. 12102 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12103 ReturnStmt **Returns = Scope->Returns.data(); 12104 12105 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12106 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12107 if (!NRVOCandidate->isNRVOVariable()) 12108 Returns[I]->setNRVOCandidate(nullptr); 12109 } 12110 } 12111 } 12112 12113 bool Sema::canDelayFunctionBody(const Declarator &D) { 12114 // We can't delay parsing the body of a constexpr function template (yet). 12115 if (D.getDeclSpec().isConstexprSpecified()) 12116 return false; 12117 12118 // We can't delay parsing the body of a function template with a deduced 12119 // return type (yet). 12120 if (D.getDeclSpec().hasAutoTypeSpec()) { 12121 // If the placeholder introduces a non-deduced trailing return type, 12122 // we can still delay parsing it. 12123 if (D.getNumTypeObjects()) { 12124 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12125 if (Outer.Kind == DeclaratorChunk::Function && 12126 Outer.Fun.hasTrailingReturnType()) { 12127 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12128 return Ty.isNull() || !Ty->isUndeducedType(); 12129 } 12130 } 12131 return false; 12132 } 12133 12134 return true; 12135 } 12136 12137 bool Sema::canSkipFunctionBody(Decl *D) { 12138 // We cannot skip the body of a function (or function template) which is 12139 // constexpr, since we may need to evaluate its body in order to parse the 12140 // rest of the file. 12141 // We cannot skip the body of a function with an undeduced return type, 12142 // because any callers of that function need to know the type. 12143 if (const FunctionDecl *FD = D->getAsFunction()) 12144 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12145 return false; 12146 return Consumer.shouldSkipFunctionBody(D); 12147 } 12148 12149 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12150 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 12151 FD->setHasSkippedBody(); 12152 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 12153 MD->setHasSkippedBody(); 12154 return Decl; 12155 } 12156 12157 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12158 return ActOnFinishFunctionBody(D, BodyArg, false); 12159 } 12160 12161 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12162 bool IsInstantiation) { 12163 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12164 12165 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12166 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12167 12168 if (getLangOpts().CoroutinesTS && getCurFunction()->CoroutinePromise) 12169 CheckCompletedCoroutineBody(FD, Body); 12170 12171 if (FD) { 12172 FD->setBody(Body); 12173 12174 if (getLangOpts().CPlusPlus14) { 12175 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12176 FD->getReturnType()->isUndeducedType()) { 12177 // If the function has a deduced result type but contains no 'return' 12178 // statements, the result type as written must be exactly 'auto', and 12179 // the deduced result type is 'void'. 12180 if (!FD->getReturnType()->getAs<AutoType>()) { 12181 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12182 << FD->getReturnType(); 12183 FD->setInvalidDecl(); 12184 } else { 12185 // Substitute 'void' for the 'auto' in the type. 12186 TypeLoc ResultType = getReturnTypeLoc(FD); 12187 Context.adjustDeducedFunctionResultType( 12188 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12189 } 12190 } 12191 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12192 // In C++11, we don't use 'auto' deduction rules for lambda call 12193 // operators because we don't support return type deduction. 12194 auto *LSI = getCurLambda(); 12195 if (LSI->HasImplicitReturnType) { 12196 deduceClosureReturnType(*LSI); 12197 12198 // C++11 [expr.prim.lambda]p4: 12199 // [...] if there are no return statements in the compound-statement 12200 // [the deduced type is] the type void 12201 QualType RetType = 12202 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12203 12204 // Update the return type to the deduced type. 12205 const FunctionProtoType *Proto = 12206 FD->getType()->getAs<FunctionProtoType>(); 12207 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12208 Proto->getExtProtoInfo())); 12209 } 12210 } 12211 12212 // The only way to be included in UndefinedButUsed is if there is an 12213 // ODR use before the definition. Avoid the expensive map lookup if this 12214 // is the first declaration. 12215 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 12216 if (!FD->isExternallyVisible()) 12217 UndefinedButUsed.erase(FD); 12218 else if (FD->isInlined() && 12219 !LangOpts.GNUInline && 12220 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 12221 UndefinedButUsed.erase(FD); 12222 } 12223 12224 // If the function implicitly returns zero (like 'main') or is naked, 12225 // don't complain about missing return statements. 12226 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12227 WP.disableCheckFallThrough(); 12228 12229 // MSVC permits the use of pure specifier (=0) on function definition, 12230 // defined at class scope, warn about this non-standard construct. 12231 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12232 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12233 12234 if (!FD->isInvalidDecl()) { 12235 // Don't diagnose unused parameters of defaulted or deleted functions. 12236 if (!FD->isDeleted() && !FD->isDefaulted()) 12237 DiagnoseUnusedParameters(FD->parameters()); 12238 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12239 FD->getReturnType(), FD); 12240 12241 // If this is a structor, we need a vtable. 12242 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12243 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12244 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12245 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12246 12247 // Try to apply the named return value optimization. We have to check 12248 // if we can do this here because lambdas keep return statements around 12249 // to deduce an implicit return type. 12250 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12251 !FD->isDependentContext()) 12252 computeNRVO(Body, getCurFunction()); 12253 } 12254 12255 // GNU warning -Wmissing-prototypes: 12256 // Warn if a global function is defined without a previous 12257 // prototype declaration. This warning is issued even if the 12258 // definition itself provides a prototype. The aim is to detect 12259 // global functions that fail to be declared in header files. 12260 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12261 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12262 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12263 12264 if (PossibleZeroParamPrototype) { 12265 // We found a declaration that is not a prototype, 12266 // but that could be a zero-parameter prototype 12267 if (TypeSourceInfo *TI = 12268 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12269 TypeLoc TL = TI->getTypeLoc(); 12270 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12271 Diag(PossibleZeroParamPrototype->getLocation(), 12272 diag::note_declaration_not_a_prototype) 12273 << PossibleZeroParamPrototype 12274 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12275 } 12276 } 12277 12278 // GNU warning -Wstrict-prototypes 12279 // Warn if K&R function is defined without a previous declaration. 12280 // This warning is issued only if the definition itself does not provide 12281 // a prototype. Only K&R definitions do not provide a prototype. 12282 // An empty list in a function declarator that is part of a definition 12283 // of that function specifies that the function has no parameters 12284 // (C99 6.7.5.3p14) 12285 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12286 !LangOpts.CPlusPlus) { 12287 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12288 TypeLoc TL = TI->getTypeLoc(); 12289 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12290 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1; 12291 } 12292 } 12293 12294 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12295 const CXXMethodDecl *KeyFunction; 12296 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12297 MD->isVirtual() && 12298 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12299 MD == KeyFunction->getCanonicalDecl()) { 12300 // Update the key-function state if necessary for this ABI. 12301 if (FD->isInlined() && 12302 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12303 Context.setNonKeyFunction(MD); 12304 12305 // If the newly-chosen key function is already defined, then we 12306 // need to mark the vtable as used retroactively. 12307 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12308 const FunctionDecl *Definition; 12309 if (KeyFunction && KeyFunction->isDefined(Definition)) 12310 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12311 } else { 12312 // We just defined they key function; mark the vtable as used. 12313 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12314 } 12315 } 12316 } 12317 12318 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12319 "Function parsing confused"); 12320 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12321 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12322 MD->setBody(Body); 12323 if (!MD->isInvalidDecl()) { 12324 DiagnoseUnusedParameters(MD->parameters()); 12325 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12326 MD->getReturnType(), MD); 12327 12328 if (Body) 12329 computeNRVO(Body, getCurFunction()); 12330 } 12331 if (getCurFunction()->ObjCShouldCallSuper) { 12332 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12333 << MD->getSelector().getAsString(); 12334 getCurFunction()->ObjCShouldCallSuper = false; 12335 } 12336 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12337 const ObjCMethodDecl *InitMethod = nullptr; 12338 bool isDesignated = 12339 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12340 assert(isDesignated && InitMethod); 12341 (void)isDesignated; 12342 12343 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12344 auto IFace = MD->getClassInterface(); 12345 if (!IFace) 12346 return false; 12347 auto SuperD = IFace->getSuperClass(); 12348 if (!SuperD) 12349 return false; 12350 return SuperD->getIdentifier() == 12351 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12352 }; 12353 // Don't issue this warning for unavailable inits or direct subclasses 12354 // of NSObject. 12355 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12356 Diag(MD->getLocation(), 12357 diag::warn_objc_designated_init_missing_super_call); 12358 Diag(InitMethod->getLocation(), 12359 diag::note_objc_designated_init_marked_here); 12360 } 12361 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12362 } 12363 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12364 // Don't issue this warning for unavaialable inits. 12365 if (!MD->isUnavailable()) 12366 Diag(MD->getLocation(), 12367 diag::warn_objc_secondary_init_missing_init_call); 12368 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12369 } 12370 } else { 12371 return nullptr; 12372 } 12373 12374 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12375 DiagnoseUnguardedAvailabilityViolations(dcl); 12376 12377 assert(!getCurFunction()->ObjCShouldCallSuper && 12378 "This should only be set for ObjC methods, which should have been " 12379 "handled in the block above."); 12380 12381 // Verify and clean out per-function state. 12382 if (Body && (!FD || !FD->isDefaulted())) { 12383 // C++ constructors that have function-try-blocks can't have return 12384 // statements in the handlers of that block. (C++ [except.handle]p14) 12385 // Verify this. 12386 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12387 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12388 12389 // Verify that gotos and switch cases don't jump into scopes illegally. 12390 if (getCurFunction()->NeedsScopeChecking() && 12391 !PP.isCodeCompletionEnabled()) 12392 DiagnoseInvalidJumps(Body); 12393 12394 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12395 if (!Destructor->getParent()->isDependentType()) 12396 CheckDestructor(Destructor); 12397 12398 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12399 Destructor->getParent()); 12400 } 12401 12402 // If any errors have occurred, clear out any temporaries that may have 12403 // been leftover. This ensures that these temporaries won't be picked up for 12404 // deletion in some later function. 12405 if (getDiagnostics().hasErrorOccurred() || 12406 getDiagnostics().getSuppressAllDiagnostics()) { 12407 DiscardCleanupsInEvaluationContext(); 12408 } 12409 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12410 !isa<FunctionTemplateDecl>(dcl)) { 12411 // Since the body is valid, issue any analysis-based warnings that are 12412 // enabled. 12413 ActivePolicy = &WP; 12414 } 12415 12416 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12417 (!CheckConstexprFunctionDecl(FD) || 12418 !CheckConstexprFunctionBody(FD, Body))) 12419 FD->setInvalidDecl(); 12420 12421 if (FD && FD->hasAttr<NakedAttr>()) { 12422 for (const Stmt *S : Body->children()) { 12423 // Allow local register variables without initializer as they don't 12424 // require prologue. 12425 bool RegisterVariables = false; 12426 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12427 for (const auto *Decl : DS->decls()) { 12428 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12429 RegisterVariables = 12430 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12431 if (!RegisterVariables) 12432 break; 12433 } 12434 } 12435 } 12436 if (RegisterVariables) 12437 continue; 12438 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12439 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12440 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12441 FD->setInvalidDecl(); 12442 break; 12443 } 12444 } 12445 } 12446 12447 assert(ExprCleanupObjects.size() == 12448 ExprEvalContexts.back().NumCleanupObjects && 12449 "Leftover temporaries in function"); 12450 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12451 assert(MaybeODRUseExprs.empty() && 12452 "Leftover expressions for odr-use checking"); 12453 } 12454 12455 if (!IsInstantiation) 12456 PopDeclContext(); 12457 12458 PopFunctionScopeInfo(ActivePolicy, dcl); 12459 // If any errors have occurred, clear out any temporaries that may have 12460 // been leftover. This ensures that these temporaries won't be picked up for 12461 // deletion in some later function. 12462 if (getDiagnostics().hasErrorOccurred()) { 12463 DiscardCleanupsInEvaluationContext(); 12464 } 12465 12466 return dcl; 12467 } 12468 12469 /// When we finish delayed parsing of an attribute, we must attach it to the 12470 /// relevant Decl. 12471 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12472 ParsedAttributes &Attrs) { 12473 // Always attach attributes to the underlying decl. 12474 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12475 D = TD->getTemplatedDecl(); 12476 ProcessDeclAttributeList(S, D, Attrs.getList()); 12477 12478 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12479 if (Method->isStatic()) 12480 checkThisInStaticMemberFunctionAttributes(Method); 12481 } 12482 12483 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12484 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12485 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12486 IdentifierInfo &II, Scope *S) { 12487 // Before we produce a declaration for an implicitly defined 12488 // function, see whether there was a locally-scoped declaration of 12489 // this name as a function or variable. If so, use that 12490 // (non-visible) declaration, and complain about it. 12491 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 12492 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 12493 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12494 return ExternCPrev; 12495 } 12496 12497 // Extension in C99. Legal in C90, but warn about it. 12498 unsigned diag_id; 12499 if (II.getName().startswith("__builtin_")) 12500 diag_id = diag::warn_builtin_unknown; 12501 else if (getLangOpts().C99) 12502 diag_id = diag::ext_implicit_function_decl; 12503 else 12504 diag_id = diag::warn_implicit_function_decl; 12505 Diag(Loc, diag_id) << &II; 12506 12507 // Because typo correction is expensive, only do it if the implicit 12508 // function declaration is going to be treated as an error. 12509 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12510 TypoCorrection Corrected; 12511 if (S && 12512 (Corrected = CorrectTypo( 12513 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12514 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12515 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12516 /*ErrorRecovery*/false); 12517 } 12518 12519 // Set a Declarator for the implicit definition: int foo(); 12520 const char *Dummy; 12521 AttributeFactory attrFactory; 12522 DeclSpec DS(attrFactory); 12523 unsigned DiagID; 12524 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12525 Context.getPrintingPolicy()); 12526 (void)Error; // Silence warning. 12527 assert(!Error && "Error setting up implicit decl!"); 12528 SourceLocation NoLoc; 12529 Declarator D(DS, Declarator::BlockContext); 12530 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12531 /*IsAmbiguous=*/false, 12532 /*LParenLoc=*/NoLoc, 12533 /*Params=*/nullptr, 12534 /*NumParams=*/0, 12535 /*EllipsisLoc=*/NoLoc, 12536 /*RParenLoc=*/NoLoc, 12537 /*TypeQuals=*/0, 12538 /*RefQualifierIsLvalueRef=*/true, 12539 /*RefQualifierLoc=*/NoLoc, 12540 /*ConstQualifierLoc=*/NoLoc, 12541 /*VolatileQualifierLoc=*/NoLoc, 12542 /*RestrictQualifierLoc=*/NoLoc, 12543 /*MutableLoc=*/NoLoc, 12544 EST_None, 12545 /*ESpecRange=*/SourceRange(), 12546 /*Exceptions=*/nullptr, 12547 /*ExceptionRanges=*/nullptr, 12548 /*NumExceptions=*/0, 12549 /*NoexceptExpr=*/nullptr, 12550 /*ExceptionSpecTokens=*/nullptr, 12551 /*DeclsInPrototype=*/None, 12552 Loc, Loc, D), 12553 DS.getAttributes(), 12554 SourceLocation()); 12555 D.SetIdentifier(&II, Loc); 12556 12557 // Insert this function into translation-unit scope. 12558 12559 DeclContext *PrevDC = CurContext; 12560 CurContext = Context.getTranslationUnitDecl(); 12561 12562 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 12563 FD->setImplicit(); 12564 12565 CurContext = PrevDC; 12566 12567 AddKnownFunctionAttributes(FD); 12568 12569 return FD; 12570 } 12571 12572 /// \brief Adds any function attributes that we know a priori based on 12573 /// the declaration of this function. 12574 /// 12575 /// These attributes can apply both to implicitly-declared builtins 12576 /// (like __builtin___printf_chk) or to library-declared functions 12577 /// like NSLog or printf. 12578 /// 12579 /// We need to check for duplicate attributes both here and where user-written 12580 /// attributes are applied to declarations. 12581 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12582 if (FD->isInvalidDecl()) 12583 return; 12584 12585 // If this is a built-in function, map its builtin attributes to 12586 // actual attributes. 12587 if (unsigned BuiltinID = FD->getBuiltinID()) { 12588 // Handle printf-formatting attributes. 12589 unsigned FormatIdx; 12590 bool HasVAListArg; 12591 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12592 if (!FD->hasAttr<FormatAttr>()) { 12593 const char *fmt = "printf"; 12594 unsigned int NumParams = FD->getNumParams(); 12595 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12596 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12597 fmt = "NSString"; 12598 FD->addAttr(FormatAttr::CreateImplicit(Context, 12599 &Context.Idents.get(fmt), 12600 FormatIdx+1, 12601 HasVAListArg ? 0 : FormatIdx+2, 12602 FD->getLocation())); 12603 } 12604 } 12605 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12606 HasVAListArg)) { 12607 if (!FD->hasAttr<FormatAttr>()) 12608 FD->addAttr(FormatAttr::CreateImplicit(Context, 12609 &Context.Idents.get("scanf"), 12610 FormatIdx+1, 12611 HasVAListArg ? 0 : FormatIdx+2, 12612 FD->getLocation())); 12613 } 12614 12615 // Mark const if we don't care about errno and that is the only 12616 // thing preventing the function from being const. This allows 12617 // IRgen to use LLVM intrinsics for such functions. 12618 if (!getLangOpts().MathErrno && 12619 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12620 if (!FD->hasAttr<ConstAttr>()) 12621 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12622 } 12623 12624 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12625 !FD->hasAttr<ReturnsTwiceAttr>()) 12626 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12627 FD->getLocation())); 12628 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12629 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12630 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12631 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12632 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12633 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12634 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12635 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12636 // Add the appropriate attribute, depending on the CUDA compilation mode 12637 // and which target the builtin belongs to. For example, during host 12638 // compilation, aux builtins are __device__, while the rest are __host__. 12639 if (getLangOpts().CUDAIsDevice != 12640 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12641 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12642 else 12643 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12644 } 12645 } 12646 12647 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12648 // throw, add an implicit nothrow attribute to any extern "C" function we come 12649 // across. 12650 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12651 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12652 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12653 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12654 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12655 } 12656 12657 IdentifierInfo *Name = FD->getIdentifier(); 12658 if (!Name) 12659 return; 12660 if ((!getLangOpts().CPlusPlus && 12661 FD->getDeclContext()->isTranslationUnit()) || 12662 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12663 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12664 LinkageSpecDecl::lang_c)) { 12665 // Okay: this could be a libc/libm/Objective-C function we know 12666 // about. 12667 } else 12668 return; 12669 12670 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12671 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12672 // target-specific builtins, perhaps? 12673 if (!FD->hasAttr<FormatAttr>()) 12674 FD->addAttr(FormatAttr::CreateImplicit(Context, 12675 &Context.Idents.get("printf"), 2, 12676 Name->isStr("vasprintf") ? 0 : 3, 12677 FD->getLocation())); 12678 } 12679 12680 if (Name->isStr("__CFStringMakeConstantString")) { 12681 // We already have a __builtin___CFStringMakeConstantString, 12682 // but builds that use -fno-constant-cfstrings don't go through that. 12683 if (!FD->hasAttr<FormatArgAttr>()) 12684 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12685 FD->getLocation())); 12686 } 12687 } 12688 12689 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12690 TypeSourceInfo *TInfo) { 12691 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12692 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12693 12694 if (!TInfo) { 12695 assert(D.isInvalidType() && "no declarator info for valid type"); 12696 TInfo = Context.getTrivialTypeSourceInfo(T); 12697 } 12698 12699 // Scope manipulation handled by caller. 12700 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12701 D.getLocStart(), 12702 D.getIdentifierLoc(), 12703 D.getIdentifier(), 12704 TInfo); 12705 12706 // Bail out immediately if we have an invalid declaration. 12707 if (D.isInvalidType()) { 12708 NewTD->setInvalidDecl(); 12709 return NewTD; 12710 } 12711 12712 if (D.getDeclSpec().isModulePrivateSpecified()) { 12713 if (CurContext->isFunctionOrMethod()) 12714 Diag(NewTD->getLocation(), diag::err_module_private_local) 12715 << 2 << NewTD->getDeclName() 12716 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12717 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12718 else 12719 NewTD->setModulePrivate(); 12720 } 12721 12722 // C++ [dcl.typedef]p8: 12723 // If the typedef declaration defines an unnamed class (or 12724 // enum), the first typedef-name declared by the declaration 12725 // to be that class type (or enum type) is used to denote the 12726 // class type (or enum type) for linkage purposes only. 12727 // We need to check whether the type was declared in the declaration. 12728 switch (D.getDeclSpec().getTypeSpecType()) { 12729 case TST_enum: 12730 case TST_struct: 12731 case TST_interface: 12732 case TST_union: 12733 case TST_class: { 12734 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12735 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12736 break; 12737 } 12738 12739 default: 12740 break; 12741 } 12742 12743 return NewTD; 12744 } 12745 12746 /// \brief Check that this is a valid underlying type for an enum declaration. 12747 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12748 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12749 QualType T = TI->getType(); 12750 12751 if (T->isDependentType()) 12752 return false; 12753 12754 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12755 if (BT->isInteger()) 12756 return false; 12757 12758 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12759 return true; 12760 } 12761 12762 /// Check whether this is a valid redeclaration of a previous enumeration. 12763 /// \return true if the redeclaration was invalid. 12764 bool Sema::CheckEnumRedeclaration( 12765 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12766 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12767 bool IsFixed = !EnumUnderlyingTy.isNull(); 12768 12769 if (IsScoped != Prev->isScoped()) { 12770 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12771 << Prev->isScoped(); 12772 Diag(Prev->getLocation(), diag::note_previous_declaration); 12773 return true; 12774 } 12775 12776 if (IsFixed && Prev->isFixed()) { 12777 if (!EnumUnderlyingTy->isDependentType() && 12778 !Prev->getIntegerType()->isDependentType() && 12779 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12780 Prev->getIntegerType())) { 12781 // TODO: Highlight the underlying type of the redeclaration. 12782 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12783 << EnumUnderlyingTy << Prev->getIntegerType(); 12784 Diag(Prev->getLocation(), diag::note_previous_declaration) 12785 << Prev->getIntegerTypeRange(); 12786 return true; 12787 } 12788 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12789 ; 12790 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 12791 ; 12792 } else if (IsFixed != Prev->isFixed()) { 12793 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 12794 << Prev->isFixed(); 12795 Diag(Prev->getLocation(), diag::note_previous_declaration); 12796 return true; 12797 } 12798 12799 return false; 12800 } 12801 12802 /// \brief Get diagnostic %select index for tag kind for 12803 /// redeclaration diagnostic message. 12804 /// WARNING: Indexes apply to particular diagnostics only! 12805 /// 12806 /// \returns diagnostic %select index. 12807 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 12808 switch (Tag) { 12809 case TTK_Struct: return 0; 12810 case TTK_Interface: return 1; 12811 case TTK_Class: return 2; 12812 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 12813 } 12814 } 12815 12816 /// \brief Determine if tag kind is a class-key compatible with 12817 /// class for redeclaration (class, struct, or __interface). 12818 /// 12819 /// \returns true iff the tag kind is compatible. 12820 static bool isClassCompatTagKind(TagTypeKind Tag) 12821 { 12822 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 12823 } 12824 12825 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 12826 TagTypeKind TTK) { 12827 if (isa<TypedefDecl>(PrevDecl)) 12828 return NTK_Typedef; 12829 else if (isa<TypeAliasDecl>(PrevDecl)) 12830 return NTK_TypeAlias; 12831 else if (isa<ClassTemplateDecl>(PrevDecl)) 12832 return NTK_Template; 12833 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 12834 return NTK_TypeAliasTemplate; 12835 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 12836 return NTK_TemplateTemplateArgument; 12837 switch (TTK) { 12838 case TTK_Struct: 12839 case TTK_Interface: 12840 case TTK_Class: 12841 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 12842 case TTK_Union: 12843 return NTK_NonUnion; 12844 case TTK_Enum: 12845 return NTK_NonEnum; 12846 } 12847 llvm_unreachable("invalid TTK"); 12848 } 12849 12850 /// \brief Determine whether a tag with a given kind is acceptable 12851 /// as a redeclaration of the given tag declaration. 12852 /// 12853 /// \returns true if the new tag kind is acceptable, false otherwise. 12854 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 12855 TagTypeKind NewTag, bool isDefinition, 12856 SourceLocation NewTagLoc, 12857 const IdentifierInfo *Name) { 12858 // C++ [dcl.type.elab]p3: 12859 // The class-key or enum keyword present in the 12860 // elaborated-type-specifier shall agree in kind with the 12861 // declaration to which the name in the elaborated-type-specifier 12862 // refers. This rule also applies to the form of 12863 // elaborated-type-specifier that declares a class-name or 12864 // friend class since it can be construed as referring to the 12865 // definition of the class. Thus, in any 12866 // elaborated-type-specifier, the enum keyword shall be used to 12867 // refer to an enumeration (7.2), the union class-key shall be 12868 // used to refer to a union (clause 9), and either the class or 12869 // struct class-key shall be used to refer to a class (clause 9) 12870 // declared using the class or struct class-key. 12871 TagTypeKind OldTag = Previous->getTagKind(); 12872 if (!isDefinition || !isClassCompatTagKind(NewTag)) 12873 if (OldTag == NewTag) 12874 return true; 12875 12876 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 12877 // Warn about the struct/class tag mismatch. 12878 bool isTemplate = false; 12879 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 12880 isTemplate = Record->getDescribedClassTemplate(); 12881 12882 if (inTemplateInstantiation()) { 12883 // In a template instantiation, do not offer fix-its for tag mismatches 12884 // since they usually mess up the template instead of fixing the problem. 12885 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12886 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12887 << getRedeclDiagFromTagKind(OldTag); 12888 return true; 12889 } 12890 12891 if (isDefinition) { 12892 // On definitions, check previous tags and issue a fix-it for each 12893 // one that doesn't match the current tag. 12894 if (Previous->getDefinition()) { 12895 // Don't suggest fix-its for redefinitions. 12896 return true; 12897 } 12898 12899 bool previousMismatch = false; 12900 for (auto I : Previous->redecls()) { 12901 if (I->getTagKind() != NewTag) { 12902 if (!previousMismatch) { 12903 previousMismatch = true; 12904 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 12905 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12906 << getRedeclDiagFromTagKind(I->getTagKind()); 12907 } 12908 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 12909 << getRedeclDiagFromTagKind(NewTag) 12910 << FixItHint::CreateReplacement(I->getInnerLocStart(), 12911 TypeWithKeyword::getTagTypeKindName(NewTag)); 12912 } 12913 } 12914 return true; 12915 } 12916 12917 // Check for a previous definition. If current tag and definition 12918 // are same type, do nothing. If no definition, but disagree with 12919 // with previous tag type, give a warning, but no fix-it. 12920 const TagDecl *Redecl = Previous->getDefinition() ? 12921 Previous->getDefinition() : Previous; 12922 if (Redecl->getTagKind() == NewTag) { 12923 return true; 12924 } 12925 12926 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 12927 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 12928 << getRedeclDiagFromTagKind(OldTag); 12929 Diag(Redecl->getLocation(), diag::note_previous_use); 12930 12931 // If there is a previous definition, suggest a fix-it. 12932 if (Previous->getDefinition()) { 12933 Diag(NewTagLoc, diag::note_struct_class_suggestion) 12934 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 12935 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 12936 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 12937 } 12938 12939 return true; 12940 } 12941 return false; 12942 } 12943 12944 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 12945 /// from an outer enclosing namespace or file scope inside a friend declaration. 12946 /// This should provide the commented out code in the following snippet: 12947 /// namespace N { 12948 /// struct X; 12949 /// namespace M { 12950 /// struct Y { friend struct /*N::*/ X; }; 12951 /// } 12952 /// } 12953 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 12954 SourceLocation NameLoc) { 12955 // While the decl is in a namespace, do repeated lookup of that name and see 12956 // if we get the same namespace back. If we do not, continue until 12957 // translation unit scope, at which point we have a fully qualified NNS. 12958 SmallVector<IdentifierInfo *, 4> Namespaces; 12959 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 12960 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 12961 // This tag should be declared in a namespace, which can only be enclosed by 12962 // other namespaces. Bail if there's an anonymous namespace in the chain. 12963 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 12964 if (!Namespace || Namespace->isAnonymousNamespace()) 12965 return FixItHint(); 12966 IdentifierInfo *II = Namespace->getIdentifier(); 12967 Namespaces.push_back(II); 12968 NamedDecl *Lookup = SemaRef.LookupSingleName( 12969 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 12970 if (Lookup == Namespace) 12971 break; 12972 } 12973 12974 // Once we have all the namespaces, reverse them to go outermost first, and 12975 // build an NNS. 12976 SmallString<64> Insertion; 12977 llvm::raw_svector_ostream OS(Insertion); 12978 if (DC->isTranslationUnit()) 12979 OS << "::"; 12980 std::reverse(Namespaces.begin(), Namespaces.end()); 12981 for (auto *II : Namespaces) 12982 OS << II->getName() << "::"; 12983 return FixItHint::CreateInsertion(NameLoc, Insertion); 12984 } 12985 12986 /// \brief Determine whether a tag originally declared in context \p OldDC can 12987 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 12988 /// found a declaration in \p OldDC as a previous decl, perhaps through a 12989 /// using-declaration). 12990 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 12991 DeclContext *NewDC) { 12992 OldDC = OldDC->getRedeclContext(); 12993 NewDC = NewDC->getRedeclContext(); 12994 12995 if (OldDC->Equals(NewDC)) 12996 return true; 12997 12998 // In MSVC mode, we allow a redeclaration if the contexts are related (either 12999 // encloses the other). 13000 if (S.getLangOpts().MSVCCompat && 13001 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13002 return true; 13003 13004 return false; 13005 } 13006 13007 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13008 /// former case, Name will be non-null. In the later case, Name will be null. 13009 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13010 /// reference/declaration/definition of a tag. 13011 /// 13012 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13013 /// trailing-type-specifier) other than one in an alias-declaration. 13014 /// 13015 /// \param SkipBody If non-null, will be set to indicate if the caller should 13016 /// skip the definition of this tag and treat it as if it were a declaration. 13017 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13018 SourceLocation KWLoc, CXXScopeSpec &SS, 13019 IdentifierInfo *Name, SourceLocation NameLoc, 13020 AttributeList *Attr, AccessSpecifier AS, 13021 SourceLocation ModulePrivateLoc, 13022 MultiTemplateParamsArg TemplateParameterLists, 13023 bool &OwnedDecl, bool &IsDependent, 13024 SourceLocation ScopedEnumKWLoc, 13025 bool ScopedEnumUsesClassTag, 13026 TypeResult UnderlyingType, 13027 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 13028 // If this is not a definition, it must have a name. 13029 IdentifierInfo *OrigName = Name; 13030 assert((Name != nullptr || TUK == TUK_Definition) && 13031 "Nameless record must be a definition!"); 13032 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13033 13034 OwnedDecl = false; 13035 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13036 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13037 13038 // FIXME: Check member specializations more carefully. 13039 bool isMemberSpecialization = false; 13040 bool Invalid = false; 13041 13042 // We only need to do this matching if we have template parameters 13043 // or a scope specifier, which also conveniently avoids this work 13044 // for non-C++ cases. 13045 if (TemplateParameterLists.size() > 0 || 13046 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13047 if (TemplateParameterList *TemplateParams = 13048 MatchTemplateParametersToScopeSpecifier( 13049 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13050 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13051 if (Kind == TTK_Enum) { 13052 Diag(KWLoc, diag::err_enum_template); 13053 return nullptr; 13054 } 13055 13056 if (TemplateParams->size() > 0) { 13057 // This is a declaration or definition of a class template (which may 13058 // be a member of another template). 13059 13060 if (Invalid) 13061 return nullptr; 13062 13063 OwnedDecl = false; 13064 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13065 SS, Name, NameLoc, Attr, 13066 TemplateParams, AS, 13067 ModulePrivateLoc, 13068 /*FriendLoc*/SourceLocation(), 13069 TemplateParameterLists.size()-1, 13070 TemplateParameterLists.data(), 13071 SkipBody); 13072 return Result.get(); 13073 } else { 13074 // The "template<>" header is extraneous. 13075 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13076 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13077 isMemberSpecialization = true; 13078 } 13079 } 13080 } 13081 13082 // Figure out the underlying type if this a enum declaration. We need to do 13083 // this early, because it's needed to detect if this is an incompatible 13084 // redeclaration. 13085 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13086 bool EnumUnderlyingIsImplicit = false; 13087 13088 if (Kind == TTK_Enum) { 13089 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 13090 // No underlying type explicitly specified, or we failed to parse the 13091 // type, default to int. 13092 EnumUnderlying = Context.IntTy.getTypePtr(); 13093 else if (UnderlyingType.get()) { 13094 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13095 // integral type; any cv-qualification is ignored. 13096 TypeSourceInfo *TI = nullptr; 13097 GetTypeFromParser(UnderlyingType.get(), &TI); 13098 EnumUnderlying = TI; 13099 13100 if (CheckEnumUnderlyingType(TI)) 13101 // Recover by falling back to int. 13102 EnumUnderlying = Context.IntTy.getTypePtr(); 13103 13104 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13105 UPPC_FixedUnderlyingType)) 13106 EnumUnderlying = Context.IntTy.getTypePtr(); 13107 13108 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13109 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 13110 // Microsoft enums are always of int type. 13111 EnumUnderlying = Context.IntTy.getTypePtr(); 13112 EnumUnderlyingIsImplicit = true; 13113 } 13114 } 13115 } 13116 13117 DeclContext *SearchDC = CurContext; 13118 DeclContext *DC = CurContext; 13119 bool isStdBadAlloc = false; 13120 bool isStdAlignValT = false; 13121 13122 RedeclarationKind Redecl = ForRedeclaration; 13123 if (TUK == TUK_Friend || TUK == TUK_Reference) 13124 Redecl = NotForRedeclaration; 13125 13126 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13127 if (Name && SS.isNotEmpty()) { 13128 // We have a nested-name tag ('struct foo::bar'). 13129 13130 // Check for invalid 'foo::'. 13131 if (SS.isInvalid()) { 13132 Name = nullptr; 13133 goto CreateNewDecl; 13134 } 13135 13136 // If this is a friend or a reference to a class in a dependent 13137 // context, don't try to make a decl for it. 13138 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13139 DC = computeDeclContext(SS, false); 13140 if (!DC) { 13141 IsDependent = true; 13142 return nullptr; 13143 } 13144 } else { 13145 DC = computeDeclContext(SS, true); 13146 if (!DC) { 13147 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13148 << SS.getRange(); 13149 return nullptr; 13150 } 13151 } 13152 13153 if (RequireCompleteDeclContext(SS, DC)) 13154 return nullptr; 13155 13156 SearchDC = DC; 13157 // Look-up name inside 'foo::'. 13158 LookupQualifiedName(Previous, DC); 13159 13160 if (Previous.isAmbiguous()) 13161 return nullptr; 13162 13163 if (Previous.empty()) { 13164 // Name lookup did not find anything. However, if the 13165 // nested-name-specifier refers to the current instantiation, 13166 // and that current instantiation has any dependent base 13167 // classes, we might find something at instantiation time: treat 13168 // this as a dependent elaborated-type-specifier. 13169 // But this only makes any sense for reference-like lookups. 13170 if (Previous.wasNotFoundInCurrentInstantiation() && 13171 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13172 IsDependent = true; 13173 return nullptr; 13174 } 13175 13176 // A tag 'foo::bar' must already exist. 13177 Diag(NameLoc, diag::err_not_tag_in_scope) 13178 << Kind << Name << DC << SS.getRange(); 13179 Name = nullptr; 13180 Invalid = true; 13181 goto CreateNewDecl; 13182 } 13183 } else if (Name) { 13184 // C++14 [class.mem]p14: 13185 // If T is the name of a class, then each of the following shall have a 13186 // name different from T: 13187 // -- every member of class T that is itself a type 13188 if (TUK != TUK_Reference && TUK != TUK_Friend && 13189 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13190 return nullptr; 13191 13192 // If this is a named struct, check to see if there was a previous forward 13193 // declaration or definition. 13194 // FIXME: We're looking into outer scopes here, even when we 13195 // shouldn't be. Doing so can result in ambiguities that we 13196 // shouldn't be diagnosing. 13197 LookupName(Previous, S); 13198 13199 // When declaring or defining a tag, ignore ambiguities introduced 13200 // by types using'ed into this scope. 13201 if (Previous.isAmbiguous() && 13202 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13203 LookupResult::Filter F = Previous.makeFilter(); 13204 while (F.hasNext()) { 13205 NamedDecl *ND = F.next(); 13206 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13207 SearchDC->getRedeclContext())) 13208 F.erase(); 13209 } 13210 F.done(); 13211 } 13212 13213 // C++11 [namespace.memdef]p3: 13214 // If the name in a friend declaration is neither qualified nor 13215 // a template-id and the declaration is a function or an 13216 // elaborated-type-specifier, the lookup to determine whether 13217 // the entity has been previously declared shall not consider 13218 // any scopes outside the innermost enclosing namespace. 13219 // 13220 // MSVC doesn't implement the above rule for types, so a friend tag 13221 // declaration may be a redeclaration of a type declared in an enclosing 13222 // scope. They do implement this rule for friend functions. 13223 // 13224 // Does it matter that this should be by scope instead of by 13225 // semantic context? 13226 if (!Previous.empty() && TUK == TUK_Friend) { 13227 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13228 LookupResult::Filter F = Previous.makeFilter(); 13229 bool FriendSawTagOutsideEnclosingNamespace = false; 13230 while (F.hasNext()) { 13231 NamedDecl *ND = F.next(); 13232 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13233 if (DC->isFileContext() && 13234 !EnclosingNS->Encloses(ND->getDeclContext())) { 13235 if (getLangOpts().MSVCCompat) 13236 FriendSawTagOutsideEnclosingNamespace = true; 13237 else 13238 F.erase(); 13239 } 13240 } 13241 F.done(); 13242 13243 // Diagnose this MSVC extension in the easy case where lookup would have 13244 // unambiguously found something outside the enclosing namespace. 13245 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13246 NamedDecl *ND = Previous.getFoundDecl(); 13247 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13248 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13249 } 13250 } 13251 13252 // Note: there used to be some attempt at recovery here. 13253 if (Previous.isAmbiguous()) 13254 return nullptr; 13255 13256 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13257 // FIXME: This makes sure that we ignore the contexts associated 13258 // with C structs, unions, and enums when looking for a matching 13259 // tag declaration or definition. See the similar lookup tweak 13260 // in Sema::LookupName; is there a better way to deal with this? 13261 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13262 SearchDC = SearchDC->getParent(); 13263 } 13264 } 13265 13266 if (Previous.isSingleResult() && 13267 Previous.getFoundDecl()->isTemplateParameter()) { 13268 // Maybe we will complain about the shadowed template parameter. 13269 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13270 // Just pretend that we didn't see the previous declaration. 13271 Previous.clear(); 13272 } 13273 13274 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13275 DC->Equals(getStdNamespace())) { 13276 if (Name->isStr("bad_alloc")) { 13277 // This is a declaration of or a reference to "std::bad_alloc". 13278 isStdBadAlloc = true; 13279 13280 // If std::bad_alloc has been implicitly declared (but made invisible to 13281 // name lookup), fill in this implicit declaration as the previous 13282 // declaration, so that the declarations get chained appropriately. 13283 if (Previous.empty() && StdBadAlloc) 13284 Previous.addDecl(getStdBadAlloc()); 13285 } else if (Name->isStr("align_val_t")) { 13286 isStdAlignValT = true; 13287 if (Previous.empty() && StdAlignValT) 13288 Previous.addDecl(getStdAlignValT()); 13289 } 13290 } 13291 13292 // If we didn't find a previous declaration, and this is a reference 13293 // (or friend reference), move to the correct scope. In C++, we 13294 // also need to do a redeclaration lookup there, just in case 13295 // there's a shadow friend decl. 13296 if (Name && Previous.empty() && 13297 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13298 if (Invalid) goto CreateNewDecl; 13299 assert(SS.isEmpty()); 13300 13301 if (TUK == TUK_Reference) { 13302 // C++ [basic.scope.pdecl]p5: 13303 // -- for an elaborated-type-specifier of the form 13304 // 13305 // class-key identifier 13306 // 13307 // if the elaborated-type-specifier is used in the 13308 // decl-specifier-seq or parameter-declaration-clause of a 13309 // function defined in namespace scope, the identifier is 13310 // declared as a class-name in the namespace that contains 13311 // the declaration; otherwise, except as a friend 13312 // declaration, the identifier is declared in the smallest 13313 // non-class, non-function-prototype scope that contains the 13314 // declaration. 13315 // 13316 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13317 // C structs and unions. 13318 // 13319 // It is an error in C++ to declare (rather than define) an enum 13320 // type, including via an elaborated type specifier. We'll 13321 // diagnose that later; for now, declare the enum in the same 13322 // scope as we would have picked for any other tag type. 13323 // 13324 // GNU C also supports this behavior as part of its incomplete 13325 // enum types extension, while GNU C++ does not. 13326 // 13327 // Find the context where we'll be declaring the tag. 13328 // FIXME: We would like to maintain the current DeclContext as the 13329 // lexical context, 13330 SearchDC = getTagInjectionContext(SearchDC); 13331 13332 // Find the scope where we'll be declaring the tag. 13333 S = getTagInjectionScope(S, getLangOpts()); 13334 } else { 13335 assert(TUK == TUK_Friend); 13336 // C++ [namespace.memdef]p3: 13337 // If a friend declaration in a non-local class first declares a 13338 // class or function, the friend class or function is a member of 13339 // the innermost enclosing namespace. 13340 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13341 } 13342 13343 // In C++, we need to do a redeclaration lookup to properly 13344 // diagnose some problems. 13345 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13346 // hidden declaration so that we don't get ambiguity errors when using a 13347 // type declared by an elaborated-type-specifier. In C that is not correct 13348 // and we should instead merge compatible types found by lookup. 13349 if (getLangOpts().CPlusPlus) { 13350 Previous.setRedeclarationKind(ForRedeclaration); 13351 LookupQualifiedName(Previous, SearchDC); 13352 } else { 13353 Previous.setRedeclarationKind(ForRedeclaration); 13354 LookupName(Previous, S); 13355 } 13356 } 13357 13358 // If we have a known previous declaration to use, then use it. 13359 if (Previous.empty() && SkipBody && SkipBody->Previous) 13360 Previous.addDecl(SkipBody->Previous); 13361 13362 if (!Previous.empty()) { 13363 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13364 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13365 13366 // It's okay to have a tag decl in the same scope as a typedef 13367 // which hides a tag decl in the same scope. Finding this 13368 // insanity with a redeclaration lookup can only actually happen 13369 // in C++. 13370 // 13371 // This is also okay for elaborated-type-specifiers, which is 13372 // technically forbidden by the current standard but which is 13373 // okay according to the likely resolution of an open issue; 13374 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13375 if (getLangOpts().CPlusPlus) { 13376 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13377 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13378 TagDecl *Tag = TT->getDecl(); 13379 if (Tag->getDeclName() == Name && 13380 Tag->getDeclContext()->getRedeclContext() 13381 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13382 PrevDecl = Tag; 13383 Previous.clear(); 13384 Previous.addDecl(Tag); 13385 Previous.resolveKind(); 13386 } 13387 } 13388 } 13389 } 13390 13391 // If this is a redeclaration of a using shadow declaration, it must 13392 // declare a tag in the same context. In MSVC mode, we allow a 13393 // redefinition if either context is within the other. 13394 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13395 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13396 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13397 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13398 !(OldTag && isAcceptableTagRedeclContext( 13399 *this, OldTag->getDeclContext(), SearchDC))) { 13400 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13401 Diag(Shadow->getTargetDecl()->getLocation(), 13402 diag::note_using_decl_target); 13403 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13404 << 0; 13405 // Recover by ignoring the old declaration. 13406 Previous.clear(); 13407 goto CreateNewDecl; 13408 } 13409 } 13410 13411 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13412 // If this is a use of a previous tag, or if the tag is already declared 13413 // in the same scope (so that the definition/declaration completes or 13414 // rementions the tag), reuse the decl. 13415 if (TUK == TUK_Reference || TUK == TUK_Friend || 13416 isDeclInScope(DirectPrevDecl, SearchDC, S, 13417 SS.isNotEmpty() || isMemberSpecialization)) { 13418 // Make sure that this wasn't declared as an enum and now used as a 13419 // struct or something similar. 13420 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13421 TUK == TUK_Definition, KWLoc, 13422 Name)) { 13423 bool SafeToContinue 13424 = (PrevTagDecl->getTagKind() != TTK_Enum && 13425 Kind != TTK_Enum); 13426 if (SafeToContinue) 13427 Diag(KWLoc, diag::err_use_with_wrong_tag) 13428 << Name 13429 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13430 PrevTagDecl->getKindName()); 13431 else 13432 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13433 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13434 13435 if (SafeToContinue) 13436 Kind = PrevTagDecl->getTagKind(); 13437 else { 13438 // Recover by making this an anonymous redefinition. 13439 Name = nullptr; 13440 Previous.clear(); 13441 Invalid = true; 13442 } 13443 } 13444 13445 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13446 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13447 13448 // If this is an elaborated-type-specifier for a scoped enumeration, 13449 // the 'class' keyword is not necessary and not permitted. 13450 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13451 if (ScopedEnum) 13452 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13453 << PrevEnum->isScoped() 13454 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13455 return PrevTagDecl; 13456 } 13457 13458 QualType EnumUnderlyingTy; 13459 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13460 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13461 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13462 EnumUnderlyingTy = QualType(T, 0); 13463 13464 // All conflicts with previous declarations are recovered by 13465 // returning the previous declaration, unless this is a definition, 13466 // in which case we want the caller to bail out. 13467 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13468 ScopedEnum, EnumUnderlyingTy, 13469 EnumUnderlyingIsImplicit, PrevEnum)) 13470 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13471 } 13472 13473 // C++11 [class.mem]p1: 13474 // A member shall not be declared twice in the member-specification, 13475 // except that a nested class or member class template can be declared 13476 // and then later defined. 13477 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13478 S->isDeclScope(PrevDecl)) { 13479 Diag(NameLoc, diag::ext_member_redeclared); 13480 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13481 } 13482 13483 if (!Invalid) { 13484 // If this is a use, just return the declaration we found, unless 13485 // we have attributes. 13486 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13487 if (Attr) { 13488 // FIXME: Diagnose these attributes. For now, we create a new 13489 // declaration to hold them. 13490 } else if (TUK == TUK_Reference && 13491 (PrevTagDecl->getFriendObjectKind() == 13492 Decl::FOK_Undeclared || 13493 PP.getModuleContainingLocation( 13494 PrevDecl->getLocation()) != 13495 PP.getModuleContainingLocation(KWLoc)) && 13496 SS.isEmpty()) { 13497 // This declaration is a reference to an existing entity, but 13498 // has different visibility from that entity: it either makes 13499 // a friend visible or it makes a type visible in a new module. 13500 // In either case, create a new declaration. We only do this if 13501 // the declaration would have meant the same thing if no prior 13502 // declaration were found, that is, if it was found in the same 13503 // scope where we would have injected a declaration. 13504 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13505 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13506 return PrevTagDecl; 13507 // This is in the injected scope, create a new declaration in 13508 // that scope. 13509 S = getTagInjectionScope(S, getLangOpts()); 13510 } else { 13511 return PrevTagDecl; 13512 } 13513 } 13514 13515 // Diagnose attempts to redefine a tag. 13516 if (TUK == TUK_Definition) { 13517 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13518 // If we're defining a specialization and the previous definition 13519 // is from an implicit instantiation, don't emit an error 13520 // here; we'll catch this in the general case below. 13521 bool IsExplicitSpecializationAfterInstantiation = false; 13522 if (isMemberSpecialization) { 13523 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13524 IsExplicitSpecializationAfterInstantiation = 13525 RD->getTemplateSpecializationKind() != 13526 TSK_ExplicitSpecialization; 13527 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13528 IsExplicitSpecializationAfterInstantiation = 13529 ED->getTemplateSpecializationKind() != 13530 TSK_ExplicitSpecialization; 13531 } 13532 13533 NamedDecl *Hidden = nullptr; 13534 if (SkipBody && getLangOpts().CPlusPlus && 13535 !hasVisibleDefinition(Def, &Hidden)) { 13536 // There is a definition of this tag, but it is not visible. We 13537 // explicitly make use of C++'s one definition rule here, and 13538 // assume that this definition is identical to the hidden one 13539 // we already have. Make the existing definition visible and 13540 // use it in place of this one. 13541 SkipBody->ShouldSkip = true; 13542 makeMergedDefinitionVisible(Hidden); 13543 return Def; 13544 } else if (!IsExplicitSpecializationAfterInstantiation) { 13545 // A redeclaration in function prototype scope in C isn't 13546 // visible elsewhere, so merely issue a warning. 13547 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13548 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13549 else 13550 Diag(NameLoc, diag::err_redefinition) << Name; 13551 notePreviousDefinition(Def->getLocation(), 13552 NameLoc.isValid() ? NameLoc : KWLoc); 13553 // If this is a redefinition, recover by making this 13554 // struct be anonymous, which will make any later 13555 // references get the previous definition. 13556 Name = nullptr; 13557 Previous.clear(); 13558 Invalid = true; 13559 } 13560 } else { 13561 // If the type is currently being defined, complain 13562 // about a nested redefinition. 13563 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13564 if (TD->isBeingDefined()) { 13565 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13566 Diag(PrevTagDecl->getLocation(), 13567 diag::note_previous_definition); 13568 Name = nullptr; 13569 Previous.clear(); 13570 Invalid = true; 13571 } 13572 } 13573 13574 // Okay, this is definition of a previously declared or referenced 13575 // tag. We're going to create a new Decl for it. 13576 } 13577 13578 // Okay, we're going to make a redeclaration. If this is some kind 13579 // of reference, make sure we build the redeclaration in the same DC 13580 // as the original, and ignore the current access specifier. 13581 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13582 SearchDC = PrevTagDecl->getDeclContext(); 13583 AS = AS_none; 13584 } 13585 } 13586 // If we get here we have (another) forward declaration or we 13587 // have a definition. Just create a new decl. 13588 13589 } else { 13590 // If we get here, this is a definition of a new tag type in a nested 13591 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13592 // new decl/type. We set PrevDecl to NULL so that the entities 13593 // have distinct types. 13594 Previous.clear(); 13595 } 13596 // If we get here, we're going to create a new Decl. If PrevDecl 13597 // is non-NULL, it's a definition of the tag declared by 13598 // PrevDecl. If it's NULL, we have a new definition. 13599 13600 // Otherwise, PrevDecl is not a tag, but was found with tag 13601 // lookup. This is only actually possible in C++, where a few 13602 // things like templates still live in the tag namespace. 13603 } else { 13604 // Use a better diagnostic if an elaborated-type-specifier 13605 // found the wrong kind of type on the first 13606 // (non-redeclaration) lookup. 13607 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13608 !Previous.isForRedeclaration()) { 13609 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13610 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13611 << Kind; 13612 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13613 Invalid = true; 13614 13615 // Otherwise, only diagnose if the declaration is in scope. 13616 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13617 SS.isNotEmpty() || isMemberSpecialization)) { 13618 // do nothing 13619 13620 // Diagnose implicit declarations introduced by elaborated types. 13621 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13622 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13623 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13624 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13625 Invalid = true; 13626 13627 // Otherwise it's a declaration. Call out a particularly common 13628 // case here. 13629 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13630 unsigned Kind = 0; 13631 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13632 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13633 << Name << Kind << TND->getUnderlyingType(); 13634 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13635 Invalid = true; 13636 13637 // Otherwise, diagnose. 13638 } else { 13639 // The tag name clashes with something else in the target scope, 13640 // issue an error and recover by making this tag be anonymous. 13641 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13642 notePreviousDefinition(PrevDecl->getLocation(), NameLoc); 13643 Name = nullptr; 13644 Invalid = true; 13645 } 13646 13647 // The existing declaration isn't relevant to us; we're in a 13648 // new scope, so clear out the previous declaration. 13649 Previous.clear(); 13650 } 13651 } 13652 13653 CreateNewDecl: 13654 13655 TagDecl *PrevDecl = nullptr; 13656 if (Previous.isSingleResult()) 13657 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13658 13659 // If there is an identifier, use the location of the identifier as the 13660 // location of the decl, otherwise use the location of the struct/union 13661 // keyword. 13662 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13663 13664 // Otherwise, create a new declaration. If there is a previous 13665 // declaration of the same entity, the two will be linked via 13666 // PrevDecl. 13667 TagDecl *New; 13668 13669 bool IsForwardReference = false; 13670 if (Kind == TTK_Enum) { 13671 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13672 // enum X { A, B, C } D; D should chain to X. 13673 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13674 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13675 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13676 13677 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13678 StdAlignValT = cast<EnumDecl>(New); 13679 13680 // If this is an undefined enum, warn. 13681 if (TUK != TUK_Definition && !Invalid) { 13682 TagDecl *Def; 13683 if (!EnumUnderlyingIsImplicit && 13684 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13685 cast<EnumDecl>(New)->isFixed()) { 13686 // C++0x: 7.2p2: opaque-enum-declaration. 13687 // Conflicts are diagnosed above. Do nothing. 13688 } 13689 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13690 Diag(Loc, diag::ext_forward_ref_enum_def) 13691 << New; 13692 Diag(Def->getLocation(), diag::note_previous_definition); 13693 } else { 13694 unsigned DiagID = diag::ext_forward_ref_enum; 13695 if (getLangOpts().MSVCCompat) 13696 DiagID = diag::ext_ms_forward_ref_enum; 13697 else if (getLangOpts().CPlusPlus) 13698 DiagID = diag::err_forward_ref_enum; 13699 Diag(Loc, DiagID); 13700 13701 // If this is a forward-declared reference to an enumeration, make a 13702 // note of it; we won't actually be introducing the declaration into 13703 // the declaration context. 13704 if (TUK == TUK_Reference) 13705 IsForwardReference = true; 13706 } 13707 } 13708 13709 if (EnumUnderlying) { 13710 EnumDecl *ED = cast<EnumDecl>(New); 13711 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13712 ED->setIntegerTypeSourceInfo(TI); 13713 else 13714 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13715 ED->setPromotionType(ED->getIntegerType()); 13716 } 13717 } else { 13718 // struct/union/class 13719 13720 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13721 // struct X { int A; } D; D should chain to X. 13722 if (getLangOpts().CPlusPlus) { 13723 // FIXME: Look for a way to use RecordDecl for simple structs. 13724 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13725 cast_or_null<CXXRecordDecl>(PrevDecl)); 13726 13727 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13728 StdBadAlloc = cast<CXXRecordDecl>(New); 13729 } else 13730 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13731 cast_or_null<RecordDecl>(PrevDecl)); 13732 } 13733 13734 // C++11 [dcl.type]p3: 13735 // A type-specifier-seq shall not define a class or enumeration [...]. 13736 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 13737 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 13738 << Context.getTagDeclType(New); 13739 Invalid = true; 13740 } 13741 13742 // Maybe add qualifier info. 13743 if (SS.isNotEmpty()) { 13744 if (SS.isSet()) { 13745 // If this is either a declaration or a definition, check the 13746 // nested-name-specifier against the current context. We don't do this 13747 // for explicit specializations, because they have similar checking 13748 // (with more specific diagnostics) in the call to 13749 // CheckMemberSpecialization, below. 13750 if (!isMemberSpecialization && 13751 (TUK == TUK_Definition || TUK == TUK_Declaration) && 13752 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 13753 Invalid = true; 13754 13755 New->setQualifierInfo(SS.getWithLocInContext(Context)); 13756 if (TemplateParameterLists.size() > 0) { 13757 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 13758 } 13759 } 13760 else 13761 Invalid = true; 13762 } 13763 13764 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13765 // Add alignment attributes if necessary; these attributes are checked when 13766 // the ASTContext lays out the structure. 13767 // 13768 // It is important for implementing the correct semantics that this 13769 // happen here (in act on tag decl). The #pragma pack stack is 13770 // maintained as a result of parser callbacks which can occur at 13771 // many points during the parsing of a struct declaration (because 13772 // the #pragma tokens are effectively skipped over during the 13773 // parsing of the struct). 13774 if (TUK == TUK_Definition) { 13775 AddAlignmentAttributesForRecord(RD); 13776 AddMsStructLayoutForRecord(RD); 13777 } 13778 } 13779 13780 if (ModulePrivateLoc.isValid()) { 13781 if (isMemberSpecialization) 13782 Diag(New->getLocation(), diag::err_module_private_specialization) 13783 << 2 13784 << FixItHint::CreateRemoval(ModulePrivateLoc); 13785 // __module_private__ does not apply to local classes. However, we only 13786 // diagnose this as an error when the declaration specifiers are 13787 // freestanding. Here, we just ignore the __module_private__. 13788 else if (!SearchDC->isFunctionOrMethod()) 13789 New->setModulePrivate(); 13790 } 13791 13792 // If this is a specialization of a member class (of a class template), 13793 // check the specialization. 13794 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 13795 Invalid = true; 13796 13797 // If we're declaring or defining a tag in function prototype scope in C, 13798 // note that this type can only be used within the function and add it to 13799 // the list of decls to inject into the function definition scope. 13800 if ((Name || Kind == TTK_Enum) && 13801 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 13802 if (getLangOpts().CPlusPlus) { 13803 // C++ [dcl.fct]p6: 13804 // Types shall not be defined in return or parameter types. 13805 if (TUK == TUK_Definition && !IsTypeSpecifier) { 13806 Diag(Loc, diag::err_type_defined_in_param_type) 13807 << Name; 13808 Invalid = true; 13809 } 13810 } else if (!PrevDecl) { 13811 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 13812 } 13813 } 13814 13815 if (Invalid) 13816 New->setInvalidDecl(); 13817 13818 // Set the lexical context. If the tag has a C++ scope specifier, the 13819 // lexical context will be different from the semantic context. 13820 New->setLexicalDeclContext(CurContext); 13821 13822 // Mark this as a friend decl if applicable. 13823 // In Microsoft mode, a friend declaration also acts as a forward 13824 // declaration so we always pass true to setObjectOfFriendDecl to make 13825 // the tag name visible. 13826 if (TUK == TUK_Friend) 13827 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 13828 13829 // Set the access specifier. 13830 if (!Invalid && SearchDC->isRecord()) 13831 SetMemberAccessSpecifier(New, PrevDecl, AS); 13832 13833 if (TUK == TUK_Definition) 13834 New->startDefinition(); 13835 13836 if (Attr) 13837 ProcessDeclAttributeList(S, New, Attr); 13838 AddPragmaAttributes(S, New); 13839 13840 // If this has an identifier, add it to the scope stack. 13841 if (TUK == TUK_Friend) { 13842 // We might be replacing an existing declaration in the lookup tables; 13843 // if so, borrow its access specifier. 13844 if (PrevDecl) 13845 New->setAccess(PrevDecl->getAccess()); 13846 13847 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 13848 DC->makeDeclVisibleInContext(New); 13849 if (Name) // can be null along some error paths 13850 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 13851 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 13852 } else if (Name) { 13853 S = getNonFieldDeclScope(S); 13854 PushOnScopeChains(New, S, !IsForwardReference); 13855 if (IsForwardReference) 13856 SearchDC->makeDeclVisibleInContext(New); 13857 } else { 13858 CurContext->addDecl(New); 13859 } 13860 13861 // If this is the C FILE type, notify the AST context. 13862 if (IdentifierInfo *II = New->getIdentifier()) 13863 if (!New->isInvalidDecl() && 13864 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 13865 II->isStr("FILE")) 13866 Context.setFILEDecl(New); 13867 13868 if (PrevDecl) 13869 mergeDeclAttributes(New, PrevDecl); 13870 13871 // If there's a #pragma GCC visibility in scope, set the visibility of this 13872 // record. 13873 AddPushedVisibilityAttribute(New); 13874 13875 if (isMemberSpecialization && !New->isInvalidDecl()) 13876 CompleteMemberSpecialization(New, Previous); 13877 13878 OwnedDecl = true; 13879 // In C++, don't return an invalid declaration. We can't recover well from 13880 // the cases where we make the type anonymous. 13881 if (Invalid && getLangOpts().CPlusPlus) { 13882 if (New->isBeingDefined()) 13883 if (auto RD = dyn_cast<RecordDecl>(New)) 13884 RD->completeDefinition(); 13885 return nullptr; 13886 } else { 13887 return New; 13888 } 13889 } 13890 13891 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 13892 AdjustDeclIfTemplate(TagD); 13893 TagDecl *Tag = cast<TagDecl>(TagD); 13894 13895 // Enter the tag context. 13896 PushDeclContext(S, Tag); 13897 13898 ActOnDocumentableDecl(TagD); 13899 13900 // If there's a #pragma GCC visibility in scope, set the visibility of this 13901 // record. 13902 AddPushedVisibilityAttribute(Tag); 13903 } 13904 13905 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 13906 assert(isa<ObjCContainerDecl>(IDecl) && 13907 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 13908 DeclContext *OCD = cast<DeclContext>(IDecl); 13909 assert(getContainingDC(OCD) == CurContext && 13910 "The next DeclContext should be lexically contained in the current one."); 13911 CurContext = OCD; 13912 return IDecl; 13913 } 13914 13915 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 13916 SourceLocation FinalLoc, 13917 bool IsFinalSpelledSealed, 13918 SourceLocation LBraceLoc) { 13919 AdjustDeclIfTemplate(TagD); 13920 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 13921 13922 FieldCollector->StartClass(); 13923 13924 if (!Record->getIdentifier()) 13925 return; 13926 13927 if (FinalLoc.isValid()) 13928 Record->addAttr(new (Context) 13929 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 13930 13931 // C++ [class]p2: 13932 // [...] The class-name is also inserted into the scope of the 13933 // class itself; this is known as the injected-class-name. For 13934 // purposes of access checking, the injected-class-name is treated 13935 // as if it were a public member name. 13936 CXXRecordDecl *InjectedClassName 13937 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 13938 Record->getLocStart(), Record->getLocation(), 13939 Record->getIdentifier(), 13940 /*PrevDecl=*/nullptr, 13941 /*DelayTypeCreation=*/true); 13942 Context.getTypeDeclType(InjectedClassName, Record); 13943 InjectedClassName->setImplicit(); 13944 InjectedClassName->setAccess(AS_public); 13945 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 13946 InjectedClassName->setDescribedClassTemplate(Template); 13947 PushOnScopeChains(InjectedClassName, S); 13948 assert(InjectedClassName->isInjectedClassName() && 13949 "Broken injected-class-name"); 13950 } 13951 13952 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 13953 SourceRange BraceRange) { 13954 AdjustDeclIfTemplate(TagD); 13955 TagDecl *Tag = cast<TagDecl>(TagD); 13956 Tag->setBraceRange(BraceRange); 13957 13958 // Make sure we "complete" the definition even it is invalid. 13959 if (Tag->isBeingDefined()) { 13960 assert(Tag->isInvalidDecl() && "We should already have completed it"); 13961 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 13962 RD->completeDefinition(); 13963 } 13964 13965 if (isa<CXXRecordDecl>(Tag)) { 13966 FieldCollector->FinishClass(); 13967 } 13968 13969 // Exit this scope of this tag's definition. 13970 PopDeclContext(); 13971 13972 if (getCurLexicalContext()->isObjCContainer() && 13973 Tag->getDeclContext()->isFileContext()) 13974 Tag->setTopLevelDeclInObjCContainer(); 13975 13976 // Notify the consumer that we've defined a tag. 13977 if (!Tag->isInvalidDecl()) 13978 Consumer.HandleTagDeclDefinition(Tag); 13979 } 13980 13981 void Sema::ActOnObjCContainerFinishDefinition() { 13982 // Exit this scope of this interface definition. 13983 PopDeclContext(); 13984 } 13985 13986 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 13987 assert(DC == CurContext && "Mismatch of container contexts"); 13988 OriginalLexicalContext = DC; 13989 ActOnObjCContainerFinishDefinition(); 13990 } 13991 13992 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 13993 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 13994 OriginalLexicalContext = nullptr; 13995 } 13996 13997 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 13998 AdjustDeclIfTemplate(TagD); 13999 TagDecl *Tag = cast<TagDecl>(TagD); 14000 Tag->setInvalidDecl(); 14001 14002 // Make sure we "complete" the definition even it is invalid. 14003 if (Tag->isBeingDefined()) { 14004 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14005 RD->completeDefinition(); 14006 } 14007 14008 // We're undoing ActOnTagStartDefinition here, not 14009 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14010 // the FieldCollector. 14011 14012 PopDeclContext(); 14013 } 14014 14015 // Note that FieldName may be null for anonymous bitfields. 14016 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14017 IdentifierInfo *FieldName, 14018 QualType FieldTy, bool IsMsStruct, 14019 Expr *BitWidth, bool *ZeroWidth) { 14020 // Default to true; that shouldn't confuse checks for emptiness 14021 if (ZeroWidth) 14022 *ZeroWidth = true; 14023 14024 // C99 6.7.2.1p4 - verify the field type. 14025 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14026 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14027 // Handle incomplete types with specific error. 14028 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14029 return ExprError(); 14030 if (FieldName) 14031 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14032 << FieldName << FieldTy << BitWidth->getSourceRange(); 14033 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14034 << FieldTy << BitWidth->getSourceRange(); 14035 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14036 UPPC_BitFieldWidth)) 14037 return ExprError(); 14038 14039 // If the bit-width is type- or value-dependent, don't try to check 14040 // it now. 14041 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14042 return BitWidth; 14043 14044 llvm::APSInt Value; 14045 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14046 if (ICE.isInvalid()) 14047 return ICE; 14048 BitWidth = ICE.get(); 14049 14050 if (Value != 0 && ZeroWidth) 14051 *ZeroWidth = false; 14052 14053 // Zero-width bitfield is ok for anonymous field. 14054 if (Value == 0 && FieldName) 14055 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14056 14057 if (Value.isSigned() && Value.isNegative()) { 14058 if (FieldName) 14059 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14060 << FieldName << Value.toString(10); 14061 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14062 << Value.toString(10); 14063 } 14064 14065 if (!FieldTy->isDependentType()) { 14066 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14067 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14068 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14069 14070 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14071 // ABI. 14072 bool CStdConstraintViolation = 14073 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14074 bool MSBitfieldViolation = 14075 Value.ugt(TypeStorageSize) && 14076 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14077 if (CStdConstraintViolation || MSBitfieldViolation) { 14078 unsigned DiagWidth = 14079 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14080 if (FieldName) 14081 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14082 << FieldName << (unsigned)Value.getZExtValue() 14083 << !CStdConstraintViolation << DiagWidth; 14084 14085 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14086 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14087 << DiagWidth; 14088 } 14089 14090 // Warn on types where the user might conceivably expect to get all 14091 // specified bits as value bits: that's all integral types other than 14092 // 'bool'. 14093 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14094 if (FieldName) 14095 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14096 << FieldName << (unsigned)Value.getZExtValue() 14097 << (unsigned)TypeWidth; 14098 else 14099 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14100 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14101 } 14102 } 14103 14104 return BitWidth; 14105 } 14106 14107 /// ActOnField - Each field of a C struct/union is passed into this in order 14108 /// to create a FieldDecl object for it. 14109 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14110 Declarator &D, Expr *BitfieldWidth) { 14111 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14112 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14113 /*InitStyle=*/ICIS_NoInit, AS_public); 14114 return Res; 14115 } 14116 14117 /// HandleField - Analyze a field of a C struct or a C++ data member. 14118 /// 14119 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14120 SourceLocation DeclStart, 14121 Declarator &D, Expr *BitWidth, 14122 InClassInitStyle InitStyle, 14123 AccessSpecifier AS) { 14124 if (D.isDecompositionDeclarator()) { 14125 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14126 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14127 << Decomp.getSourceRange(); 14128 return nullptr; 14129 } 14130 14131 IdentifierInfo *II = D.getIdentifier(); 14132 SourceLocation Loc = DeclStart; 14133 if (II) Loc = D.getIdentifierLoc(); 14134 14135 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14136 QualType T = TInfo->getType(); 14137 if (getLangOpts().CPlusPlus) { 14138 CheckExtraCXXDefaultArguments(D); 14139 14140 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14141 UPPC_DataMemberType)) { 14142 D.setInvalidType(); 14143 T = Context.IntTy; 14144 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14145 } 14146 } 14147 14148 // TR 18037 does not allow fields to be declared with address spaces. 14149 if (T.getQualifiers().hasAddressSpace()) { 14150 Diag(Loc, diag::err_field_with_address_space); 14151 D.setInvalidType(); 14152 } 14153 14154 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14155 // used as structure or union field: image, sampler, event or block types. 14156 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14157 T->isSamplerT() || T->isBlockPointerType())) { 14158 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14159 D.setInvalidType(); 14160 } 14161 14162 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14163 14164 if (D.getDeclSpec().isInlineSpecified()) 14165 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14166 << getLangOpts().CPlusPlus1z; 14167 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14168 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14169 diag::err_invalid_thread) 14170 << DeclSpec::getSpecifierName(TSCS); 14171 14172 // Check to see if this name was declared as a member previously 14173 NamedDecl *PrevDecl = nullptr; 14174 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 14175 LookupName(Previous, S); 14176 switch (Previous.getResultKind()) { 14177 case LookupResult::Found: 14178 case LookupResult::FoundUnresolvedValue: 14179 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14180 break; 14181 14182 case LookupResult::FoundOverloaded: 14183 PrevDecl = Previous.getRepresentativeDecl(); 14184 break; 14185 14186 case LookupResult::NotFound: 14187 case LookupResult::NotFoundInCurrentInstantiation: 14188 case LookupResult::Ambiguous: 14189 break; 14190 } 14191 Previous.suppressDiagnostics(); 14192 14193 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14194 // Maybe we will complain about the shadowed template parameter. 14195 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14196 // Just pretend that we didn't see the previous declaration. 14197 PrevDecl = nullptr; 14198 } 14199 14200 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14201 PrevDecl = nullptr; 14202 14203 bool Mutable 14204 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14205 SourceLocation TSSL = D.getLocStart(); 14206 FieldDecl *NewFD 14207 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14208 TSSL, AS, PrevDecl, &D); 14209 14210 if (NewFD->isInvalidDecl()) 14211 Record->setInvalidDecl(); 14212 14213 if (D.getDeclSpec().isModulePrivateSpecified()) 14214 NewFD->setModulePrivate(); 14215 14216 if (NewFD->isInvalidDecl() && PrevDecl) { 14217 // Don't introduce NewFD into scope; there's already something 14218 // with the same name in the same scope. 14219 } else if (II) { 14220 PushOnScopeChains(NewFD, S); 14221 } else 14222 Record->addDecl(NewFD); 14223 14224 return NewFD; 14225 } 14226 14227 /// \brief Build a new FieldDecl and check its well-formedness. 14228 /// 14229 /// This routine builds a new FieldDecl given the fields name, type, 14230 /// record, etc. \p PrevDecl should refer to any previous declaration 14231 /// with the same name and in the same scope as the field to be 14232 /// created. 14233 /// 14234 /// \returns a new FieldDecl. 14235 /// 14236 /// \todo The Declarator argument is a hack. It will be removed once 14237 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14238 TypeSourceInfo *TInfo, 14239 RecordDecl *Record, SourceLocation Loc, 14240 bool Mutable, Expr *BitWidth, 14241 InClassInitStyle InitStyle, 14242 SourceLocation TSSL, 14243 AccessSpecifier AS, NamedDecl *PrevDecl, 14244 Declarator *D) { 14245 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14246 bool InvalidDecl = false; 14247 if (D) InvalidDecl = D->isInvalidType(); 14248 14249 // If we receive a broken type, recover by assuming 'int' and 14250 // marking this declaration as invalid. 14251 if (T.isNull()) { 14252 InvalidDecl = true; 14253 T = Context.IntTy; 14254 } 14255 14256 QualType EltTy = Context.getBaseElementType(T); 14257 if (!EltTy->isDependentType()) { 14258 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14259 // Fields of incomplete type force their record to be invalid. 14260 Record->setInvalidDecl(); 14261 InvalidDecl = true; 14262 } else { 14263 NamedDecl *Def; 14264 EltTy->isIncompleteType(&Def); 14265 if (Def && Def->isInvalidDecl()) { 14266 Record->setInvalidDecl(); 14267 InvalidDecl = true; 14268 } 14269 } 14270 } 14271 14272 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14273 if (BitWidth && getLangOpts().OpenCL) { 14274 Diag(Loc, diag::err_opencl_bitfields); 14275 InvalidDecl = true; 14276 } 14277 14278 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14279 // than a variably modified type. 14280 if (!InvalidDecl && T->isVariablyModifiedType()) { 14281 bool SizeIsNegative; 14282 llvm::APSInt Oversized; 14283 14284 TypeSourceInfo *FixedTInfo = 14285 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14286 SizeIsNegative, 14287 Oversized); 14288 if (FixedTInfo) { 14289 Diag(Loc, diag::warn_illegal_constant_array_size); 14290 TInfo = FixedTInfo; 14291 T = FixedTInfo->getType(); 14292 } else { 14293 if (SizeIsNegative) 14294 Diag(Loc, diag::err_typecheck_negative_array_size); 14295 else if (Oversized.getBoolValue()) 14296 Diag(Loc, diag::err_array_too_large) 14297 << Oversized.toString(10); 14298 else 14299 Diag(Loc, diag::err_typecheck_field_variable_size); 14300 InvalidDecl = true; 14301 } 14302 } 14303 14304 // Fields can not have abstract class types 14305 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14306 diag::err_abstract_type_in_decl, 14307 AbstractFieldType)) 14308 InvalidDecl = true; 14309 14310 bool ZeroWidth = false; 14311 if (InvalidDecl) 14312 BitWidth = nullptr; 14313 // If this is declared as a bit-field, check the bit-field. 14314 if (BitWidth) { 14315 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14316 &ZeroWidth).get(); 14317 if (!BitWidth) { 14318 InvalidDecl = true; 14319 BitWidth = nullptr; 14320 ZeroWidth = false; 14321 } 14322 } 14323 14324 // Check that 'mutable' is consistent with the type of the declaration. 14325 if (!InvalidDecl && Mutable) { 14326 unsigned DiagID = 0; 14327 if (T->isReferenceType()) 14328 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14329 : diag::err_mutable_reference; 14330 else if (T.isConstQualified()) 14331 DiagID = diag::err_mutable_const; 14332 14333 if (DiagID) { 14334 SourceLocation ErrLoc = Loc; 14335 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14336 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14337 Diag(ErrLoc, DiagID); 14338 if (DiagID != diag::ext_mutable_reference) { 14339 Mutable = false; 14340 InvalidDecl = true; 14341 } 14342 } 14343 } 14344 14345 // C++11 [class.union]p8 (DR1460): 14346 // At most one variant member of a union may have a 14347 // brace-or-equal-initializer. 14348 if (InitStyle != ICIS_NoInit) 14349 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14350 14351 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14352 BitWidth, Mutable, InitStyle); 14353 if (InvalidDecl) 14354 NewFD->setInvalidDecl(); 14355 14356 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14357 Diag(Loc, diag::err_duplicate_member) << II; 14358 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14359 NewFD->setInvalidDecl(); 14360 } 14361 14362 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14363 if (Record->isUnion()) { 14364 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14365 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14366 if (RDecl->getDefinition()) { 14367 // C++ [class.union]p1: An object of a class with a non-trivial 14368 // constructor, a non-trivial copy constructor, a non-trivial 14369 // destructor, or a non-trivial copy assignment operator 14370 // cannot be a member of a union, nor can an array of such 14371 // objects. 14372 if (CheckNontrivialField(NewFD)) 14373 NewFD->setInvalidDecl(); 14374 } 14375 } 14376 14377 // C++ [class.union]p1: If a union contains a member of reference type, 14378 // the program is ill-formed, except when compiling with MSVC extensions 14379 // enabled. 14380 if (EltTy->isReferenceType()) { 14381 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14382 diag::ext_union_member_of_reference_type : 14383 diag::err_union_member_of_reference_type) 14384 << NewFD->getDeclName() << EltTy; 14385 if (!getLangOpts().MicrosoftExt) 14386 NewFD->setInvalidDecl(); 14387 } 14388 } 14389 } 14390 14391 // FIXME: We need to pass in the attributes given an AST 14392 // representation, not a parser representation. 14393 if (D) { 14394 // FIXME: The current scope is almost... but not entirely... correct here. 14395 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14396 14397 if (NewFD->hasAttrs()) 14398 CheckAlignasUnderalignment(NewFD); 14399 } 14400 14401 // In auto-retain/release, infer strong retension for fields of 14402 // retainable type. 14403 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14404 NewFD->setInvalidDecl(); 14405 14406 if (T.isObjCGCWeak()) 14407 Diag(Loc, diag::warn_attribute_weak_on_field); 14408 14409 NewFD->setAccess(AS); 14410 return NewFD; 14411 } 14412 14413 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14414 assert(FD); 14415 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14416 14417 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14418 return false; 14419 14420 QualType EltTy = Context.getBaseElementType(FD->getType()); 14421 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14422 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14423 if (RDecl->getDefinition()) { 14424 // We check for copy constructors before constructors 14425 // because otherwise we'll never get complaints about 14426 // copy constructors. 14427 14428 CXXSpecialMember member = CXXInvalid; 14429 // We're required to check for any non-trivial constructors. Since the 14430 // implicit default constructor is suppressed if there are any 14431 // user-declared constructors, we just need to check that there is a 14432 // trivial default constructor and a trivial copy constructor. (We don't 14433 // worry about move constructors here, since this is a C++98 check.) 14434 if (RDecl->hasNonTrivialCopyConstructor()) 14435 member = CXXCopyConstructor; 14436 else if (!RDecl->hasTrivialDefaultConstructor()) 14437 member = CXXDefaultConstructor; 14438 else if (RDecl->hasNonTrivialCopyAssignment()) 14439 member = CXXCopyAssignment; 14440 else if (RDecl->hasNonTrivialDestructor()) 14441 member = CXXDestructor; 14442 14443 if (member != CXXInvalid) { 14444 if (!getLangOpts().CPlusPlus11 && 14445 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14446 // Objective-C++ ARC: it is an error to have a non-trivial field of 14447 // a union. However, system headers in Objective-C programs 14448 // occasionally have Objective-C lifetime objects within unions, 14449 // and rather than cause the program to fail, we make those 14450 // members unavailable. 14451 SourceLocation Loc = FD->getLocation(); 14452 if (getSourceManager().isInSystemHeader(Loc)) { 14453 if (!FD->hasAttr<UnavailableAttr>()) 14454 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14455 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14456 return false; 14457 } 14458 } 14459 14460 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14461 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14462 diag::err_illegal_union_or_anon_struct_member) 14463 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14464 DiagnoseNontrivial(RDecl, member); 14465 return !getLangOpts().CPlusPlus11; 14466 } 14467 } 14468 } 14469 14470 return false; 14471 } 14472 14473 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14474 /// AST enum value. 14475 static ObjCIvarDecl::AccessControl 14476 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14477 switch (ivarVisibility) { 14478 default: llvm_unreachable("Unknown visitibility kind"); 14479 case tok::objc_private: return ObjCIvarDecl::Private; 14480 case tok::objc_public: return ObjCIvarDecl::Public; 14481 case tok::objc_protected: return ObjCIvarDecl::Protected; 14482 case tok::objc_package: return ObjCIvarDecl::Package; 14483 } 14484 } 14485 14486 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14487 /// in order to create an IvarDecl object for it. 14488 Decl *Sema::ActOnIvar(Scope *S, 14489 SourceLocation DeclStart, 14490 Declarator &D, Expr *BitfieldWidth, 14491 tok::ObjCKeywordKind Visibility) { 14492 14493 IdentifierInfo *II = D.getIdentifier(); 14494 Expr *BitWidth = (Expr*)BitfieldWidth; 14495 SourceLocation Loc = DeclStart; 14496 if (II) Loc = D.getIdentifierLoc(); 14497 14498 // FIXME: Unnamed fields can be handled in various different ways, for 14499 // example, unnamed unions inject all members into the struct namespace! 14500 14501 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14502 QualType T = TInfo->getType(); 14503 14504 if (BitWidth) { 14505 // 6.7.2.1p3, 6.7.2.1p4 14506 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14507 if (!BitWidth) 14508 D.setInvalidType(); 14509 } else { 14510 // Not a bitfield. 14511 14512 // validate II. 14513 14514 } 14515 if (T->isReferenceType()) { 14516 Diag(Loc, diag::err_ivar_reference_type); 14517 D.setInvalidType(); 14518 } 14519 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14520 // than a variably modified type. 14521 else if (T->isVariablyModifiedType()) { 14522 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14523 D.setInvalidType(); 14524 } 14525 14526 // Get the visibility (access control) for this ivar. 14527 ObjCIvarDecl::AccessControl ac = 14528 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14529 : ObjCIvarDecl::None; 14530 // Must set ivar's DeclContext to its enclosing interface. 14531 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14532 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14533 return nullptr; 14534 ObjCContainerDecl *EnclosingContext; 14535 if (ObjCImplementationDecl *IMPDecl = 14536 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14537 if (LangOpts.ObjCRuntime.isFragile()) { 14538 // Case of ivar declared in an implementation. Context is that of its class. 14539 EnclosingContext = IMPDecl->getClassInterface(); 14540 assert(EnclosingContext && "Implementation has no class interface!"); 14541 } 14542 else 14543 EnclosingContext = EnclosingDecl; 14544 } else { 14545 if (ObjCCategoryDecl *CDecl = 14546 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14547 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14548 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14549 return nullptr; 14550 } 14551 } 14552 EnclosingContext = EnclosingDecl; 14553 } 14554 14555 // Construct the decl. 14556 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14557 DeclStart, Loc, II, T, 14558 TInfo, ac, (Expr *)BitfieldWidth); 14559 14560 if (II) { 14561 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14562 ForRedeclaration); 14563 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14564 && !isa<TagDecl>(PrevDecl)) { 14565 Diag(Loc, diag::err_duplicate_member) << II; 14566 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14567 NewID->setInvalidDecl(); 14568 } 14569 } 14570 14571 // Process attributes attached to the ivar. 14572 ProcessDeclAttributes(S, NewID, D); 14573 14574 if (D.isInvalidType()) 14575 NewID->setInvalidDecl(); 14576 14577 // In ARC, infer 'retaining' for ivars of retainable type. 14578 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14579 NewID->setInvalidDecl(); 14580 14581 if (D.getDeclSpec().isModulePrivateSpecified()) 14582 NewID->setModulePrivate(); 14583 14584 if (II) { 14585 // FIXME: When interfaces are DeclContexts, we'll need to add 14586 // these to the interface. 14587 S->AddDecl(NewID); 14588 IdResolver.AddDecl(NewID); 14589 } 14590 14591 if (LangOpts.ObjCRuntime.isNonFragile() && 14592 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14593 Diag(Loc, diag::warn_ivars_in_interface); 14594 14595 return NewID; 14596 } 14597 14598 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14599 /// class and class extensions. For every class \@interface and class 14600 /// extension \@interface, if the last ivar is a bitfield of any type, 14601 /// then add an implicit `char :0` ivar to the end of that interface. 14602 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14603 SmallVectorImpl<Decl *> &AllIvarDecls) { 14604 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14605 return; 14606 14607 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14608 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14609 14610 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14611 return; 14612 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14613 if (!ID) { 14614 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14615 if (!CD->IsClassExtension()) 14616 return; 14617 } 14618 // No need to add this to end of @implementation. 14619 else 14620 return; 14621 } 14622 // All conditions are met. Add a new bitfield to the tail end of ivars. 14623 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14624 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14625 14626 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14627 DeclLoc, DeclLoc, nullptr, 14628 Context.CharTy, 14629 Context.getTrivialTypeSourceInfo(Context.CharTy, 14630 DeclLoc), 14631 ObjCIvarDecl::Private, BW, 14632 true); 14633 AllIvarDecls.push_back(Ivar); 14634 } 14635 14636 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14637 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14638 SourceLocation RBrac, AttributeList *Attr) { 14639 assert(EnclosingDecl && "missing record or interface decl"); 14640 14641 // If this is an Objective-C @implementation or category and we have 14642 // new fields here we should reset the layout of the interface since 14643 // it will now change. 14644 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14645 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14646 switch (DC->getKind()) { 14647 default: break; 14648 case Decl::ObjCCategory: 14649 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14650 break; 14651 case Decl::ObjCImplementation: 14652 Context. 14653 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14654 break; 14655 } 14656 } 14657 14658 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14659 14660 // Start counting up the number of named members; make sure to include 14661 // members of anonymous structs and unions in the total. 14662 unsigned NumNamedMembers = 0; 14663 if (Record) { 14664 for (const auto *I : Record->decls()) { 14665 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14666 if (IFD->getDeclName()) 14667 ++NumNamedMembers; 14668 } 14669 } 14670 14671 // Verify that all the fields are okay. 14672 SmallVector<FieldDecl*, 32> RecFields; 14673 14674 bool ObjCFieldLifetimeErrReported = false; 14675 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14676 i != end; ++i) { 14677 FieldDecl *FD = cast<FieldDecl>(*i); 14678 14679 // Get the type for the field. 14680 const Type *FDTy = FD->getType().getTypePtr(); 14681 14682 if (!FD->isAnonymousStructOrUnion()) { 14683 // Remember all fields written by the user. 14684 RecFields.push_back(FD); 14685 } 14686 14687 // If the field is already invalid for some reason, don't emit more 14688 // diagnostics about it. 14689 if (FD->isInvalidDecl()) { 14690 EnclosingDecl->setInvalidDecl(); 14691 continue; 14692 } 14693 14694 // C99 6.7.2.1p2: 14695 // A structure or union shall not contain a member with 14696 // incomplete or function type (hence, a structure shall not 14697 // contain an instance of itself, but may contain a pointer to 14698 // an instance of itself), except that the last member of a 14699 // structure with more than one named member may have incomplete 14700 // array type; such a structure (and any union containing, 14701 // possibly recursively, a member that is such a structure) 14702 // shall not be a member of a structure or an element of an 14703 // array. 14704 if (FDTy->isFunctionType()) { 14705 // Field declared as a function. 14706 Diag(FD->getLocation(), diag::err_field_declared_as_function) 14707 << FD->getDeclName(); 14708 FD->setInvalidDecl(); 14709 EnclosingDecl->setInvalidDecl(); 14710 continue; 14711 } else if (FDTy->isIncompleteArrayType() && Record && 14712 ((i + 1 == Fields.end() && !Record->isUnion()) || 14713 ((getLangOpts().MicrosoftExt || 14714 getLangOpts().CPlusPlus) && 14715 (i + 1 == Fields.end() || Record->isUnion())))) { 14716 // Flexible array member. 14717 // Microsoft and g++ is more permissive regarding flexible array. 14718 // It will accept flexible array in union and also 14719 // as the sole element of a struct/class. 14720 unsigned DiagID = 0; 14721 if (Record->isUnion()) 14722 DiagID = getLangOpts().MicrosoftExt 14723 ? diag::ext_flexible_array_union_ms 14724 : getLangOpts().CPlusPlus 14725 ? diag::ext_flexible_array_union_gnu 14726 : diag::err_flexible_array_union; 14727 else if (NumNamedMembers < 1) 14728 DiagID = getLangOpts().MicrosoftExt 14729 ? diag::ext_flexible_array_empty_aggregate_ms 14730 : getLangOpts().CPlusPlus 14731 ? diag::ext_flexible_array_empty_aggregate_gnu 14732 : diag::err_flexible_array_empty_aggregate; 14733 14734 if (DiagID) 14735 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 14736 << Record->getTagKind(); 14737 // While the layout of types that contain virtual bases is not specified 14738 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 14739 // virtual bases after the derived members. This would make a flexible 14740 // array member declared at the end of an object not adjacent to the end 14741 // of the type. 14742 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 14743 if (RD->getNumVBases() != 0) 14744 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 14745 << FD->getDeclName() << Record->getTagKind(); 14746 if (!getLangOpts().C99) 14747 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 14748 << FD->getDeclName() << Record->getTagKind(); 14749 14750 // If the element type has a non-trivial destructor, we would not 14751 // implicitly destroy the elements, so disallow it for now. 14752 // 14753 // FIXME: GCC allows this. We should probably either implicitly delete 14754 // the destructor of the containing class, or just allow this. 14755 QualType BaseElem = Context.getBaseElementType(FD->getType()); 14756 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 14757 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 14758 << FD->getDeclName() << FD->getType(); 14759 FD->setInvalidDecl(); 14760 EnclosingDecl->setInvalidDecl(); 14761 continue; 14762 } 14763 // Okay, we have a legal flexible array member at the end of the struct. 14764 Record->setHasFlexibleArrayMember(true); 14765 } else if (!FDTy->isDependentType() && 14766 RequireCompleteType(FD->getLocation(), FD->getType(), 14767 diag::err_field_incomplete)) { 14768 // Incomplete type 14769 FD->setInvalidDecl(); 14770 EnclosingDecl->setInvalidDecl(); 14771 continue; 14772 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 14773 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 14774 // A type which contains a flexible array member is considered to be a 14775 // flexible array member. 14776 Record->setHasFlexibleArrayMember(true); 14777 if (!Record->isUnion()) { 14778 // If this is a struct/class and this is not the last element, reject 14779 // it. Note that GCC supports variable sized arrays in the middle of 14780 // structures. 14781 if (i + 1 != Fields.end()) 14782 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 14783 << FD->getDeclName() << FD->getType(); 14784 else { 14785 // We support flexible arrays at the end of structs in 14786 // other structs as an extension. 14787 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 14788 << FD->getDeclName(); 14789 } 14790 } 14791 } 14792 if (isa<ObjCContainerDecl>(EnclosingDecl) && 14793 RequireNonAbstractType(FD->getLocation(), FD->getType(), 14794 diag::err_abstract_type_in_decl, 14795 AbstractIvarType)) { 14796 // Ivars can not have abstract class types 14797 FD->setInvalidDecl(); 14798 } 14799 if (Record && FDTTy->getDecl()->hasObjectMember()) 14800 Record->setHasObjectMember(true); 14801 if (Record && FDTTy->getDecl()->hasVolatileMember()) 14802 Record->setHasVolatileMember(true); 14803 } else if (FDTy->isObjCObjectType()) { 14804 /// A field cannot be an Objective-c object 14805 Diag(FD->getLocation(), diag::err_statically_allocated_object) 14806 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 14807 QualType T = Context.getObjCObjectPointerType(FD->getType()); 14808 FD->setType(T); 14809 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 14810 Record && !ObjCFieldLifetimeErrReported && 14811 (!getLangOpts().CPlusPlus || Record->isUnion())) { 14812 // It's an error in ARC or Weak if a field has lifetime. 14813 // We don't want to report this in a system header, though, 14814 // so we just make the field unavailable. 14815 // FIXME: that's really not sufficient; we need to make the type 14816 // itself invalid to, say, initialize or copy. 14817 QualType T = FD->getType(); 14818 if (T.hasNonTrivialObjCLifetime()) { 14819 SourceLocation loc = FD->getLocation(); 14820 if (getSourceManager().isInSystemHeader(loc)) { 14821 if (!FD->hasAttr<UnavailableAttr>()) { 14822 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14823 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 14824 } 14825 } else { 14826 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 14827 << T->isBlockPointerType() << Record->getTagKind(); 14828 } 14829 ObjCFieldLifetimeErrReported = true; 14830 } 14831 } else if (getLangOpts().ObjC1 && 14832 getLangOpts().getGC() != LangOptions::NonGC && 14833 Record && !Record->hasObjectMember()) { 14834 if (FD->getType()->isObjCObjectPointerType() || 14835 FD->getType().isObjCGCStrong()) 14836 Record->setHasObjectMember(true); 14837 else if (Context.getAsArrayType(FD->getType())) { 14838 QualType BaseType = Context.getBaseElementType(FD->getType()); 14839 if (BaseType->isRecordType() && 14840 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 14841 Record->setHasObjectMember(true); 14842 else if (BaseType->isObjCObjectPointerType() || 14843 BaseType.isObjCGCStrong()) 14844 Record->setHasObjectMember(true); 14845 } 14846 } 14847 if (Record && FD->getType().isVolatileQualified()) 14848 Record->setHasVolatileMember(true); 14849 // Keep track of the number of named members. 14850 if (FD->getIdentifier()) 14851 ++NumNamedMembers; 14852 } 14853 14854 // Okay, we successfully defined 'Record'. 14855 if (Record) { 14856 bool Completed = false; 14857 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14858 if (!CXXRecord->isInvalidDecl()) { 14859 // Set access bits correctly on the directly-declared conversions. 14860 for (CXXRecordDecl::conversion_iterator 14861 I = CXXRecord->conversion_begin(), 14862 E = CXXRecord->conversion_end(); I != E; ++I) 14863 I.setAccess((*I)->getAccess()); 14864 } 14865 14866 if (!CXXRecord->isDependentType()) { 14867 if (CXXRecord->hasUserDeclaredDestructor()) { 14868 // Adjust user-defined destructor exception spec. 14869 if (getLangOpts().CPlusPlus11) 14870 AdjustDestructorExceptionSpec(CXXRecord, 14871 CXXRecord->getDestructor()); 14872 } 14873 14874 if (!CXXRecord->isInvalidDecl()) { 14875 // Add any implicitly-declared members to this class. 14876 AddImplicitlyDeclaredMembersToClass(CXXRecord); 14877 14878 // If we have virtual base classes, we may end up finding multiple 14879 // final overriders for a given virtual function. Check for this 14880 // problem now. 14881 if (CXXRecord->getNumVBases()) { 14882 CXXFinalOverriderMap FinalOverriders; 14883 CXXRecord->getFinalOverriders(FinalOverriders); 14884 14885 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 14886 MEnd = FinalOverriders.end(); 14887 M != MEnd; ++M) { 14888 for (OverridingMethods::iterator SO = M->second.begin(), 14889 SOEnd = M->second.end(); 14890 SO != SOEnd; ++SO) { 14891 assert(SO->second.size() > 0 && 14892 "Virtual function without overridding functions?"); 14893 if (SO->second.size() == 1) 14894 continue; 14895 14896 // C++ [class.virtual]p2: 14897 // In a derived class, if a virtual member function of a base 14898 // class subobject has more than one final overrider the 14899 // program is ill-formed. 14900 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 14901 << (const NamedDecl *)M->first << Record; 14902 Diag(M->first->getLocation(), 14903 diag::note_overridden_virtual_function); 14904 for (OverridingMethods::overriding_iterator 14905 OM = SO->second.begin(), 14906 OMEnd = SO->second.end(); 14907 OM != OMEnd; ++OM) 14908 Diag(OM->Method->getLocation(), diag::note_final_overrider) 14909 << (const NamedDecl *)M->first << OM->Method->getParent(); 14910 14911 Record->setInvalidDecl(); 14912 } 14913 } 14914 CXXRecord->completeDefinition(&FinalOverriders); 14915 Completed = true; 14916 } 14917 } 14918 } 14919 } 14920 14921 if (!Completed) 14922 Record->completeDefinition(); 14923 14924 // We may have deferred checking for a deleted destructor. Check now. 14925 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 14926 auto *Dtor = CXXRecord->getDestructor(); 14927 if (Dtor && Dtor->isImplicit() && 14928 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) 14929 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 14930 } 14931 14932 if (Record->hasAttrs()) { 14933 CheckAlignasUnderalignment(Record); 14934 14935 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 14936 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 14937 IA->getRange(), IA->getBestCase(), 14938 IA->getSemanticSpelling()); 14939 } 14940 14941 // Check if the structure/union declaration is a type that can have zero 14942 // size in C. For C this is a language extension, for C++ it may cause 14943 // compatibility problems. 14944 bool CheckForZeroSize; 14945 if (!getLangOpts().CPlusPlus) { 14946 CheckForZeroSize = true; 14947 } else { 14948 // For C++ filter out types that cannot be referenced in C code. 14949 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 14950 CheckForZeroSize = 14951 CXXRecord->getLexicalDeclContext()->isExternCContext() && 14952 !CXXRecord->isDependentType() && 14953 CXXRecord->isCLike(); 14954 } 14955 if (CheckForZeroSize) { 14956 bool ZeroSize = true; 14957 bool IsEmpty = true; 14958 unsigned NonBitFields = 0; 14959 for (RecordDecl::field_iterator I = Record->field_begin(), 14960 E = Record->field_end(); 14961 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 14962 IsEmpty = false; 14963 if (I->isUnnamedBitfield()) { 14964 if (I->getBitWidthValue(Context) > 0) 14965 ZeroSize = false; 14966 } else { 14967 ++NonBitFields; 14968 QualType FieldType = I->getType(); 14969 if (FieldType->isIncompleteType() || 14970 !Context.getTypeSizeInChars(FieldType).isZero()) 14971 ZeroSize = false; 14972 } 14973 } 14974 14975 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 14976 // allowed in C++, but warn if its declaration is inside 14977 // extern "C" block. 14978 if (ZeroSize) { 14979 Diag(RecLoc, getLangOpts().CPlusPlus ? 14980 diag::warn_zero_size_struct_union_in_extern_c : 14981 diag::warn_zero_size_struct_union_compat) 14982 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 14983 } 14984 14985 // Structs without named members are extension in C (C99 6.7.2.1p7), 14986 // but are accepted by GCC. 14987 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 14988 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 14989 diag::ext_no_named_members_in_struct_union) 14990 << Record->isUnion(); 14991 } 14992 } 14993 } else { 14994 ObjCIvarDecl **ClsFields = 14995 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 14996 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 14997 ID->setEndOfDefinitionLoc(RBrac); 14998 // Add ivar's to class's DeclContext. 14999 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15000 ClsFields[i]->setLexicalDeclContext(ID); 15001 ID->addDecl(ClsFields[i]); 15002 } 15003 // Must enforce the rule that ivars in the base classes may not be 15004 // duplicates. 15005 if (ID->getSuperClass()) 15006 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15007 } else if (ObjCImplementationDecl *IMPDecl = 15008 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15009 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15010 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15011 // Ivar declared in @implementation never belongs to the implementation. 15012 // Only it is in implementation's lexical context. 15013 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15014 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15015 IMPDecl->setIvarLBraceLoc(LBrac); 15016 IMPDecl->setIvarRBraceLoc(RBrac); 15017 } else if (ObjCCategoryDecl *CDecl = 15018 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15019 // case of ivars in class extension; all other cases have been 15020 // reported as errors elsewhere. 15021 // FIXME. Class extension does not have a LocEnd field. 15022 // CDecl->setLocEnd(RBrac); 15023 // Add ivar's to class extension's DeclContext. 15024 // Diagnose redeclaration of private ivars. 15025 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15026 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15027 if (IDecl) { 15028 if (const ObjCIvarDecl *ClsIvar = 15029 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15030 Diag(ClsFields[i]->getLocation(), 15031 diag::err_duplicate_ivar_declaration); 15032 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15033 continue; 15034 } 15035 for (const auto *Ext : IDecl->known_extensions()) { 15036 if (const ObjCIvarDecl *ClsExtIvar 15037 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15038 Diag(ClsFields[i]->getLocation(), 15039 diag::err_duplicate_ivar_declaration); 15040 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15041 continue; 15042 } 15043 } 15044 } 15045 ClsFields[i]->setLexicalDeclContext(CDecl); 15046 CDecl->addDecl(ClsFields[i]); 15047 } 15048 CDecl->setIvarLBraceLoc(LBrac); 15049 CDecl->setIvarRBraceLoc(RBrac); 15050 } 15051 } 15052 15053 if (Attr) 15054 ProcessDeclAttributeList(S, Record, Attr); 15055 } 15056 15057 /// \brief Determine whether the given integral value is representable within 15058 /// the given type T. 15059 static bool isRepresentableIntegerValue(ASTContext &Context, 15060 llvm::APSInt &Value, 15061 QualType T) { 15062 assert(T->isIntegralType(Context) && "Integral type required!"); 15063 unsigned BitWidth = Context.getIntWidth(T); 15064 15065 if (Value.isUnsigned() || Value.isNonNegative()) { 15066 if (T->isSignedIntegerOrEnumerationType()) 15067 --BitWidth; 15068 return Value.getActiveBits() <= BitWidth; 15069 } 15070 return Value.getMinSignedBits() <= BitWidth; 15071 } 15072 15073 // \brief Given an integral type, return the next larger integral type 15074 // (or a NULL type of no such type exists). 15075 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15076 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15077 // enum checking below. 15078 assert(T->isIntegralType(Context) && "Integral type required!"); 15079 const unsigned NumTypes = 4; 15080 QualType SignedIntegralTypes[NumTypes] = { 15081 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15082 }; 15083 QualType UnsignedIntegralTypes[NumTypes] = { 15084 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15085 Context.UnsignedLongLongTy 15086 }; 15087 15088 unsigned BitWidth = Context.getTypeSize(T); 15089 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15090 : UnsignedIntegralTypes; 15091 for (unsigned I = 0; I != NumTypes; ++I) 15092 if (Context.getTypeSize(Types[I]) > BitWidth) 15093 return Types[I]; 15094 15095 return QualType(); 15096 } 15097 15098 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15099 EnumConstantDecl *LastEnumConst, 15100 SourceLocation IdLoc, 15101 IdentifierInfo *Id, 15102 Expr *Val) { 15103 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15104 llvm::APSInt EnumVal(IntWidth); 15105 QualType EltTy; 15106 15107 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15108 Val = nullptr; 15109 15110 if (Val) 15111 Val = DefaultLvalueConversion(Val).get(); 15112 15113 if (Val) { 15114 if (Enum->isDependentType() || Val->isTypeDependent()) 15115 EltTy = Context.DependentTy; 15116 else { 15117 SourceLocation ExpLoc; 15118 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15119 !getLangOpts().MSVCCompat) { 15120 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15121 // constant-expression in the enumerator-definition shall be a converted 15122 // constant expression of the underlying type. 15123 EltTy = Enum->getIntegerType(); 15124 ExprResult Converted = 15125 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15126 CCEK_Enumerator); 15127 if (Converted.isInvalid()) 15128 Val = nullptr; 15129 else 15130 Val = Converted.get(); 15131 } else if (!Val->isValueDependent() && 15132 !(Val = VerifyIntegerConstantExpression(Val, 15133 &EnumVal).get())) { 15134 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15135 } else { 15136 if (Enum->isFixed()) { 15137 EltTy = Enum->getIntegerType(); 15138 15139 // In Obj-C and Microsoft mode, require the enumeration value to be 15140 // representable in the underlying type of the enumeration. In C++11, 15141 // we perform a non-narrowing conversion as part of converted constant 15142 // expression checking. 15143 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15144 if (getLangOpts().MSVCCompat) { 15145 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15146 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15147 } else 15148 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15149 } else 15150 Val = ImpCastExprToType(Val, EltTy, 15151 EltTy->isBooleanType() ? 15152 CK_IntegralToBoolean : CK_IntegralCast) 15153 .get(); 15154 } else if (getLangOpts().CPlusPlus) { 15155 // C++11 [dcl.enum]p5: 15156 // If the underlying type is not fixed, the type of each enumerator 15157 // is the type of its initializing value: 15158 // - If an initializer is specified for an enumerator, the 15159 // initializing value has the same type as the expression. 15160 EltTy = Val->getType(); 15161 } else { 15162 // C99 6.7.2.2p2: 15163 // The expression that defines the value of an enumeration constant 15164 // shall be an integer constant expression that has a value 15165 // representable as an int. 15166 15167 // Complain if the value is not representable in an int. 15168 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15169 Diag(IdLoc, diag::ext_enum_value_not_int) 15170 << EnumVal.toString(10) << Val->getSourceRange() 15171 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15172 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15173 // Force the type of the expression to 'int'. 15174 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15175 } 15176 EltTy = Val->getType(); 15177 } 15178 } 15179 } 15180 } 15181 15182 if (!Val) { 15183 if (Enum->isDependentType()) 15184 EltTy = Context.DependentTy; 15185 else if (!LastEnumConst) { 15186 // C++0x [dcl.enum]p5: 15187 // If the underlying type is not fixed, the type of each enumerator 15188 // is the type of its initializing value: 15189 // - If no initializer is specified for the first enumerator, the 15190 // initializing value has an unspecified integral type. 15191 // 15192 // GCC uses 'int' for its unspecified integral type, as does 15193 // C99 6.7.2.2p3. 15194 if (Enum->isFixed()) { 15195 EltTy = Enum->getIntegerType(); 15196 } 15197 else { 15198 EltTy = Context.IntTy; 15199 } 15200 } else { 15201 // Assign the last value + 1. 15202 EnumVal = LastEnumConst->getInitVal(); 15203 ++EnumVal; 15204 EltTy = LastEnumConst->getType(); 15205 15206 // Check for overflow on increment. 15207 if (EnumVal < LastEnumConst->getInitVal()) { 15208 // C++0x [dcl.enum]p5: 15209 // If the underlying type is not fixed, the type of each enumerator 15210 // is the type of its initializing value: 15211 // 15212 // - Otherwise the type of the initializing value is the same as 15213 // the type of the initializing value of the preceding enumerator 15214 // unless the incremented value is not representable in that type, 15215 // in which case the type is an unspecified integral type 15216 // sufficient to contain the incremented value. If no such type 15217 // exists, the program is ill-formed. 15218 QualType T = getNextLargerIntegralType(Context, EltTy); 15219 if (T.isNull() || Enum->isFixed()) { 15220 // There is no integral type larger enough to represent this 15221 // value. Complain, then allow the value to wrap around. 15222 EnumVal = LastEnumConst->getInitVal(); 15223 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15224 ++EnumVal; 15225 if (Enum->isFixed()) 15226 // When the underlying type is fixed, this is ill-formed. 15227 Diag(IdLoc, diag::err_enumerator_wrapped) 15228 << EnumVal.toString(10) 15229 << EltTy; 15230 else 15231 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15232 << EnumVal.toString(10); 15233 } else { 15234 EltTy = T; 15235 } 15236 15237 // Retrieve the last enumerator's value, extent that type to the 15238 // type that is supposed to be large enough to represent the incremented 15239 // value, then increment. 15240 EnumVal = LastEnumConst->getInitVal(); 15241 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15242 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15243 ++EnumVal; 15244 15245 // If we're not in C++, diagnose the overflow of enumerator values, 15246 // which in C99 means that the enumerator value is not representable in 15247 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15248 // permits enumerator values that are representable in some larger 15249 // integral type. 15250 if (!getLangOpts().CPlusPlus && !T.isNull()) 15251 Diag(IdLoc, diag::warn_enum_value_overflow); 15252 } else if (!getLangOpts().CPlusPlus && 15253 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15254 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15255 Diag(IdLoc, diag::ext_enum_value_not_int) 15256 << EnumVal.toString(10) << 1; 15257 } 15258 } 15259 } 15260 15261 if (!EltTy->isDependentType()) { 15262 // Make the enumerator value match the signedness and size of the 15263 // enumerator's type. 15264 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15265 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15266 } 15267 15268 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15269 Val, EnumVal); 15270 } 15271 15272 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15273 SourceLocation IILoc) { 15274 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15275 !getLangOpts().CPlusPlus) 15276 return SkipBodyInfo(); 15277 15278 // We have an anonymous enum definition. Look up the first enumerator to 15279 // determine if we should merge the definition with an existing one and 15280 // skip the body. 15281 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15282 ForRedeclaration); 15283 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15284 if (!PrevECD) 15285 return SkipBodyInfo(); 15286 15287 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15288 NamedDecl *Hidden; 15289 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15290 SkipBodyInfo Skip; 15291 Skip.Previous = Hidden; 15292 return Skip; 15293 } 15294 15295 return SkipBodyInfo(); 15296 } 15297 15298 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15299 SourceLocation IdLoc, IdentifierInfo *Id, 15300 AttributeList *Attr, 15301 SourceLocation EqualLoc, Expr *Val) { 15302 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15303 EnumConstantDecl *LastEnumConst = 15304 cast_or_null<EnumConstantDecl>(lastEnumConst); 15305 15306 // The scope passed in may not be a decl scope. Zip up the scope tree until 15307 // we find one that is. 15308 S = getNonFieldDeclScope(S); 15309 15310 // Verify that there isn't already something declared with this name in this 15311 // scope. 15312 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15313 ForRedeclaration); 15314 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15315 // Maybe we will complain about the shadowed template parameter. 15316 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15317 // Just pretend that we didn't see the previous declaration. 15318 PrevDecl = nullptr; 15319 } 15320 15321 // C++ [class.mem]p15: 15322 // If T is the name of a class, then each of the following shall have a name 15323 // different from T: 15324 // - every enumerator of every member of class T that is an unscoped 15325 // enumerated type 15326 if (!TheEnumDecl->isScoped()) 15327 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15328 DeclarationNameInfo(Id, IdLoc)); 15329 15330 EnumConstantDecl *New = 15331 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15332 if (!New) 15333 return nullptr; 15334 15335 if (PrevDecl) { 15336 // When in C++, we may get a TagDecl with the same name; in this case the 15337 // enum constant will 'hide' the tag. 15338 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15339 "Received TagDecl when not in C++!"); 15340 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) && 15341 shouldLinkPossiblyHiddenDecl(PrevDecl, New)) { 15342 if (isa<EnumConstantDecl>(PrevDecl)) 15343 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15344 else 15345 Diag(IdLoc, diag::err_redefinition) << Id; 15346 notePreviousDefinition(PrevDecl->getLocation(), IdLoc); 15347 return nullptr; 15348 } 15349 } 15350 15351 // Process attributes. 15352 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15353 AddPragmaAttributes(S, New); 15354 15355 // Register this decl in the current scope stack. 15356 New->setAccess(TheEnumDecl->getAccess()); 15357 PushOnScopeChains(New, S); 15358 15359 ActOnDocumentableDecl(New); 15360 15361 return New; 15362 } 15363 15364 // Returns true when the enum initial expression does not trigger the 15365 // duplicate enum warning. A few common cases are exempted as follows: 15366 // Element2 = Element1 15367 // Element2 = Element1 + 1 15368 // Element2 = Element1 - 1 15369 // Where Element2 and Element1 are from the same enum. 15370 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15371 Expr *InitExpr = ECD->getInitExpr(); 15372 if (!InitExpr) 15373 return true; 15374 InitExpr = InitExpr->IgnoreImpCasts(); 15375 15376 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15377 if (!BO->isAdditiveOp()) 15378 return true; 15379 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15380 if (!IL) 15381 return true; 15382 if (IL->getValue() != 1) 15383 return true; 15384 15385 InitExpr = BO->getLHS(); 15386 } 15387 15388 // This checks if the elements are from the same enum. 15389 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15390 if (!DRE) 15391 return true; 15392 15393 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15394 if (!EnumConstant) 15395 return true; 15396 15397 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15398 Enum) 15399 return true; 15400 15401 return false; 15402 } 15403 15404 namespace { 15405 struct DupKey { 15406 int64_t val; 15407 bool isTombstoneOrEmptyKey; 15408 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15409 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15410 }; 15411 15412 static DupKey GetDupKey(const llvm::APSInt& Val) { 15413 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15414 false); 15415 } 15416 15417 struct DenseMapInfoDupKey { 15418 static DupKey getEmptyKey() { return DupKey(0, true); } 15419 static DupKey getTombstoneKey() { return DupKey(1, true); } 15420 static unsigned getHashValue(const DupKey Key) { 15421 return (unsigned)(Key.val * 37); 15422 } 15423 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15424 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15425 LHS.val == RHS.val; 15426 } 15427 }; 15428 } // end anonymous namespace 15429 15430 // Emits a warning when an element is implicitly set a value that 15431 // a previous element has already been set to. 15432 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15433 EnumDecl *Enum, 15434 QualType EnumType) { 15435 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15436 return; 15437 // Avoid anonymous enums 15438 if (!Enum->getIdentifier()) 15439 return; 15440 15441 // Only check for small enums. 15442 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15443 return; 15444 15445 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15446 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15447 15448 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15449 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15450 ValueToVectorMap; 15451 15452 DuplicatesVector DupVector; 15453 ValueToVectorMap EnumMap; 15454 15455 // Populate the EnumMap with all values represented by enum constants without 15456 // an initialier. 15457 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15458 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15459 15460 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15461 // this constant. Skip this enum since it may be ill-formed. 15462 if (!ECD) { 15463 return; 15464 } 15465 15466 if (ECD->getInitExpr()) 15467 continue; 15468 15469 DupKey Key = GetDupKey(ECD->getInitVal()); 15470 DeclOrVector &Entry = EnumMap[Key]; 15471 15472 // First time encountering this value. 15473 if (Entry.isNull()) 15474 Entry = ECD; 15475 } 15476 15477 // Create vectors for any values that has duplicates. 15478 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15479 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15480 if (!ValidDuplicateEnum(ECD, Enum)) 15481 continue; 15482 15483 DupKey Key = GetDupKey(ECD->getInitVal()); 15484 15485 DeclOrVector& Entry = EnumMap[Key]; 15486 if (Entry.isNull()) 15487 continue; 15488 15489 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15490 // Ensure constants are different. 15491 if (D == ECD) 15492 continue; 15493 15494 // Create new vector and push values onto it. 15495 ECDVector *Vec = new ECDVector(); 15496 Vec->push_back(D); 15497 Vec->push_back(ECD); 15498 15499 // Update entry to point to the duplicates vector. 15500 Entry = Vec; 15501 15502 // Store the vector somewhere we can consult later for quick emission of 15503 // diagnostics. 15504 DupVector.push_back(Vec); 15505 continue; 15506 } 15507 15508 ECDVector *Vec = Entry.get<ECDVector*>(); 15509 // Make sure constants are not added more than once. 15510 if (*Vec->begin() == ECD) 15511 continue; 15512 15513 Vec->push_back(ECD); 15514 } 15515 15516 // Emit diagnostics. 15517 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15518 DupVectorEnd = DupVector.end(); 15519 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15520 ECDVector *Vec = *DupVectorIter; 15521 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15522 15523 // Emit warning for one enum constant. 15524 ECDVector::iterator I = Vec->begin(); 15525 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15526 << (*I)->getName() << (*I)->getInitVal().toString(10) 15527 << (*I)->getSourceRange(); 15528 ++I; 15529 15530 // Emit one note for each of the remaining enum constants with 15531 // the same value. 15532 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15533 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15534 << (*I)->getName() << (*I)->getInitVal().toString(10) 15535 << (*I)->getSourceRange(); 15536 delete Vec; 15537 } 15538 } 15539 15540 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15541 bool AllowMask) const { 15542 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 15543 assert(ED->isCompleteDefinition() && "expected enum definition"); 15544 15545 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15546 llvm::APInt &FlagBits = R.first->second; 15547 15548 if (R.second) { 15549 for (auto *E : ED->enumerators()) { 15550 const auto &EVal = E->getInitVal(); 15551 // Only single-bit enumerators introduce new flag values. 15552 if (EVal.isPowerOf2()) 15553 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15554 } 15555 } 15556 15557 // A value is in a flag enum if either its bits are a subset of the enum's 15558 // flag bits (the first condition) or we are allowing masks and the same is 15559 // true of its complement (the second condition). When masks are allowed, we 15560 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15561 // 15562 // While it's true that any value could be used as a mask, the assumption is 15563 // that a mask will have all of the insignificant bits set. Anything else is 15564 // likely a logic error. 15565 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15566 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15567 } 15568 15569 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15570 Decl *EnumDeclX, 15571 ArrayRef<Decl *> Elements, 15572 Scope *S, AttributeList *Attr) { 15573 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15574 QualType EnumType = Context.getTypeDeclType(Enum); 15575 15576 if (Attr) 15577 ProcessDeclAttributeList(S, Enum, Attr); 15578 15579 if (Enum->isDependentType()) { 15580 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15581 EnumConstantDecl *ECD = 15582 cast_or_null<EnumConstantDecl>(Elements[i]); 15583 if (!ECD) continue; 15584 15585 ECD->setType(EnumType); 15586 } 15587 15588 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15589 return; 15590 } 15591 15592 // TODO: If the result value doesn't fit in an int, it must be a long or long 15593 // long value. ISO C does not support this, but GCC does as an extension, 15594 // emit a warning. 15595 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15596 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15597 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15598 15599 // Verify that all the values are okay, compute the size of the values, and 15600 // reverse the list. 15601 unsigned NumNegativeBits = 0; 15602 unsigned NumPositiveBits = 0; 15603 15604 // Keep track of whether all elements have type int. 15605 bool AllElementsInt = true; 15606 15607 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15608 EnumConstantDecl *ECD = 15609 cast_or_null<EnumConstantDecl>(Elements[i]); 15610 if (!ECD) continue; // Already issued a diagnostic. 15611 15612 const llvm::APSInt &InitVal = ECD->getInitVal(); 15613 15614 // Keep track of the size of positive and negative values. 15615 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15616 NumPositiveBits = std::max(NumPositiveBits, 15617 (unsigned)InitVal.getActiveBits()); 15618 else 15619 NumNegativeBits = std::max(NumNegativeBits, 15620 (unsigned)InitVal.getMinSignedBits()); 15621 15622 // Keep track of whether every enum element has type int (very commmon). 15623 if (AllElementsInt) 15624 AllElementsInt = ECD->getType() == Context.IntTy; 15625 } 15626 15627 // Figure out the type that should be used for this enum. 15628 QualType BestType; 15629 unsigned BestWidth; 15630 15631 // C++0x N3000 [conv.prom]p3: 15632 // An rvalue of an unscoped enumeration type whose underlying 15633 // type is not fixed can be converted to an rvalue of the first 15634 // of the following types that can represent all the values of 15635 // the enumeration: int, unsigned int, long int, unsigned long 15636 // int, long long int, or unsigned long long int. 15637 // C99 6.4.4.3p2: 15638 // An identifier declared as an enumeration constant has type int. 15639 // The C99 rule is modified by a gcc extension 15640 QualType BestPromotionType; 15641 15642 bool Packed = Enum->hasAttr<PackedAttr>(); 15643 // -fshort-enums is the equivalent to specifying the packed attribute on all 15644 // enum definitions. 15645 if (LangOpts.ShortEnums) 15646 Packed = true; 15647 15648 if (Enum->isFixed()) { 15649 BestType = Enum->getIntegerType(); 15650 if (BestType->isPromotableIntegerType()) 15651 BestPromotionType = Context.getPromotedIntegerType(BestType); 15652 else 15653 BestPromotionType = BestType; 15654 15655 BestWidth = Context.getIntWidth(BestType); 15656 } 15657 else if (NumNegativeBits) { 15658 // If there is a negative value, figure out the smallest integer type (of 15659 // int/long/longlong) that fits. 15660 // If it's packed, check also if it fits a char or a short. 15661 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15662 BestType = Context.SignedCharTy; 15663 BestWidth = CharWidth; 15664 } else if (Packed && NumNegativeBits <= ShortWidth && 15665 NumPositiveBits < ShortWidth) { 15666 BestType = Context.ShortTy; 15667 BestWidth = ShortWidth; 15668 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15669 BestType = Context.IntTy; 15670 BestWidth = IntWidth; 15671 } else { 15672 BestWidth = Context.getTargetInfo().getLongWidth(); 15673 15674 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15675 BestType = Context.LongTy; 15676 } else { 15677 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15678 15679 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15680 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15681 BestType = Context.LongLongTy; 15682 } 15683 } 15684 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15685 } else { 15686 // If there is no negative value, figure out the smallest type that fits 15687 // all of the enumerator values. 15688 // If it's packed, check also if it fits a char or a short. 15689 if (Packed && NumPositiveBits <= CharWidth) { 15690 BestType = Context.UnsignedCharTy; 15691 BestPromotionType = Context.IntTy; 15692 BestWidth = CharWidth; 15693 } else if (Packed && NumPositiveBits <= ShortWidth) { 15694 BestType = Context.UnsignedShortTy; 15695 BestPromotionType = Context.IntTy; 15696 BestWidth = ShortWidth; 15697 } else if (NumPositiveBits <= IntWidth) { 15698 BestType = Context.UnsignedIntTy; 15699 BestWidth = IntWidth; 15700 BestPromotionType 15701 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15702 ? Context.UnsignedIntTy : Context.IntTy; 15703 } else if (NumPositiveBits <= 15704 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15705 BestType = Context.UnsignedLongTy; 15706 BestPromotionType 15707 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15708 ? Context.UnsignedLongTy : Context.LongTy; 15709 } else { 15710 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15711 assert(NumPositiveBits <= BestWidth && 15712 "How could an initializer get larger than ULL?"); 15713 BestType = Context.UnsignedLongLongTy; 15714 BestPromotionType 15715 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15716 ? Context.UnsignedLongLongTy : Context.LongLongTy; 15717 } 15718 } 15719 15720 // Loop over all of the enumerator constants, changing their types to match 15721 // the type of the enum if needed. 15722 for (auto *D : Elements) { 15723 auto *ECD = cast_or_null<EnumConstantDecl>(D); 15724 if (!ECD) continue; // Already issued a diagnostic. 15725 15726 // Standard C says the enumerators have int type, but we allow, as an 15727 // extension, the enumerators to be larger than int size. If each 15728 // enumerator value fits in an int, type it as an int, otherwise type it the 15729 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 15730 // that X has type 'int', not 'unsigned'. 15731 15732 // Determine whether the value fits into an int. 15733 llvm::APSInt InitVal = ECD->getInitVal(); 15734 15735 // If it fits into an integer type, force it. Otherwise force it to match 15736 // the enum decl type. 15737 QualType NewTy; 15738 unsigned NewWidth; 15739 bool NewSign; 15740 if (!getLangOpts().CPlusPlus && 15741 !Enum->isFixed() && 15742 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 15743 NewTy = Context.IntTy; 15744 NewWidth = IntWidth; 15745 NewSign = true; 15746 } else if (ECD->getType() == BestType) { 15747 // Already the right type! 15748 if (getLangOpts().CPlusPlus) 15749 // C++ [dcl.enum]p4: Following the closing brace of an 15750 // enum-specifier, each enumerator has the type of its 15751 // enumeration. 15752 ECD->setType(EnumType); 15753 continue; 15754 } else { 15755 NewTy = BestType; 15756 NewWidth = BestWidth; 15757 NewSign = BestType->isSignedIntegerOrEnumerationType(); 15758 } 15759 15760 // Adjust the APSInt value. 15761 InitVal = InitVal.extOrTrunc(NewWidth); 15762 InitVal.setIsSigned(NewSign); 15763 ECD->setInitVal(InitVal); 15764 15765 // Adjust the Expr initializer and type. 15766 if (ECD->getInitExpr() && 15767 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 15768 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 15769 CK_IntegralCast, 15770 ECD->getInitExpr(), 15771 /*base paths*/ nullptr, 15772 VK_RValue)); 15773 if (getLangOpts().CPlusPlus) 15774 // C++ [dcl.enum]p4: Following the closing brace of an 15775 // enum-specifier, each enumerator has the type of its 15776 // enumeration. 15777 ECD->setType(EnumType); 15778 else 15779 ECD->setType(NewTy); 15780 } 15781 15782 Enum->completeDefinition(BestType, BestPromotionType, 15783 NumPositiveBits, NumNegativeBits); 15784 15785 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 15786 15787 if (Enum->isClosedFlag()) { 15788 for (Decl *D : Elements) { 15789 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 15790 if (!ECD) continue; // Already issued a diagnostic. 15791 15792 llvm::APSInt InitVal = ECD->getInitVal(); 15793 if (InitVal != 0 && !InitVal.isPowerOf2() && 15794 !IsValueInFlagEnum(Enum, InitVal, true)) 15795 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 15796 << ECD << Enum; 15797 } 15798 } 15799 15800 // Now that the enum type is defined, ensure it's not been underaligned. 15801 if (Enum->hasAttrs()) 15802 CheckAlignasUnderalignment(Enum); 15803 } 15804 15805 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 15806 SourceLocation StartLoc, 15807 SourceLocation EndLoc) { 15808 StringLiteral *AsmString = cast<StringLiteral>(expr); 15809 15810 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 15811 AsmString, StartLoc, 15812 EndLoc); 15813 CurContext->addDecl(New); 15814 return New; 15815 } 15816 15817 static void checkModuleImportContext(Sema &S, Module *M, 15818 SourceLocation ImportLoc, DeclContext *DC, 15819 bool FromInclude = false) { 15820 SourceLocation ExternCLoc; 15821 15822 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 15823 switch (LSD->getLanguage()) { 15824 case LinkageSpecDecl::lang_c: 15825 if (ExternCLoc.isInvalid()) 15826 ExternCLoc = LSD->getLocStart(); 15827 break; 15828 case LinkageSpecDecl::lang_cxx: 15829 break; 15830 } 15831 DC = LSD->getParent(); 15832 } 15833 15834 while (isa<LinkageSpecDecl>(DC)) 15835 DC = DC->getParent(); 15836 15837 if (!isa<TranslationUnitDecl>(DC)) { 15838 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 15839 ? diag::ext_module_import_not_at_top_level_noop 15840 : diag::err_module_import_not_at_top_level_fatal) 15841 << M->getFullModuleName() << DC; 15842 S.Diag(cast<Decl>(DC)->getLocStart(), 15843 diag::note_module_import_not_at_top_level) << DC; 15844 } else if (!M->IsExternC && ExternCLoc.isValid()) { 15845 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 15846 << M->getFullModuleName(); 15847 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 15848 } 15849 } 15850 15851 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 15852 SourceLocation ModuleLoc, 15853 ModuleDeclKind MDK, 15854 ModuleIdPath Path) { 15855 // A module implementation unit requires that we are not compiling a module 15856 // of any kind. A module interface unit requires that we are not compiling a 15857 // module map. 15858 switch (getLangOpts().getCompilingModule()) { 15859 case LangOptions::CMK_None: 15860 // It's OK to compile a module interface as a normal translation unit. 15861 break; 15862 15863 case LangOptions::CMK_ModuleInterface: 15864 if (MDK != ModuleDeclKind::Implementation) 15865 break; 15866 15867 // We were asked to compile a module interface unit but this is a module 15868 // implementation unit. That indicates the 'export' is missing. 15869 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 15870 << FixItHint::CreateInsertion(ModuleLoc, "export "); 15871 break; 15872 15873 case LangOptions::CMK_ModuleMap: 15874 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 15875 return nullptr; 15876 } 15877 15878 // FIXME: Create a ModuleDecl and return it. 15879 15880 // FIXME: Most of this work should be done by the preprocessor rather than 15881 // here, in order to support macro import. 15882 15883 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 15884 // modules, the dots here are just another character that can appear in a 15885 // module name. 15886 std::string ModuleName; 15887 for (auto &Piece : Path) { 15888 if (!ModuleName.empty()) 15889 ModuleName += "."; 15890 ModuleName += Piece.first->getName(); 15891 } 15892 15893 // If a module name was explicitly specified on the command line, it must be 15894 // correct. 15895 if (!getLangOpts().CurrentModule.empty() && 15896 getLangOpts().CurrentModule != ModuleName) { 15897 Diag(Path.front().second, diag::err_current_module_name_mismatch) 15898 << SourceRange(Path.front().second, Path.back().second) 15899 << getLangOpts().CurrentModule; 15900 return nullptr; 15901 } 15902 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 15903 15904 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 15905 15906 switch (MDK) { 15907 case ModuleDeclKind::Module: { 15908 // FIXME: Check we're not in a submodule. 15909 15910 // We can't have parsed or imported a definition of this module or parsed a 15911 // module map defining it already. 15912 if (auto *M = Map.findModule(ModuleName)) { 15913 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 15914 if (M->DefinitionLoc.isValid()) 15915 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 15916 else if (const auto *FE = M->getASTFile()) 15917 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 15918 << FE->getName(); 15919 return nullptr; 15920 } 15921 15922 // Create a Module for the module that we're defining. 15923 Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 15924 assert(Mod && "module creation should not fail"); 15925 15926 // Enter the semantic scope of the module. 15927 ActOnModuleBegin(ModuleLoc, Mod); 15928 return nullptr; 15929 } 15930 15931 case ModuleDeclKind::Partition: 15932 // FIXME: Check we are in a submodule of the named module. 15933 return nullptr; 15934 15935 case ModuleDeclKind::Implementation: 15936 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 15937 PP.getIdentifierInfo(ModuleName), Path[0].second); 15938 15939 DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc); 15940 if (Import.isInvalid()) 15941 return nullptr; 15942 return ConvertDeclToDeclGroup(Import.get()); 15943 } 15944 15945 llvm_unreachable("unexpected module decl kind"); 15946 } 15947 15948 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 15949 SourceLocation ImportLoc, 15950 ModuleIdPath Path) { 15951 Module *Mod = 15952 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 15953 /*IsIncludeDirective=*/false); 15954 if (!Mod) 15955 return true; 15956 15957 VisibleModules.setVisible(Mod, ImportLoc); 15958 15959 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 15960 15961 // FIXME: we should support importing a submodule within a different submodule 15962 // of the same top-level module. Until we do, make it an error rather than 15963 // silently ignoring the import. 15964 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 15965 // warn on a redundant import of the current module? 15966 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 15967 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 15968 Diag(ImportLoc, getLangOpts().isCompilingModule() 15969 ? diag::err_module_self_import 15970 : diag::err_module_import_in_implementation) 15971 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 15972 15973 SmallVector<SourceLocation, 2> IdentifierLocs; 15974 Module *ModCheck = Mod; 15975 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 15976 // If we've run out of module parents, just drop the remaining identifiers. 15977 // We need the length to be consistent. 15978 if (!ModCheck) 15979 break; 15980 ModCheck = ModCheck->Parent; 15981 15982 IdentifierLocs.push_back(Path[I].second); 15983 } 15984 15985 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 15986 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 15987 Mod, IdentifierLocs); 15988 if (!ModuleScopes.empty()) 15989 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 15990 TU->addDecl(Import); 15991 return Import; 15992 } 15993 15994 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 15995 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 15996 BuildModuleInclude(DirectiveLoc, Mod); 15997 } 15998 15999 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16000 // Determine whether we're in the #include buffer for a module. The #includes 16001 // in that buffer do not qualify as module imports; they're just an 16002 // implementation detail of us building the module. 16003 // 16004 // FIXME: Should we even get ActOnModuleInclude calls for those? 16005 bool IsInModuleIncludes = 16006 TUKind == TU_Module && 16007 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16008 16009 bool ShouldAddImport = !IsInModuleIncludes; 16010 16011 // If this module import was due to an inclusion directive, create an 16012 // implicit import declaration to capture it in the AST. 16013 if (ShouldAddImport) { 16014 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16015 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16016 DirectiveLoc, Mod, 16017 DirectiveLoc); 16018 if (!ModuleScopes.empty()) 16019 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16020 TU->addDecl(ImportD); 16021 Consumer.HandleImplicitImportDecl(ImportD); 16022 } 16023 16024 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16025 VisibleModules.setVisible(Mod, DirectiveLoc); 16026 } 16027 16028 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16029 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16030 16031 ModuleScopes.push_back({}); 16032 ModuleScopes.back().Module = Mod; 16033 if (getLangOpts().ModulesLocalVisibility) 16034 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16035 16036 VisibleModules.setVisible(Mod, DirectiveLoc); 16037 16038 // The enclosing context is now part of this module. 16039 // FIXME: Consider creating a child DeclContext to hold the entities 16040 // lexically within the module. 16041 if (getLangOpts().trackLocalOwningModule()) { 16042 cast<Decl>(CurContext)->setHidden(true); 16043 cast<Decl>(CurContext)->setLocalOwningModule(Mod); 16044 } 16045 } 16046 16047 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16048 if (getLangOpts().ModulesLocalVisibility) { 16049 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16050 // Leaving a module hides namespace names, so our visible namespace cache 16051 // is now out of date. 16052 VisibleNamespaceCache.clear(); 16053 } 16054 16055 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16056 "left the wrong module scope"); 16057 ModuleScopes.pop_back(); 16058 16059 // We got to the end of processing a local module. Create an 16060 // ImportDecl as we would for an imported module. 16061 FileID File = getSourceManager().getFileID(EomLoc); 16062 SourceLocation DirectiveLoc; 16063 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16064 // We reached the end of a #included module header. Use the #include loc. 16065 assert(File != getSourceManager().getMainFileID() && 16066 "end of submodule in main source file"); 16067 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16068 } else { 16069 // We reached an EOM pragma. Use the pragma location. 16070 DirectiveLoc = EomLoc; 16071 } 16072 BuildModuleInclude(DirectiveLoc, Mod); 16073 16074 // Any further declarations are in whatever module we returned to. 16075 if (getLangOpts().trackLocalOwningModule()) { 16076 cast<Decl>(CurContext)->setLocalOwningModule(getCurrentModule()); 16077 if (!getCurrentModule()) 16078 cast<Decl>(CurContext)->setHidden(false); 16079 } 16080 } 16081 16082 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16083 Module *Mod) { 16084 // Bail if we're not allowed to implicitly import a module here. 16085 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 16086 return; 16087 16088 // Create the implicit import declaration. 16089 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16090 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16091 Loc, Mod, Loc); 16092 TU->addDecl(ImportD); 16093 Consumer.HandleImplicitImportDecl(ImportD); 16094 16095 // Make the module visible. 16096 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16097 VisibleModules.setVisible(Mod, Loc); 16098 } 16099 16100 /// We have parsed the start of an export declaration, including the '{' 16101 /// (if present). 16102 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16103 SourceLocation LBraceLoc) { 16104 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16105 16106 // C++ Modules TS draft: 16107 // An export-declaration shall appear in the purview of a module other than 16108 // the global module. 16109 if (ModuleScopes.empty() || !ModuleScopes.back().Module || 16110 ModuleScopes.back().Module->Kind != Module::ModuleInterfaceUnit) 16111 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16112 16113 // An export-declaration [...] shall not contain more than one 16114 // export keyword. 16115 // 16116 // The intent here is that an export-declaration cannot appear within another 16117 // export-declaration. 16118 if (D->isExported()) 16119 Diag(ExportLoc, diag::err_export_within_export); 16120 16121 CurContext->addDecl(D); 16122 PushDeclContext(S, D); 16123 return D; 16124 } 16125 16126 /// Complete the definition of an export declaration. 16127 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16128 auto *ED = cast<ExportDecl>(D); 16129 if (RBraceLoc.isValid()) 16130 ED->setRBraceLoc(RBraceLoc); 16131 16132 // FIXME: Diagnose export of internal-linkage declaration (including 16133 // anonymous namespace). 16134 16135 PopDeclContext(); 16136 return D; 16137 } 16138 16139 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16140 IdentifierInfo* AliasName, 16141 SourceLocation PragmaLoc, 16142 SourceLocation NameLoc, 16143 SourceLocation AliasNameLoc) { 16144 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16145 LookupOrdinaryName); 16146 AsmLabelAttr *Attr = 16147 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16148 16149 // If a declaration that: 16150 // 1) declares a function or a variable 16151 // 2) has external linkage 16152 // already exists, add a label attribute to it. 16153 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16154 if (isDeclExternC(PrevDecl)) 16155 PrevDecl->addAttr(Attr); 16156 else 16157 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16158 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16159 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16160 } else 16161 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16162 } 16163 16164 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16165 SourceLocation PragmaLoc, 16166 SourceLocation NameLoc) { 16167 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16168 16169 if (PrevDecl) { 16170 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16171 } else { 16172 (void)WeakUndeclaredIdentifiers.insert( 16173 std::pair<IdentifierInfo*,WeakInfo> 16174 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16175 } 16176 } 16177 16178 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16179 IdentifierInfo* AliasName, 16180 SourceLocation PragmaLoc, 16181 SourceLocation NameLoc, 16182 SourceLocation AliasNameLoc) { 16183 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16184 LookupOrdinaryName); 16185 WeakInfo W = WeakInfo(Name, NameLoc); 16186 16187 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16188 if (!PrevDecl->hasAttr<AliasAttr>()) 16189 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16190 DeclApplyPragmaWeak(TUScope, ND, W); 16191 } else { 16192 (void)WeakUndeclaredIdentifiers.insert( 16193 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16194 } 16195 } 16196 16197 Decl *Sema::getObjCDeclContext() const { 16198 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16199 } 16200