1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// \brief Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw__Float16: 136 case tok::kw___float128: 137 case tok::kw_wchar_t: 138 case tok::kw_bool: 139 case tok::kw___underlying_type: 140 case tok::kw___auto_type: 141 return true; 142 143 case tok::annot_typename: 144 case tok::kw_char16_t: 145 case tok::kw_char32_t: 146 case tok::kw_typeof: 147 case tok::annot_decltype: 148 case tok::kw_decltype: 149 return getLangOpts().CPlusPlus; 150 151 default: 152 break; 153 } 154 155 return false; 156 } 157 158 namespace { 159 enum class UnqualifiedTypeNameLookupResult { 160 NotFound, 161 FoundNonType, 162 FoundType 163 }; 164 } // end anonymous namespace 165 166 /// \brief Tries to perform unqualified lookup of the type decls in bases for 167 /// dependent class. 168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 169 /// type decl, \a FoundType if only type decls are found. 170 static UnqualifiedTypeNameLookupResult 171 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 172 SourceLocation NameLoc, 173 const CXXRecordDecl *RD) { 174 if (!RD->hasDefinition()) 175 return UnqualifiedTypeNameLookupResult::NotFound; 176 // Look for type decls in base classes. 177 UnqualifiedTypeNameLookupResult FoundTypeDecl = 178 UnqualifiedTypeNameLookupResult::NotFound; 179 for (const auto &Base : RD->bases()) { 180 const CXXRecordDecl *BaseRD = nullptr; 181 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 182 BaseRD = BaseTT->getAsCXXRecordDecl(); 183 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 184 // Look for type decls in dependent base classes that have known primary 185 // templates. 186 if (!TST || !TST->isDependentType()) 187 continue; 188 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 189 if (!TD) 190 continue; 191 if (auto *BasePrimaryTemplate = 192 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 193 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 194 BaseRD = BasePrimaryTemplate; 195 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 196 if (const ClassTemplatePartialSpecializationDecl *PS = 197 CTD->findPartialSpecialization(Base.getType())) 198 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 199 BaseRD = PS; 200 } 201 } 202 } 203 if (BaseRD) { 204 for (NamedDecl *ND : BaseRD->lookup(&II)) { 205 if (!isa<TypeDecl>(ND)) 206 return UnqualifiedTypeNameLookupResult::FoundNonType; 207 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 208 } 209 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 210 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 211 case UnqualifiedTypeNameLookupResult::FoundNonType: 212 return UnqualifiedTypeNameLookupResult::FoundNonType; 213 case UnqualifiedTypeNameLookupResult::FoundType: 214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 215 break; 216 case UnqualifiedTypeNameLookupResult::NotFound: 217 break; 218 } 219 } 220 } 221 } 222 223 return FoundTypeDecl; 224 } 225 226 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 227 const IdentifierInfo &II, 228 SourceLocation NameLoc) { 229 // Lookup in the parent class template context, if any. 230 const CXXRecordDecl *RD = nullptr; 231 UnqualifiedTypeNameLookupResult FoundTypeDecl = 232 UnqualifiedTypeNameLookupResult::NotFound; 233 for (DeclContext *DC = S.CurContext; 234 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 235 DC = DC->getParent()) { 236 // Look for type decls in dependent base classes that have known primary 237 // templates. 238 RD = dyn_cast<CXXRecordDecl>(DC); 239 if (RD && RD->getDescribedClassTemplate()) 240 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 241 } 242 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 243 return nullptr; 244 245 // We found some types in dependent base classes. Recover as if the user 246 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 247 // lookup during template instantiation. 248 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 249 250 ASTContext &Context = S.Context; 251 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 252 cast<Type>(Context.getRecordType(RD))); 253 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 254 255 CXXScopeSpec SS; 256 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 257 258 TypeLocBuilder Builder; 259 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 260 DepTL.setNameLoc(NameLoc); 261 DepTL.setElaboratedKeywordLoc(SourceLocation()); 262 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 263 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 264 } 265 266 /// \brief If the identifier refers to a type name within this scope, 267 /// return the declaration of that type. 268 /// 269 /// This routine performs ordinary name lookup of the identifier II 270 /// within the given scope, with optional C++ scope specifier SS, to 271 /// determine whether the name refers to a type. If so, returns an 272 /// opaque pointer (actually a QualType) corresponding to that 273 /// type. Otherwise, returns NULL. 274 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 275 Scope *S, CXXScopeSpec *SS, 276 bool isClassName, bool HasTrailingDot, 277 ParsedType ObjectTypePtr, 278 bool IsCtorOrDtorName, 279 bool WantNontrivialTypeSourceInfo, 280 bool IsClassTemplateDeductionContext, 281 IdentifierInfo **CorrectedII) { 282 // FIXME: Consider allowing this outside C++1z mode as an extension. 283 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 284 getLangOpts().CPlusPlus1z && !IsCtorOrDtorName && 285 !isClassName && !HasTrailingDot; 286 287 // Determine where we will perform name lookup. 288 DeclContext *LookupCtx = nullptr; 289 if (ObjectTypePtr) { 290 QualType ObjectType = ObjectTypePtr.get(); 291 if (ObjectType->isRecordType()) 292 LookupCtx = computeDeclContext(ObjectType); 293 } else if (SS && SS->isNotEmpty()) { 294 LookupCtx = computeDeclContext(*SS, false); 295 296 if (!LookupCtx) { 297 if (isDependentScopeSpecifier(*SS)) { 298 // C++ [temp.res]p3: 299 // A qualified-id that refers to a type and in which the 300 // nested-name-specifier depends on a template-parameter (14.6.2) 301 // shall be prefixed by the keyword typename to indicate that the 302 // qualified-id denotes a type, forming an 303 // elaborated-type-specifier (7.1.5.3). 304 // 305 // We therefore do not perform any name lookup if the result would 306 // refer to a member of an unknown specialization. 307 if (!isClassName && !IsCtorOrDtorName) 308 return nullptr; 309 310 // We know from the grammar that this name refers to a type, 311 // so build a dependent node to describe the type. 312 if (WantNontrivialTypeSourceInfo) 313 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 314 315 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 316 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 317 II, NameLoc); 318 return ParsedType::make(T); 319 } 320 321 return nullptr; 322 } 323 324 if (!LookupCtx->isDependentContext() && 325 RequireCompleteDeclContext(*SS, LookupCtx)) 326 return nullptr; 327 } 328 329 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 330 // lookup for class-names. 331 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 332 LookupOrdinaryName; 333 LookupResult Result(*this, &II, NameLoc, Kind); 334 if (LookupCtx) { 335 // Perform "qualified" name lookup into the declaration context we 336 // computed, which is either the type of the base of a member access 337 // expression or the declaration context associated with a prior 338 // nested-name-specifier. 339 LookupQualifiedName(Result, LookupCtx); 340 341 if (ObjectTypePtr && Result.empty()) { 342 // C++ [basic.lookup.classref]p3: 343 // If the unqualified-id is ~type-name, the type-name is looked up 344 // in the context of the entire postfix-expression. If the type T of 345 // the object expression is of a class type C, the type-name is also 346 // looked up in the scope of class C. At least one of the lookups shall 347 // find a name that refers to (possibly cv-qualified) T. 348 LookupName(Result, S); 349 } 350 } else { 351 // Perform unqualified name lookup. 352 LookupName(Result, S); 353 354 // For unqualified lookup in a class template in MSVC mode, look into 355 // dependent base classes where the primary class template is known. 356 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 357 if (ParsedType TypeInBase = 358 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 359 return TypeInBase; 360 } 361 } 362 363 NamedDecl *IIDecl = nullptr; 364 switch (Result.getResultKind()) { 365 case LookupResult::NotFound: 366 case LookupResult::NotFoundInCurrentInstantiation: 367 if (CorrectedII) { 368 TypoCorrection Correction = 369 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 370 llvm::make_unique<TypeNameValidatorCCC>( 371 true, isClassName, AllowDeducedTemplate), 372 CTK_ErrorRecovery); 373 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 374 TemplateTy Template; 375 bool MemberOfUnknownSpecialization; 376 UnqualifiedId TemplateName; 377 TemplateName.setIdentifier(NewII, NameLoc); 378 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 379 CXXScopeSpec NewSS, *NewSSPtr = SS; 380 if (SS && NNS) { 381 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 382 NewSSPtr = &NewSS; 383 } 384 if (Correction && (NNS || NewII != &II) && 385 // Ignore a correction to a template type as the to-be-corrected 386 // identifier is not a template (typo correction for template names 387 // is handled elsewhere). 388 !(getLangOpts().CPlusPlus && NewSSPtr && 389 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 390 Template, MemberOfUnknownSpecialization))) { 391 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 392 isClassName, HasTrailingDot, ObjectTypePtr, 393 IsCtorOrDtorName, 394 WantNontrivialTypeSourceInfo, 395 IsClassTemplateDeductionContext); 396 if (Ty) { 397 diagnoseTypo(Correction, 398 PDiag(diag::err_unknown_type_or_class_name_suggest) 399 << Result.getLookupName() << isClassName); 400 if (SS && NNS) 401 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 402 *CorrectedII = NewII; 403 return Ty; 404 } 405 } 406 } 407 // If typo correction failed or was not performed, fall through 408 LLVM_FALLTHROUGH; 409 case LookupResult::FoundOverloaded: 410 case LookupResult::FoundUnresolvedValue: 411 Result.suppressDiagnostics(); 412 return nullptr; 413 414 case LookupResult::Ambiguous: 415 // Recover from type-hiding ambiguities by hiding the type. We'll 416 // do the lookup again when looking for an object, and we can 417 // diagnose the error then. If we don't do this, then the error 418 // about hiding the type will be immediately followed by an error 419 // that only makes sense if the identifier was treated like a type. 420 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 421 Result.suppressDiagnostics(); 422 return nullptr; 423 } 424 425 // Look to see if we have a type anywhere in the list of results. 426 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 427 Res != ResEnd; ++Res) { 428 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 429 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 430 if (!IIDecl || 431 (*Res)->getLocation().getRawEncoding() < 432 IIDecl->getLocation().getRawEncoding()) 433 IIDecl = *Res; 434 } 435 } 436 437 if (!IIDecl) { 438 // None of the entities we found is a type, so there is no way 439 // to even assume that the result is a type. In this case, don't 440 // complain about the ambiguity. The parser will either try to 441 // perform this lookup again (e.g., as an object name), which 442 // will produce the ambiguity, or will complain that it expected 443 // a type name. 444 Result.suppressDiagnostics(); 445 return nullptr; 446 } 447 448 // We found a type within the ambiguous lookup; diagnose the 449 // ambiguity and then return that type. This might be the right 450 // answer, or it might not be, but it suppresses any attempt to 451 // perform the name lookup again. 452 break; 453 454 case LookupResult::Found: 455 IIDecl = Result.getFoundDecl(); 456 break; 457 } 458 459 assert(IIDecl && "Didn't find decl"); 460 461 QualType T; 462 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 463 // C++ [class.qual]p2: A lookup that would find the injected-class-name 464 // instead names the constructors of the class, except when naming a class. 465 // This is ill-formed when we're not actually forming a ctor or dtor name. 466 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 467 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 468 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 469 FoundRD->isInjectedClassName() && 470 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 471 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 472 << &II << /*Type*/1; 473 474 DiagnoseUseOfDecl(IIDecl, NameLoc); 475 476 T = Context.getTypeDeclType(TD); 477 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 478 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 479 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 480 if (!HasTrailingDot) 481 T = Context.getObjCInterfaceType(IDecl); 482 } else if (AllowDeducedTemplate) { 483 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 484 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 485 QualType(), false); 486 } 487 488 if (T.isNull()) { 489 // If it's not plausibly a type, suppress diagnostics. 490 Result.suppressDiagnostics(); 491 return nullptr; 492 } 493 494 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 495 // constructor or destructor name (in such a case, the scope specifier 496 // will be attached to the enclosing Expr or Decl node). 497 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 498 !isa<ObjCInterfaceDecl>(IIDecl)) { 499 if (WantNontrivialTypeSourceInfo) { 500 // Construct a type with type-source information. 501 TypeLocBuilder Builder; 502 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 503 504 T = getElaboratedType(ETK_None, *SS, T); 505 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 506 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 507 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 508 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 509 } else { 510 T = getElaboratedType(ETK_None, *SS, T); 511 } 512 } 513 514 return ParsedType::make(T); 515 } 516 517 // Builds a fake NNS for the given decl context. 518 static NestedNameSpecifier * 519 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 520 for (;; DC = DC->getLookupParent()) { 521 DC = DC->getPrimaryContext(); 522 auto *ND = dyn_cast<NamespaceDecl>(DC); 523 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 524 return NestedNameSpecifier::Create(Context, nullptr, ND); 525 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 526 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 527 RD->getTypeForDecl()); 528 else if (isa<TranslationUnitDecl>(DC)) 529 return NestedNameSpecifier::GlobalSpecifier(Context); 530 } 531 llvm_unreachable("something isn't in TU scope?"); 532 } 533 534 /// Find the parent class with dependent bases of the innermost enclosing method 535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 536 /// up allowing unqualified dependent type names at class-level, which MSVC 537 /// correctly rejects. 538 static const CXXRecordDecl * 539 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 540 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 541 DC = DC->getPrimaryContext(); 542 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 543 if (MD->getParent()->hasAnyDependentBases()) 544 return MD->getParent(); 545 } 546 return nullptr; 547 } 548 549 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 550 SourceLocation NameLoc, 551 bool IsTemplateTypeArg) { 552 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 553 554 NestedNameSpecifier *NNS = nullptr; 555 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 556 // If we weren't able to parse a default template argument, delay lookup 557 // until instantiation time by making a non-dependent DependentTypeName. We 558 // pretend we saw a NestedNameSpecifier referring to the current scope, and 559 // lookup is retried. 560 // FIXME: This hurts our diagnostic quality, since we get errors like "no 561 // type named 'Foo' in 'current_namespace'" when the user didn't write any 562 // name specifiers. 563 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 564 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 565 } else if (const CXXRecordDecl *RD = 566 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 567 // Build a DependentNameType that will perform lookup into RD at 568 // instantiation time. 569 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 570 RD->getTypeForDecl()); 571 572 // Diagnose that this identifier was undeclared, and retry the lookup during 573 // template instantiation. 574 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 575 << RD; 576 } else { 577 // This is not a situation that we should recover from. 578 return ParsedType(); 579 } 580 581 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 582 583 // Build type location information. We synthesized the qualifier, so we have 584 // to build a fake NestedNameSpecifierLoc. 585 NestedNameSpecifierLocBuilder NNSLocBuilder; 586 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 587 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 588 589 TypeLocBuilder Builder; 590 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 591 DepTL.setNameLoc(NameLoc); 592 DepTL.setElaboratedKeywordLoc(SourceLocation()); 593 DepTL.setQualifierLoc(QualifierLoc); 594 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 595 } 596 597 /// isTagName() - This method is called *for error recovery purposes only* 598 /// to determine if the specified name is a valid tag name ("struct foo"). If 599 /// so, this returns the TST for the tag corresponding to it (TST_enum, 600 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 601 /// cases in C where the user forgot to specify the tag. 602 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 603 // Do a tag name lookup in this scope. 604 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 605 LookupName(R, S, false); 606 R.suppressDiagnostics(); 607 if (R.getResultKind() == LookupResult::Found) 608 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 609 switch (TD->getTagKind()) { 610 case TTK_Struct: return DeclSpec::TST_struct; 611 case TTK_Interface: return DeclSpec::TST_interface; 612 case TTK_Union: return DeclSpec::TST_union; 613 case TTK_Class: return DeclSpec::TST_class; 614 case TTK_Enum: return DeclSpec::TST_enum; 615 } 616 } 617 618 return DeclSpec::TST_unspecified; 619 } 620 621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 623 /// then downgrade the missing typename error to a warning. 624 /// This is needed for MSVC compatibility; Example: 625 /// @code 626 /// template<class T> class A { 627 /// public: 628 /// typedef int TYPE; 629 /// }; 630 /// template<class T> class B : public A<T> { 631 /// public: 632 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 633 /// }; 634 /// @endcode 635 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 636 if (CurContext->isRecord()) { 637 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 638 return true; 639 640 const Type *Ty = SS->getScopeRep()->getAsType(); 641 642 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 643 for (const auto &Base : RD->bases()) 644 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 645 return true; 646 return S->isFunctionPrototypeScope(); 647 } 648 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 649 } 650 651 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 652 SourceLocation IILoc, 653 Scope *S, 654 CXXScopeSpec *SS, 655 ParsedType &SuggestedType, 656 bool IsTemplateName) { 657 // Don't report typename errors for editor placeholders. 658 if (II->isEditorPlaceholder()) 659 return; 660 // We don't have anything to suggest (yet). 661 SuggestedType = nullptr; 662 663 // There may have been a typo in the name of the type. Look up typo 664 // results, in case we have something that we can suggest. 665 if (TypoCorrection Corrected = 666 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 667 llvm::make_unique<TypeNameValidatorCCC>( 668 false, false, IsTemplateName, !IsTemplateName), 669 CTK_ErrorRecovery)) { 670 // FIXME: Support error recovery for the template-name case. 671 bool CanRecover = !IsTemplateName; 672 if (Corrected.isKeyword()) { 673 // We corrected to a keyword. 674 diagnoseTypo(Corrected, 675 PDiag(IsTemplateName ? diag::err_no_template_suggest 676 : diag::err_unknown_typename_suggest) 677 << II); 678 II = Corrected.getCorrectionAsIdentifierInfo(); 679 } else { 680 // We found a similarly-named type or interface; suggest that. 681 if (!SS || !SS->isSet()) { 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II, CanRecover); 686 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 687 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 688 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 689 II->getName().equals(CorrectedStr); 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName 692 ? diag::err_no_member_template_suggest 693 : diag::err_unknown_nested_typename_suggest) 694 << II << DC << DroppedSpecifier << SS->getRange(), 695 CanRecover); 696 } else { 697 llvm_unreachable("could not have corrected a typo here"); 698 } 699 700 if (!CanRecover) 701 return; 702 703 CXXScopeSpec tmpSS; 704 if (Corrected.getCorrectionSpecifier()) 705 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 706 SourceRange(IILoc)); 707 // FIXME: Support class template argument deduction here. 708 SuggestedType = 709 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 710 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 711 /*IsCtorOrDtorName=*/false, 712 /*NonTrivialTypeSourceInfo=*/true); 713 } 714 return; 715 } 716 717 if (getLangOpts().CPlusPlus && !IsTemplateName) { 718 // See if II is a class template that the user forgot to pass arguments to. 719 UnqualifiedId Name; 720 Name.setIdentifier(II, IILoc); 721 CXXScopeSpec EmptySS; 722 TemplateTy TemplateResult; 723 bool MemberOfUnknownSpecialization; 724 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 725 Name, nullptr, true, TemplateResult, 726 MemberOfUnknownSpecialization) == TNK_Type_template) { 727 TemplateName TplName = TemplateResult.get(); 728 Diag(IILoc, diag::err_template_missing_args) 729 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName; 730 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 731 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 732 << TplDecl->getTemplateParameters()->getSourceRange(); 733 } 734 return; 735 } 736 } 737 738 // FIXME: Should we move the logic that tries to recover from a missing tag 739 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 740 741 if (!SS || (!SS->isSet() && !SS->isInvalid())) 742 Diag(IILoc, IsTemplateName ? diag::err_no_template 743 : diag::err_unknown_typename) 744 << II; 745 else if (DeclContext *DC = computeDeclContext(*SS, false)) 746 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 747 : diag::err_typename_nested_not_found) 748 << II << DC << SS->getRange(); 749 else if (isDependentScopeSpecifier(*SS)) { 750 unsigned DiagID = diag::err_typename_missing; 751 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 752 DiagID = diag::ext_typename_missing; 753 754 Diag(SS->getRange().getBegin(), DiagID) 755 << SS->getScopeRep() << II->getName() 756 << SourceRange(SS->getRange().getBegin(), IILoc) 757 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 758 SuggestedType = ActOnTypenameType(S, SourceLocation(), 759 *SS, *II, IILoc).get(); 760 } else { 761 assert(SS && SS->isInvalid() && 762 "Invalid scope specifier has already been diagnosed"); 763 } 764 } 765 766 /// \brief Determine whether the given result set contains either a type name 767 /// or 768 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 769 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 770 NextToken.is(tok::less); 771 772 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 773 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 774 return true; 775 776 if (CheckTemplate && isa<TemplateDecl>(*I)) 777 return true; 778 } 779 780 return false; 781 } 782 783 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 784 Scope *S, CXXScopeSpec &SS, 785 IdentifierInfo *&Name, 786 SourceLocation NameLoc) { 787 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 788 SemaRef.LookupParsedName(R, S, &SS); 789 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 790 StringRef FixItTagName; 791 switch (Tag->getTagKind()) { 792 case TTK_Class: 793 FixItTagName = "class "; 794 break; 795 796 case TTK_Enum: 797 FixItTagName = "enum "; 798 break; 799 800 case TTK_Struct: 801 FixItTagName = "struct "; 802 break; 803 804 case TTK_Interface: 805 FixItTagName = "__interface "; 806 break; 807 808 case TTK_Union: 809 FixItTagName = "union "; 810 break; 811 } 812 813 StringRef TagName = FixItTagName.drop_back(); 814 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 815 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 816 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 817 818 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 819 I != IEnd; ++I) 820 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 821 << Name << TagName; 822 823 // Replace lookup results with just the tag decl. 824 Result.clear(Sema::LookupTagName); 825 SemaRef.LookupParsedName(Result, S, &SS); 826 return true; 827 } 828 829 return false; 830 } 831 832 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 833 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 834 QualType T, SourceLocation NameLoc) { 835 ASTContext &Context = S.Context; 836 837 TypeLocBuilder Builder; 838 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 839 840 T = S.getElaboratedType(ETK_None, SS, T); 841 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 842 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 843 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 844 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 845 } 846 847 Sema::NameClassification 848 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 849 SourceLocation NameLoc, const Token &NextToken, 850 bool IsAddressOfOperand, 851 std::unique_ptr<CorrectionCandidateCallback> CCC) { 852 DeclarationNameInfo NameInfo(Name, NameLoc); 853 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 854 855 if (NextToken.is(tok::coloncolon)) { 856 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 857 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 858 } else if (getLangOpts().CPlusPlus && SS.isSet() && 859 isCurrentClassName(*Name, S, &SS)) { 860 // Per [class.qual]p2, this names the constructors of SS, not the 861 // injected-class-name. We don't have a classification for that. 862 // There's not much point caching this result, since the parser 863 // will reject it later. 864 return NameClassification::Unknown(); 865 } 866 867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 868 LookupParsedName(Result, S, &SS, !CurMethod); 869 870 // For unqualified lookup in a class template in MSVC mode, look into 871 // dependent base classes where the primary class template is known. 872 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 873 if (ParsedType TypeInBase = 874 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 875 return TypeInBase; 876 } 877 878 // Perform lookup for Objective-C instance variables (including automatically 879 // synthesized instance variables), if we're in an Objective-C method. 880 // FIXME: This lookup really, really needs to be folded in to the normal 881 // unqualified lookup mechanism. 882 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 883 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 884 if (E.get() || E.isInvalid()) 885 return E; 886 } 887 888 bool SecondTry = false; 889 bool IsFilteredTemplateName = false; 890 891 Corrected: 892 switch (Result.getResultKind()) { 893 case LookupResult::NotFound: 894 // If an unqualified-id is followed by a '(', then we have a function 895 // call. 896 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 897 // In C++, this is an ADL-only call. 898 // FIXME: Reference? 899 if (getLangOpts().CPlusPlus) 900 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 901 902 // C90 6.3.2.2: 903 // If the expression that precedes the parenthesized argument list in a 904 // function call consists solely of an identifier, and if no 905 // declaration is visible for this identifier, the identifier is 906 // implicitly declared exactly as if, in the innermost block containing 907 // the function call, the declaration 908 // 909 // extern int identifier (); 910 // 911 // appeared. 912 // 913 // We also allow this in C99 as an extension. 914 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 915 Result.addDecl(D); 916 Result.resolveKind(); 917 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 918 } 919 } 920 921 // In C, we first see whether there is a tag type by the same name, in 922 // which case it's likely that the user just forgot to write "enum", 923 // "struct", or "union". 924 if (!getLangOpts().CPlusPlus && !SecondTry && 925 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 926 break; 927 } 928 929 // Perform typo correction to determine if there is another name that is 930 // close to this name. 931 if (!SecondTry && CCC) { 932 SecondTry = true; 933 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 934 Result.getLookupKind(), S, 935 &SS, std::move(CCC), 936 CTK_ErrorRecovery)) { 937 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 938 unsigned QualifiedDiag = diag::err_no_member_suggest; 939 940 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 941 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 942 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 943 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 944 UnqualifiedDiag = diag::err_no_template_suggest; 945 QualifiedDiag = diag::err_no_member_template_suggest; 946 } else if (UnderlyingFirstDecl && 947 (isa<TypeDecl>(UnderlyingFirstDecl) || 948 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 949 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 950 UnqualifiedDiag = diag::err_unknown_typename_suggest; 951 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 952 } 953 954 if (SS.isEmpty()) { 955 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 956 } else {// FIXME: is this even reachable? Test it. 957 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 958 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 959 Name->getName().equals(CorrectedStr); 960 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 961 << Name << computeDeclContext(SS, false) 962 << DroppedSpecifier << SS.getRange()); 963 } 964 965 // Update the name, so that the caller has the new name. 966 Name = Corrected.getCorrectionAsIdentifierInfo(); 967 968 // Typo correction corrected to a keyword. 969 if (Corrected.isKeyword()) 970 return Name; 971 972 // Also update the LookupResult... 973 // FIXME: This should probably go away at some point 974 Result.clear(); 975 Result.setLookupName(Corrected.getCorrection()); 976 if (FirstDecl) 977 Result.addDecl(FirstDecl); 978 979 // If we found an Objective-C instance variable, let 980 // LookupInObjCMethod build the appropriate expression to 981 // reference the ivar. 982 // FIXME: This is a gross hack. 983 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 984 Result.clear(); 985 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 986 return E; 987 } 988 989 goto Corrected; 990 } 991 } 992 993 // We failed to correct; just fall through and let the parser deal with it. 994 Result.suppressDiagnostics(); 995 return NameClassification::Unknown(); 996 997 case LookupResult::NotFoundInCurrentInstantiation: { 998 // We performed name lookup into the current instantiation, and there were 999 // dependent bases, so we treat this result the same way as any other 1000 // dependent nested-name-specifier. 1001 1002 // C++ [temp.res]p2: 1003 // A name used in a template declaration or definition and that is 1004 // dependent on a template-parameter is assumed not to name a type 1005 // unless the applicable name lookup finds a type name or the name is 1006 // qualified by the keyword typename. 1007 // 1008 // FIXME: If the next token is '<', we might want to ask the parser to 1009 // perform some heroics to see if we actually have a 1010 // template-argument-list, which would indicate a missing 'template' 1011 // keyword here. 1012 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1013 NameInfo, IsAddressOfOperand, 1014 /*TemplateArgs=*/nullptr); 1015 } 1016 1017 case LookupResult::Found: 1018 case LookupResult::FoundOverloaded: 1019 case LookupResult::FoundUnresolvedValue: 1020 break; 1021 1022 case LookupResult::Ambiguous: 1023 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1024 hasAnyAcceptableTemplateNames(Result)) { 1025 // C++ [temp.local]p3: 1026 // A lookup that finds an injected-class-name (10.2) can result in an 1027 // ambiguity in certain cases (for example, if it is found in more than 1028 // one base class). If all of the injected-class-names that are found 1029 // refer to specializations of the same class template, and if the name 1030 // is followed by a template-argument-list, the reference refers to the 1031 // class template itself and not a specialization thereof, and is not 1032 // ambiguous. 1033 // 1034 // This filtering can make an ambiguous result into an unambiguous one, 1035 // so try again after filtering out template names. 1036 FilterAcceptableTemplateNames(Result); 1037 if (!Result.isAmbiguous()) { 1038 IsFilteredTemplateName = true; 1039 break; 1040 } 1041 } 1042 1043 // Diagnose the ambiguity and return an error. 1044 return NameClassification::Error(); 1045 } 1046 1047 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1048 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1049 // C++ [temp.names]p3: 1050 // After name lookup (3.4) finds that a name is a template-name or that 1051 // an operator-function-id or a literal- operator-id refers to a set of 1052 // overloaded functions any member of which is a function template if 1053 // this is followed by a <, the < is always taken as the delimiter of a 1054 // template-argument-list and never as the less-than operator. 1055 if (!IsFilteredTemplateName) 1056 FilterAcceptableTemplateNames(Result); 1057 1058 if (!Result.empty()) { 1059 bool IsFunctionTemplate; 1060 bool IsVarTemplate; 1061 TemplateName Template; 1062 if (Result.end() - Result.begin() > 1) { 1063 IsFunctionTemplate = true; 1064 Template = Context.getOverloadedTemplateName(Result.begin(), 1065 Result.end()); 1066 } else { 1067 TemplateDecl *TD 1068 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1069 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1070 IsVarTemplate = isa<VarTemplateDecl>(TD); 1071 1072 if (SS.isSet() && !SS.isInvalid()) 1073 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1074 /*TemplateKeyword=*/false, 1075 TD); 1076 else 1077 Template = TemplateName(TD); 1078 } 1079 1080 if (IsFunctionTemplate) { 1081 // Function templates always go through overload resolution, at which 1082 // point we'll perform the various checks (e.g., accessibility) we need 1083 // to based on which function we selected. 1084 Result.suppressDiagnostics(); 1085 1086 return NameClassification::FunctionTemplate(Template); 1087 } 1088 1089 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1090 : NameClassification::TypeTemplate(Template); 1091 } 1092 } 1093 1094 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1095 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1096 DiagnoseUseOfDecl(Type, NameLoc); 1097 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1098 QualType T = Context.getTypeDeclType(Type); 1099 if (SS.isNotEmpty()) 1100 return buildNestedType(*this, SS, T, NameLoc); 1101 return ParsedType::make(T); 1102 } 1103 1104 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1105 if (!Class) { 1106 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1107 if (ObjCCompatibleAliasDecl *Alias = 1108 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1109 Class = Alias->getClassInterface(); 1110 } 1111 1112 if (Class) { 1113 DiagnoseUseOfDecl(Class, NameLoc); 1114 1115 if (NextToken.is(tok::period)) { 1116 // Interface. <something> is parsed as a property reference expression. 1117 // Just return "unknown" as a fall-through for now. 1118 Result.suppressDiagnostics(); 1119 return NameClassification::Unknown(); 1120 } 1121 1122 QualType T = Context.getObjCInterfaceType(Class); 1123 return ParsedType::make(T); 1124 } 1125 1126 // We can have a type template here if we're classifying a template argument. 1127 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1128 !isa<VarTemplateDecl>(FirstDecl)) 1129 return NameClassification::TypeTemplate( 1130 TemplateName(cast<TemplateDecl>(FirstDecl))); 1131 1132 // Check for a tag type hidden by a non-type decl in a few cases where it 1133 // seems likely a type is wanted instead of the non-type that was found. 1134 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1135 if ((NextToken.is(tok::identifier) || 1136 (NextIsOp && 1137 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1138 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1139 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1140 DiagnoseUseOfDecl(Type, NameLoc); 1141 QualType T = Context.getTypeDeclType(Type); 1142 if (SS.isNotEmpty()) 1143 return buildNestedType(*this, SS, T, NameLoc); 1144 return ParsedType::make(T); 1145 } 1146 1147 if (FirstDecl->isCXXClassMember()) 1148 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1149 nullptr, S); 1150 1151 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1152 return BuildDeclarationNameExpr(SS, Result, ADL); 1153 } 1154 1155 Sema::TemplateNameKindForDiagnostics 1156 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1157 auto *TD = Name.getAsTemplateDecl(); 1158 if (!TD) 1159 return TemplateNameKindForDiagnostics::DependentTemplate; 1160 if (isa<ClassTemplateDecl>(TD)) 1161 return TemplateNameKindForDiagnostics::ClassTemplate; 1162 if (isa<FunctionTemplateDecl>(TD)) 1163 return TemplateNameKindForDiagnostics::FunctionTemplate; 1164 if (isa<VarTemplateDecl>(TD)) 1165 return TemplateNameKindForDiagnostics::VarTemplate; 1166 if (isa<TypeAliasTemplateDecl>(TD)) 1167 return TemplateNameKindForDiagnostics::AliasTemplate; 1168 if (isa<TemplateTemplateParmDecl>(TD)) 1169 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1170 return TemplateNameKindForDiagnostics::DependentTemplate; 1171 } 1172 1173 // Determines the context to return to after temporarily entering a 1174 // context. This depends in an unnecessarily complicated way on the 1175 // exact ordering of callbacks from the parser. 1176 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1177 1178 // Functions defined inline within classes aren't parsed until we've 1179 // finished parsing the top-level class, so the top-level class is 1180 // the context we'll need to return to. 1181 // A Lambda call operator whose parent is a class must not be treated 1182 // as an inline member function. A Lambda can be used legally 1183 // either as an in-class member initializer or a default argument. These 1184 // are parsed once the class has been marked complete and so the containing 1185 // context would be the nested class (when the lambda is defined in one); 1186 // If the class is not complete, then the lambda is being used in an 1187 // ill-formed fashion (such as to specify the width of a bit-field, or 1188 // in an array-bound) - in which case we still want to return the 1189 // lexically containing DC (which could be a nested class). 1190 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1191 DC = DC->getLexicalParent(); 1192 1193 // A function not defined within a class will always return to its 1194 // lexical context. 1195 if (!isa<CXXRecordDecl>(DC)) 1196 return DC; 1197 1198 // A C++ inline method/friend is parsed *after* the topmost class 1199 // it was declared in is fully parsed ("complete"); the topmost 1200 // class is the context we need to return to. 1201 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1202 DC = RD; 1203 1204 // Return the declaration context of the topmost class the inline method is 1205 // declared in. 1206 return DC; 1207 } 1208 1209 return DC->getLexicalParent(); 1210 } 1211 1212 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1213 assert(getContainingDC(DC) == CurContext && 1214 "The next DeclContext should be lexically contained in the current one."); 1215 CurContext = DC; 1216 S->setEntity(DC); 1217 } 1218 1219 void Sema::PopDeclContext() { 1220 assert(CurContext && "DeclContext imbalance!"); 1221 1222 CurContext = getContainingDC(CurContext); 1223 assert(CurContext && "Popped translation unit!"); 1224 } 1225 1226 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1227 Decl *D) { 1228 // Unlike PushDeclContext, the context to which we return is not necessarily 1229 // the containing DC of TD, because the new context will be some pre-existing 1230 // TagDecl definition instead of a fresh one. 1231 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1232 CurContext = cast<TagDecl>(D)->getDefinition(); 1233 assert(CurContext && "skipping definition of undefined tag"); 1234 // Start lookups from the parent of the current context; we don't want to look 1235 // into the pre-existing complete definition. 1236 S->setEntity(CurContext->getLookupParent()); 1237 return Result; 1238 } 1239 1240 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1241 CurContext = static_cast<decltype(CurContext)>(Context); 1242 } 1243 1244 /// EnterDeclaratorContext - Used when we must lookup names in the context 1245 /// of a declarator's nested name specifier. 1246 /// 1247 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1248 // C++0x [basic.lookup.unqual]p13: 1249 // A name used in the definition of a static data member of class 1250 // X (after the qualified-id of the static member) is looked up as 1251 // if the name was used in a member function of X. 1252 // C++0x [basic.lookup.unqual]p14: 1253 // If a variable member of a namespace is defined outside of the 1254 // scope of its namespace then any name used in the definition of 1255 // the variable member (after the declarator-id) is looked up as 1256 // if the definition of the variable member occurred in its 1257 // namespace. 1258 // Both of these imply that we should push a scope whose context 1259 // is the semantic context of the declaration. We can't use 1260 // PushDeclContext here because that context is not necessarily 1261 // lexically contained in the current context. Fortunately, 1262 // the containing scope should have the appropriate information. 1263 1264 assert(!S->getEntity() && "scope already has entity"); 1265 1266 #ifndef NDEBUG 1267 Scope *Ancestor = S->getParent(); 1268 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1269 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1270 #endif 1271 1272 CurContext = DC; 1273 S->setEntity(DC); 1274 } 1275 1276 void Sema::ExitDeclaratorContext(Scope *S) { 1277 assert(S->getEntity() == CurContext && "Context imbalance!"); 1278 1279 // Switch back to the lexical context. The safety of this is 1280 // enforced by an assert in EnterDeclaratorContext. 1281 Scope *Ancestor = S->getParent(); 1282 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1283 CurContext = Ancestor->getEntity(); 1284 1285 // We don't need to do anything with the scope, which is going to 1286 // disappear. 1287 } 1288 1289 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1290 // We assume that the caller has already called 1291 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1292 FunctionDecl *FD = D->getAsFunction(); 1293 if (!FD) 1294 return; 1295 1296 // Same implementation as PushDeclContext, but enters the context 1297 // from the lexical parent, rather than the top-level class. 1298 assert(CurContext == FD->getLexicalParent() && 1299 "The next DeclContext should be lexically contained in the current one."); 1300 CurContext = FD; 1301 S->setEntity(CurContext); 1302 1303 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1304 ParmVarDecl *Param = FD->getParamDecl(P); 1305 // If the parameter has an identifier, then add it to the scope 1306 if (Param->getIdentifier()) { 1307 S->AddDecl(Param); 1308 IdResolver.AddDecl(Param); 1309 } 1310 } 1311 } 1312 1313 void Sema::ActOnExitFunctionContext() { 1314 // Same implementation as PopDeclContext, but returns to the lexical parent, 1315 // rather than the top-level class. 1316 assert(CurContext && "DeclContext imbalance!"); 1317 CurContext = CurContext->getLexicalParent(); 1318 assert(CurContext && "Popped translation unit!"); 1319 } 1320 1321 /// \brief Determine whether we allow overloading of the function 1322 /// PrevDecl with another declaration. 1323 /// 1324 /// This routine determines whether overloading is possible, not 1325 /// whether some new function is actually an overload. It will return 1326 /// true in C++ (where we can always provide overloads) or, as an 1327 /// extension, in C when the previous function is already an 1328 /// overloaded function declaration or has the "overloadable" 1329 /// attribute. 1330 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1331 ASTContext &Context, 1332 const FunctionDecl *New) { 1333 if (Context.getLangOpts().CPlusPlus) 1334 return true; 1335 1336 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1337 return true; 1338 1339 return Previous.getResultKind() == LookupResult::Found && 1340 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1341 New->hasAttr<OverloadableAttr>()); 1342 } 1343 1344 /// Add this decl to the scope shadowed decl chains. 1345 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1346 // Move up the scope chain until we find the nearest enclosing 1347 // non-transparent context. The declaration will be introduced into this 1348 // scope. 1349 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1350 S = S->getParent(); 1351 1352 // Add scoped declarations into their context, so that they can be 1353 // found later. Declarations without a context won't be inserted 1354 // into any context. 1355 if (AddToContext) 1356 CurContext->addDecl(D); 1357 1358 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1359 // are function-local declarations. 1360 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1361 !D->getDeclContext()->getRedeclContext()->Equals( 1362 D->getLexicalDeclContext()->getRedeclContext()) && 1363 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1364 return; 1365 1366 // Template instantiations should also not be pushed into scope. 1367 if (isa<FunctionDecl>(D) && 1368 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1369 return; 1370 1371 // If this replaces anything in the current scope, 1372 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1373 IEnd = IdResolver.end(); 1374 for (; I != IEnd; ++I) { 1375 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1376 S->RemoveDecl(*I); 1377 IdResolver.RemoveDecl(*I); 1378 1379 // Should only need to replace one decl. 1380 break; 1381 } 1382 } 1383 1384 S->AddDecl(D); 1385 1386 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1387 // Implicitly-generated labels may end up getting generated in an order that 1388 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1389 // the label at the appropriate place in the identifier chain. 1390 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1391 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1392 if (IDC == CurContext) { 1393 if (!S->isDeclScope(*I)) 1394 continue; 1395 } else if (IDC->Encloses(CurContext)) 1396 break; 1397 } 1398 1399 IdResolver.InsertDeclAfter(I, D); 1400 } else { 1401 IdResolver.AddDecl(D); 1402 } 1403 } 1404 1405 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1406 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1407 TUScope->AddDecl(D); 1408 } 1409 1410 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1411 bool AllowInlineNamespace) { 1412 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1413 } 1414 1415 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1416 DeclContext *TargetDC = DC->getPrimaryContext(); 1417 do { 1418 if (DeclContext *ScopeDC = S->getEntity()) 1419 if (ScopeDC->getPrimaryContext() == TargetDC) 1420 return S; 1421 } while ((S = S->getParent())); 1422 1423 return nullptr; 1424 } 1425 1426 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1427 DeclContext*, 1428 ASTContext&); 1429 1430 /// Filters out lookup results that don't fall within the given scope 1431 /// as determined by isDeclInScope. 1432 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1433 bool ConsiderLinkage, 1434 bool AllowInlineNamespace) { 1435 LookupResult::Filter F = R.makeFilter(); 1436 while (F.hasNext()) { 1437 NamedDecl *D = F.next(); 1438 1439 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1440 continue; 1441 1442 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1443 continue; 1444 1445 F.erase(); 1446 } 1447 1448 F.done(); 1449 } 1450 1451 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1452 /// have compatible owning modules. 1453 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1454 // FIXME: The Modules TS is not clear about how friend declarations are 1455 // to be treated. It's not meaningful to have different owning modules for 1456 // linkage in redeclarations of the same entity, so for now allow the 1457 // redeclaration and change the owning modules to match. 1458 if (New->getFriendObjectKind() && 1459 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1460 New->setLocalOwningModule(Old->getOwningModule()); 1461 makeMergedDefinitionVisible(New); 1462 return false; 1463 } 1464 1465 Module *NewM = New->getOwningModule(); 1466 Module *OldM = Old->getOwningModule(); 1467 if (NewM == OldM) 1468 return false; 1469 1470 // FIXME: Check proclaimed-ownership-declarations here too. 1471 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit; 1472 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit; 1473 if (NewIsModuleInterface || OldIsModuleInterface) { 1474 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1475 // if a declaration of D [...] appears in the purview of a module, all 1476 // other such declarations shall appear in the purview of the same module 1477 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1478 << New 1479 << NewIsModuleInterface 1480 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1481 << OldIsModuleInterface 1482 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1483 Diag(Old->getLocation(), diag::note_previous_declaration); 1484 New->setInvalidDecl(); 1485 return true; 1486 } 1487 1488 return false; 1489 } 1490 1491 static bool isUsingDecl(NamedDecl *D) { 1492 return isa<UsingShadowDecl>(D) || 1493 isa<UnresolvedUsingTypenameDecl>(D) || 1494 isa<UnresolvedUsingValueDecl>(D); 1495 } 1496 1497 /// Removes using shadow declarations from the lookup results. 1498 static void RemoveUsingDecls(LookupResult &R) { 1499 LookupResult::Filter F = R.makeFilter(); 1500 while (F.hasNext()) 1501 if (isUsingDecl(F.next())) 1502 F.erase(); 1503 1504 F.done(); 1505 } 1506 1507 /// \brief Check for this common pattern: 1508 /// @code 1509 /// class S { 1510 /// S(const S&); // DO NOT IMPLEMENT 1511 /// void operator=(const S&); // DO NOT IMPLEMENT 1512 /// }; 1513 /// @endcode 1514 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1515 // FIXME: Should check for private access too but access is set after we get 1516 // the decl here. 1517 if (D->doesThisDeclarationHaveABody()) 1518 return false; 1519 1520 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1521 return CD->isCopyConstructor(); 1522 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1523 return Method->isCopyAssignmentOperator(); 1524 return false; 1525 } 1526 1527 // We need this to handle 1528 // 1529 // typedef struct { 1530 // void *foo() { return 0; } 1531 // } A; 1532 // 1533 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1534 // for example. If 'A', foo will have external linkage. If we have '*A', 1535 // foo will have no linkage. Since we can't know until we get to the end 1536 // of the typedef, this function finds out if D might have non-external linkage. 1537 // Callers should verify at the end of the TU if it D has external linkage or 1538 // not. 1539 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1540 const DeclContext *DC = D->getDeclContext(); 1541 while (!DC->isTranslationUnit()) { 1542 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1543 if (!RD->hasNameForLinkage()) 1544 return true; 1545 } 1546 DC = DC->getParent(); 1547 } 1548 1549 return !D->isExternallyVisible(); 1550 } 1551 1552 // FIXME: This needs to be refactored; some other isInMainFile users want 1553 // these semantics. 1554 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1555 if (S.TUKind != TU_Complete) 1556 return false; 1557 return S.SourceMgr.isInMainFile(Loc); 1558 } 1559 1560 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1561 assert(D); 1562 1563 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1564 return false; 1565 1566 // Ignore all entities declared within templates, and out-of-line definitions 1567 // of members of class templates. 1568 if (D->getDeclContext()->isDependentContext() || 1569 D->getLexicalDeclContext()->isDependentContext()) 1570 return false; 1571 1572 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1573 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1574 return false; 1575 // A non-out-of-line declaration of a member specialization was implicitly 1576 // instantiated; it's the out-of-line declaration that we're interested in. 1577 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1578 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1579 return false; 1580 1581 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1582 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1583 return false; 1584 } else { 1585 // 'static inline' functions are defined in headers; don't warn. 1586 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1587 return false; 1588 } 1589 1590 if (FD->doesThisDeclarationHaveABody() && 1591 Context.DeclMustBeEmitted(FD)) 1592 return false; 1593 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1594 // Constants and utility variables are defined in headers with internal 1595 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1596 // like "inline".) 1597 if (!isMainFileLoc(*this, VD->getLocation())) 1598 return false; 1599 1600 if (Context.DeclMustBeEmitted(VD)) 1601 return false; 1602 1603 if (VD->isStaticDataMember() && 1604 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1605 return false; 1606 if (VD->isStaticDataMember() && 1607 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1608 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1609 return false; 1610 1611 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1612 return false; 1613 } else { 1614 return false; 1615 } 1616 1617 // Only warn for unused decls internal to the translation unit. 1618 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1619 // for inline functions defined in the main source file, for instance. 1620 return mightHaveNonExternalLinkage(D); 1621 } 1622 1623 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1624 if (!D) 1625 return; 1626 1627 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1628 const FunctionDecl *First = FD->getFirstDecl(); 1629 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1630 return; // First should already be in the vector. 1631 } 1632 1633 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1634 const VarDecl *First = VD->getFirstDecl(); 1635 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1636 return; // First should already be in the vector. 1637 } 1638 1639 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1640 UnusedFileScopedDecls.push_back(D); 1641 } 1642 1643 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1644 if (D->isInvalidDecl()) 1645 return false; 1646 1647 bool Referenced = false; 1648 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1649 // For a decomposition declaration, warn if none of the bindings are 1650 // referenced, instead of if the variable itself is referenced (which 1651 // it is, by the bindings' expressions). 1652 for (auto *BD : DD->bindings()) { 1653 if (BD->isReferenced()) { 1654 Referenced = true; 1655 break; 1656 } 1657 } 1658 } else if (!D->getDeclName()) { 1659 return false; 1660 } else if (D->isReferenced() || D->isUsed()) { 1661 Referenced = true; 1662 } 1663 1664 if (Referenced || D->hasAttr<UnusedAttr>() || 1665 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1666 return false; 1667 1668 if (isa<LabelDecl>(D)) 1669 return true; 1670 1671 // Except for labels, we only care about unused decls that are local to 1672 // functions. 1673 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1674 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1675 // For dependent types, the diagnostic is deferred. 1676 WithinFunction = 1677 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1678 if (!WithinFunction) 1679 return false; 1680 1681 if (isa<TypedefNameDecl>(D)) 1682 return true; 1683 1684 // White-list anything that isn't a local variable. 1685 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1686 return false; 1687 1688 // Types of valid local variables should be complete, so this should succeed. 1689 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1690 1691 // White-list anything with an __attribute__((unused)) type. 1692 const auto *Ty = VD->getType().getTypePtr(); 1693 1694 // Only look at the outermost level of typedef. 1695 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1696 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1697 return false; 1698 } 1699 1700 // If we failed to complete the type for some reason, or if the type is 1701 // dependent, don't diagnose the variable. 1702 if (Ty->isIncompleteType() || Ty->isDependentType()) 1703 return false; 1704 1705 // Look at the element type to ensure that the warning behaviour is 1706 // consistent for both scalars and arrays. 1707 Ty = Ty->getBaseElementTypeUnsafe(); 1708 1709 if (const TagType *TT = Ty->getAs<TagType>()) { 1710 const TagDecl *Tag = TT->getDecl(); 1711 if (Tag->hasAttr<UnusedAttr>()) 1712 return false; 1713 1714 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1715 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1716 return false; 1717 1718 if (const Expr *Init = VD->getInit()) { 1719 if (const ExprWithCleanups *Cleanups = 1720 dyn_cast<ExprWithCleanups>(Init)) 1721 Init = Cleanups->getSubExpr(); 1722 const CXXConstructExpr *Construct = 1723 dyn_cast<CXXConstructExpr>(Init); 1724 if (Construct && !Construct->isElidable()) { 1725 CXXConstructorDecl *CD = Construct->getConstructor(); 1726 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1727 return false; 1728 } 1729 } 1730 } 1731 } 1732 1733 // TODO: __attribute__((unused)) templates? 1734 } 1735 1736 return true; 1737 } 1738 1739 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1740 FixItHint &Hint) { 1741 if (isa<LabelDecl>(D)) { 1742 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1743 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1744 if (AfterColon.isInvalid()) 1745 return; 1746 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1747 getCharRange(D->getLocStart(), AfterColon)); 1748 } 1749 } 1750 1751 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1752 if (D->getTypeForDecl()->isDependentType()) 1753 return; 1754 1755 for (auto *TmpD : D->decls()) { 1756 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1757 DiagnoseUnusedDecl(T); 1758 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1759 DiagnoseUnusedNestedTypedefs(R); 1760 } 1761 } 1762 1763 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1764 /// unless they are marked attr(unused). 1765 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1766 if (!ShouldDiagnoseUnusedDecl(D)) 1767 return; 1768 1769 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1770 // typedefs can be referenced later on, so the diagnostics are emitted 1771 // at end-of-translation-unit. 1772 UnusedLocalTypedefNameCandidates.insert(TD); 1773 return; 1774 } 1775 1776 FixItHint Hint; 1777 GenerateFixForUnusedDecl(D, Context, Hint); 1778 1779 unsigned DiagID; 1780 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1781 DiagID = diag::warn_unused_exception_param; 1782 else if (isa<LabelDecl>(D)) 1783 DiagID = diag::warn_unused_label; 1784 else 1785 DiagID = diag::warn_unused_variable; 1786 1787 Diag(D->getLocation(), DiagID) << D << Hint; 1788 } 1789 1790 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1791 // Verify that we have no forward references left. If so, there was a goto 1792 // or address of a label taken, but no definition of it. Label fwd 1793 // definitions are indicated with a null substmt which is also not a resolved 1794 // MS inline assembly label name. 1795 bool Diagnose = false; 1796 if (L->isMSAsmLabel()) 1797 Diagnose = !L->isResolvedMSAsmLabel(); 1798 else 1799 Diagnose = L->getStmt() == nullptr; 1800 if (Diagnose) 1801 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1802 } 1803 1804 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1805 S->mergeNRVOIntoParent(); 1806 1807 if (S->decl_empty()) return; 1808 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1809 "Scope shouldn't contain decls!"); 1810 1811 for (auto *TmpD : S->decls()) { 1812 assert(TmpD && "This decl didn't get pushed??"); 1813 1814 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1815 NamedDecl *D = cast<NamedDecl>(TmpD); 1816 1817 // Diagnose unused variables in this scope. 1818 if (!S->hasUnrecoverableErrorOccurred()) { 1819 DiagnoseUnusedDecl(D); 1820 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1821 DiagnoseUnusedNestedTypedefs(RD); 1822 } 1823 1824 if (!D->getDeclName()) continue; 1825 1826 // If this was a forward reference to a label, verify it was defined. 1827 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1828 CheckPoppedLabel(LD, *this); 1829 1830 // Remove this name from our lexical scope, and warn on it if we haven't 1831 // already. 1832 IdResolver.RemoveDecl(D); 1833 auto ShadowI = ShadowingDecls.find(D); 1834 if (ShadowI != ShadowingDecls.end()) { 1835 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1836 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1837 << D << FD << FD->getParent(); 1838 Diag(FD->getLocation(), diag::note_previous_declaration); 1839 } 1840 ShadowingDecls.erase(ShadowI); 1841 } 1842 } 1843 } 1844 1845 /// \brief Look for an Objective-C class in the translation unit. 1846 /// 1847 /// \param Id The name of the Objective-C class we're looking for. If 1848 /// typo-correction fixes this name, the Id will be updated 1849 /// to the fixed name. 1850 /// 1851 /// \param IdLoc The location of the name in the translation unit. 1852 /// 1853 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1854 /// if there is no class with the given name. 1855 /// 1856 /// \returns The declaration of the named Objective-C class, or NULL if the 1857 /// class could not be found. 1858 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1859 SourceLocation IdLoc, 1860 bool DoTypoCorrection) { 1861 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1862 // creation from this context. 1863 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1864 1865 if (!IDecl && DoTypoCorrection) { 1866 // Perform typo correction at the given location, but only if we 1867 // find an Objective-C class name. 1868 if (TypoCorrection C = CorrectTypo( 1869 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1870 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1871 CTK_ErrorRecovery)) { 1872 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1873 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1874 Id = IDecl->getIdentifier(); 1875 } 1876 } 1877 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1878 // This routine must always return a class definition, if any. 1879 if (Def && Def->getDefinition()) 1880 Def = Def->getDefinition(); 1881 return Def; 1882 } 1883 1884 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1885 /// from S, where a non-field would be declared. This routine copes 1886 /// with the difference between C and C++ scoping rules in structs and 1887 /// unions. For example, the following code is well-formed in C but 1888 /// ill-formed in C++: 1889 /// @code 1890 /// struct S6 { 1891 /// enum { BAR } e; 1892 /// }; 1893 /// 1894 /// void test_S6() { 1895 /// struct S6 a; 1896 /// a.e = BAR; 1897 /// } 1898 /// @endcode 1899 /// For the declaration of BAR, this routine will return a different 1900 /// scope. The scope S will be the scope of the unnamed enumeration 1901 /// within S6. In C++, this routine will return the scope associated 1902 /// with S6, because the enumeration's scope is a transparent 1903 /// context but structures can contain non-field names. In C, this 1904 /// routine will return the translation unit scope, since the 1905 /// enumeration's scope is a transparent context and structures cannot 1906 /// contain non-field names. 1907 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1908 while (((S->getFlags() & Scope::DeclScope) == 0) || 1909 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1910 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1911 S = S->getParent(); 1912 return S; 1913 } 1914 1915 /// \brief Looks up the declaration of "struct objc_super" and 1916 /// saves it for later use in building builtin declaration of 1917 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1918 /// pre-existing declaration exists no action takes place. 1919 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1920 IdentifierInfo *II) { 1921 if (!II->isStr("objc_msgSendSuper")) 1922 return; 1923 ASTContext &Context = ThisSema.Context; 1924 1925 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1926 SourceLocation(), Sema::LookupTagName); 1927 ThisSema.LookupName(Result, S); 1928 if (Result.getResultKind() == LookupResult::Found) 1929 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1930 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1931 } 1932 1933 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1934 switch (Error) { 1935 case ASTContext::GE_None: 1936 return ""; 1937 case ASTContext::GE_Missing_stdio: 1938 return "stdio.h"; 1939 case ASTContext::GE_Missing_setjmp: 1940 return "setjmp.h"; 1941 case ASTContext::GE_Missing_ucontext: 1942 return "ucontext.h"; 1943 } 1944 llvm_unreachable("unhandled error kind"); 1945 } 1946 1947 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1948 /// file scope. lazily create a decl for it. ForRedeclaration is true 1949 /// if we're creating this built-in in anticipation of redeclaring the 1950 /// built-in. 1951 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1952 Scope *S, bool ForRedeclaration, 1953 SourceLocation Loc) { 1954 LookupPredefedObjCSuperType(*this, S, II); 1955 1956 ASTContext::GetBuiltinTypeError Error; 1957 QualType R = Context.GetBuiltinType(ID, Error); 1958 if (Error) { 1959 if (ForRedeclaration) 1960 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1961 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1962 return nullptr; 1963 } 1964 1965 if (!ForRedeclaration && 1966 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1967 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1968 Diag(Loc, diag::ext_implicit_lib_function_decl) 1969 << Context.BuiltinInfo.getName(ID) << R; 1970 if (Context.BuiltinInfo.getHeaderName(ID) && 1971 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1972 Diag(Loc, diag::note_include_header_or_declare) 1973 << Context.BuiltinInfo.getHeaderName(ID) 1974 << Context.BuiltinInfo.getName(ID); 1975 } 1976 1977 if (R.isNull()) 1978 return nullptr; 1979 1980 DeclContext *Parent = Context.getTranslationUnitDecl(); 1981 if (getLangOpts().CPlusPlus) { 1982 LinkageSpecDecl *CLinkageDecl = 1983 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1984 LinkageSpecDecl::lang_c, false); 1985 CLinkageDecl->setImplicit(); 1986 Parent->addDecl(CLinkageDecl); 1987 Parent = CLinkageDecl; 1988 } 1989 1990 FunctionDecl *New = FunctionDecl::Create(Context, 1991 Parent, 1992 Loc, Loc, II, R, /*TInfo=*/nullptr, 1993 SC_Extern, 1994 false, 1995 R->isFunctionProtoType()); 1996 New->setImplicit(); 1997 1998 // Create Decl objects for each parameter, adding them to the 1999 // FunctionDecl. 2000 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2001 SmallVector<ParmVarDecl*, 16> Params; 2002 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2003 ParmVarDecl *parm = 2004 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2005 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2006 SC_None, nullptr); 2007 parm->setScopeInfo(0, i); 2008 Params.push_back(parm); 2009 } 2010 New->setParams(Params); 2011 } 2012 2013 AddKnownFunctionAttributes(New); 2014 RegisterLocallyScopedExternCDecl(New, S); 2015 2016 // TUScope is the translation-unit scope to insert this function into. 2017 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2018 // relate Scopes to DeclContexts, and probably eliminate CurContext 2019 // entirely, but we're not there yet. 2020 DeclContext *SavedContext = CurContext; 2021 CurContext = Parent; 2022 PushOnScopeChains(New, TUScope); 2023 CurContext = SavedContext; 2024 return New; 2025 } 2026 2027 /// Typedef declarations don't have linkage, but they still denote the same 2028 /// entity if their types are the same. 2029 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2030 /// isSameEntity. 2031 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2032 TypedefNameDecl *Decl, 2033 LookupResult &Previous) { 2034 // This is only interesting when modules are enabled. 2035 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2036 return; 2037 2038 // Empty sets are uninteresting. 2039 if (Previous.empty()) 2040 return; 2041 2042 LookupResult::Filter Filter = Previous.makeFilter(); 2043 while (Filter.hasNext()) { 2044 NamedDecl *Old = Filter.next(); 2045 2046 // Non-hidden declarations are never ignored. 2047 if (S.isVisible(Old)) 2048 continue; 2049 2050 // Declarations of the same entity are not ignored, even if they have 2051 // different linkages. 2052 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2053 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2054 Decl->getUnderlyingType())) 2055 continue; 2056 2057 // If both declarations give a tag declaration a typedef name for linkage 2058 // purposes, then they declare the same entity. 2059 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2060 Decl->getAnonDeclWithTypedefName()) 2061 continue; 2062 } 2063 2064 Filter.erase(); 2065 } 2066 2067 Filter.done(); 2068 } 2069 2070 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2071 QualType OldType; 2072 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2073 OldType = OldTypedef->getUnderlyingType(); 2074 else 2075 OldType = Context.getTypeDeclType(Old); 2076 QualType NewType = New->getUnderlyingType(); 2077 2078 if (NewType->isVariablyModifiedType()) { 2079 // Must not redefine a typedef with a variably-modified type. 2080 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2081 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2082 << Kind << NewType; 2083 if (Old->getLocation().isValid()) 2084 notePreviousDefinition(Old, New->getLocation()); 2085 New->setInvalidDecl(); 2086 return true; 2087 } 2088 2089 if (OldType != NewType && 2090 !OldType->isDependentType() && 2091 !NewType->isDependentType() && 2092 !Context.hasSameType(OldType, NewType)) { 2093 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2094 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2095 << Kind << NewType << OldType; 2096 if (Old->getLocation().isValid()) 2097 notePreviousDefinition(Old, New->getLocation()); 2098 New->setInvalidDecl(); 2099 return true; 2100 } 2101 return false; 2102 } 2103 2104 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2105 /// same name and scope as a previous declaration 'Old'. Figure out 2106 /// how to resolve this situation, merging decls or emitting 2107 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2108 /// 2109 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2110 LookupResult &OldDecls) { 2111 // If the new decl is known invalid already, don't bother doing any 2112 // merging checks. 2113 if (New->isInvalidDecl()) return; 2114 2115 // Allow multiple definitions for ObjC built-in typedefs. 2116 // FIXME: Verify the underlying types are equivalent! 2117 if (getLangOpts().ObjC1) { 2118 const IdentifierInfo *TypeID = New->getIdentifier(); 2119 switch (TypeID->getLength()) { 2120 default: break; 2121 case 2: 2122 { 2123 if (!TypeID->isStr("id")) 2124 break; 2125 QualType T = New->getUnderlyingType(); 2126 if (!T->isPointerType()) 2127 break; 2128 if (!T->isVoidPointerType()) { 2129 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2130 if (!PT->isStructureType()) 2131 break; 2132 } 2133 Context.setObjCIdRedefinitionType(T); 2134 // Install the built-in type for 'id', ignoring the current definition. 2135 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2136 return; 2137 } 2138 case 5: 2139 if (!TypeID->isStr("Class")) 2140 break; 2141 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2142 // Install the built-in type for 'Class', ignoring the current definition. 2143 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2144 return; 2145 case 3: 2146 if (!TypeID->isStr("SEL")) 2147 break; 2148 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2149 // Install the built-in type for 'SEL', ignoring the current definition. 2150 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2151 return; 2152 } 2153 // Fall through - the typedef name was not a builtin type. 2154 } 2155 2156 // Verify the old decl was also a type. 2157 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2158 if (!Old) { 2159 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2160 << New->getDeclName(); 2161 2162 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2163 if (OldD->getLocation().isValid()) 2164 notePreviousDefinition(OldD, New->getLocation()); 2165 2166 return New->setInvalidDecl(); 2167 } 2168 2169 // If the old declaration is invalid, just give up here. 2170 if (Old->isInvalidDecl()) 2171 return New->setInvalidDecl(); 2172 2173 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2174 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2175 auto *NewTag = New->getAnonDeclWithTypedefName(); 2176 NamedDecl *Hidden = nullptr; 2177 if (OldTag && NewTag && 2178 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2179 !hasVisibleDefinition(OldTag, &Hidden)) { 2180 // There is a definition of this tag, but it is not visible. Use it 2181 // instead of our tag. 2182 New->setTypeForDecl(OldTD->getTypeForDecl()); 2183 if (OldTD->isModed()) 2184 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2185 OldTD->getUnderlyingType()); 2186 else 2187 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2188 2189 // Make the old tag definition visible. 2190 makeMergedDefinitionVisible(Hidden); 2191 2192 // If this was an unscoped enumeration, yank all of its enumerators 2193 // out of the scope. 2194 if (isa<EnumDecl>(NewTag)) { 2195 Scope *EnumScope = getNonFieldDeclScope(S); 2196 for (auto *D : NewTag->decls()) { 2197 auto *ED = cast<EnumConstantDecl>(D); 2198 assert(EnumScope->isDeclScope(ED)); 2199 EnumScope->RemoveDecl(ED); 2200 IdResolver.RemoveDecl(ED); 2201 ED->getLexicalDeclContext()->removeDecl(ED); 2202 } 2203 } 2204 } 2205 } 2206 2207 // If the typedef types are not identical, reject them in all languages and 2208 // with any extensions enabled. 2209 if (isIncompatibleTypedef(Old, New)) 2210 return; 2211 2212 // The types match. Link up the redeclaration chain and merge attributes if 2213 // the old declaration was a typedef. 2214 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2215 New->setPreviousDecl(Typedef); 2216 mergeDeclAttributes(New, Old); 2217 } 2218 2219 if (getLangOpts().MicrosoftExt) 2220 return; 2221 2222 if (getLangOpts().CPlusPlus) { 2223 // C++ [dcl.typedef]p2: 2224 // In a given non-class scope, a typedef specifier can be used to 2225 // redefine the name of any type declared in that scope to refer 2226 // to the type to which it already refers. 2227 if (!isa<CXXRecordDecl>(CurContext)) 2228 return; 2229 2230 // C++0x [dcl.typedef]p4: 2231 // In a given class scope, a typedef specifier can be used to redefine 2232 // any class-name declared in that scope that is not also a typedef-name 2233 // to refer to the type to which it already refers. 2234 // 2235 // This wording came in via DR424, which was a correction to the 2236 // wording in DR56, which accidentally banned code like: 2237 // 2238 // struct S { 2239 // typedef struct A { } A; 2240 // }; 2241 // 2242 // in the C++03 standard. We implement the C++0x semantics, which 2243 // allow the above but disallow 2244 // 2245 // struct S { 2246 // typedef int I; 2247 // typedef int I; 2248 // }; 2249 // 2250 // since that was the intent of DR56. 2251 if (!isa<TypedefNameDecl>(Old)) 2252 return; 2253 2254 Diag(New->getLocation(), diag::err_redefinition) 2255 << New->getDeclName(); 2256 notePreviousDefinition(Old, New->getLocation()); 2257 return New->setInvalidDecl(); 2258 } 2259 2260 // Modules always permit redefinition of typedefs, as does C11. 2261 if (getLangOpts().Modules || getLangOpts().C11) 2262 return; 2263 2264 // If we have a redefinition of a typedef in C, emit a warning. This warning 2265 // is normally mapped to an error, but can be controlled with 2266 // -Wtypedef-redefinition. If either the original or the redefinition is 2267 // in a system header, don't emit this for compatibility with GCC. 2268 if (getDiagnostics().getSuppressSystemWarnings() && 2269 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2270 (Old->isImplicit() || 2271 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2272 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2273 return; 2274 2275 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2276 << New->getDeclName(); 2277 notePreviousDefinition(Old, New->getLocation()); 2278 } 2279 2280 /// DeclhasAttr - returns true if decl Declaration already has the target 2281 /// attribute. 2282 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2283 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2284 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2285 for (const auto *i : D->attrs()) 2286 if (i->getKind() == A->getKind()) { 2287 if (Ann) { 2288 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2289 return true; 2290 continue; 2291 } 2292 // FIXME: Don't hardcode this check 2293 if (OA && isa<OwnershipAttr>(i)) 2294 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2295 return true; 2296 } 2297 2298 return false; 2299 } 2300 2301 static bool isAttributeTargetADefinition(Decl *D) { 2302 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2303 return VD->isThisDeclarationADefinition(); 2304 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2305 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2306 return true; 2307 } 2308 2309 /// Merge alignment attributes from \p Old to \p New, taking into account the 2310 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2311 /// 2312 /// \return \c true if any attributes were added to \p New. 2313 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2314 // Look for alignas attributes on Old, and pick out whichever attribute 2315 // specifies the strictest alignment requirement. 2316 AlignedAttr *OldAlignasAttr = nullptr; 2317 AlignedAttr *OldStrictestAlignAttr = nullptr; 2318 unsigned OldAlign = 0; 2319 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2320 // FIXME: We have no way of representing inherited dependent alignments 2321 // in a case like: 2322 // template<int A, int B> struct alignas(A) X; 2323 // template<int A, int B> struct alignas(B) X {}; 2324 // For now, we just ignore any alignas attributes which are not on the 2325 // definition in such a case. 2326 if (I->isAlignmentDependent()) 2327 return false; 2328 2329 if (I->isAlignas()) 2330 OldAlignasAttr = I; 2331 2332 unsigned Align = I->getAlignment(S.Context); 2333 if (Align > OldAlign) { 2334 OldAlign = Align; 2335 OldStrictestAlignAttr = I; 2336 } 2337 } 2338 2339 // Look for alignas attributes on New. 2340 AlignedAttr *NewAlignasAttr = nullptr; 2341 unsigned NewAlign = 0; 2342 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2343 if (I->isAlignmentDependent()) 2344 return false; 2345 2346 if (I->isAlignas()) 2347 NewAlignasAttr = I; 2348 2349 unsigned Align = I->getAlignment(S.Context); 2350 if (Align > NewAlign) 2351 NewAlign = Align; 2352 } 2353 2354 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2355 // Both declarations have 'alignas' attributes. We require them to match. 2356 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2357 // fall short. (If two declarations both have alignas, they must both match 2358 // every definition, and so must match each other if there is a definition.) 2359 2360 // If either declaration only contains 'alignas(0)' specifiers, then it 2361 // specifies the natural alignment for the type. 2362 if (OldAlign == 0 || NewAlign == 0) { 2363 QualType Ty; 2364 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2365 Ty = VD->getType(); 2366 else 2367 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2368 2369 if (OldAlign == 0) 2370 OldAlign = S.Context.getTypeAlign(Ty); 2371 if (NewAlign == 0) 2372 NewAlign = S.Context.getTypeAlign(Ty); 2373 } 2374 2375 if (OldAlign != NewAlign) { 2376 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2377 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2378 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2379 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2380 } 2381 } 2382 2383 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2384 // C++11 [dcl.align]p6: 2385 // if any declaration of an entity has an alignment-specifier, 2386 // every defining declaration of that entity shall specify an 2387 // equivalent alignment. 2388 // C11 6.7.5/7: 2389 // If the definition of an object does not have an alignment 2390 // specifier, any other declaration of that object shall also 2391 // have no alignment specifier. 2392 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2393 << OldAlignasAttr; 2394 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2395 << OldAlignasAttr; 2396 } 2397 2398 bool AnyAdded = false; 2399 2400 // Ensure we have an attribute representing the strictest alignment. 2401 if (OldAlign > NewAlign) { 2402 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2403 Clone->setInherited(true); 2404 New->addAttr(Clone); 2405 AnyAdded = true; 2406 } 2407 2408 // Ensure we have an alignas attribute if the old declaration had one. 2409 if (OldAlignasAttr && !NewAlignasAttr && 2410 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2411 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2412 Clone->setInherited(true); 2413 New->addAttr(Clone); 2414 AnyAdded = true; 2415 } 2416 2417 return AnyAdded; 2418 } 2419 2420 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2421 const InheritableAttr *Attr, 2422 Sema::AvailabilityMergeKind AMK) { 2423 // This function copies an attribute Attr from a previous declaration to the 2424 // new declaration D if the new declaration doesn't itself have that attribute 2425 // yet or if that attribute allows duplicates. 2426 // If you're adding a new attribute that requires logic different from 2427 // "use explicit attribute on decl if present, else use attribute from 2428 // previous decl", for example if the attribute needs to be consistent 2429 // between redeclarations, you need to call a custom merge function here. 2430 InheritableAttr *NewAttr = nullptr; 2431 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2432 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2433 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2434 AA->isImplicit(), AA->getIntroduced(), 2435 AA->getDeprecated(), 2436 AA->getObsoleted(), AA->getUnavailable(), 2437 AA->getMessage(), AA->getStrict(), 2438 AA->getReplacement(), AMK, 2439 AttrSpellingListIndex); 2440 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2441 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2442 AttrSpellingListIndex); 2443 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2444 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2445 AttrSpellingListIndex); 2446 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2447 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2448 AttrSpellingListIndex); 2449 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2450 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2451 AttrSpellingListIndex); 2452 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2453 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2454 FA->getFormatIdx(), FA->getFirstArg(), 2455 AttrSpellingListIndex); 2456 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2457 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2458 AttrSpellingListIndex); 2459 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2460 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2461 AttrSpellingListIndex, 2462 IA->getSemanticSpelling()); 2463 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2464 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2465 &S.Context.Idents.get(AA->getSpelling()), 2466 AttrSpellingListIndex); 2467 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2468 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2469 isa<CUDAGlobalAttr>(Attr))) { 2470 // CUDA target attributes are part of function signature for 2471 // overloading purposes and must not be merged. 2472 return false; 2473 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2474 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2475 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2476 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2477 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2478 NewAttr = S.mergeInternalLinkageAttr( 2479 D, InternalLinkageA->getRange(), 2480 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2481 AttrSpellingListIndex); 2482 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2483 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2484 &S.Context.Idents.get(CommonA->getSpelling()), 2485 AttrSpellingListIndex); 2486 else if (isa<AlignedAttr>(Attr)) 2487 // AlignedAttrs are handled separately, because we need to handle all 2488 // such attributes on a declaration at the same time. 2489 NewAttr = nullptr; 2490 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2491 (AMK == Sema::AMK_Override || 2492 AMK == Sema::AMK_ProtocolImplementation)) 2493 NewAttr = nullptr; 2494 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2495 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2496 UA->getGuid()); 2497 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2498 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2499 2500 if (NewAttr) { 2501 NewAttr->setInherited(true); 2502 D->addAttr(NewAttr); 2503 if (isa<MSInheritanceAttr>(NewAttr)) 2504 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2505 return true; 2506 } 2507 2508 return false; 2509 } 2510 2511 static const NamedDecl *getDefinition(const Decl *D) { 2512 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2513 return TD->getDefinition(); 2514 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2515 const VarDecl *Def = VD->getDefinition(); 2516 if (Def) 2517 return Def; 2518 return VD->getActingDefinition(); 2519 } 2520 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2521 return FD->getDefinition(); 2522 return nullptr; 2523 } 2524 2525 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2526 for (const auto *Attribute : D->attrs()) 2527 if (Attribute->getKind() == Kind) 2528 return true; 2529 return false; 2530 } 2531 2532 /// checkNewAttributesAfterDef - If we already have a definition, check that 2533 /// there are no new attributes in this declaration. 2534 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2535 if (!New->hasAttrs()) 2536 return; 2537 2538 const NamedDecl *Def = getDefinition(Old); 2539 if (!Def || Def == New) 2540 return; 2541 2542 AttrVec &NewAttributes = New->getAttrs(); 2543 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2544 const Attr *NewAttribute = NewAttributes[I]; 2545 2546 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2547 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2548 Sema::SkipBodyInfo SkipBody; 2549 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2550 2551 // If we're skipping this definition, drop the "alias" attribute. 2552 if (SkipBody.ShouldSkip) { 2553 NewAttributes.erase(NewAttributes.begin() + I); 2554 --E; 2555 continue; 2556 } 2557 } else { 2558 VarDecl *VD = cast<VarDecl>(New); 2559 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2560 VarDecl::TentativeDefinition 2561 ? diag::err_alias_after_tentative 2562 : diag::err_redefinition; 2563 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2564 if (Diag == diag::err_redefinition) 2565 S.notePreviousDefinition(Def, VD->getLocation()); 2566 else 2567 S.Diag(Def->getLocation(), diag::note_previous_definition); 2568 VD->setInvalidDecl(); 2569 } 2570 ++I; 2571 continue; 2572 } 2573 2574 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2575 // Tentative definitions are only interesting for the alias check above. 2576 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2577 ++I; 2578 continue; 2579 } 2580 } 2581 2582 if (hasAttribute(Def, NewAttribute->getKind())) { 2583 ++I; 2584 continue; // regular attr merging will take care of validating this. 2585 } 2586 2587 if (isa<C11NoReturnAttr>(NewAttribute)) { 2588 // C's _Noreturn is allowed to be added to a function after it is defined. 2589 ++I; 2590 continue; 2591 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2592 if (AA->isAlignas()) { 2593 // C++11 [dcl.align]p6: 2594 // if any declaration of an entity has an alignment-specifier, 2595 // every defining declaration of that entity shall specify an 2596 // equivalent alignment. 2597 // C11 6.7.5/7: 2598 // If the definition of an object does not have an alignment 2599 // specifier, any other declaration of that object shall also 2600 // have no alignment specifier. 2601 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2602 << AA; 2603 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2604 << AA; 2605 NewAttributes.erase(NewAttributes.begin() + I); 2606 --E; 2607 continue; 2608 } 2609 } 2610 2611 S.Diag(NewAttribute->getLocation(), 2612 diag::warn_attribute_precede_definition); 2613 S.Diag(Def->getLocation(), diag::note_previous_definition); 2614 NewAttributes.erase(NewAttributes.begin() + I); 2615 --E; 2616 } 2617 } 2618 2619 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2620 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2621 AvailabilityMergeKind AMK) { 2622 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2623 UsedAttr *NewAttr = OldAttr->clone(Context); 2624 NewAttr->setInherited(true); 2625 New->addAttr(NewAttr); 2626 } 2627 2628 if (!Old->hasAttrs() && !New->hasAttrs()) 2629 return; 2630 2631 // Attributes declared post-definition are currently ignored. 2632 checkNewAttributesAfterDef(*this, New, Old); 2633 2634 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2635 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2636 if (OldA->getLabel() != NewA->getLabel()) { 2637 // This redeclaration changes __asm__ label. 2638 Diag(New->getLocation(), diag::err_different_asm_label); 2639 Diag(OldA->getLocation(), diag::note_previous_declaration); 2640 } 2641 } else if (Old->isUsed()) { 2642 // This redeclaration adds an __asm__ label to a declaration that has 2643 // already been ODR-used. 2644 Diag(New->getLocation(), diag::err_late_asm_label_name) 2645 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2646 } 2647 } 2648 2649 // Re-declaration cannot add abi_tag's. 2650 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2651 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2652 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2653 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2654 NewTag) == OldAbiTagAttr->tags_end()) { 2655 Diag(NewAbiTagAttr->getLocation(), 2656 diag::err_new_abi_tag_on_redeclaration) 2657 << NewTag; 2658 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2659 } 2660 } 2661 } else { 2662 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2663 Diag(Old->getLocation(), diag::note_previous_declaration); 2664 } 2665 } 2666 2667 // This redeclaration adds a section attribute. 2668 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2669 if (auto *VD = dyn_cast<VarDecl>(New)) { 2670 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2671 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2672 Diag(Old->getLocation(), diag::note_previous_declaration); 2673 } 2674 } 2675 } 2676 2677 if (!Old->hasAttrs()) 2678 return; 2679 2680 bool foundAny = New->hasAttrs(); 2681 2682 // Ensure that any moving of objects within the allocated map is done before 2683 // we process them. 2684 if (!foundAny) New->setAttrs(AttrVec()); 2685 2686 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2687 // Ignore deprecated/unavailable/availability attributes if requested. 2688 AvailabilityMergeKind LocalAMK = AMK_None; 2689 if (isa<DeprecatedAttr>(I) || 2690 isa<UnavailableAttr>(I) || 2691 isa<AvailabilityAttr>(I)) { 2692 switch (AMK) { 2693 case AMK_None: 2694 continue; 2695 2696 case AMK_Redeclaration: 2697 case AMK_Override: 2698 case AMK_ProtocolImplementation: 2699 LocalAMK = AMK; 2700 break; 2701 } 2702 } 2703 2704 // Already handled. 2705 if (isa<UsedAttr>(I)) 2706 continue; 2707 2708 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2709 foundAny = true; 2710 } 2711 2712 if (mergeAlignedAttrs(*this, New, Old)) 2713 foundAny = true; 2714 2715 if (!foundAny) New->dropAttrs(); 2716 } 2717 2718 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2719 /// to the new one. 2720 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2721 const ParmVarDecl *oldDecl, 2722 Sema &S) { 2723 // C++11 [dcl.attr.depend]p2: 2724 // The first declaration of a function shall specify the 2725 // carries_dependency attribute for its declarator-id if any declaration 2726 // of the function specifies the carries_dependency attribute. 2727 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2728 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2729 S.Diag(CDA->getLocation(), 2730 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2731 // Find the first declaration of the parameter. 2732 // FIXME: Should we build redeclaration chains for function parameters? 2733 const FunctionDecl *FirstFD = 2734 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2735 const ParmVarDecl *FirstVD = 2736 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2737 S.Diag(FirstVD->getLocation(), 2738 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2739 } 2740 2741 if (!oldDecl->hasAttrs()) 2742 return; 2743 2744 bool foundAny = newDecl->hasAttrs(); 2745 2746 // Ensure that any moving of objects within the allocated map is 2747 // done before we process them. 2748 if (!foundAny) newDecl->setAttrs(AttrVec()); 2749 2750 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2751 if (!DeclHasAttr(newDecl, I)) { 2752 InheritableAttr *newAttr = 2753 cast<InheritableParamAttr>(I->clone(S.Context)); 2754 newAttr->setInherited(true); 2755 newDecl->addAttr(newAttr); 2756 foundAny = true; 2757 } 2758 } 2759 2760 if (!foundAny) newDecl->dropAttrs(); 2761 } 2762 2763 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2764 const ParmVarDecl *OldParam, 2765 Sema &S) { 2766 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2767 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2768 if (*Oldnullability != *Newnullability) { 2769 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2770 << DiagNullabilityKind( 2771 *Newnullability, 2772 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2773 != 0)) 2774 << DiagNullabilityKind( 2775 *Oldnullability, 2776 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2777 != 0)); 2778 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2779 } 2780 } else { 2781 QualType NewT = NewParam->getType(); 2782 NewT = S.Context.getAttributedType( 2783 AttributedType::getNullabilityAttrKind(*Oldnullability), 2784 NewT, NewT); 2785 NewParam->setType(NewT); 2786 } 2787 } 2788 } 2789 2790 namespace { 2791 2792 /// Used in MergeFunctionDecl to keep track of function parameters in 2793 /// C. 2794 struct GNUCompatibleParamWarning { 2795 ParmVarDecl *OldParm; 2796 ParmVarDecl *NewParm; 2797 QualType PromotedType; 2798 }; 2799 2800 } // end anonymous namespace 2801 2802 /// getSpecialMember - get the special member enum for a method. 2803 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2804 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2805 if (Ctor->isDefaultConstructor()) 2806 return Sema::CXXDefaultConstructor; 2807 2808 if (Ctor->isCopyConstructor()) 2809 return Sema::CXXCopyConstructor; 2810 2811 if (Ctor->isMoveConstructor()) 2812 return Sema::CXXMoveConstructor; 2813 } else if (isa<CXXDestructorDecl>(MD)) { 2814 return Sema::CXXDestructor; 2815 } else if (MD->isCopyAssignmentOperator()) { 2816 return Sema::CXXCopyAssignment; 2817 } else if (MD->isMoveAssignmentOperator()) { 2818 return Sema::CXXMoveAssignment; 2819 } 2820 2821 return Sema::CXXInvalid; 2822 } 2823 2824 // Determine whether the previous declaration was a definition, implicit 2825 // declaration, or a declaration. 2826 template <typename T> 2827 static std::pair<diag::kind, SourceLocation> 2828 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2829 diag::kind PrevDiag; 2830 SourceLocation OldLocation = Old->getLocation(); 2831 if (Old->isThisDeclarationADefinition()) 2832 PrevDiag = diag::note_previous_definition; 2833 else if (Old->isImplicit()) { 2834 PrevDiag = diag::note_previous_implicit_declaration; 2835 if (OldLocation.isInvalid()) 2836 OldLocation = New->getLocation(); 2837 } else 2838 PrevDiag = diag::note_previous_declaration; 2839 return std::make_pair(PrevDiag, OldLocation); 2840 } 2841 2842 /// canRedefineFunction - checks if a function can be redefined. Currently, 2843 /// only extern inline functions can be redefined, and even then only in 2844 /// GNU89 mode. 2845 static bool canRedefineFunction(const FunctionDecl *FD, 2846 const LangOptions& LangOpts) { 2847 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2848 !LangOpts.CPlusPlus && 2849 FD->isInlineSpecified() && 2850 FD->getStorageClass() == SC_Extern); 2851 } 2852 2853 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2854 const AttributedType *AT = T->getAs<AttributedType>(); 2855 while (AT && !AT->isCallingConv()) 2856 AT = AT->getModifiedType()->getAs<AttributedType>(); 2857 return AT; 2858 } 2859 2860 template <typename T> 2861 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2862 const DeclContext *DC = Old->getDeclContext(); 2863 if (DC->isRecord()) 2864 return false; 2865 2866 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2867 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2868 return true; 2869 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2870 return true; 2871 return false; 2872 } 2873 2874 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2875 static bool isExternC(VarTemplateDecl *) { return false; } 2876 2877 /// \brief Check whether a redeclaration of an entity introduced by a 2878 /// using-declaration is valid, given that we know it's not an overload 2879 /// (nor a hidden tag declaration). 2880 template<typename ExpectedDecl> 2881 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2882 ExpectedDecl *New) { 2883 // C++11 [basic.scope.declarative]p4: 2884 // Given a set of declarations in a single declarative region, each of 2885 // which specifies the same unqualified name, 2886 // -- they shall all refer to the same entity, or all refer to functions 2887 // and function templates; or 2888 // -- exactly one declaration shall declare a class name or enumeration 2889 // name that is not a typedef name and the other declarations shall all 2890 // refer to the same variable or enumerator, or all refer to functions 2891 // and function templates; in this case the class name or enumeration 2892 // name is hidden (3.3.10). 2893 2894 // C++11 [namespace.udecl]p14: 2895 // If a function declaration in namespace scope or block scope has the 2896 // same name and the same parameter-type-list as a function introduced 2897 // by a using-declaration, and the declarations do not declare the same 2898 // function, the program is ill-formed. 2899 2900 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2901 if (Old && 2902 !Old->getDeclContext()->getRedeclContext()->Equals( 2903 New->getDeclContext()->getRedeclContext()) && 2904 !(isExternC(Old) && isExternC(New))) 2905 Old = nullptr; 2906 2907 if (!Old) { 2908 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2909 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2910 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2911 return true; 2912 } 2913 return false; 2914 } 2915 2916 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2917 const FunctionDecl *B) { 2918 assert(A->getNumParams() == B->getNumParams()); 2919 2920 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2921 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2922 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2923 if (AttrA == AttrB) 2924 return true; 2925 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2926 }; 2927 2928 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2929 } 2930 2931 /// MergeFunctionDecl - We just parsed a function 'New' from 2932 /// declarator D which has the same name and scope as a previous 2933 /// declaration 'Old'. Figure out how to resolve this situation, 2934 /// merging decls or emitting diagnostics as appropriate. 2935 /// 2936 /// In C++, New and Old must be declarations that are not 2937 /// overloaded. Use IsOverload to determine whether New and Old are 2938 /// overloaded, and to select the Old declaration that New should be 2939 /// merged with. 2940 /// 2941 /// Returns true if there was an error, false otherwise. 2942 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2943 Scope *S, bool MergeTypeWithOld) { 2944 // Verify the old decl was also a function. 2945 FunctionDecl *Old = OldD->getAsFunction(); 2946 if (!Old) { 2947 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2948 if (New->getFriendObjectKind()) { 2949 Diag(New->getLocation(), diag::err_using_decl_friend); 2950 Diag(Shadow->getTargetDecl()->getLocation(), 2951 diag::note_using_decl_target); 2952 Diag(Shadow->getUsingDecl()->getLocation(), 2953 diag::note_using_decl) << 0; 2954 return true; 2955 } 2956 2957 // Check whether the two declarations might declare the same function. 2958 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2959 return true; 2960 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2961 } else { 2962 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2963 << New->getDeclName(); 2964 notePreviousDefinition(OldD, New->getLocation()); 2965 return true; 2966 } 2967 } 2968 2969 // If the old declaration is invalid, just give up here. 2970 if (Old->isInvalidDecl()) 2971 return true; 2972 2973 diag::kind PrevDiag; 2974 SourceLocation OldLocation; 2975 std::tie(PrevDiag, OldLocation) = 2976 getNoteDiagForInvalidRedeclaration(Old, New); 2977 2978 // Don't complain about this if we're in GNU89 mode and the old function 2979 // is an extern inline function. 2980 // Don't complain about specializations. They are not supposed to have 2981 // storage classes. 2982 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2983 New->getStorageClass() == SC_Static && 2984 Old->hasExternalFormalLinkage() && 2985 !New->getTemplateSpecializationInfo() && 2986 !canRedefineFunction(Old, getLangOpts())) { 2987 if (getLangOpts().MicrosoftExt) { 2988 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2989 Diag(OldLocation, PrevDiag); 2990 } else { 2991 Diag(New->getLocation(), diag::err_static_non_static) << New; 2992 Diag(OldLocation, PrevDiag); 2993 return true; 2994 } 2995 } 2996 2997 if (New->hasAttr<InternalLinkageAttr>() && 2998 !Old->hasAttr<InternalLinkageAttr>()) { 2999 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3000 << New->getDeclName(); 3001 notePreviousDefinition(Old, New->getLocation()); 3002 New->dropAttr<InternalLinkageAttr>(); 3003 } 3004 3005 if (CheckRedeclarationModuleOwnership(New, Old)) 3006 return true; 3007 3008 if (!getLangOpts().CPlusPlus) { 3009 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3010 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3011 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3012 << New << OldOvl; 3013 3014 // Try our best to find a decl that actually has the overloadable 3015 // attribute for the note. In most cases (e.g. programs with only one 3016 // broken declaration/definition), this won't matter. 3017 // 3018 // FIXME: We could do this if we juggled some extra state in 3019 // OverloadableAttr, rather than just removing it. 3020 const Decl *DiagOld = Old; 3021 if (OldOvl) { 3022 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3023 const auto *A = D->getAttr<OverloadableAttr>(); 3024 return A && !A->isImplicit(); 3025 }); 3026 // If we've implicitly added *all* of the overloadable attrs to this 3027 // chain, emitting a "previous redecl" note is pointless. 3028 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3029 } 3030 3031 if (DiagOld) 3032 Diag(DiagOld->getLocation(), 3033 diag::note_attribute_overloadable_prev_overload) 3034 << OldOvl; 3035 3036 if (OldOvl) 3037 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3038 else 3039 New->dropAttr<OverloadableAttr>(); 3040 } 3041 } 3042 3043 // If a function is first declared with a calling convention, but is later 3044 // declared or defined without one, all following decls assume the calling 3045 // convention of the first. 3046 // 3047 // It's OK if a function is first declared without a calling convention, 3048 // but is later declared or defined with the default calling convention. 3049 // 3050 // To test if either decl has an explicit calling convention, we look for 3051 // AttributedType sugar nodes on the type as written. If they are missing or 3052 // were canonicalized away, we assume the calling convention was implicit. 3053 // 3054 // Note also that we DO NOT return at this point, because we still have 3055 // other tests to run. 3056 QualType OldQType = Context.getCanonicalType(Old->getType()); 3057 QualType NewQType = Context.getCanonicalType(New->getType()); 3058 const FunctionType *OldType = cast<FunctionType>(OldQType); 3059 const FunctionType *NewType = cast<FunctionType>(NewQType); 3060 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3061 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3062 bool RequiresAdjustment = false; 3063 3064 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3065 FunctionDecl *First = Old->getFirstDecl(); 3066 const FunctionType *FT = 3067 First->getType().getCanonicalType()->castAs<FunctionType>(); 3068 FunctionType::ExtInfo FI = FT->getExtInfo(); 3069 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3070 if (!NewCCExplicit) { 3071 // Inherit the CC from the previous declaration if it was specified 3072 // there but not here. 3073 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3074 RequiresAdjustment = true; 3075 } else { 3076 // Calling conventions aren't compatible, so complain. 3077 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3078 Diag(New->getLocation(), diag::err_cconv_change) 3079 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3080 << !FirstCCExplicit 3081 << (!FirstCCExplicit ? "" : 3082 FunctionType::getNameForCallConv(FI.getCC())); 3083 3084 // Put the note on the first decl, since it is the one that matters. 3085 Diag(First->getLocation(), diag::note_previous_declaration); 3086 return true; 3087 } 3088 } 3089 3090 // FIXME: diagnose the other way around? 3091 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3092 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3093 RequiresAdjustment = true; 3094 } 3095 3096 // Merge regparm attribute. 3097 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3098 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3099 if (NewTypeInfo.getHasRegParm()) { 3100 Diag(New->getLocation(), diag::err_regparm_mismatch) 3101 << NewType->getRegParmType() 3102 << OldType->getRegParmType(); 3103 Diag(OldLocation, diag::note_previous_declaration); 3104 return true; 3105 } 3106 3107 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3108 RequiresAdjustment = true; 3109 } 3110 3111 // Merge ns_returns_retained attribute. 3112 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3113 if (NewTypeInfo.getProducesResult()) { 3114 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3115 << "'ns_returns_retained'"; 3116 Diag(OldLocation, diag::note_previous_declaration); 3117 return true; 3118 } 3119 3120 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3121 RequiresAdjustment = true; 3122 } 3123 3124 if (OldTypeInfo.getNoCallerSavedRegs() != 3125 NewTypeInfo.getNoCallerSavedRegs()) { 3126 if (NewTypeInfo.getNoCallerSavedRegs()) { 3127 AnyX86NoCallerSavedRegistersAttr *Attr = 3128 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3129 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3130 Diag(OldLocation, diag::note_previous_declaration); 3131 return true; 3132 } 3133 3134 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3135 RequiresAdjustment = true; 3136 } 3137 3138 if (RequiresAdjustment) { 3139 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3140 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3141 New->setType(QualType(AdjustedType, 0)); 3142 NewQType = Context.getCanonicalType(New->getType()); 3143 NewType = cast<FunctionType>(NewQType); 3144 } 3145 3146 // If this redeclaration makes the function inline, we may need to add it to 3147 // UndefinedButUsed. 3148 if (!Old->isInlined() && New->isInlined() && 3149 !New->hasAttr<GNUInlineAttr>() && 3150 !getLangOpts().GNUInline && 3151 Old->isUsed(false) && 3152 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3153 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3154 SourceLocation())); 3155 3156 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3157 // about it. 3158 if (New->hasAttr<GNUInlineAttr>() && 3159 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3160 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3161 } 3162 3163 // If pass_object_size params don't match up perfectly, this isn't a valid 3164 // redeclaration. 3165 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3166 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3167 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3168 << New->getDeclName(); 3169 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3170 return true; 3171 } 3172 3173 if (getLangOpts().CPlusPlus) { 3174 // C++1z [over.load]p2 3175 // Certain function declarations cannot be overloaded: 3176 // -- Function declarations that differ only in the return type, 3177 // the exception specification, or both cannot be overloaded. 3178 3179 // Check the exception specifications match. This may recompute the type of 3180 // both Old and New if it resolved exception specifications, so grab the 3181 // types again after this. Because this updates the type, we do this before 3182 // any of the other checks below, which may update the "de facto" NewQType 3183 // but do not necessarily update the type of New. 3184 if (CheckEquivalentExceptionSpec(Old, New)) 3185 return true; 3186 OldQType = Context.getCanonicalType(Old->getType()); 3187 NewQType = Context.getCanonicalType(New->getType()); 3188 3189 // Go back to the type source info to compare the declared return types, 3190 // per C++1y [dcl.type.auto]p13: 3191 // Redeclarations or specializations of a function or function template 3192 // with a declared return type that uses a placeholder type shall also 3193 // use that placeholder, not a deduced type. 3194 QualType OldDeclaredReturnType = 3195 (Old->getTypeSourceInfo() 3196 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3197 : OldType)->getReturnType(); 3198 QualType NewDeclaredReturnType = 3199 (New->getTypeSourceInfo() 3200 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3201 : NewType)->getReturnType(); 3202 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3203 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3204 New->isLocalExternDecl())) { 3205 QualType ResQT; 3206 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3207 OldDeclaredReturnType->isObjCObjectPointerType()) 3208 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3209 if (ResQT.isNull()) { 3210 if (New->isCXXClassMember() && New->isOutOfLine()) 3211 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3212 << New << New->getReturnTypeSourceRange(); 3213 else 3214 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3215 << New->getReturnTypeSourceRange(); 3216 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3217 << Old->getReturnTypeSourceRange(); 3218 return true; 3219 } 3220 else 3221 NewQType = ResQT; 3222 } 3223 3224 QualType OldReturnType = OldType->getReturnType(); 3225 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3226 if (OldReturnType != NewReturnType) { 3227 // If this function has a deduced return type and has already been 3228 // defined, copy the deduced value from the old declaration. 3229 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3230 if (OldAT && OldAT->isDeduced()) { 3231 New->setType( 3232 SubstAutoType(New->getType(), 3233 OldAT->isDependentType() ? Context.DependentTy 3234 : OldAT->getDeducedType())); 3235 NewQType = Context.getCanonicalType( 3236 SubstAutoType(NewQType, 3237 OldAT->isDependentType() ? Context.DependentTy 3238 : OldAT->getDeducedType())); 3239 } 3240 } 3241 3242 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3243 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3244 if (OldMethod && NewMethod) { 3245 // Preserve triviality. 3246 NewMethod->setTrivial(OldMethod->isTrivial()); 3247 3248 // MSVC allows explicit template specialization at class scope: 3249 // 2 CXXMethodDecls referring to the same function will be injected. 3250 // We don't want a redeclaration error. 3251 bool IsClassScopeExplicitSpecialization = 3252 OldMethod->isFunctionTemplateSpecialization() && 3253 NewMethod->isFunctionTemplateSpecialization(); 3254 bool isFriend = NewMethod->getFriendObjectKind(); 3255 3256 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3257 !IsClassScopeExplicitSpecialization) { 3258 // -- Member function declarations with the same name and the 3259 // same parameter types cannot be overloaded if any of them 3260 // is a static member function declaration. 3261 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3262 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3263 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3264 return true; 3265 } 3266 3267 // C++ [class.mem]p1: 3268 // [...] A member shall not be declared twice in the 3269 // member-specification, except that a nested class or member 3270 // class template can be declared and then later defined. 3271 if (!inTemplateInstantiation()) { 3272 unsigned NewDiag; 3273 if (isa<CXXConstructorDecl>(OldMethod)) 3274 NewDiag = diag::err_constructor_redeclared; 3275 else if (isa<CXXDestructorDecl>(NewMethod)) 3276 NewDiag = diag::err_destructor_redeclared; 3277 else if (isa<CXXConversionDecl>(NewMethod)) 3278 NewDiag = diag::err_conv_function_redeclared; 3279 else 3280 NewDiag = diag::err_member_redeclared; 3281 3282 Diag(New->getLocation(), NewDiag); 3283 } else { 3284 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3285 << New << New->getType(); 3286 } 3287 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3288 return true; 3289 3290 // Complain if this is an explicit declaration of a special 3291 // member that was initially declared implicitly. 3292 // 3293 // As an exception, it's okay to befriend such methods in order 3294 // to permit the implicit constructor/destructor/operator calls. 3295 } else if (OldMethod->isImplicit()) { 3296 if (isFriend) { 3297 NewMethod->setImplicit(); 3298 } else { 3299 Diag(NewMethod->getLocation(), 3300 diag::err_definition_of_implicitly_declared_member) 3301 << New << getSpecialMember(OldMethod); 3302 return true; 3303 } 3304 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3305 Diag(NewMethod->getLocation(), 3306 diag::err_definition_of_explicitly_defaulted_member) 3307 << getSpecialMember(OldMethod); 3308 return true; 3309 } 3310 } 3311 3312 // C++11 [dcl.attr.noreturn]p1: 3313 // The first declaration of a function shall specify the noreturn 3314 // attribute if any declaration of that function specifies the noreturn 3315 // attribute. 3316 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3317 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3318 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3319 Diag(Old->getFirstDecl()->getLocation(), 3320 diag::note_noreturn_missing_first_decl); 3321 } 3322 3323 // C++11 [dcl.attr.depend]p2: 3324 // The first declaration of a function shall specify the 3325 // carries_dependency attribute for its declarator-id if any declaration 3326 // of the function specifies the carries_dependency attribute. 3327 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3328 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3329 Diag(CDA->getLocation(), 3330 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3331 Diag(Old->getFirstDecl()->getLocation(), 3332 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3333 } 3334 3335 // (C++98 8.3.5p3): 3336 // All declarations for a function shall agree exactly in both the 3337 // return type and the parameter-type-list. 3338 // We also want to respect all the extended bits except noreturn. 3339 3340 // noreturn should now match unless the old type info didn't have it. 3341 QualType OldQTypeForComparison = OldQType; 3342 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3343 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3344 const FunctionType *OldTypeForComparison 3345 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3346 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3347 assert(OldQTypeForComparison.isCanonical()); 3348 } 3349 3350 if (haveIncompatibleLanguageLinkages(Old, New)) { 3351 // As a special case, retain the language linkage from previous 3352 // declarations of a friend function as an extension. 3353 // 3354 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3355 // and is useful because there's otherwise no way to specify language 3356 // linkage within class scope. 3357 // 3358 // Check cautiously as the friend object kind isn't yet complete. 3359 if (New->getFriendObjectKind() != Decl::FOK_None) { 3360 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3361 Diag(OldLocation, PrevDiag); 3362 } else { 3363 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3364 Diag(OldLocation, PrevDiag); 3365 return true; 3366 } 3367 } 3368 3369 if (OldQTypeForComparison == NewQType) 3370 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3371 3372 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3373 New->isLocalExternDecl()) { 3374 // It's OK if we couldn't merge types for a local function declaraton 3375 // if either the old or new type is dependent. We'll merge the types 3376 // when we instantiate the function. 3377 return false; 3378 } 3379 3380 // Fall through for conflicting redeclarations and redefinitions. 3381 } 3382 3383 // C: Function types need to be compatible, not identical. This handles 3384 // duplicate function decls like "void f(int); void f(enum X);" properly. 3385 if (!getLangOpts().CPlusPlus && 3386 Context.typesAreCompatible(OldQType, NewQType)) { 3387 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3388 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3389 const FunctionProtoType *OldProto = nullptr; 3390 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3391 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3392 // The old declaration provided a function prototype, but the 3393 // new declaration does not. Merge in the prototype. 3394 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3395 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3396 NewQType = 3397 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3398 OldProto->getExtProtoInfo()); 3399 New->setType(NewQType); 3400 New->setHasInheritedPrototype(); 3401 3402 // Synthesize parameters with the same types. 3403 SmallVector<ParmVarDecl*, 16> Params; 3404 for (const auto &ParamType : OldProto->param_types()) { 3405 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3406 SourceLocation(), nullptr, 3407 ParamType, /*TInfo=*/nullptr, 3408 SC_None, nullptr); 3409 Param->setScopeInfo(0, Params.size()); 3410 Param->setImplicit(); 3411 Params.push_back(Param); 3412 } 3413 3414 New->setParams(Params); 3415 } 3416 3417 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3418 } 3419 3420 // GNU C permits a K&R definition to follow a prototype declaration 3421 // if the declared types of the parameters in the K&R definition 3422 // match the types in the prototype declaration, even when the 3423 // promoted types of the parameters from the K&R definition differ 3424 // from the types in the prototype. GCC then keeps the types from 3425 // the prototype. 3426 // 3427 // If a variadic prototype is followed by a non-variadic K&R definition, 3428 // the K&R definition becomes variadic. This is sort of an edge case, but 3429 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3430 // C99 6.9.1p8. 3431 if (!getLangOpts().CPlusPlus && 3432 Old->hasPrototype() && !New->hasPrototype() && 3433 New->getType()->getAs<FunctionProtoType>() && 3434 Old->getNumParams() == New->getNumParams()) { 3435 SmallVector<QualType, 16> ArgTypes; 3436 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3437 const FunctionProtoType *OldProto 3438 = Old->getType()->getAs<FunctionProtoType>(); 3439 const FunctionProtoType *NewProto 3440 = New->getType()->getAs<FunctionProtoType>(); 3441 3442 // Determine whether this is the GNU C extension. 3443 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3444 NewProto->getReturnType()); 3445 bool LooseCompatible = !MergedReturn.isNull(); 3446 for (unsigned Idx = 0, End = Old->getNumParams(); 3447 LooseCompatible && Idx != End; ++Idx) { 3448 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3449 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3450 if (Context.typesAreCompatible(OldParm->getType(), 3451 NewProto->getParamType(Idx))) { 3452 ArgTypes.push_back(NewParm->getType()); 3453 } else if (Context.typesAreCompatible(OldParm->getType(), 3454 NewParm->getType(), 3455 /*CompareUnqualified=*/true)) { 3456 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3457 NewProto->getParamType(Idx) }; 3458 Warnings.push_back(Warn); 3459 ArgTypes.push_back(NewParm->getType()); 3460 } else 3461 LooseCompatible = false; 3462 } 3463 3464 if (LooseCompatible) { 3465 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3466 Diag(Warnings[Warn].NewParm->getLocation(), 3467 diag::ext_param_promoted_not_compatible_with_prototype) 3468 << Warnings[Warn].PromotedType 3469 << Warnings[Warn].OldParm->getType(); 3470 if (Warnings[Warn].OldParm->getLocation().isValid()) 3471 Diag(Warnings[Warn].OldParm->getLocation(), 3472 diag::note_previous_declaration); 3473 } 3474 3475 if (MergeTypeWithOld) 3476 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3477 OldProto->getExtProtoInfo())); 3478 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3479 } 3480 3481 // Fall through to diagnose conflicting types. 3482 } 3483 3484 // A function that has already been declared has been redeclared or 3485 // defined with a different type; show an appropriate diagnostic. 3486 3487 // If the previous declaration was an implicitly-generated builtin 3488 // declaration, then at the very least we should use a specialized note. 3489 unsigned BuiltinID; 3490 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3491 // If it's actually a library-defined builtin function like 'malloc' 3492 // or 'printf', just warn about the incompatible redeclaration. 3493 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3494 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3495 Diag(OldLocation, diag::note_previous_builtin_declaration) 3496 << Old << Old->getType(); 3497 3498 // If this is a global redeclaration, just forget hereafter 3499 // about the "builtin-ness" of the function. 3500 // 3501 // Doing this for local extern declarations is problematic. If 3502 // the builtin declaration remains visible, a second invalid 3503 // local declaration will produce a hard error; if it doesn't 3504 // remain visible, a single bogus local redeclaration (which is 3505 // actually only a warning) could break all the downstream code. 3506 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3507 New->getIdentifier()->revertBuiltin(); 3508 3509 return false; 3510 } 3511 3512 PrevDiag = diag::note_previous_builtin_declaration; 3513 } 3514 3515 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3516 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3517 return true; 3518 } 3519 3520 /// \brief Completes the merge of two function declarations that are 3521 /// known to be compatible. 3522 /// 3523 /// This routine handles the merging of attributes and other 3524 /// properties of function declarations from the old declaration to 3525 /// the new declaration, once we know that New is in fact a 3526 /// redeclaration of Old. 3527 /// 3528 /// \returns false 3529 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3530 Scope *S, bool MergeTypeWithOld) { 3531 // Merge the attributes 3532 mergeDeclAttributes(New, Old); 3533 3534 // Merge "pure" flag. 3535 if (Old->isPure()) 3536 New->setPure(); 3537 3538 // Merge "used" flag. 3539 if (Old->getMostRecentDecl()->isUsed(false)) 3540 New->setIsUsed(); 3541 3542 // Merge attributes from the parameters. These can mismatch with K&R 3543 // declarations. 3544 if (New->getNumParams() == Old->getNumParams()) 3545 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3546 ParmVarDecl *NewParam = New->getParamDecl(i); 3547 ParmVarDecl *OldParam = Old->getParamDecl(i); 3548 mergeParamDeclAttributes(NewParam, OldParam, *this); 3549 mergeParamDeclTypes(NewParam, OldParam, *this); 3550 } 3551 3552 if (getLangOpts().CPlusPlus) 3553 return MergeCXXFunctionDecl(New, Old, S); 3554 3555 // Merge the function types so the we get the composite types for the return 3556 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3557 // was visible. 3558 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3559 if (!Merged.isNull() && MergeTypeWithOld) 3560 New->setType(Merged); 3561 3562 return false; 3563 } 3564 3565 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3566 ObjCMethodDecl *oldMethod) { 3567 // Merge the attributes, including deprecated/unavailable 3568 AvailabilityMergeKind MergeKind = 3569 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3570 ? AMK_ProtocolImplementation 3571 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3572 : AMK_Override; 3573 3574 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3575 3576 // Merge attributes from the parameters. 3577 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3578 oe = oldMethod->param_end(); 3579 for (ObjCMethodDecl::param_iterator 3580 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3581 ni != ne && oi != oe; ++ni, ++oi) 3582 mergeParamDeclAttributes(*ni, *oi, *this); 3583 } 3584 3585 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3586 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3587 3588 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3589 ? diag::err_redefinition_different_type 3590 : diag::err_redeclaration_different_type) 3591 << New->getDeclName() << New->getType() << Old->getType(); 3592 3593 diag::kind PrevDiag; 3594 SourceLocation OldLocation; 3595 std::tie(PrevDiag, OldLocation) 3596 = getNoteDiagForInvalidRedeclaration(Old, New); 3597 S.Diag(OldLocation, PrevDiag); 3598 New->setInvalidDecl(); 3599 } 3600 3601 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3602 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3603 /// emitting diagnostics as appropriate. 3604 /// 3605 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3606 /// to here in AddInitializerToDecl. We can't check them before the initializer 3607 /// is attached. 3608 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3609 bool MergeTypeWithOld) { 3610 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3611 return; 3612 3613 QualType MergedT; 3614 if (getLangOpts().CPlusPlus) { 3615 if (New->getType()->isUndeducedType()) { 3616 // We don't know what the new type is until the initializer is attached. 3617 return; 3618 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3619 // These could still be something that needs exception specs checked. 3620 return MergeVarDeclExceptionSpecs(New, Old); 3621 } 3622 // C++ [basic.link]p10: 3623 // [...] the types specified by all declarations referring to a given 3624 // object or function shall be identical, except that declarations for an 3625 // array object can specify array types that differ by the presence or 3626 // absence of a major array bound (8.3.4). 3627 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3628 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3629 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3630 3631 // We are merging a variable declaration New into Old. If it has an array 3632 // bound, and that bound differs from Old's bound, we should diagnose the 3633 // mismatch. 3634 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3635 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3636 PrevVD = PrevVD->getPreviousDecl()) { 3637 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3638 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3639 continue; 3640 3641 if (!Context.hasSameType(NewArray, PrevVDTy)) 3642 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3643 } 3644 } 3645 3646 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3647 if (Context.hasSameType(OldArray->getElementType(), 3648 NewArray->getElementType())) 3649 MergedT = New->getType(); 3650 } 3651 // FIXME: Check visibility. New is hidden but has a complete type. If New 3652 // has no array bound, it should not inherit one from Old, if Old is not 3653 // visible. 3654 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3655 if (Context.hasSameType(OldArray->getElementType(), 3656 NewArray->getElementType())) 3657 MergedT = Old->getType(); 3658 } 3659 } 3660 else if (New->getType()->isObjCObjectPointerType() && 3661 Old->getType()->isObjCObjectPointerType()) { 3662 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3663 Old->getType()); 3664 } 3665 } else { 3666 // C 6.2.7p2: 3667 // All declarations that refer to the same object or function shall have 3668 // compatible type. 3669 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3670 } 3671 if (MergedT.isNull()) { 3672 // It's OK if we couldn't merge types if either type is dependent, for a 3673 // block-scope variable. In other cases (static data members of class 3674 // templates, variable templates, ...), we require the types to be 3675 // equivalent. 3676 // FIXME: The C++ standard doesn't say anything about this. 3677 if ((New->getType()->isDependentType() || 3678 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3679 // If the old type was dependent, we can't merge with it, so the new type 3680 // becomes dependent for now. We'll reproduce the original type when we 3681 // instantiate the TypeSourceInfo for the variable. 3682 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3683 New->setType(Context.DependentTy); 3684 return; 3685 } 3686 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3687 } 3688 3689 // Don't actually update the type on the new declaration if the old 3690 // declaration was an extern declaration in a different scope. 3691 if (MergeTypeWithOld) 3692 New->setType(MergedT); 3693 } 3694 3695 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3696 LookupResult &Previous) { 3697 // C11 6.2.7p4: 3698 // For an identifier with internal or external linkage declared 3699 // in a scope in which a prior declaration of that identifier is 3700 // visible, if the prior declaration specifies internal or 3701 // external linkage, the type of the identifier at the later 3702 // declaration becomes the composite type. 3703 // 3704 // If the variable isn't visible, we do not merge with its type. 3705 if (Previous.isShadowed()) 3706 return false; 3707 3708 if (S.getLangOpts().CPlusPlus) { 3709 // C++11 [dcl.array]p3: 3710 // If there is a preceding declaration of the entity in the same 3711 // scope in which the bound was specified, an omitted array bound 3712 // is taken to be the same as in that earlier declaration. 3713 return NewVD->isPreviousDeclInSameBlockScope() || 3714 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3715 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3716 } else { 3717 // If the old declaration was function-local, don't merge with its 3718 // type unless we're in the same function. 3719 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3720 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3721 } 3722 } 3723 3724 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3725 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3726 /// situation, merging decls or emitting diagnostics as appropriate. 3727 /// 3728 /// Tentative definition rules (C99 6.9.2p2) are checked by 3729 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3730 /// definitions here, since the initializer hasn't been attached. 3731 /// 3732 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3733 // If the new decl is already invalid, don't do any other checking. 3734 if (New->isInvalidDecl()) 3735 return; 3736 3737 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3738 return; 3739 3740 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3741 3742 // Verify the old decl was also a variable or variable template. 3743 VarDecl *Old = nullptr; 3744 VarTemplateDecl *OldTemplate = nullptr; 3745 if (Previous.isSingleResult()) { 3746 if (NewTemplate) { 3747 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3748 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3749 3750 if (auto *Shadow = 3751 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3752 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3753 return New->setInvalidDecl(); 3754 } else { 3755 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3756 3757 if (auto *Shadow = 3758 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3759 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3760 return New->setInvalidDecl(); 3761 } 3762 } 3763 if (!Old) { 3764 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3765 << New->getDeclName(); 3766 notePreviousDefinition(Previous.getRepresentativeDecl(), 3767 New->getLocation()); 3768 return New->setInvalidDecl(); 3769 } 3770 3771 // Ensure the template parameters are compatible. 3772 if (NewTemplate && 3773 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3774 OldTemplate->getTemplateParameters(), 3775 /*Complain=*/true, TPL_TemplateMatch)) 3776 return New->setInvalidDecl(); 3777 3778 // C++ [class.mem]p1: 3779 // A member shall not be declared twice in the member-specification [...] 3780 // 3781 // Here, we need only consider static data members. 3782 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3783 Diag(New->getLocation(), diag::err_duplicate_member) 3784 << New->getIdentifier(); 3785 Diag(Old->getLocation(), diag::note_previous_declaration); 3786 New->setInvalidDecl(); 3787 } 3788 3789 mergeDeclAttributes(New, Old); 3790 // Warn if an already-declared variable is made a weak_import in a subsequent 3791 // declaration 3792 if (New->hasAttr<WeakImportAttr>() && 3793 Old->getStorageClass() == SC_None && 3794 !Old->hasAttr<WeakImportAttr>()) { 3795 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3796 notePreviousDefinition(Old, New->getLocation()); 3797 // Remove weak_import attribute on new declaration. 3798 New->dropAttr<WeakImportAttr>(); 3799 } 3800 3801 if (New->hasAttr<InternalLinkageAttr>() && 3802 !Old->hasAttr<InternalLinkageAttr>()) { 3803 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3804 << New->getDeclName(); 3805 notePreviousDefinition(Old, New->getLocation()); 3806 New->dropAttr<InternalLinkageAttr>(); 3807 } 3808 3809 // Merge the types. 3810 VarDecl *MostRecent = Old->getMostRecentDecl(); 3811 if (MostRecent != Old) { 3812 MergeVarDeclTypes(New, MostRecent, 3813 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3814 if (New->isInvalidDecl()) 3815 return; 3816 } 3817 3818 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3819 if (New->isInvalidDecl()) 3820 return; 3821 3822 diag::kind PrevDiag; 3823 SourceLocation OldLocation; 3824 std::tie(PrevDiag, OldLocation) = 3825 getNoteDiagForInvalidRedeclaration(Old, New); 3826 3827 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3828 if (New->getStorageClass() == SC_Static && 3829 !New->isStaticDataMember() && 3830 Old->hasExternalFormalLinkage()) { 3831 if (getLangOpts().MicrosoftExt) { 3832 Diag(New->getLocation(), diag::ext_static_non_static) 3833 << New->getDeclName(); 3834 Diag(OldLocation, PrevDiag); 3835 } else { 3836 Diag(New->getLocation(), diag::err_static_non_static) 3837 << New->getDeclName(); 3838 Diag(OldLocation, PrevDiag); 3839 return New->setInvalidDecl(); 3840 } 3841 } 3842 // C99 6.2.2p4: 3843 // For an identifier declared with the storage-class specifier 3844 // extern in a scope in which a prior declaration of that 3845 // identifier is visible,23) if the prior declaration specifies 3846 // internal or external linkage, the linkage of the identifier at 3847 // the later declaration is the same as the linkage specified at 3848 // the prior declaration. If no prior declaration is visible, or 3849 // if the prior declaration specifies no linkage, then the 3850 // identifier has external linkage. 3851 if (New->hasExternalStorage() && Old->hasLinkage()) 3852 /* Okay */; 3853 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3854 !New->isStaticDataMember() && 3855 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3856 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3857 Diag(OldLocation, PrevDiag); 3858 return New->setInvalidDecl(); 3859 } 3860 3861 // Check if extern is followed by non-extern and vice-versa. 3862 if (New->hasExternalStorage() && 3863 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3864 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3865 Diag(OldLocation, PrevDiag); 3866 return New->setInvalidDecl(); 3867 } 3868 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3869 !New->hasExternalStorage()) { 3870 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3871 Diag(OldLocation, PrevDiag); 3872 return New->setInvalidDecl(); 3873 } 3874 3875 if (CheckRedeclarationModuleOwnership(New, Old)) 3876 return; 3877 3878 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3879 3880 // FIXME: The test for external storage here seems wrong? We still 3881 // need to check for mismatches. 3882 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3883 // Don't complain about out-of-line definitions of static members. 3884 !(Old->getLexicalDeclContext()->isRecord() && 3885 !New->getLexicalDeclContext()->isRecord())) { 3886 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3887 Diag(OldLocation, PrevDiag); 3888 return New->setInvalidDecl(); 3889 } 3890 3891 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3892 if (VarDecl *Def = Old->getDefinition()) { 3893 // C++1z [dcl.fcn.spec]p4: 3894 // If the definition of a variable appears in a translation unit before 3895 // its first declaration as inline, the program is ill-formed. 3896 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3897 Diag(Def->getLocation(), diag::note_previous_definition); 3898 } 3899 } 3900 3901 // If this redeclaration makes the variable inline, we may need to add it to 3902 // UndefinedButUsed. 3903 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3904 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3905 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3906 SourceLocation())); 3907 3908 if (New->getTLSKind() != Old->getTLSKind()) { 3909 if (!Old->getTLSKind()) { 3910 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3911 Diag(OldLocation, PrevDiag); 3912 } else if (!New->getTLSKind()) { 3913 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3914 Diag(OldLocation, PrevDiag); 3915 } else { 3916 // Do not allow redeclaration to change the variable between requiring 3917 // static and dynamic initialization. 3918 // FIXME: GCC allows this, but uses the TLS keyword on the first 3919 // declaration to determine the kind. Do we need to be compatible here? 3920 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3921 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3922 Diag(OldLocation, PrevDiag); 3923 } 3924 } 3925 3926 // C++ doesn't have tentative definitions, so go right ahead and check here. 3927 if (getLangOpts().CPlusPlus && 3928 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3929 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3930 Old->getCanonicalDecl()->isConstexpr()) { 3931 // This definition won't be a definition any more once it's been merged. 3932 Diag(New->getLocation(), 3933 diag::warn_deprecated_redundant_constexpr_static_def); 3934 } else if (VarDecl *Def = Old->getDefinition()) { 3935 if (checkVarDeclRedefinition(Def, New)) 3936 return; 3937 } 3938 } 3939 3940 if (haveIncompatibleLanguageLinkages(Old, New)) { 3941 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3942 Diag(OldLocation, PrevDiag); 3943 New->setInvalidDecl(); 3944 return; 3945 } 3946 3947 // Merge "used" flag. 3948 if (Old->getMostRecentDecl()->isUsed(false)) 3949 New->setIsUsed(); 3950 3951 // Keep a chain of previous declarations. 3952 New->setPreviousDecl(Old); 3953 if (NewTemplate) 3954 NewTemplate->setPreviousDecl(OldTemplate); 3955 3956 // Inherit access appropriately. 3957 New->setAccess(Old->getAccess()); 3958 if (NewTemplate) 3959 NewTemplate->setAccess(New->getAccess()); 3960 3961 if (Old->isInline()) 3962 New->setImplicitlyInline(); 3963 } 3964 3965 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 3966 SourceManager &SrcMgr = getSourceManager(); 3967 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 3968 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 3969 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 3970 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 3971 auto &HSI = PP.getHeaderSearchInfo(); 3972 StringRef HdrFilename = 3973 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 3974 3975 auto noteFromModuleOrInclude = [&](Module *Mod, 3976 SourceLocation IncLoc) -> bool { 3977 // Redefinition errors with modules are common with non modular mapped 3978 // headers, example: a non-modular header H in module A that also gets 3979 // included directly in a TU. Pointing twice to the same header/definition 3980 // is confusing, try to get better diagnostics when modules is on. 3981 if (IncLoc.isValid()) { 3982 if (Mod) { 3983 Diag(IncLoc, diag::note_redefinition_modules_same_file) 3984 << HdrFilename.str() << Mod->getFullModuleName(); 3985 if (!Mod->DefinitionLoc.isInvalid()) 3986 Diag(Mod->DefinitionLoc, diag::note_defined_here) 3987 << Mod->getFullModuleName(); 3988 } else { 3989 Diag(IncLoc, diag::note_redefinition_include_same_file) 3990 << HdrFilename.str(); 3991 } 3992 return true; 3993 } 3994 3995 return false; 3996 }; 3997 3998 // Is it the same file and same offset? Provide more information on why 3999 // this leads to a redefinition error. 4000 bool EmittedDiag = false; 4001 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4002 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4003 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4004 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4005 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4006 4007 // If the header has no guards, emit a note suggesting one. 4008 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4009 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4010 4011 if (EmittedDiag) 4012 return; 4013 } 4014 4015 // Redefinition coming from different files or couldn't do better above. 4016 Diag(Old->getLocation(), diag::note_previous_definition); 4017 } 4018 4019 /// We've just determined that \p Old and \p New both appear to be definitions 4020 /// of the same variable. Either diagnose or fix the problem. 4021 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4022 if (!hasVisibleDefinition(Old) && 4023 (New->getFormalLinkage() == InternalLinkage || 4024 New->isInline() || 4025 New->getDescribedVarTemplate() || 4026 New->getNumTemplateParameterLists() || 4027 New->getDeclContext()->isDependentContext())) { 4028 // The previous definition is hidden, and multiple definitions are 4029 // permitted (in separate TUs). Demote this to a declaration. 4030 New->demoteThisDefinitionToDeclaration(); 4031 4032 // Make the canonical definition visible. 4033 if (auto *OldTD = Old->getDescribedVarTemplate()) 4034 makeMergedDefinitionVisible(OldTD); 4035 makeMergedDefinitionVisible(Old); 4036 return false; 4037 } else { 4038 Diag(New->getLocation(), diag::err_redefinition) << New; 4039 notePreviousDefinition(Old, New->getLocation()); 4040 New->setInvalidDecl(); 4041 return true; 4042 } 4043 } 4044 4045 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4046 /// no declarator (e.g. "struct foo;") is parsed. 4047 Decl * 4048 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4049 RecordDecl *&AnonRecord) { 4050 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4051 AnonRecord); 4052 } 4053 4054 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4055 // disambiguate entities defined in different scopes. 4056 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4057 // compatibility. 4058 // We will pick our mangling number depending on which version of MSVC is being 4059 // targeted. 4060 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4061 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4062 ? S->getMSCurManglingNumber() 4063 : S->getMSLastManglingNumber(); 4064 } 4065 4066 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4067 if (!Context.getLangOpts().CPlusPlus) 4068 return; 4069 4070 if (isa<CXXRecordDecl>(Tag->getParent())) { 4071 // If this tag is the direct child of a class, number it if 4072 // it is anonymous. 4073 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4074 return; 4075 MangleNumberingContext &MCtx = 4076 Context.getManglingNumberContext(Tag->getParent()); 4077 Context.setManglingNumber( 4078 Tag, MCtx.getManglingNumber( 4079 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4080 return; 4081 } 4082 4083 // If this tag isn't a direct child of a class, number it if it is local. 4084 Decl *ManglingContextDecl; 4085 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4086 Tag->getDeclContext(), ManglingContextDecl)) { 4087 Context.setManglingNumber( 4088 Tag, MCtx->getManglingNumber( 4089 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4090 } 4091 } 4092 4093 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4094 TypedefNameDecl *NewTD) { 4095 if (TagFromDeclSpec->isInvalidDecl()) 4096 return; 4097 4098 // Do nothing if the tag already has a name for linkage purposes. 4099 if (TagFromDeclSpec->hasNameForLinkage()) 4100 return; 4101 4102 // A well-formed anonymous tag must always be a TUK_Definition. 4103 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4104 4105 // The type must match the tag exactly; no qualifiers allowed. 4106 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4107 Context.getTagDeclType(TagFromDeclSpec))) { 4108 if (getLangOpts().CPlusPlus) 4109 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4110 return; 4111 } 4112 4113 // If we've already computed linkage for the anonymous tag, then 4114 // adding a typedef name for the anonymous decl can change that 4115 // linkage, which might be a serious problem. Diagnose this as 4116 // unsupported and ignore the typedef name. TODO: we should 4117 // pursue this as a language defect and establish a formal rule 4118 // for how to handle it. 4119 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4120 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4121 4122 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4123 tagLoc = getLocForEndOfToken(tagLoc); 4124 4125 llvm::SmallString<40> textToInsert; 4126 textToInsert += ' '; 4127 textToInsert += NewTD->getIdentifier()->getName(); 4128 Diag(tagLoc, diag::note_typedef_changes_linkage) 4129 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4130 return; 4131 } 4132 4133 // Otherwise, set this is the anon-decl typedef for the tag. 4134 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4135 } 4136 4137 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4138 switch (T) { 4139 case DeclSpec::TST_class: 4140 return 0; 4141 case DeclSpec::TST_struct: 4142 return 1; 4143 case DeclSpec::TST_interface: 4144 return 2; 4145 case DeclSpec::TST_union: 4146 return 3; 4147 case DeclSpec::TST_enum: 4148 return 4; 4149 default: 4150 llvm_unreachable("unexpected type specifier"); 4151 } 4152 } 4153 4154 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4155 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4156 /// parameters to cope with template friend declarations. 4157 Decl * 4158 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4159 MultiTemplateParamsArg TemplateParams, 4160 bool IsExplicitInstantiation, 4161 RecordDecl *&AnonRecord) { 4162 Decl *TagD = nullptr; 4163 TagDecl *Tag = nullptr; 4164 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4165 DS.getTypeSpecType() == DeclSpec::TST_struct || 4166 DS.getTypeSpecType() == DeclSpec::TST_interface || 4167 DS.getTypeSpecType() == DeclSpec::TST_union || 4168 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4169 TagD = DS.getRepAsDecl(); 4170 4171 if (!TagD) // We probably had an error 4172 return nullptr; 4173 4174 // Note that the above type specs guarantee that the 4175 // type rep is a Decl, whereas in many of the others 4176 // it's a Type. 4177 if (isa<TagDecl>(TagD)) 4178 Tag = cast<TagDecl>(TagD); 4179 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4180 Tag = CTD->getTemplatedDecl(); 4181 } 4182 4183 if (Tag) { 4184 handleTagNumbering(Tag, S); 4185 Tag->setFreeStanding(); 4186 if (Tag->isInvalidDecl()) 4187 return Tag; 4188 } 4189 4190 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4191 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4192 // or incomplete types shall not be restrict-qualified." 4193 if (TypeQuals & DeclSpec::TQ_restrict) 4194 Diag(DS.getRestrictSpecLoc(), 4195 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4196 << DS.getSourceRange(); 4197 } 4198 4199 if (DS.isInlineSpecified()) 4200 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4201 << getLangOpts().CPlusPlus1z; 4202 4203 if (DS.isConstexprSpecified()) { 4204 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4205 // and definitions of functions and variables. 4206 if (Tag) 4207 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4208 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4209 else 4210 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4211 // Don't emit warnings after this error. 4212 return TagD; 4213 } 4214 4215 if (DS.isConceptSpecified()) { 4216 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 4217 // either a function concept and its definition or a variable concept and 4218 // its initializer. 4219 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 4220 return TagD; 4221 } 4222 4223 DiagnoseFunctionSpecifiers(DS); 4224 4225 if (DS.isFriendSpecified()) { 4226 // If we're dealing with a decl but not a TagDecl, assume that 4227 // whatever routines created it handled the friendship aspect. 4228 if (TagD && !Tag) 4229 return nullptr; 4230 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4231 } 4232 4233 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4234 bool IsExplicitSpecialization = 4235 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4236 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4237 !IsExplicitInstantiation && !IsExplicitSpecialization && 4238 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4239 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4240 // nested-name-specifier unless it is an explicit instantiation 4241 // or an explicit specialization. 4242 // 4243 // FIXME: We allow class template partial specializations here too, per the 4244 // obvious intent of DR1819. 4245 // 4246 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4247 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4248 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4249 return nullptr; 4250 } 4251 4252 // Track whether this decl-specifier declares anything. 4253 bool DeclaresAnything = true; 4254 4255 // Handle anonymous struct definitions. 4256 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4257 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4258 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4259 if (getLangOpts().CPlusPlus || 4260 Record->getDeclContext()->isRecord()) { 4261 // If CurContext is a DeclContext that can contain statements, 4262 // RecursiveASTVisitor won't visit the decls that 4263 // BuildAnonymousStructOrUnion() will put into CurContext. 4264 // Also store them here so that they can be part of the 4265 // DeclStmt that gets created in this case. 4266 // FIXME: Also return the IndirectFieldDecls created by 4267 // BuildAnonymousStructOr union, for the same reason? 4268 if (CurContext->isFunctionOrMethod()) 4269 AnonRecord = Record; 4270 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4271 Context.getPrintingPolicy()); 4272 } 4273 4274 DeclaresAnything = false; 4275 } 4276 } 4277 4278 // C11 6.7.2.1p2: 4279 // A struct-declaration that does not declare an anonymous structure or 4280 // anonymous union shall contain a struct-declarator-list. 4281 // 4282 // This rule also existed in C89 and C99; the grammar for struct-declaration 4283 // did not permit a struct-declaration without a struct-declarator-list. 4284 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4285 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4286 // Check for Microsoft C extension: anonymous struct/union member. 4287 // Handle 2 kinds of anonymous struct/union: 4288 // struct STRUCT; 4289 // union UNION; 4290 // and 4291 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4292 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4293 if ((Tag && Tag->getDeclName()) || 4294 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4295 RecordDecl *Record = nullptr; 4296 if (Tag) 4297 Record = dyn_cast<RecordDecl>(Tag); 4298 else if (const RecordType *RT = 4299 DS.getRepAsType().get()->getAsStructureType()) 4300 Record = RT->getDecl(); 4301 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4302 Record = UT->getDecl(); 4303 4304 if (Record && getLangOpts().MicrosoftExt) { 4305 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4306 << Record->isUnion() << DS.getSourceRange(); 4307 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4308 } 4309 4310 DeclaresAnything = false; 4311 } 4312 } 4313 4314 // Skip all the checks below if we have a type error. 4315 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4316 (TagD && TagD->isInvalidDecl())) 4317 return TagD; 4318 4319 if (getLangOpts().CPlusPlus && 4320 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4321 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4322 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4323 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4324 DeclaresAnything = false; 4325 4326 if (!DS.isMissingDeclaratorOk()) { 4327 // Customize diagnostic for a typedef missing a name. 4328 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4329 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4330 << DS.getSourceRange(); 4331 else 4332 DeclaresAnything = false; 4333 } 4334 4335 if (DS.isModulePrivateSpecified() && 4336 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4337 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4338 << Tag->getTagKind() 4339 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4340 4341 ActOnDocumentableDecl(TagD); 4342 4343 // C 6.7/2: 4344 // A declaration [...] shall declare at least a declarator [...], a tag, 4345 // or the members of an enumeration. 4346 // C++ [dcl.dcl]p3: 4347 // [If there are no declarators], and except for the declaration of an 4348 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4349 // names into the program, or shall redeclare a name introduced by a 4350 // previous declaration. 4351 if (!DeclaresAnything) { 4352 // In C, we allow this as a (popular) extension / bug. Don't bother 4353 // producing further diagnostics for redundant qualifiers after this. 4354 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4355 return TagD; 4356 } 4357 4358 // C++ [dcl.stc]p1: 4359 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4360 // init-declarator-list of the declaration shall not be empty. 4361 // C++ [dcl.fct.spec]p1: 4362 // If a cv-qualifier appears in a decl-specifier-seq, the 4363 // init-declarator-list of the declaration shall not be empty. 4364 // 4365 // Spurious qualifiers here appear to be valid in C. 4366 unsigned DiagID = diag::warn_standalone_specifier; 4367 if (getLangOpts().CPlusPlus) 4368 DiagID = diag::ext_standalone_specifier; 4369 4370 // Note that a linkage-specification sets a storage class, but 4371 // 'extern "C" struct foo;' is actually valid and not theoretically 4372 // useless. 4373 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4374 if (SCS == DeclSpec::SCS_mutable) 4375 // Since mutable is not a viable storage class specifier in C, there is 4376 // no reason to treat it as an extension. Instead, diagnose as an error. 4377 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4378 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4379 Diag(DS.getStorageClassSpecLoc(), DiagID) 4380 << DeclSpec::getSpecifierName(SCS); 4381 } 4382 4383 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4384 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4385 << DeclSpec::getSpecifierName(TSCS); 4386 if (DS.getTypeQualifiers()) { 4387 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4388 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4389 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4390 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4391 // Restrict is covered above. 4392 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4393 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4394 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4395 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4396 } 4397 4398 // Warn about ignored type attributes, for example: 4399 // __attribute__((aligned)) struct A; 4400 // Attributes should be placed after tag to apply to type declaration. 4401 if (!DS.getAttributes().empty()) { 4402 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4403 if (TypeSpecType == DeclSpec::TST_class || 4404 TypeSpecType == DeclSpec::TST_struct || 4405 TypeSpecType == DeclSpec::TST_interface || 4406 TypeSpecType == DeclSpec::TST_union || 4407 TypeSpecType == DeclSpec::TST_enum) { 4408 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4409 attrs = attrs->getNext()) 4410 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4411 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4412 } 4413 } 4414 4415 return TagD; 4416 } 4417 4418 /// We are trying to inject an anonymous member into the given scope; 4419 /// check if there's an existing declaration that can't be overloaded. 4420 /// 4421 /// \return true if this is a forbidden redeclaration 4422 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4423 Scope *S, 4424 DeclContext *Owner, 4425 DeclarationName Name, 4426 SourceLocation NameLoc, 4427 bool IsUnion) { 4428 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4429 Sema::ForVisibleRedeclaration); 4430 if (!SemaRef.LookupName(R, S)) return false; 4431 4432 // Pick a representative declaration. 4433 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4434 assert(PrevDecl && "Expected a non-null Decl"); 4435 4436 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4437 return false; 4438 4439 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4440 << IsUnion << Name; 4441 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4442 4443 return true; 4444 } 4445 4446 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4447 /// anonymous struct or union AnonRecord into the owning context Owner 4448 /// and scope S. This routine will be invoked just after we realize 4449 /// that an unnamed union or struct is actually an anonymous union or 4450 /// struct, e.g., 4451 /// 4452 /// @code 4453 /// union { 4454 /// int i; 4455 /// float f; 4456 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4457 /// // f into the surrounding scope.x 4458 /// @endcode 4459 /// 4460 /// This routine is recursive, injecting the names of nested anonymous 4461 /// structs/unions into the owning context and scope as well. 4462 static bool 4463 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4464 RecordDecl *AnonRecord, AccessSpecifier AS, 4465 SmallVectorImpl<NamedDecl *> &Chaining) { 4466 bool Invalid = false; 4467 4468 // Look every FieldDecl and IndirectFieldDecl with a name. 4469 for (auto *D : AnonRecord->decls()) { 4470 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4471 cast<NamedDecl>(D)->getDeclName()) { 4472 ValueDecl *VD = cast<ValueDecl>(D); 4473 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4474 VD->getLocation(), 4475 AnonRecord->isUnion())) { 4476 // C++ [class.union]p2: 4477 // The names of the members of an anonymous union shall be 4478 // distinct from the names of any other entity in the 4479 // scope in which the anonymous union is declared. 4480 Invalid = true; 4481 } else { 4482 // C++ [class.union]p2: 4483 // For the purpose of name lookup, after the anonymous union 4484 // definition, the members of the anonymous union are 4485 // considered to have been defined in the scope in which the 4486 // anonymous union is declared. 4487 unsigned OldChainingSize = Chaining.size(); 4488 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4489 Chaining.append(IF->chain_begin(), IF->chain_end()); 4490 else 4491 Chaining.push_back(VD); 4492 4493 assert(Chaining.size() >= 2); 4494 NamedDecl **NamedChain = 4495 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4496 for (unsigned i = 0; i < Chaining.size(); i++) 4497 NamedChain[i] = Chaining[i]; 4498 4499 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4500 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4501 VD->getType(), {NamedChain, Chaining.size()}); 4502 4503 for (const auto *Attr : VD->attrs()) 4504 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4505 4506 IndirectField->setAccess(AS); 4507 IndirectField->setImplicit(); 4508 SemaRef.PushOnScopeChains(IndirectField, S); 4509 4510 // That includes picking up the appropriate access specifier. 4511 if (AS != AS_none) IndirectField->setAccess(AS); 4512 4513 Chaining.resize(OldChainingSize); 4514 } 4515 } 4516 } 4517 4518 return Invalid; 4519 } 4520 4521 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4522 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4523 /// illegal input values are mapped to SC_None. 4524 static StorageClass 4525 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4526 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4527 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4528 "Parser allowed 'typedef' as storage class VarDecl."); 4529 switch (StorageClassSpec) { 4530 case DeclSpec::SCS_unspecified: return SC_None; 4531 case DeclSpec::SCS_extern: 4532 if (DS.isExternInLinkageSpec()) 4533 return SC_None; 4534 return SC_Extern; 4535 case DeclSpec::SCS_static: return SC_Static; 4536 case DeclSpec::SCS_auto: return SC_Auto; 4537 case DeclSpec::SCS_register: return SC_Register; 4538 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4539 // Illegal SCSs map to None: error reporting is up to the caller. 4540 case DeclSpec::SCS_mutable: // Fall through. 4541 case DeclSpec::SCS_typedef: return SC_None; 4542 } 4543 llvm_unreachable("unknown storage class specifier"); 4544 } 4545 4546 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4547 assert(Record->hasInClassInitializer()); 4548 4549 for (const auto *I : Record->decls()) { 4550 const auto *FD = dyn_cast<FieldDecl>(I); 4551 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4552 FD = IFD->getAnonField(); 4553 if (FD && FD->hasInClassInitializer()) 4554 return FD->getLocation(); 4555 } 4556 4557 llvm_unreachable("couldn't find in-class initializer"); 4558 } 4559 4560 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4561 SourceLocation DefaultInitLoc) { 4562 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4563 return; 4564 4565 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4566 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4567 } 4568 4569 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4570 CXXRecordDecl *AnonUnion) { 4571 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4572 return; 4573 4574 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4575 } 4576 4577 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4578 /// anonymous structure or union. Anonymous unions are a C++ feature 4579 /// (C++ [class.union]) and a C11 feature; anonymous structures 4580 /// are a C11 feature and GNU C++ extension. 4581 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4582 AccessSpecifier AS, 4583 RecordDecl *Record, 4584 const PrintingPolicy &Policy) { 4585 DeclContext *Owner = Record->getDeclContext(); 4586 4587 // Diagnose whether this anonymous struct/union is an extension. 4588 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4589 Diag(Record->getLocation(), diag::ext_anonymous_union); 4590 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4591 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4592 else if (!Record->isUnion() && !getLangOpts().C11) 4593 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4594 4595 // C and C++ require different kinds of checks for anonymous 4596 // structs/unions. 4597 bool Invalid = false; 4598 if (getLangOpts().CPlusPlus) { 4599 const char *PrevSpec = nullptr; 4600 unsigned DiagID; 4601 if (Record->isUnion()) { 4602 // C++ [class.union]p6: 4603 // Anonymous unions declared in a named namespace or in the 4604 // global namespace shall be declared static. 4605 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4606 (isa<TranslationUnitDecl>(Owner) || 4607 (isa<NamespaceDecl>(Owner) && 4608 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4609 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4610 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4611 4612 // Recover by adding 'static'. 4613 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4614 PrevSpec, DiagID, Policy); 4615 } 4616 // C++ [class.union]p6: 4617 // A storage class is not allowed in a declaration of an 4618 // anonymous union in a class scope. 4619 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4620 isa<RecordDecl>(Owner)) { 4621 Diag(DS.getStorageClassSpecLoc(), 4622 diag::err_anonymous_union_with_storage_spec) 4623 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4624 4625 // Recover by removing the storage specifier. 4626 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4627 SourceLocation(), 4628 PrevSpec, DiagID, Context.getPrintingPolicy()); 4629 } 4630 } 4631 4632 // Ignore const/volatile/restrict qualifiers. 4633 if (DS.getTypeQualifiers()) { 4634 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4635 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4636 << Record->isUnion() << "const" 4637 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4638 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4639 Diag(DS.getVolatileSpecLoc(), 4640 diag::ext_anonymous_struct_union_qualified) 4641 << Record->isUnion() << "volatile" 4642 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4643 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4644 Diag(DS.getRestrictSpecLoc(), 4645 diag::ext_anonymous_struct_union_qualified) 4646 << Record->isUnion() << "restrict" 4647 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4648 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4649 Diag(DS.getAtomicSpecLoc(), 4650 diag::ext_anonymous_struct_union_qualified) 4651 << Record->isUnion() << "_Atomic" 4652 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4653 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4654 Diag(DS.getUnalignedSpecLoc(), 4655 diag::ext_anonymous_struct_union_qualified) 4656 << Record->isUnion() << "__unaligned" 4657 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4658 4659 DS.ClearTypeQualifiers(); 4660 } 4661 4662 // C++ [class.union]p2: 4663 // The member-specification of an anonymous union shall only 4664 // define non-static data members. [Note: nested types and 4665 // functions cannot be declared within an anonymous union. ] 4666 for (auto *Mem : Record->decls()) { 4667 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4668 // C++ [class.union]p3: 4669 // An anonymous union shall not have private or protected 4670 // members (clause 11). 4671 assert(FD->getAccess() != AS_none); 4672 if (FD->getAccess() != AS_public) { 4673 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4674 << Record->isUnion() << (FD->getAccess() == AS_protected); 4675 Invalid = true; 4676 } 4677 4678 // C++ [class.union]p1 4679 // An object of a class with a non-trivial constructor, a non-trivial 4680 // copy constructor, a non-trivial destructor, or a non-trivial copy 4681 // assignment operator cannot be a member of a union, nor can an 4682 // array of such objects. 4683 if (CheckNontrivialField(FD)) 4684 Invalid = true; 4685 } else if (Mem->isImplicit()) { 4686 // Any implicit members are fine. 4687 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4688 // This is a type that showed up in an 4689 // elaborated-type-specifier inside the anonymous struct or 4690 // union, but which actually declares a type outside of the 4691 // anonymous struct or union. It's okay. 4692 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4693 if (!MemRecord->isAnonymousStructOrUnion() && 4694 MemRecord->getDeclName()) { 4695 // Visual C++ allows type definition in anonymous struct or union. 4696 if (getLangOpts().MicrosoftExt) 4697 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4698 << Record->isUnion(); 4699 else { 4700 // This is a nested type declaration. 4701 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4702 << Record->isUnion(); 4703 Invalid = true; 4704 } 4705 } else { 4706 // This is an anonymous type definition within another anonymous type. 4707 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4708 // not part of standard C++. 4709 Diag(MemRecord->getLocation(), 4710 diag::ext_anonymous_record_with_anonymous_type) 4711 << Record->isUnion(); 4712 } 4713 } else if (isa<AccessSpecDecl>(Mem)) { 4714 // Any access specifier is fine. 4715 } else if (isa<StaticAssertDecl>(Mem)) { 4716 // In C++1z, static_assert declarations are also fine. 4717 } else { 4718 // We have something that isn't a non-static data 4719 // member. Complain about it. 4720 unsigned DK = diag::err_anonymous_record_bad_member; 4721 if (isa<TypeDecl>(Mem)) 4722 DK = diag::err_anonymous_record_with_type; 4723 else if (isa<FunctionDecl>(Mem)) 4724 DK = diag::err_anonymous_record_with_function; 4725 else if (isa<VarDecl>(Mem)) 4726 DK = diag::err_anonymous_record_with_static; 4727 4728 // Visual C++ allows type definition in anonymous struct or union. 4729 if (getLangOpts().MicrosoftExt && 4730 DK == diag::err_anonymous_record_with_type) 4731 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4732 << Record->isUnion(); 4733 else { 4734 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4735 Invalid = true; 4736 } 4737 } 4738 } 4739 4740 // C++11 [class.union]p8 (DR1460): 4741 // At most one variant member of a union may have a 4742 // brace-or-equal-initializer. 4743 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4744 Owner->isRecord()) 4745 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4746 cast<CXXRecordDecl>(Record)); 4747 } 4748 4749 if (!Record->isUnion() && !Owner->isRecord()) { 4750 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4751 << getLangOpts().CPlusPlus; 4752 Invalid = true; 4753 } 4754 4755 // Mock up a declarator. 4756 Declarator Dc(DS, Declarator::MemberContext); 4757 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4758 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4759 4760 // Create a declaration for this anonymous struct/union. 4761 NamedDecl *Anon = nullptr; 4762 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4763 Anon = FieldDecl::Create(Context, OwningClass, 4764 DS.getLocStart(), 4765 Record->getLocation(), 4766 /*IdentifierInfo=*/nullptr, 4767 Context.getTypeDeclType(Record), 4768 TInfo, 4769 /*BitWidth=*/nullptr, /*Mutable=*/false, 4770 /*InitStyle=*/ICIS_NoInit); 4771 Anon->setAccess(AS); 4772 if (getLangOpts().CPlusPlus) 4773 FieldCollector->Add(cast<FieldDecl>(Anon)); 4774 } else { 4775 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4776 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4777 if (SCSpec == DeclSpec::SCS_mutable) { 4778 // mutable can only appear on non-static class members, so it's always 4779 // an error here 4780 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4781 Invalid = true; 4782 SC = SC_None; 4783 } 4784 4785 Anon = VarDecl::Create(Context, Owner, 4786 DS.getLocStart(), 4787 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4788 Context.getTypeDeclType(Record), 4789 TInfo, SC); 4790 4791 // Default-initialize the implicit variable. This initialization will be 4792 // trivial in almost all cases, except if a union member has an in-class 4793 // initializer: 4794 // union { int n = 0; }; 4795 ActOnUninitializedDecl(Anon); 4796 } 4797 Anon->setImplicit(); 4798 4799 // Mark this as an anonymous struct/union type. 4800 Record->setAnonymousStructOrUnion(true); 4801 4802 // Add the anonymous struct/union object to the current 4803 // context. We'll be referencing this object when we refer to one of 4804 // its members. 4805 Owner->addDecl(Anon); 4806 4807 // Inject the members of the anonymous struct/union into the owning 4808 // context and into the identifier resolver chain for name lookup 4809 // purposes. 4810 SmallVector<NamedDecl*, 2> Chain; 4811 Chain.push_back(Anon); 4812 4813 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4814 Invalid = true; 4815 4816 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4817 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4818 Decl *ManglingContextDecl; 4819 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4820 NewVD->getDeclContext(), ManglingContextDecl)) { 4821 Context.setManglingNumber( 4822 NewVD, MCtx->getManglingNumber( 4823 NewVD, getMSManglingNumber(getLangOpts(), S))); 4824 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4825 } 4826 } 4827 } 4828 4829 if (Invalid) 4830 Anon->setInvalidDecl(); 4831 4832 return Anon; 4833 } 4834 4835 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4836 /// Microsoft C anonymous structure. 4837 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4838 /// Example: 4839 /// 4840 /// struct A { int a; }; 4841 /// struct B { struct A; int b; }; 4842 /// 4843 /// void foo() { 4844 /// B var; 4845 /// var.a = 3; 4846 /// } 4847 /// 4848 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4849 RecordDecl *Record) { 4850 assert(Record && "expected a record!"); 4851 4852 // Mock up a declarator. 4853 Declarator Dc(DS, Declarator::TypeNameContext); 4854 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4855 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4856 4857 auto *ParentDecl = cast<RecordDecl>(CurContext); 4858 QualType RecTy = Context.getTypeDeclType(Record); 4859 4860 // Create a declaration for this anonymous struct. 4861 NamedDecl *Anon = FieldDecl::Create(Context, 4862 ParentDecl, 4863 DS.getLocStart(), 4864 DS.getLocStart(), 4865 /*IdentifierInfo=*/nullptr, 4866 RecTy, 4867 TInfo, 4868 /*BitWidth=*/nullptr, /*Mutable=*/false, 4869 /*InitStyle=*/ICIS_NoInit); 4870 Anon->setImplicit(); 4871 4872 // Add the anonymous struct object to the current context. 4873 CurContext->addDecl(Anon); 4874 4875 // Inject the members of the anonymous struct into the current 4876 // context and into the identifier resolver chain for name lookup 4877 // purposes. 4878 SmallVector<NamedDecl*, 2> Chain; 4879 Chain.push_back(Anon); 4880 4881 RecordDecl *RecordDef = Record->getDefinition(); 4882 if (RequireCompleteType(Anon->getLocation(), RecTy, 4883 diag::err_field_incomplete) || 4884 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4885 AS_none, Chain)) { 4886 Anon->setInvalidDecl(); 4887 ParentDecl->setInvalidDecl(); 4888 } 4889 4890 return Anon; 4891 } 4892 4893 /// GetNameForDeclarator - Determine the full declaration name for the 4894 /// given Declarator. 4895 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4896 return GetNameFromUnqualifiedId(D.getName()); 4897 } 4898 4899 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4900 DeclarationNameInfo 4901 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4902 DeclarationNameInfo NameInfo; 4903 NameInfo.setLoc(Name.StartLocation); 4904 4905 switch (Name.getKind()) { 4906 4907 case UnqualifiedId::IK_ImplicitSelfParam: 4908 case UnqualifiedId::IK_Identifier: 4909 NameInfo.setName(Name.Identifier); 4910 NameInfo.setLoc(Name.StartLocation); 4911 return NameInfo; 4912 4913 case UnqualifiedId::IK_DeductionGuideName: { 4914 // C++ [temp.deduct.guide]p3: 4915 // The simple-template-id shall name a class template specialization. 4916 // The template-name shall be the same identifier as the template-name 4917 // of the simple-template-id. 4918 // These together intend to imply that the template-name shall name a 4919 // class template. 4920 // FIXME: template<typename T> struct X {}; 4921 // template<typename T> using Y = X<T>; 4922 // Y(int) -> Y<int>; 4923 // satisfies these rules but does not name a class template. 4924 TemplateName TN = Name.TemplateName.get().get(); 4925 auto *Template = TN.getAsTemplateDecl(); 4926 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4927 Diag(Name.StartLocation, 4928 diag::err_deduction_guide_name_not_class_template) 4929 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4930 if (Template) 4931 Diag(Template->getLocation(), diag::note_template_decl_here); 4932 return DeclarationNameInfo(); 4933 } 4934 4935 NameInfo.setName( 4936 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4937 NameInfo.setLoc(Name.StartLocation); 4938 return NameInfo; 4939 } 4940 4941 case UnqualifiedId::IK_OperatorFunctionId: 4942 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4943 Name.OperatorFunctionId.Operator)); 4944 NameInfo.setLoc(Name.StartLocation); 4945 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4946 = Name.OperatorFunctionId.SymbolLocations[0]; 4947 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4948 = Name.EndLocation.getRawEncoding(); 4949 return NameInfo; 4950 4951 case UnqualifiedId::IK_LiteralOperatorId: 4952 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4953 Name.Identifier)); 4954 NameInfo.setLoc(Name.StartLocation); 4955 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4956 return NameInfo; 4957 4958 case UnqualifiedId::IK_ConversionFunctionId: { 4959 TypeSourceInfo *TInfo; 4960 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4961 if (Ty.isNull()) 4962 return DeclarationNameInfo(); 4963 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4964 Context.getCanonicalType(Ty))); 4965 NameInfo.setLoc(Name.StartLocation); 4966 NameInfo.setNamedTypeInfo(TInfo); 4967 return NameInfo; 4968 } 4969 4970 case UnqualifiedId::IK_ConstructorName: { 4971 TypeSourceInfo *TInfo; 4972 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4973 if (Ty.isNull()) 4974 return DeclarationNameInfo(); 4975 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4976 Context.getCanonicalType(Ty))); 4977 NameInfo.setLoc(Name.StartLocation); 4978 NameInfo.setNamedTypeInfo(TInfo); 4979 return NameInfo; 4980 } 4981 4982 case UnqualifiedId::IK_ConstructorTemplateId: { 4983 // In well-formed code, we can only have a constructor 4984 // template-id that refers to the current context, so go there 4985 // to find the actual type being constructed. 4986 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4987 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4988 return DeclarationNameInfo(); 4989 4990 // Determine the type of the class being constructed. 4991 QualType CurClassType = Context.getTypeDeclType(CurClass); 4992 4993 // FIXME: Check two things: that the template-id names the same type as 4994 // CurClassType, and that the template-id does not occur when the name 4995 // was qualified. 4996 4997 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4998 Context.getCanonicalType(CurClassType))); 4999 NameInfo.setLoc(Name.StartLocation); 5000 // FIXME: should we retrieve TypeSourceInfo? 5001 NameInfo.setNamedTypeInfo(nullptr); 5002 return NameInfo; 5003 } 5004 5005 case UnqualifiedId::IK_DestructorName: { 5006 TypeSourceInfo *TInfo; 5007 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5008 if (Ty.isNull()) 5009 return DeclarationNameInfo(); 5010 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5011 Context.getCanonicalType(Ty))); 5012 NameInfo.setLoc(Name.StartLocation); 5013 NameInfo.setNamedTypeInfo(TInfo); 5014 return NameInfo; 5015 } 5016 5017 case UnqualifiedId::IK_TemplateId: { 5018 TemplateName TName = Name.TemplateId->Template.get(); 5019 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5020 return Context.getNameForTemplate(TName, TNameLoc); 5021 } 5022 5023 } // switch (Name.getKind()) 5024 5025 llvm_unreachable("Unknown name kind"); 5026 } 5027 5028 static QualType getCoreType(QualType Ty) { 5029 do { 5030 if (Ty->isPointerType() || Ty->isReferenceType()) 5031 Ty = Ty->getPointeeType(); 5032 else if (Ty->isArrayType()) 5033 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5034 else 5035 return Ty.withoutLocalFastQualifiers(); 5036 } while (true); 5037 } 5038 5039 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5040 /// and Definition have "nearly" matching parameters. This heuristic is 5041 /// used to improve diagnostics in the case where an out-of-line function 5042 /// definition doesn't match any declaration within the class or namespace. 5043 /// Also sets Params to the list of indices to the parameters that differ 5044 /// between the declaration and the definition. If hasSimilarParameters 5045 /// returns true and Params is empty, then all of the parameters match. 5046 static bool hasSimilarParameters(ASTContext &Context, 5047 FunctionDecl *Declaration, 5048 FunctionDecl *Definition, 5049 SmallVectorImpl<unsigned> &Params) { 5050 Params.clear(); 5051 if (Declaration->param_size() != Definition->param_size()) 5052 return false; 5053 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5054 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5055 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5056 5057 // The parameter types are identical 5058 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5059 continue; 5060 5061 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5062 QualType DefParamBaseTy = getCoreType(DefParamTy); 5063 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5064 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5065 5066 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5067 (DeclTyName && DeclTyName == DefTyName)) 5068 Params.push_back(Idx); 5069 else // The two parameters aren't even close 5070 return false; 5071 } 5072 5073 return true; 5074 } 5075 5076 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5077 /// declarator needs to be rebuilt in the current instantiation. 5078 /// Any bits of declarator which appear before the name are valid for 5079 /// consideration here. That's specifically the type in the decl spec 5080 /// and the base type in any member-pointer chunks. 5081 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5082 DeclarationName Name) { 5083 // The types we specifically need to rebuild are: 5084 // - typenames, typeofs, and decltypes 5085 // - types which will become injected class names 5086 // Of course, we also need to rebuild any type referencing such a 5087 // type. It's safest to just say "dependent", but we call out a 5088 // few cases here. 5089 5090 DeclSpec &DS = D.getMutableDeclSpec(); 5091 switch (DS.getTypeSpecType()) { 5092 case DeclSpec::TST_typename: 5093 case DeclSpec::TST_typeofType: 5094 case DeclSpec::TST_underlyingType: 5095 case DeclSpec::TST_atomic: { 5096 // Grab the type from the parser. 5097 TypeSourceInfo *TSI = nullptr; 5098 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5099 if (T.isNull() || !T->isDependentType()) break; 5100 5101 // Make sure there's a type source info. This isn't really much 5102 // of a waste; most dependent types should have type source info 5103 // attached already. 5104 if (!TSI) 5105 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5106 5107 // Rebuild the type in the current instantiation. 5108 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5109 if (!TSI) return true; 5110 5111 // Store the new type back in the decl spec. 5112 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5113 DS.UpdateTypeRep(LocType); 5114 break; 5115 } 5116 5117 case DeclSpec::TST_decltype: 5118 case DeclSpec::TST_typeofExpr: { 5119 Expr *E = DS.getRepAsExpr(); 5120 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5121 if (Result.isInvalid()) return true; 5122 DS.UpdateExprRep(Result.get()); 5123 break; 5124 } 5125 5126 default: 5127 // Nothing to do for these decl specs. 5128 break; 5129 } 5130 5131 // It doesn't matter what order we do this in. 5132 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5133 DeclaratorChunk &Chunk = D.getTypeObject(I); 5134 5135 // The only type information in the declarator which can come 5136 // before the declaration name is the base type of a member 5137 // pointer. 5138 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5139 continue; 5140 5141 // Rebuild the scope specifier in-place. 5142 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5143 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5144 return true; 5145 } 5146 5147 return false; 5148 } 5149 5150 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5151 D.setFunctionDefinitionKind(FDK_Declaration); 5152 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5153 5154 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5155 Dcl && Dcl->getDeclContext()->isFileContext()) 5156 Dcl->setTopLevelDeclInObjCContainer(); 5157 5158 if (getLangOpts().OpenCL) 5159 setCurrentOpenCLExtensionForDecl(Dcl); 5160 5161 return Dcl; 5162 } 5163 5164 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5165 /// If T is the name of a class, then each of the following shall have a 5166 /// name different from T: 5167 /// - every static data member of class T; 5168 /// - every member function of class T 5169 /// - every member of class T that is itself a type; 5170 /// \returns true if the declaration name violates these rules. 5171 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5172 DeclarationNameInfo NameInfo) { 5173 DeclarationName Name = NameInfo.getName(); 5174 5175 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5176 while (Record && Record->isAnonymousStructOrUnion()) 5177 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5178 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5179 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5180 return true; 5181 } 5182 5183 return false; 5184 } 5185 5186 /// \brief Diagnose a declaration whose declarator-id has the given 5187 /// nested-name-specifier. 5188 /// 5189 /// \param SS The nested-name-specifier of the declarator-id. 5190 /// 5191 /// \param DC The declaration context to which the nested-name-specifier 5192 /// resolves. 5193 /// 5194 /// \param Name The name of the entity being declared. 5195 /// 5196 /// \param Loc The location of the name of the entity being declared. 5197 /// 5198 /// \returns true if we cannot safely recover from this error, false otherwise. 5199 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5200 DeclarationName Name, 5201 SourceLocation Loc) { 5202 DeclContext *Cur = CurContext; 5203 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5204 Cur = Cur->getParent(); 5205 5206 // If the user provided a superfluous scope specifier that refers back to the 5207 // class in which the entity is already declared, diagnose and ignore it. 5208 // 5209 // class X { 5210 // void X::f(); 5211 // }; 5212 // 5213 // Note, it was once ill-formed to give redundant qualification in all 5214 // contexts, but that rule was removed by DR482. 5215 if (Cur->Equals(DC)) { 5216 if (Cur->isRecord()) { 5217 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5218 : diag::err_member_extra_qualification) 5219 << Name << FixItHint::CreateRemoval(SS.getRange()); 5220 SS.clear(); 5221 } else { 5222 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5223 } 5224 return false; 5225 } 5226 5227 // Check whether the qualifying scope encloses the scope of the original 5228 // declaration. 5229 if (!Cur->Encloses(DC)) { 5230 if (Cur->isRecord()) 5231 Diag(Loc, diag::err_member_qualification) 5232 << Name << SS.getRange(); 5233 else if (isa<TranslationUnitDecl>(DC)) 5234 Diag(Loc, diag::err_invalid_declarator_global_scope) 5235 << Name << SS.getRange(); 5236 else if (isa<FunctionDecl>(Cur)) 5237 Diag(Loc, diag::err_invalid_declarator_in_function) 5238 << Name << SS.getRange(); 5239 else if (isa<BlockDecl>(Cur)) 5240 Diag(Loc, diag::err_invalid_declarator_in_block) 5241 << Name << SS.getRange(); 5242 else 5243 Diag(Loc, diag::err_invalid_declarator_scope) 5244 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5245 5246 return true; 5247 } 5248 5249 if (Cur->isRecord()) { 5250 // Cannot qualify members within a class. 5251 Diag(Loc, diag::err_member_qualification) 5252 << Name << SS.getRange(); 5253 SS.clear(); 5254 5255 // C++ constructors and destructors with incorrect scopes can break 5256 // our AST invariants by having the wrong underlying types. If 5257 // that's the case, then drop this declaration entirely. 5258 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5259 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5260 !Context.hasSameType(Name.getCXXNameType(), 5261 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5262 return true; 5263 5264 return false; 5265 } 5266 5267 // C++11 [dcl.meaning]p1: 5268 // [...] "The nested-name-specifier of the qualified declarator-id shall 5269 // not begin with a decltype-specifer" 5270 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5271 while (SpecLoc.getPrefix()) 5272 SpecLoc = SpecLoc.getPrefix(); 5273 if (dyn_cast_or_null<DecltypeType>( 5274 SpecLoc.getNestedNameSpecifier()->getAsType())) 5275 Diag(Loc, diag::err_decltype_in_declarator) 5276 << SpecLoc.getTypeLoc().getSourceRange(); 5277 5278 return false; 5279 } 5280 5281 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5282 MultiTemplateParamsArg TemplateParamLists) { 5283 // TODO: consider using NameInfo for diagnostic. 5284 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5285 DeclarationName Name = NameInfo.getName(); 5286 5287 // All of these full declarators require an identifier. If it doesn't have 5288 // one, the ParsedFreeStandingDeclSpec action should be used. 5289 if (D.isDecompositionDeclarator()) { 5290 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5291 } else if (!Name) { 5292 if (!D.isInvalidType()) // Reject this if we think it is valid. 5293 Diag(D.getDeclSpec().getLocStart(), 5294 diag::err_declarator_need_ident) 5295 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5296 return nullptr; 5297 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5298 return nullptr; 5299 5300 // The scope passed in may not be a decl scope. Zip up the scope tree until 5301 // we find one that is. 5302 while ((S->getFlags() & Scope::DeclScope) == 0 || 5303 (S->getFlags() & Scope::TemplateParamScope) != 0) 5304 S = S->getParent(); 5305 5306 DeclContext *DC = CurContext; 5307 if (D.getCXXScopeSpec().isInvalid()) 5308 D.setInvalidType(); 5309 else if (D.getCXXScopeSpec().isSet()) { 5310 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5311 UPPC_DeclarationQualifier)) 5312 return nullptr; 5313 5314 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5315 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5316 if (!DC || isa<EnumDecl>(DC)) { 5317 // If we could not compute the declaration context, it's because the 5318 // declaration context is dependent but does not refer to a class, 5319 // class template, or class template partial specialization. Complain 5320 // and return early, to avoid the coming semantic disaster. 5321 Diag(D.getIdentifierLoc(), 5322 diag::err_template_qualified_declarator_no_match) 5323 << D.getCXXScopeSpec().getScopeRep() 5324 << D.getCXXScopeSpec().getRange(); 5325 return nullptr; 5326 } 5327 bool IsDependentContext = DC->isDependentContext(); 5328 5329 if (!IsDependentContext && 5330 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5331 return nullptr; 5332 5333 // If a class is incomplete, do not parse entities inside it. 5334 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5335 Diag(D.getIdentifierLoc(), 5336 diag::err_member_def_undefined_record) 5337 << Name << DC << D.getCXXScopeSpec().getRange(); 5338 return nullptr; 5339 } 5340 if (!D.getDeclSpec().isFriendSpecified()) { 5341 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 5342 Name, D.getIdentifierLoc())) { 5343 if (DC->isRecord()) 5344 return nullptr; 5345 5346 D.setInvalidType(); 5347 } 5348 } 5349 5350 // Check whether we need to rebuild the type of the given 5351 // declaration in the current instantiation. 5352 if (EnteringContext && IsDependentContext && 5353 TemplateParamLists.size() != 0) { 5354 ContextRAII SavedContext(*this, DC); 5355 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5356 D.setInvalidType(); 5357 } 5358 } 5359 5360 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5361 QualType R = TInfo->getType(); 5362 5363 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5364 UPPC_DeclarationType)) 5365 D.setInvalidType(); 5366 5367 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5368 forRedeclarationInCurContext()); 5369 5370 // See if this is a redefinition of a variable in the same scope. 5371 if (!D.getCXXScopeSpec().isSet()) { 5372 bool IsLinkageLookup = false; 5373 bool CreateBuiltins = false; 5374 5375 // If the declaration we're planning to build will be a function 5376 // or object with linkage, then look for another declaration with 5377 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5378 // 5379 // If the declaration we're planning to build will be declared with 5380 // external linkage in the translation unit, create any builtin with 5381 // the same name. 5382 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5383 /* Do nothing*/; 5384 else if (CurContext->isFunctionOrMethod() && 5385 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5386 R->isFunctionType())) { 5387 IsLinkageLookup = true; 5388 CreateBuiltins = 5389 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5390 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5391 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5392 CreateBuiltins = true; 5393 5394 if (IsLinkageLookup) { 5395 Previous.clear(LookupRedeclarationWithLinkage); 5396 Previous.setRedeclarationKind(ForExternalRedeclaration); 5397 } 5398 5399 LookupName(Previous, S, CreateBuiltins); 5400 } else { // Something like "int foo::x;" 5401 LookupQualifiedName(Previous, DC); 5402 5403 // C++ [dcl.meaning]p1: 5404 // When the declarator-id is qualified, the declaration shall refer to a 5405 // previously declared member of the class or namespace to which the 5406 // qualifier refers (or, in the case of a namespace, of an element of the 5407 // inline namespace set of that namespace (7.3.1)) or to a specialization 5408 // thereof; [...] 5409 // 5410 // Note that we already checked the context above, and that we do not have 5411 // enough information to make sure that Previous contains the declaration 5412 // we want to match. For example, given: 5413 // 5414 // class X { 5415 // void f(); 5416 // void f(float); 5417 // }; 5418 // 5419 // void X::f(int) { } // ill-formed 5420 // 5421 // In this case, Previous will point to the overload set 5422 // containing the two f's declared in X, but neither of them 5423 // matches. 5424 5425 // C++ [dcl.meaning]p1: 5426 // [...] the member shall not merely have been introduced by a 5427 // using-declaration in the scope of the class or namespace nominated by 5428 // the nested-name-specifier of the declarator-id. 5429 RemoveUsingDecls(Previous); 5430 } 5431 5432 if (Previous.isSingleResult() && 5433 Previous.getFoundDecl()->isTemplateParameter()) { 5434 // Maybe we will complain about the shadowed template parameter. 5435 if (!D.isInvalidType()) 5436 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5437 Previous.getFoundDecl()); 5438 5439 // Just pretend that we didn't see the previous declaration. 5440 Previous.clear(); 5441 } 5442 5443 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5444 // Forget that the previous declaration is the injected-class-name. 5445 Previous.clear(); 5446 5447 // In C++, the previous declaration we find might be a tag type 5448 // (class or enum). In this case, the new declaration will hide the 5449 // tag type. Note that this applies to functions, function templates, and 5450 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5451 if (Previous.isSingleTagDecl() && 5452 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5453 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5454 Previous.clear(); 5455 5456 // Check that there are no default arguments other than in the parameters 5457 // of a function declaration (C++ only). 5458 if (getLangOpts().CPlusPlus) 5459 CheckExtraCXXDefaultArguments(D); 5460 5461 if (D.getDeclSpec().isConceptSpecified()) { 5462 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 5463 // applied only to the definition of a function template or variable 5464 // template, declared in namespace scope 5465 if (!TemplateParamLists.size()) { 5466 Diag(D.getDeclSpec().getConceptSpecLoc(), 5467 diag:: err_concept_wrong_decl_kind); 5468 return nullptr; 5469 } 5470 5471 if (!DC->getRedeclContext()->isFileContext()) { 5472 Diag(D.getIdentifierLoc(), 5473 diag::err_concept_decls_may_only_appear_in_namespace_scope); 5474 return nullptr; 5475 } 5476 } 5477 5478 NamedDecl *New; 5479 5480 bool AddToScope = true; 5481 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5482 if (TemplateParamLists.size()) { 5483 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5484 return nullptr; 5485 } 5486 5487 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5488 } else if (R->isFunctionType()) { 5489 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5490 TemplateParamLists, 5491 AddToScope); 5492 } else { 5493 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5494 AddToScope); 5495 } 5496 5497 if (!New) 5498 return nullptr; 5499 5500 // If this has an identifier and is not a function template specialization, 5501 // add it to the scope stack. 5502 if (New->getDeclName() && AddToScope) { 5503 // Only make a locally-scoped extern declaration visible if it is the first 5504 // declaration of this entity. Qualified lookup for such an entity should 5505 // only find this declaration if there is no visible declaration of it. 5506 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5507 PushOnScopeChains(New, S, AddToContext); 5508 if (!AddToContext) 5509 CurContext->addHiddenDecl(New); 5510 } 5511 5512 if (isInOpenMPDeclareTargetContext()) 5513 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5514 5515 return New; 5516 } 5517 5518 /// Helper method to turn variable array types into constant array 5519 /// types in certain situations which would otherwise be errors (for 5520 /// GCC compatibility). 5521 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5522 ASTContext &Context, 5523 bool &SizeIsNegative, 5524 llvm::APSInt &Oversized) { 5525 // This method tries to turn a variable array into a constant 5526 // array even when the size isn't an ICE. This is necessary 5527 // for compatibility with code that depends on gcc's buggy 5528 // constant expression folding, like struct {char x[(int)(char*)2];} 5529 SizeIsNegative = false; 5530 Oversized = 0; 5531 5532 if (T->isDependentType()) 5533 return QualType(); 5534 5535 QualifierCollector Qs; 5536 const Type *Ty = Qs.strip(T); 5537 5538 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5539 QualType Pointee = PTy->getPointeeType(); 5540 QualType FixedType = 5541 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5542 Oversized); 5543 if (FixedType.isNull()) return FixedType; 5544 FixedType = Context.getPointerType(FixedType); 5545 return Qs.apply(Context, FixedType); 5546 } 5547 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5548 QualType Inner = PTy->getInnerType(); 5549 QualType FixedType = 5550 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5551 Oversized); 5552 if (FixedType.isNull()) return FixedType; 5553 FixedType = Context.getParenType(FixedType); 5554 return Qs.apply(Context, FixedType); 5555 } 5556 5557 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5558 if (!VLATy) 5559 return QualType(); 5560 // FIXME: We should probably handle this case 5561 if (VLATy->getElementType()->isVariablyModifiedType()) 5562 return QualType(); 5563 5564 llvm::APSInt Res; 5565 if (!VLATy->getSizeExpr() || 5566 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5567 return QualType(); 5568 5569 // Check whether the array size is negative. 5570 if (Res.isSigned() && Res.isNegative()) { 5571 SizeIsNegative = true; 5572 return QualType(); 5573 } 5574 5575 // Check whether the array is too large to be addressed. 5576 unsigned ActiveSizeBits 5577 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5578 Res); 5579 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5580 Oversized = Res; 5581 return QualType(); 5582 } 5583 5584 return Context.getConstantArrayType(VLATy->getElementType(), 5585 Res, ArrayType::Normal, 0); 5586 } 5587 5588 static void 5589 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5590 SrcTL = SrcTL.getUnqualifiedLoc(); 5591 DstTL = DstTL.getUnqualifiedLoc(); 5592 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5593 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5594 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5595 DstPTL.getPointeeLoc()); 5596 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5597 return; 5598 } 5599 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5600 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5601 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5602 DstPTL.getInnerLoc()); 5603 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5604 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5605 return; 5606 } 5607 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5608 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5609 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5610 TypeLoc DstElemTL = DstATL.getElementLoc(); 5611 DstElemTL.initializeFullCopy(SrcElemTL); 5612 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5613 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5614 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5615 } 5616 5617 /// Helper method to turn variable array types into constant array 5618 /// types in certain situations which would otherwise be errors (for 5619 /// GCC compatibility). 5620 static TypeSourceInfo* 5621 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5622 ASTContext &Context, 5623 bool &SizeIsNegative, 5624 llvm::APSInt &Oversized) { 5625 QualType FixedTy 5626 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5627 SizeIsNegative, Oversized); 5628 if (FixedTy.isNull()) 5629 return nullptr; 5630 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5631 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5632 FixedTInfo->getTypeLoc()); 5633 return FixedTInfo; 5634 } 5635 5636 /// \brief Register the given locally-scoped extern "C" declaration so 5637 /// that it can be found later for redeclarations. We include any extern "C" 5638 /// declaration that is not visible in the translation unit here, not just 5639 /// function-scope declarations. 5640 void 5641 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5642 if (!getLangOpts().CPlusPlus && 5643 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5644 // Don't need to track declarations in the TU in C. 5645 return; 5646 5647 // Note that we have a locally-scoped external with this name. 5648 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5649 } 5650 5651 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5652 // FIXME: We can have multiple results via __attribute__((overloadable)). 5653 auto Result = Context.getExternCContextDecl()->lookup(Name); 5654 return Result.empty() ? nullptr : *Result.begin(); 5655 } 5656 5657 /// \brief Diagnose function specifiers on a declaration of an identifier that 5658 /// does not identify a function. 5659 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5660 // FIXME: We should probably indicate the identifier in question to avoid 5661 // confusion for constructs like "virtual int a(), b;" 5662 if (DS.isVirtualSpecified()) 5663 Diag(DS.getVirtualSpecLoc(), 5664 diag::err_virtual_non_function); 5665 5666 if (DS.isExplicitSpecified()) 5667 Diag(DS.getExplicitSpecLoc(), 5668 diag::err_explicit_non_function); 5669 5670 if (DS.isNoreturnSpecified()) 5671 Diag(DS.getNoreturnSpecLoc(), 5672 diag::err_noreturn_non_function); 5673 } 5674 5675 NamedDecl* 5676 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5677 TypeSourceInfo *TInfo, LookupResult &Previous) { 5678 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5679 if (D.getCXXScopeSpec().isSet()) { 5680 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5681 << D.getCXXScopeSpec().getRange(); 5682 D.setInvalidType(); 5683 // Pretend we didn't see the scope specifier. 5684 DC = CurContext; 5685 Previous.clear(); 5686 } 5687 5688 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5689 5690 if (D.getDeclSpec().isInlineSpecified()) 5691 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5692 << getLangOpts().CPlusPlus1z; 5693 if (D.getDeclSpec().isConstexprSpecified()) 5694 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5695 << 1; 5696 if (D.getDeclSpec().isConceptSpecified()) 5697 Diag(D.getDeclSpec().getConceptSpecLoc(), 5698 diag::err_concept_wrong_decl_kind); 5699 5700 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5701 if (D.getName().Kind == UnqualifiedId::IK_DeductionGuideName) 5702 Diag(D.getName().StartLocation, 5703 diag::err_deduction_guide_invalid_specifier) 5704 << "typedef"; 5705 else 5706 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5707 << D.getName().getSourceRange(); 5708 return nullptr; 5709 } 5710 5711 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5712 if (!NewTD) return nullptr; 5713 5714 // Handle attributes prior to checking for duplicates in MergeVarDecl 5715 ProcessDeclAttributes(S, NewTD, D); 5716 5717 CheckTypedefForVariablyModifiedType(S, NewTD); 5718 5719 bool Redeclaration = D.isRedeclaration(); 5720 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5721 D.setRedeclaration(Redeclaration); 5722 return ND; 5723 } 5724 5725 void 5726 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5727 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5728 // then it shall have block scope. 5729 // Note that variably modified types must be fixed before merging the decl so 5730 // that redeclarations will match. 5731 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5732 QualType T = TInfo->getType(); 5733 if (T->isVariablyModifiedType()) { 5734 getCurFunction()->setHasBranchProtectedScope(); 5735 5736 if (S->getFnParent() == nullptr) { 5737 bool SizeIsNegative; 5738 llvm::APSInt Oversized; 5739 TypeSourceInfo *FixedTInfo = 5740 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5741 SizeIsNegative, 5742 Oversized); 5743 if (FixedTInfo) { 5744 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5745 NewTD->setTypeSourceInfo(FixedTInfo); 5746 } else { 5747 if (SizeIsNegative) 5748 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5749 else if (T->isVariableArrayType()) 5750 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5751 else if (Oversized.getBoolValue()) 5752 Diag(NewTD->getLocation(), diag::err_array_too_large) 5753 << Oversized.toString(10); 5754 else 5755 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5756 NewTD->setInvalidDecl(); 5757 } 5758 } 5759 } 5760 } 5761 5762 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5763 /// declares a typedef-name, either using the 'typedef' type specifier or via 5764 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5765 NamedDecl* 5766 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5767 LookupResult &Previous, bool &Redeclaration) { 5768 5769 // Find the shadowed declaration before filtering for scope. 5770 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5771 5772 // Merge the decl with the existing one if appropriate. If the decl is 5773 // in an outer scope, it isn't the same thing. 5774 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5775 /*AllowInlineNamespace*/false); 5776 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5777 if (!Previous.empty()) { 5778 Redeclaration = true; 5779 MergeTypedefNameDecl(S, NewTD, Previous); 5780 } 5781 5782 if (ShadowedDecl && !Redeclaration) 5783 CheckShadow(NewTD, ShadowedDecl, Previous); 5784 5785 // If this is the C FILE type, notify the AST context. 5786 if (IdentifierInfo *II = NewTD->getIdentifier()) 5787 if (!NewTD->isInvalidDecl() && 5788 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5789 if (II->isStr("FILE")) 5790 Context.setFILEDecl(NewTD); 5791 else if (II->isStr("jmp_buf")) 5792 Context.setjmp_bufDecl(NewTD); 5793 else if (II->isStr("sigjmp_buf")) 5794 Context.setsigjmp_bufDecl(NewTD); 5795 else if (II->isStr("ucontext_t")) 5796 Context.setucontext_tDecl(NewTD); 5797 } 5798 5799 return NewTD; 5800 } 5801 5802 /// \brief Determines whether the given declaration is an out-of-scope 5803 /// previous declaration. 5804 /// 5805 /// This routine should be invoked when name lookup has found a 5806 /// previous declaration (PrevDecl) that is not in the scope where a 5807 /// new declaration by the same name is being introduced. If the new 5808 /// declaration occurs in a local scope, previous declarations with 5809 /// linkage may still be considered previous declarations (C99 5810 /// 6.2.2p4-5, C++ [basic.link]p6). 5811 /// 5812 /// \param PrevDecl the previous declaration found by name 5813 /// lookup 5814 /// 5815 /// \param DC the context in which the new declaration is being 5816 /// declared. 5817 /// 5818 /// \returns true if PrevDecl is an out-of-scope previous declaration 5819 /// for a new delcaration with the same name. 5820 static bool 5821 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5822 ASTContext &Context) { 5823 if (!PrevDecl) 5824 return false; 5825 5826 if (!PrevDecl->hasLinkage()) 5827 return false; 5828 5829 if (Context.getLangOpts().CPlusPlus) { 5830 // C++ [basic.link]p6: 5831 // If there is a visible declaration of an entity with linkage 5832 // having the same name and type, ignoring entities declared 5833 // outside the innermost enclosing namespace scope, the block 5834 // scope declaration declares that same entity and receives the 5835 // linkage of the previous declaration. 5836 DeclContext *OuterContext = DC->getRedeclContext(); 5837 if (!OuterContext->isFunctionOrMethod()) 5838 // This rule only applies to block-scope declarations. 5839 return false; 5840 5841 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5842 if (PrevOuterContext->isRecord()) 5843 // We found a member function: ignore it. 5844 return false; 5845 5846 // Find the innermost enclosing namespace for the new and 5847 // previous declarations. 5848 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5849 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5850 5851 // The previous declaration is in a different namespace, so it 5852 // isn't the same function. 5853 if (!OuterContext->Equals(PrevOuterContext)) 5854 return false; 5855 } 5856 5857 return true; 5858 } 5859 5860 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5861 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5862 if (!SS.isSet()) return; 5863 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5864 } 5865 5866 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5867 QualType type = decl->getType(); 5868 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5869 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5870 // Various kinds of declaration aren't allowed to be __autoreleasing. 5871 unsigned kind = -1U; 5872 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5873 if (var->hasAttr<BlocksAttr>()) 5874 kind = 0; // __block 5875 else if (!var->hasLocalStorage()) 5876 kind = 1; // global 5877 } else if (isa<ObjCIvarDecl>(decl)) { 5878 kind = 3; // ivar 5879 } else if (isa<FieldDecl>(decl)) { 5880 kind = 2; // field 5881 } 5882 5883 if (kind != -1U) { 5884 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5885 << kind; 5886 } 5887 } else if (lifetime == Qualifiers::OCL_None) { 5888 // Try to infer lifetime. 5889 if (!type->isObjCLifetimeType()) 5890 return false; 5891 5892 lifetime = type->getObjCARCImplicitLifetime(); 5893 type = Context.getLifetimeQualifiedType(type, lifetime); 5894 decl->setType(type); 5895 } 5896 5897 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5898 // Thread-local variables cannot have lifetime. 5899 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5900 var->getTLSKind()) { 5901 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5902 << var->getType(); 5903 return true; 5904 } 5905 } 5906 5907 return false; 5908 } 5909 5910 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5911 // Ensure that an auto decl is deduced otherwise the checks below might cache 5912 // the wrong linkage. 5913 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5914 5915 // 'weak' only applies to declarations with external linkage. 5916 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5917 if (!ND.isExternallyVisible()) { 5918 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5919 ND.dropAttr<WeakAttr>(); 5920 } 5921 } 5922 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5923 if (ND.isExternallyVisible()) { 5924 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5925 ND.dropAttr<WeakRefAttr>(); 5926 ND.dropAttr<AliasAttr>(); 5927 } 5928 } 5929 5930 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5931 if (VD->hasInit()) { 5932 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5933 assert(VD->isThisDeclarationADefinition() && 5934 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5935 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5936 VD->dropAttr<AliasAttr>(); 5937 } 5938 } 5939 } 5940 5941 // 'selectany' only applies to externally visible variable declarations. 5942 // It does not apply to functions. 5943 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5944 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5945 S.Diag(Attr->getLocation(), 5946 diag::err_attribute_selectany_non_extern_data); 5947 ND.dropAttr<SelectAnyAttr>(); 5948 } 5949 } 5950 5951 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5952 // dll attributes require external linkage. Static locals may have external 5953 // linkage but still cannot be explicitly imported or exported. 5954 auto *VD = dyn_cast<VarDecl>(&ND); 5955 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5956 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5957 << &ND << Attr; 5958 ND.setInvalidDecl(); 5959 } 5960 } 5961 5962 // Virtual functions cannot be marked as 'notail'. 5963 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5964 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5965 if (MD->isVirtual()) { 5966 S.Diag(ND.getLocation(), 5967 diag::err_invalid_attribute_on_virtual_function) 5968 << Attr; 5969 ND.dropAttr<NotTailCalledAttr>(); 5970 } 5971 } 5972 5973 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5974 NamedDecl *NewDecl, 5975 bool IsSpecialization, 5976 bool IsDefinition) { 5977 if (OldDecl->isInvalidDecl()) 5978 return; 5979 5980 bool IsTemplate = false; 5981 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 5982 OldDecl = OldTD->getTemplatedDecl(); 5983 IsTemplate = true; 5984 if (!IsSpecialization) 5985 IsDefinition = false; 5986 } 5987 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 5988 NewDecl = NewTD->getTemplatedDecl(); 5989 IsTemplate = true; 5990 } 5991 5992 if (!OldDecl || !NewDecl) 5993 return; 5994 5995 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5996 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5997 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5998 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5999 6000 // dllimport and dllexport are inheritable attributes so we have to exclude 6001 // inherited attribute instances. 6002 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6003 (NewExportAttr && !NewExportAttr->isInherited()); 6004 6005 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6006 // the only exception being explicit specializations. 6007 // Implicitly generated declarations are also excluded for now because there 6008 // is no other way to switch these to use dllimport or dllexport. 6009 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6010 6011 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6012 // Allow with a warning for free functions and global variables. 6013 bool JustWarn = false; 6014 if (!OldDecl->isCXXClassMember()) { 6015 auto *VD = dyn_cast<VarDecl>(OldDecl); 6016 if (VD && !VD->getDescribedVarTemplate()) 6017 JustWarn = true; 6018 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6019 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6020 JustWarn = true; 6021 } 6022 6023 // We cannot change a declaration that's been used because IR has already 6024 // been emitted. Dllimported functions will still work though (modulo 6025 // address equality) as they can use the thunk. 6026 if (OldDecl->isUsed()) 6027 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6028 JustWarn = false; 6029 6030 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6031 : diag::err_attribute_dll_redeclaration; 6032 S.Diag(NewDecl->getLocation(), DiagID) 6033 << NewDecl 6034 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6035 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6036 if (!JustWarn) { 6037 NewDecl->setInvalidDecl(); 6038 return; 6039 } 6040 } 6041 6042 // A redeclaration is not allowed to drop a dllimport attribute, the only 6043 // exceptions being inline function definitions (except for function 6044 // templates), local extern declarations, qualified friend declarations or 6045 // special MSVC extension: in the last case, the declaration is treated as if 6046 // it were marked dllexport. 6047 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6048 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6049 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6050 // Ignore static data because out-of-line definitions are diagnosed 6051 // separately. 6052 IsStaticDataMember = VD->isStaticDataMember(); 6053 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6054 VarDecl::DeclarationOnly; 6055 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6056 IsInline = FD->isInlined(); 6057 IsQualifiedFriend = FD->getQualifier() && 6058 FD->getFriendObjectKind() == Decl::FOK_Declared; 6059 } 6060 6061 if (OldImportAttr && !HasNewAttr && 6062 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6063 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6064 if (IsMicrosoft && IsDefinition) { 6065 S.Diag(NewDecl->getLocation(), 6066 diag::warn_redeclaration_without_import_attribute) 6067 << NewDecl; 6068 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6069 NewDecl->dropAttr<DLLImportAttr>(); 6070 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6071 NewImportAttr->getRange(), S.Context, 6072 NewImportAttr->getSpellingListIndex())); 6073 } else { 6074 S.Diag(NewDecl->getLocation(), 6075 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6076 << NewDecl << OldImportAttr; 6077 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6078 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6079 OldDecl->dropAttr<DLLImportAttr>(); 6080 NewDecl->dropAttr<DLLImportAttr>(); 6081 } 6082 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6083 // In MinGW, seeing a function declared inline drops the dllimport attribute. 6084 OldDecl->dropAttr<DLLImportAttr>(); 6085 NewDecl->dropAttr<DLLImportAttr>(); 6086 S.Diag(NewDecl->getLocation(), 6087 diag::warn_dllimport_dropped_from_inline_function) 6088 << NewDecl << OldImportAttr; 6089 } 6090 6091 // A specialization of a class template member function is processed here 6092 // since it's a redeclaration. If the parent class is dllexport, the 6093 // specialization inherits that attribute. This doesn't happen automatically 6094 // since the parent class isn't instantiated until later. 6095 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6096 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6097 !NewImportAttr && !NewExportAttr) { 6098 if (const DLLExportAttr *ParentExportAttr = 6099 MD->getParent()->getAttr<DLLExportAttr>()) { 6100 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6101 NewAttr->setInherited(true); 6102 NewDecl->addAttr(NewAttr); 6103 } 6104 } 6105 } 6106 } 6107 6108 /// Given that we are within the definition of the given function, 6109 /// will that definition behave like C99's 'inline', where the 6110 /// definition is discarded except for optimization purposes? 6111 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6112 // Try to avoid calling GetGVALinkageForFunction. 6113 6114 // All cases of this require the 'inline' keyword. 6115 if (!FD->isInlined()) return false; 6116 6117 // This is only possible in C++ with the gnu_inline attribute. 6118 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6119 return false; 6120 6121 // Okay, go ahead and call the relatively-more-expensive function. 6122 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6123 } 6124 6125 /// Determine whether a variable is extern "C" prior to attaching 6126 /// an initializer. We can't just call isExternC() here, because that 6127 /// will also compute and cache whether the declaration is externally 6128 /// visible, which might change when we attach the initializer. 6129 /// 6130 /// This can only be used if the declaration is known to not be a 6131 /// redeclaration of an internal linkage declaration. 6132 /// 6133 /// For instance: 6134 /// 6135 /// auto x = []{}; 6136 /// 6137 /// Attaching the initializer here makes this declaration not externally 6138 /// visible, because its type has internal linkage. 6139 /// 6140 /// FIXME: This is a hack. 6141 template<typename T> 6142 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6143 if (S.getLangOpts().CPlusPlus) { 6144 // In C++, the overloadable attribute negates the effects of extern "C". 6145 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6146 return false; 6147 6148 // So do CUDA's host/device attributes. 6149 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6150 D->template hasAttr<CUDAHostAttr>())) 6151 return false; 6152 } 6153 return D->isExternC(); 6154 } 6155 6156 static bool shouldConsiderLinkage(const VarDecl *VD) { 6157 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6158 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6159 return VD->hasExternalStorage(); 6160 if (DC->isFileContext()) 6161 return true; 6162 if (DC->isRecord()) 6163 return false; 6164 llvm_unreachable("Unexpected context"); 6165 } 6166 6167 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6168 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6169 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6170 isa<OMPDeclareReductionDecl>(DC)) 6171 return true; 6172 if (DC->isRecord()) 6173 return false; 6174 llvm_unreachable("Unexpected context"); 6175 } 6176 6177 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6178 AttributeList::Kind Kind) { 6179 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6180 if (L->getKind() == Kind) 6181 return true; 6182 return false; 6183 } 6184 6185 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6186 AttributeList::Kind Kind) { 6187 // Check decl attributes on the DeclSpec. 6188 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6189 return true; 6190 6191 // Walk the declarator structure, checking decl attributes that were in a type 6192 // position to the decl itself. 6193 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6194 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6195 return true; 6196 } 6197 6198 // Finally, check attributes on the decl itself. 6199 return hasParsedAttr(S, PD.getAttributes(), Kind); 6200 } 6201 6202 /// Adjust the \c DeclContext for a function or variable that might be a 6203 /// function-local external declaration. 6204 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6205 if (!DC->isFunctionOrMethod()) 6206 return false; 6207 6208 // If this is a local extern function or variable declared within a function 6209 // template, don't add it into the enclosing namespace scope until it is 6210 // instantiated; it might have a dependent type right now. 6211 if (DC->isDependentContext()) 6212 return true; 6213 6214 // C++11 [basic.link]p7: 6215 // When a block scope declaration of an entity with linkage is not found to 6216 // refer to some other declaration, then that entity is a member of the 6217 // innermost enclosing namespace. 6218 // 6219 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6220 // semantically-enclosing namespace, not a lexically-enclosing one. 6221 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6222 DC = DC->getParent(); 6223 return true; 6224 } 6225 6226 /// \brief Returns true if given declaration has external C language linkage. 6227 static bool isDeclExternC(const Decl *D) { 6228 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6229 return FD->isExternC(); 6230 if (const auto *VD = dyn_cast<VarDecl>(D)) 6231 return VD->isExternC(); 6232 6233 llvm_unreachable("Unknown type of decl!"); 6234 } 6235 6236 NamedDecl *Sema::ActOnVariableDeclarator( 6237 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6238 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6239 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6240 QualType R = TInfo->getType(); 6241 DeclarationName Name = GetNameForDeclarator(D).getName(); 6242 6243 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6244 6245 if (D.isDecompositionDeclarator()) { 6246 // Take the name of the first declarator as our name for diagnostic 6247 // purposes. 6248 auto &Decomp = D.getDecompositionDeclarator(); 6249 if (!Decomp.bindings().empty()) { 6250 II = Decomp.bindings()[0].Name; 6251 Name = II; 6252 } 6253 } else if (!II) { 6254 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6255 return nullptr; 6256 } 6257 6258 if (getLangOpts().OpenCL) { 6259 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6260 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6261 // argument. 6262 if (R->isImageType() || R->isPipeType()) { 6263 Diag(D.getIdentifierLoc(), 6264 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6265 << R; 6266 D.setInvalidType(); 6267 return nullptr; 6268 } 6269 6270 // OpenCL v1.2 s6.9.r: 6271 // The event type cannot be used to declare a program scope variable. 6272 // OpenCL v2.0 s6.9.q: 6273 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6274 if (NULL == S->getParent()) { 6275 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6276 Diag(D.getIdentifierLoc(), 6277 diag::err_invalid_type_for_program_scope_var) << R; 6278 D.setInvalidType(); 6279 return nullptr; 6280 } 6281 } 6282 6283 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6284 QualType NR = R; 6285 while (NR->isPointerType()) { 6286 if (NR->isFunctionPointerType()) { 6287 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6288 D.setInvalidType(); 6289 break; 6290 } 6291 NR = NR->getPointeeType(); 6292 } 6293 6294 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6295 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6296 // half array type (unless the cl_khr_fp16 extension is enabled). 6297 if (Context.getBaseElementType(R)->isHalfType()) { 6298 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6299 D.setInvalidType(); 6300 } 6301 } 6302 6303 if (R->isSamplerT()) { 6304 // OpenCL v1.2 s6.9.b p4: 6305 // The sampler type cannot be used with the __local and __global address 6306 // space qualifiers. 6307 if (R.getAddressSpace() == LangAS::opencl_local || 6308 R.getAddressSpace() == LangAS::opencl_global) { 6309 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6310 } 6311 6312 // OpenCL v1.2 s6.12.14.1: 6313 // A global sampler must be declared with either the constant address 6314 // space qualifier or with the const qualifier. 6315 if (DC->isTranslationUnit() && 6316 !(R.getAddressSpace() == LangAS::opencl_constant || 6317 R.isConstQualified())) { 6318 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6319 D.setInvalidType(); 6320 } 6321 } 6322 6323 // OpenCL v1.2 s6.9.r: 6324 // The event type cannot be used with the __local, __constant and __global 6325 // address space qualifiers. 6326 if (R->isEventT()) { 6327 if (R.getAddressSpace() != LangAS::opencl_private) { 6328 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6329 D.setInvalidType(); 6330 } 6331 } 6332 } 6333 6334 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6335 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6336 6337 // dllimport globals without explicit storage class are treated as extern. We 6338 // have to change the storage class this early to get the right DeclContext. 6339 if (SC == SC_None && !DC->isRecord() && 6340 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6341 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6342 SC = SC_Extern; 6343 6344 DeclContext *OriginalDC = DC; 6345 bool IsLocalExternDecl = SC == SC_Extern && 6346 adjustContextForLocalExternDecl(DC); 6347 6348 if (SCSpec == DeclSpec::SCS_mutable) { 6349 // mutable can only appear on non-static class members, so it's always 6350 // an error here 6351 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6352 D.setInvalidType(); 6353 SC = SC_None; 6354 } 6355 6356 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6357 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6358 D.getDeclSpec().getStorageClassSpecLoc())) { 6359 // In C++11, the 'register' storage class specifier is deprecated. 6360 // Suppress the warning in system macros, it's used in macros in some 6361 // popular C system headers, such as in glibc's htonl() macro. 6362 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6363 getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class 6364 : diag::warn_deprecated_register) 6365 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6366 } 6367 6368 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6369 6370 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6371 // C99 6.9p2: The storage-class specifiers auto and register shall not 6372 // appear in the declaration specifiers in an external declaration. 6373 // Global Register+Asm is a GNU extension we support. 6374 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6375 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6376 D.setInvalidType(); 6377 } 6378 } 6379 6380 bool IsMemberSpecialization = false; 6381 bool IsVariableTemplateSpecialization = false; 6382 bool IsPartialSpecialization = false; 6383 bool IsVariableTemplate = false; 6384 VarDecl *NewVD = nullptr; 6385 VarTemplateDecl *NewTemplate = nullptr; 6386 TemplateParameterList *TemplateParams = nullptr; 6387 if (!getLangOpts().CPlusPlus) { 6388 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6389 D.getIdentifierLoc(), II, 6390 R, TInfo, SC); 6391 6392 if (R->getContainedDeducedType()) 6393 ParsingInitForAutoVars.insert(NewVD); 6394 6395 if (D.isInvalidType()) 6396 NewVD->setInvalidDecl(); 6397 } else { 6398 bool Invalid = false; 6399 6400 if (DC->isRecord() && !CurContext->isRecord()) { 6401 // This is an out-of-line definition of a static data member. 6402 switch (SC) { 6403 case SC_None: 6404 break; 6405 case SC_Static: 6406 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6407 diag::err_static_out_of_line) 6408 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6409 break; 6410 case SC_Auto: 6411 case SC_Register: 6412 case SC_Extern: 6413 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6414 // to names of variables declared in a block or to function parameters. 6415 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6416 // of class members 6417 6418 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6419 diag::err_storage_class_for_static_member) 6420 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6421 break; 6422 case SC_PrivateExtern: 6423 llvm_unreachable("C storage class in c++!"); 6424 } 6425 } 6426 6427 if (SC == SC_Static && CurContext->isRecord()) { 6428 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6429 if (RD->isLocalClass()) 6430 Diag(D.getIdentifierLoc(), 6431 diag::err_static_data_member_not_allowed_in_local_class) 6432 << Name << RD->getDeclName(); 6433 6434 // C++98 [class.union]p1: If a union contains a static data member, 6435 // the program is ill-formed. C++11 drops this restriction. 6436 if (RD->isUnion()) 6437 Diag(D.getIdentifierLoc(), 6438 getLangOpts().CPlusPlus11 6439 ? diag::warn_cxx98_compat_static_data_member_in_union 6440 : diag::ext_static_data_member_in_union) << Name; 6441 // We conservatively disallow static data members in anonymous structs. 6442 else if (!RD->getDeclName()) 6443 Diag(D.getIdentifierLoc(), 6444 diag::err_static_data_member_not_allowed_in_anon_struct) 6445 << Name << RD->isUnion(); 6446 } 6447 } 6448 6449 // Match up the template parameter lists with the scope specifier, then 6450 // determine whether we have a template or a template specialization. 6451 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6452 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6453 D.getCXXScopeSpec(), 6454 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6455 ? D.getName().TemplateId 6456 : nullptr, 6457 TemplateParamLists, 6458 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6459 6460 if (TemplateParams) { 6461 if (!TemplateParams->size() && 6462 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 6463 // There is an extraneous 'template<>' for this variable. Complain 6464 // about it, but allow the declaration of the variable. 6465 Diag(TemplateParams->getTemplateLoc(), 6466 diag::err_template_variable_noparams) 6467 << II 6468 << SourceRange(TemplateParams->getTemplateLoc(), 6469 TemplateParams->getRAngleLoc()); 6470 TemplateParams = nullptr; 6471 } else { 6472 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 6473 // This is an explicit specialization or a partial specialization. 6474 // FIXME: Check that we can declare a specialization here. 6475 IsVariableTemplateSpecialization = true; 6476 IsPartialSpecialization = TemplateParams->size() > 0; 6477 } else { // if (TemplateParams->size() > 0) 6478 // This is a template declaration. 6479 IsVariableTemplate = true; 6480 6481 // Check that we can declare a template here. 6482 if (CheckTemplateDeclScope(S, TemplateParams)) 6483 return nullptr; 6484 6485 // Only C++1y supports variable templates (N3651). 6486 Diag(D.getIdentifierLoc(), 6487 getLangOpts().CPlusPlus14 6488 ? diag::warn_cxx11_compat_variable_template 6489 : diag::ext_variable_template); 6490 } 6491 } 6492 } else { 6493 assert( 6494 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 6495 "should have a 'template<>' for this decl"); 6496 } 6497 6498 if (IsVariableTemplateSpecialization) { 6499 SourceLocation TemplateKWLoc = 6500 TemplateParamLists.size() > 0 6501 ? TemplateParamLists[0]->getTemplateLoc() 6502 : SourceLocation(); 6503 DeclResult Res = ActOnVarTemplateSpecialization( 6504 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6505 IsPartialSpecialization); 6506 if (Res.isInvalid()) 6507 return nullptr; 6508 NewVD = cast<VarDecl>(Res.get()); 6509 AddToScope = false; 6510 } else if (D.isDecompositionDeclarator()) { 6511 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6512 D.getIdentifierLoc(), R, TInfo, SC, 6513 Bindings); 6514 } else 6515 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6516 D.getIdentifierLoc(), II, R, TInfo, SC); 6517 6518 // If this is supposed to be a variable template, create it as such. 6519 if (IsVariableTemplate) { 6520 NewTemplate = 6521 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6522 TemplateParams, NewVD); 6523 NewVD->setDescribedVarTemplate(NewTemplate); 6524 } 6525 6526 // If this decl has an auto type in need of deduction, make a note of the 6527 // Decl so we can diagnose uses of it in its own initializer. 6528 if (R->getContainedDeducedType()) 6529 ParsingInitForAutoVars.insert(NewVD); 6530 6531 if (D.isInvalidType() || Invalid) { 6532 NewVD->setInvalidDecl(); 6533 if (NewTemplate) 6534 NewTemplate->setInvalidDecl(); 6535 } 6536 6537 SetNestedNameSpecifier(NewVD, D); 6538 6539 // If we have any template parameter lists that don't directly belong to 6540 // the variable (matching the scope specifier), store them. 6541 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6542 if (TemplateParamLists.size() > VDTemplateParamLists) 6543 NewVD->setTemplateParameterListsInfo( 6544 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6545 6546 if (D.getDeclSpec().isConstexprSpecified()) { 6547 NewVD->setConstexpr(true); 6548 // C++1z [dcl.spec.constexpr]p1: 6549 // A static data member declared with the constexpr specifier is 6550 // implicitly an inline variable. 6551 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z) 6552 NewVD->setImplicitlyInline(); 6553 } 6554 6555 if (D.getDeclSpec().isConceptSpecified()) { 6556 if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate()) 6557 VTD->setConcept(); 6558 6559 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 6560 // be declared with the thread_local, inline, friend, or constexpr 6561 // specifiers, [...] 6562 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 6563 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6564 diag::err_concept_decl_invalid_specifiers) 6565 << 0 << 0; 6566 NewVD->setInvalidDecl(true); 6567 } 6568 6569 if (D.getDeclSpec().isConstexprSpecified()) { 6570 Diag(D.getDeclSpec().getConstexprSpecLoc(), 6571 diag::err_concept_decl_invalid_specifiers) 6572 << 0 << 3; 6573 NewVD->setInvalidDecl(true); 6574 } 6575 6576 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 6577 // applied only to the definition of a function template or variable 6578 // template, declared in namespace scope. 6579 if (IsVariableTemplateSpecialization) { 6580 Diag(D.getDeclSpec().getConceptSpecLoc(), 6581 diag::err_concept_specified_specialization) 6582 << (IsPartialSpecialization ? 2 : 1); 6583 } 6584 6585 // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the 6586 // following restrictions: 6587 // - The declared type shall have the type bool. 6588 if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) && 6589 !NewVD->isInvalidDecl()) { 6590 Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl); 6591 NewVD->setInvalidDecl(true); 6592 } 6593 } 6594 } 6595 6596 if (D.getDeclSpec().isInlineSpecified()) { 6597 if (!getLangOpts().CPlusPlus) { 6598 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6599 << 0; 6600 } else if (CurContext->isFunctionOrMethod()) { 6601 // 'inline' is not allowed on block scope variable declaration. 6602 Diag(D.getDeclSpec().getInlineSpecLoc(), 6603 diag::err_inline_declaration_block_scope) << Name 6604 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6605 } else { 6606 Diag(D.getDeclSpec().getInlineSpecLoc(), 6607 getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable 6608 : diag::ext_inline_variable); 6609 NewVD->setInlineSpecified(); 6610 } 6611 } 6612 6613 // Set the lexical context. If the declarator has a C++ scope specifier, the 6614 // lexical context will be different from the semantic context. 6615 NewVD->setLexicalDeclContext(CurContext); 6616 if (NewTemplate) 6617 NewTemplate->setLexicalDeclContext(CurContext); 6618 6619 if (IsLocalExternDecl) { 6620 if (D.isDecompositionDeclarator()) 6621 for (auto *B : Bindings) 6622 B->setLocalExternDecl(); 6623 else 6624 NewVD->setLocalExternDecl(); 6625 } 6626 6627 bool EmitTLSUnsupportedError = false; 6628 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6629 // C++11 [dcl.stc]p4: 6630 // When thread_local is applied to a variable of block scope the 6631 // storage-class-specifier static is implied if it does not appear 6632 // explicitly. 6633 // Core issue: 'static' is not implied if the variable is declared 6634 // 'extern'. 6635 if (NewVD->hasLocalStorage() && 6636 (SCSpec != DeclSpec::SCS_unspecified || 6637 TSCS != DeclSpec::TSCS_thread_local || 6638 !DC->isFunctionOrMethod())) 6639 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6640 diag::err_thread_non_global) 6641 << DeclSpec::getSpecifierName(TSCS); 6642 else if (!Context.getTargetInfo().isTLSSupported()) { 6643 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6644 // Postpone error emission until we've collected attributes required to 6645 // figure out whether it's a host or device variable and whether the 6646 // error should be ignored. 6647 EmitTLSUnsupportedError = true; 6648 // We still need to mark the variable as TLS so it shows up in AST with 6649 // proper storage class for other tools to use even if we're not going 6650 // to emit any code for it. 6651 NewVD->setTSCSpec(TSCS); 6652 } else 6653 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6654 diag::err_thread_unsupported); 6655 } else 6656 NewVD->setTSCSpec(TSCS); 6657 } 6658 6659 // C99 6.7.4p3 6660 // An inline definition of a function with external linkage shall 6661 // not contain a definition of a modifiable object with static or 6662 // thread storage duration... 6663 // We only apply this when the function is required to be defined 6664 // elsewhere, i.e. when the function is not 'extern inline'. Note 6665 // that a local variable with thread storage duration still has to 6666 // be marked 'static'. Also note that it's possible to get these 6667 // semantics in C++ using __attribute__((gnu_inline)). 6668 if (SC == SC_Static && S->getFnParent() != nullptr && 6669 !NewVD->getType().isConstQualified()) { 6670 FunctionDecl *CurFD = getCurFunctionDecl(); 6671 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6672 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6673 diag::warn_static_local_in_extern_inline); 6674 MaybeSuggestAddingStaticToDecl(CurFD); 6675 } 6676 } 6677 6678 if (D.getDeclSpec().isModulePrivateSpecified()) { 6679 if (IsVariableTemplateSpecialization) 6680 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6681 << (IsPartialSpecialization ? 1 : 0) 6682 << FixItHint::CreateRemoval( 6683 D.getDeclSpec().getModulePrivateSpecLoc()); 6684 else if (IsMemberSpecialization) 6685 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6686 << 2 6687 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6688 else if (NewVD->hasLocalStorage()) 6689 Diag(NewVD->getLocation(), diag::err_module_private_local) 6690 << 0 << NewVD->getDeclName() 6691 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6692 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6693 else { 6694 NewVD->setModulePrivate(); 6695 if (NewTemplate) 6696 NewTemplate->setModulePrivate(); 6697 for (auto *B : Bindings) 6698 B->setModulePrivate(); 6699 } 6700 } 6701 6702 // Handle attributes prior to checking for duplicates in MergeVarDecl 6703 ProcessDeclAttributes(S, NewVD, D); 6704 6705 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6706 if (EmitTLSUnsupportedError && 6707 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6708 (getLangOpts().OpenMPIsDevice && 6709 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6710 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6711 diag::err_thread_unsupported); 6712 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6713 // storage [duration]." 6714 if (SC == SC_None && S->getFnParent() != nullptr && 6715 (NewVD->hasAttr<CUDASharedAttr>() || 6716 NewVD->hasAttr<CUDAConstantAttr>())) { 6717 NewVD->setStorageClass(SC_Static); 6718 } 6719 } 6720 6721 // Ensure that dllimport globals without explicit storage class are treated as 6722 // extern. The storage class is set above using parsed attributes. Now we can 6723 // check the VarDecl itself. 6724 assert(!NewVD->hasAttr<DLLImportAttr>() || 6725 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6726 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6727 6728 // In auto-retain/release, infer strong retension for variables of 6729 // retainable type. 6730 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6731 NewVD->setInvalidDecl(); 6732 6733 // Handle GNU asm-label extension (encoded as an attribute). 6734 if (Expr *E = (Expr*)D.getAsmLabel()) { 6735 // The parser guarantees this is a string. 6736 StringLiteral *SE = cast<StringLiteral>(E); 6737 StringRef Label = SE->getString(); 6738 if (S->getFnParent() != nullptr) { 6739 switch (SC) { 6740 case SC_None: 6741 case SC_Auto: 6742 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6743 break; 6744 case SC_Register: 6745 // Local Named register 6746 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6747 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6748 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6749 break; 6750 case SC_Static: 6751 case SC_Extern: 6752 case SC_PrivateExtern: 6753 break; 6754 } 6755 } else if (SC == SC_Register) { 6756 // Global Named register 6757 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6758 const auto &TI = Context.getTargetInfo(); 6759 bool HasSizeMismatch; 6760 6761 if (!TI.isValidGCCRegisterName(Label)) 6762 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6763 else if (!TI.validateGlobalRegisterVariable(Label, 6764 Context.getTypeSize(R), 6765 HasSizeMismatch)) 6766 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6767 else if (HasSizeMismatch) 6768 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6769 } 6770 6771 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6772 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6773 NewVD->setInvalidDecl(true); 6774 } 6775 } 6776 6777 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6778 Context, Label, 0)); 6779 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6780 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6781 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6782 if (I != ExtnameUndeclaredIdentifiers.end()) { 6783 if (isDeclExternC(NewVD)) { 6784 NewVD->addAttr(I->second); 6785 ExtnameUndeclaredIdentifiers.erase(I); 6786 } else 6787 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6788 << /*Variable*/1 << NewVD; 6789 } 6790 } 6791 6792 // Find the shadowed declaration before filtering for scope. 6793 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6794 ? getShadowedDeclaration(NewVD, Previous) 6795 : nullptr; 6796 6797 // Don't consider existing declarations that are in a different 6798 // scope and are out-of-semantic-context declarations (if the new 6799 // declaration has linkage). 6800 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6801 D.getCXXScopeSpec().isNotEmpty() || 6802 IsMemberSpecialization || 6803 IsVariableTemplateSpecialization); 6804 6805 // Check whether the previous declaration is in the same block scope. This 6806 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6807 if (getLangOpts().CPlusPlus && 6808 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6809 NewVD->setPreviousDeclInSameBlockScope( 6810 Previous.isSingleResult() && !Previous.isShadowed() && 6811 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6812 6813 if (!getLangOpts().CPlusPlus) { 6814 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6815 } else { 6816 // If this is an explicit specialization of a static data member, check it. 6817 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6818 CheckMemberSpecialization(NewVD, Previous)) 6819 NewVD->setInvalidDecl(); 6820 6821 // Merge the decl with the existing one if appropriate. 6822 if (!Previous.empty()) { 6823 if (Previous.isSingleResult() && 6824 isa<FieldDecl>(Previous.getFoundDecl()) && 6825 D.getCXXScopeSpec().isSet()) { 6826 // The user tried to define a non-static data member 6827 // out-of-line (C++ [dcl.meaning]p1). 6828 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6829 << D.getCXXScopeSpec().getRange(); 6830 Previous.clear(); 6831 NewVD->setInvalidDecl(); 6832 } 6833 } else if (D.getCXXScopeSpec().isSet()) { 6834 // No previous declaration in the qualifying scope. 6835 Diag(D.getIdentifierLoc(), diag::err_no_member) 6836 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6837 << D.getCXXScopeSpec().getRange(); 6838 NewVD->setInvalidDecl(); 6839 } 6840 6841 if (!IsVariableTemplateSpecialization) 6842 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6843 6844 // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...] 6845 // an explicit specialization (14.8.3) or a partial specialization of a 6846 // concept definition. 6847 if (IsVariableTemplateSpecialization && 6848 !D.getDeclSpec().isConceptSpecified() && !Previous.empty() && 6849 Previous.isSingleResult()) { 6850 NamedDecl *PreviousDecl = Previous.getFoundDecl(); 6851 if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) { 6852 if (VarTmpl->isConcept()) { 6853 Diag(NewVD->getLocation(), diag::err_concept_specialized) 6854 << 1 /*variable*/ 6855 << (IsPartialSpecialization ? 2 /*partially specialized*/ 6856 : 1 /*explicitly specialized*/); 6857 Diag(VarTmpl->getLocation(), diag::note_previous_declaration); 6858 NewVD->setInvalidDecl(); 6859 } 6860 } 6861 } 6862 6863 if (NewTemplate) { 6864 VarTemplateDecl *PrevVarTemplate = 6865 NewVD->getPreviousDecl() 6866 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6867 : nullptr; 6868 6869 // Check the template parameter list of this declaration, possibly 6870 // merging in the template parameter list from the previous variable 6871 // template declaration. 6872 if (CheckTemplateParameterList( 6873 TemplateParams, 6874 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6875 : nullptr, 6876 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6877 DC->isDependentContext()) 6878 ? TPC_ClassTemplateMember 6879 : TPC_VarTemplate)) 6880 NewVD->setInvalidDecl(); 6881 6882 // If we are providing an explicit specialization of a static variable 6883 // template, make a note of that. 6884 if (PrevVarTemplate && 6885 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6886 PrevVarTemplate->setMemberSpecialization(); 6887 } 6888 } 6889 6890 // Diagnose shadowed variables iff this isn't a redeclaration. 6891 if (ShadowedDecl && !D.isRedeclaration()) 6892 CheckShadow(NewVD, ShadowedDecl, Previous); 6893 6894 ProcessPragmaWeak(S, NewVD); 6895 6896 // If this is the first declaration of an extern C variable, update 6897 // the map of such variables. 6898 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6899 isIncompleteDeclExternC(*this, NewVD)) 6900 RegisterLocallyScopedExternCDecl(NewVD, S); 6901 6902 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6903 Decl *ManglingContextDecl; 6904 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6905 NewVD->getDeclContext(), ManglingContextDecl)) { 6906 Context.setManglingNumber( 6907 NewVD, MCtx->getManglingNumber( 6908 NewVD, getMSManglingNumber(getLangOpts(), S))); 6909 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6910 } 6911 } 6912 6913 // Special handling of variable named 'main'. 6914 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6915 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6916 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6917 6918 // C++ [basic.start.main]p3 6919 // A program that declares a variable main at global scope is ill-formed. 6920 if (getLangOpts().CPlusPlus) 6921 Diag(D.getLocStart(), diag::err_main_global_variable); 6922 6923 // In C, and external-linkage variable named main results in undefined 6924 // behavior. 6925 else if (NewVD->hasExternalFormalLinkage()) 6926 Diag(D.getLocStart(), diag::warn_main_redefined); 6927 } 6928 6929 if (D.isRedeclaration() && !Previous.empty()) { 6930 checkDLLAttributeRedeclaration( 6931 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6932 IsMemberSpecialization, D.isFunctionDefinition()); 6933 } 6934 6935 if (NewTemplate) { 6936 if (NewVD->isInvalidDecl()) 6937 NewTemplate->setInvalidDecl(); 6938 ActOnDocumentableDecl(NewTemplate); 6939 return NewTemplate; 6940 } 6941 6942 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6943 CompleteMemberSpecialization(NewVD, Previous); 6944 6945 return NewVD; 6946 } 6947 6948 /// Enum describing the %select options in diag::warn_decl_shadow. 6949 enum ShadowedDeclKind { 6950 SDK_Local, 6951 SDK_Global, 6952 SDK_StaticMember, 6953 SDK_Field, 6954 SDK_Typedef, 6955 SDK_Using 6956 }; 6957 6958 /// Determine what kind of declaration we're shadowing. 6959 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6960 const DeclContext *OldDC) { 6961 if (isa<TypeAliasDecl>(ShadowedDecl)) 6962 return SDK_Using; 6963 else if (isa<TypedefDecl>(ShadowedDecl)) 6964 return SDK_Typedef; 6965 else if (isa<RecordDecl>(OldDC)) 6966 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6967 6968 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6969 } 6970 6971 /// Return the location of the capture if the given lambda captures the given 6972 /// variable \p VD, or an invalid source location otherwise. 6973 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6974 const VarDecl *VD) { 6975 for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) { 6976 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6977 return Capture.getLocation(); 6978 } 6979 return SourceLocation(); 6980 } 6981 6982 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6983 const LookupResult &R) { 6984 // Only diagnose if we're shadowing an unambiguous field or variable. 6985 if (R.getResultKind() != LookupResult::Found) 6986 return false; 6987 6988 // Return false if warning is ignored. 6989 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6990 } 6991 6992 /// \brief Return the declaration shadowed by the given variable \p D, or null 6993 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6994 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6995 const LookupResult &R) { 6996 if (!shouldWarnIfShadowedDecl(Diags, R)) 6997 return nullptr; 6998 6999 // Don't diagnose declarations at file scope. 7000 if (D->hasGlobalStorage()) 7001 return nullptr; 7002 7003 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7004 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7005 ? ShadowedDecl 7006 : nullptr; 7007 } 7008 7009 /// \brief Return the declaration shadowed by the given typedef \p D, or null 7010 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7011 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7012 const LookupResult &R) { 7013 // Don't warn if typedef declaration is part of a class 7014 if (D->getDeclContext()->isRecord()) 7015 return nullptr; 7016 7017 if (!shouldWarnIfShadowedDecl(Diags, R)) 7018 return nullptr; 7019 7020 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7021 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7022 } 7023 7024 /// \brief Diagnose variable or built-in function shadowing. Implements 7025 /// -Wshadow. 7026 /// 7027 /// This method is called whenever a VarDecl is added to a "useful" 7028 /// scope. 7029 /// 7030 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7031 /// \param R the lookup of the name 7032 /// 7033 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7034 const LookupResult &R) { 7035 DeclContext *NewDC = D->getDeclContext(); 7036 7037 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7038 // Fields are not shadowed by variables in C++ static methods. 7039 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7040 if (MD->isStatic()) 7041 return; 7042 7043 // Fields shadowed by constructor parameters are a special case. Usually 7044 // the constructor initializes the field with the parameter. 7045 if (isa<CXXConstructorDecl>(NewDC)) 7046 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7047 // Remember that this was shadowed so we can either warn about its 7048 // modification or its existence depending on warning settings. 7049 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7050 return; 7051 } 7052 } 7053 7054 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7055 if (shadowedVar->isExternC()) { 7056 // For shadowing external vars, make sure that we point to the global 7057 // declaration, not a locally scoped extern declaration. 7058 for (auto I : shadowedVar->redecls()) 7059 if (I->isFileVarDecl()) { 7060 ShadowedDecl = I; 7061 break; 7062 } 7063 } 7064 7065 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7066 7067 unsigned WarningDiag = diag::warn_decl_shadow; 7068 SourceLocation CaptureLoc; 7069 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7070 isa<CXXMethodDecl>(NewDC)) { 7071 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7072 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7073 if (RD->getLambdaCaptureDefault() == LCD_None) { 7074 // Try to avoid warnings for lambdas with an explicit capture list. 7075 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7076 // Warn only when the lambda captures the shadowed decl explicitly. 7077 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7078 if (CaptureLoc.isInvalid()) 7079 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7080 } else { 7081 // Remember that this was shadowed so we can avoid the warning if the 7082 // shadowed decl isn't captured and the warning settings allow it. 7083 cast<LambdaScopeInfo>(getCurFunction()) 7084 ->ShadowingDecls.push_back( 7085 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7086 return; 7087 } 7088 } 7089 7090 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7091 // A variable can't shadow a local variable in an enclosing scope, if 7092 // they are separated by a non-capturing declaration context. 7093 for (DeclContext *ParentDC = NewDC; 7094 ParentDC && !ParentDC->Equals(OldDC); 7095 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7096 // Only block literals, captured statements, and lambda expressions 7097 // can capture; other scopes don't. 7098 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7099 !isLambdaCallOperator(ParentDC)) { 7100 return; 7101 } 7102 } 7103 } 7104 } 7105 } 7106 7107 // Only warn about certain kinds of shadowing for class members. 7108 if (NewDC && NewDC->isRecord()) { 7109 // In particular, don't warn about shadowing non-class members. 7110 if (!OldDC->isRecord()) 7111 return; 7112 7113 // TODO: should we warn about static data members shadowing 7114 // static data members from base classes? 7115 7116 // TODO: don't diagnose for inaccessible shadowed members. 7117 // This is hard to do perfectly because we might friend the 7118 // shadowing context, but that's just a false negative. 7119 } 7120 7121 7122 DeclarationName Name = R.getLookupName(); 7123 7124 // Emit warning and note. 7125 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7126 return; 7127 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7128 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7129 if (!CaptureLoc.isInvalid()) 7130 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7131 << Name << /*explicitly*/ 1; 7132 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7133 } 7134 7135 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7136 /// when these variables are captured by the lambda. 7137 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7138 for (const auto &Shadow : LSI->ShadowingDecls) { 7139 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7140 // Try to avoid the warning when the shadowed decl isn't captured. 7141 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7142 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7143 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7144 ? diag::warn_decl_shadow_uncaptured_local 7145 : diag::warn_decl_shadow) 7146 << Shadow.VD->getDeclName() 7147 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7148 if (!CaptureLoc.isInvalid()) 7149 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7150 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7151 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7152 } 7153 } 7154 7155 /// \brief Check -Wshadow without the advantage of a previous lookup. 7156 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7157 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7158 return; 7159 7160 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7161 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7162 LookupName(R, S); 7163 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7164 CheckShadow(D, ShadowedDecl, R); 7165 } 7166 7167 /// Check if 'E', which is an expression that is about to be modified, refers 7168 /// to a constructor parameter that shadows a field. 7169 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7170 // Quickly ignore expressions that can't be shadowing ctor parameters. 7171 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7172 return; 7173 E = E->IgnoreParenImpCasts(); 7174 auto *DRE = dyn_cast<DeclRefExpr>(E); 7175 if (!DRE) 7176 return; 7177 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7178 auto I = ShadowingDecls.find(D); 7179 if (I == ShadowingDecls.end()) 7180 return; 7181 const NamedDecl *ShadowedDecl = I->second; 7182 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7183 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7184 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7185 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7186 7187 // Avoid issuing multiple warnings about the same decl. 7188 ShadowingDecls.erase(I); 7189 } 7190 7191 /// Check for conflict between this global or extern "C" declaration and 7192 /// previous global or extern "C" declarations. This is only used in C++. 7193 template<typename T> 7194 static bool checkGlobalOrExternCConflict( 7195 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7196 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7197 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7198 7199 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7200 // The common case: this global doesn't conflict with any extern "C" 7201 // declaration. 7202 return false; 7203 } 7204 7205 if (Prev) { 7206 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7207 // Both the old and new declarations have C language linkage. This is a 7208 // redeclaration. 7209 Previous.clear(); 7210 Previous.addDecl(Prev); 7211 return true; 7212 } 7213 7214 // This is a global, non-extern "C" declaration, and there is a previous 7215 // non-global extern "C" declaration. Diagnose if this is a variable 7216 // declaration. 7217 if (!isa<VarDecl>(ND)) 7218 return false; 7219 } else { 7220 // The declaration is extern "C". Check for any declaration in the 7221 // translation unit which might conflict. 7222 if (IsGlobal) { 7223 // We have already performed the lookup into the translation unit. 7224 IsGlobal = false; 7225 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7226 I != E; ++I) { 7227 if (isa<VarDecl>(*I)) { 7228 Prev = *I; 7229 break; 7230 } 7231 } 7232 } else { 7233 DeclContext::lookup_result R = 7234 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7235 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7236 I != E; ++I) { 7237 if (isa<VarDecl>(*I)) { 7238 Prev = *I; 7239 break; 7240 } 7241 // FIXME: If we have any other entity with this name in global scope, 7242 // the declaration is ill-formed, but that is a defect: it breaks the 7243 // 'stat' hack, for instance. Only variables can have mangled name 7244 // clashes with extern "C" declarations, so only they deserve a 7245 // diagnostic. 7246 } 7247 } 7248 7249 if (!Prev) 7250 return false; 7251 } 7252 7253 // Use the first declaration's location to ensure we point at something which 7254 // is lexically inside an extern "C" linkage-spec. 7255 assert(Prev && "should have found a previous declaration to diagnose"); 7256 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7257 Prev = FD->getFirstDecl(); 7258 else 7259 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7260 7261 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7262 << IsGlobal << ND; 7263 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7264 << IsGlobal; 7265 return false; 7266 } 7267 7268 /// Apply special rules for handling extern "C" declarations. Returns \c true 7269 /// if we have found that this is a redeclaration of some prior entity. 7270 /// 7271 /// Per C++ [dcl.link]p6: 7272 /// Two declarations [for a function or variable] with C language linkage 7273 /// with the same name that appear in different scopes refer to the same 7274 /// [entity]. An entity with C language linkage shall not be declared with 7275 /// the same name as an entity in global scope. 7276 template<typename T> 7277 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7278 LookupResult &Previous) { 7279 if (!S.getLangOpts().CPlusPlus) { 7280 // In C, when declaring a global variable, look for a corresponding 'extern' 7281 // variable declared in function scope. We don't need this in C++, because 7282 // we find local extern decls in the surrounding file-scope DeclContext. 7283 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7284 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7285 Previous.clear(); 7286 Previous.addDecl(Prev); 7287 return true; 7288 } 7289 } 7290 return false; 7291 } 7292 7293 // A declaration in the translation unit can conflict with an extern "C" 7294 // declaration. 7295 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7296 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7297 7298 // An extern "C" declaration can conflict with a declaration in the 7299 // translation unit or can be a redeclaration of an extern "C" declaration 7300 // in another scope. 7301 if (isIncompleteDeclExternC(S,ND)) 7302 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7303 7304 // Neither global nor extern "C": nothing to do. 7305 return false; 7306 } 7307 7308 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7309 // If the decl is already known invalid, don't check it. 7310 if (NewVD->isInvalidDecl()) 7311 return; 7312 7313 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7314 QualType T = TInfo->getType(); 7315 7316 // Defer checking an 'auto' type until its initializer is attached. 7317 if (T->isUndeducedType()) 7318 return; 7319 7320 if (NewVD->hasAttrs()) 7321 CheckAlignasUnderalignment(NewVD); 7322 7323 if (T->isObjCObjectType()) { 7324 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7325 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7326 T = Context.getObjCObjectPointerType(T); 7327 NewVD->setType(T); 7328 } 7329 7330 // Emit an error if an address space was applied to decl with local storage. 7331 // This includes arrays of objects with address space qualifiers, but not 7332 // automatic variables that point to other address spaces. 7333 // ISO/IEC TR 18037 S5.1.2 7334 if (!getLangOpts().OpenCL 7335 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 7336 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7337 NewVD->setInvalidDecl(); 7338 return; 7339 } 7340 7341 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7342 // scope. 7343 if (getLangOpts().OpenCLVersion == 120 && 7344 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7345 NewVD->isStaticLocal()) { 7346 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7347 NewVD->setInvalidDecl(); 7348 return; 7349 } 7350 7351 if (getLangOpts().OpenCL) { 7352 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7353 if (NewVD->hasAttr<BlocksAttr>()) { 7354 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7355 return; 7356 } 7357 7358 if (T->isBlockPointerType()) { 7359 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7360 // can't use 'extern' storage class. 7361 if (!T.isConstQualified()) { 7362 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7363 << 0 /*const*/; 7364 NewVD->setInvalidDecl(); 7365 return; 7366 } 7367 if (NewVD->hasExternalStorage()) { 7368 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7369 NewVD->setInvalidDecl(); 7370 return; 7371 } 7372 } 7373 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7374 // __constant address space. 7375 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7376 // variables inside a function can also be declared in the global 7377 // address space. 7378 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7379 NewVD->hasExternalStorage()) { 7380 if (!T->isSamplerT() && 7381 !(T.getAddressSpace() == LangAS::opencl_constant || 7382 (T.getAddressSpace() == LangAS::opencl_global && 7383 getLangOpts().OpenCLVersion == 200))) { 7384 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7385 if (getLangOpts().OpenCLVersion == 200) 7386 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7387 << Scope << "global or constant"; 7388 else 7389 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7390 << Scope << "constant"; 7391 NewVD->setInvalidDecl(); 7392 return; 7393 } 7394 } else { 7395 if (T.getAddressSpace() == LangAS::opencl_global) { 7396 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7397 << 1 /*is any function*/ << "global"; 7398 NewVD->setInvalidDecl(); 7399 return; 7400 } 7401 if (T.getAddressSpace() == LangAS::opencl_constant || 7402 T.getAddressSpace() == LangAS::opencl_local) { 7403 FunctionDecl *FD = getCurFunctionDecl(); 7404 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7405 // in functions. 7406 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7407 if (T.getAddressSpace() == LangAS::opencl_constant) 7408 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7409 << 0 /*non-kernel only*/ << "constant"; 7410 else 7411 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7412 << 0 /*non-kernel only*/ << "local"; 7413 NewVD->setInvalidDecl(); 7414 return; 7415 } 7416 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7417 // in the outermost scope of a kernel function. 7418 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7419 if (!getCurScope()->isFunctionScope()) { 7420 if (T.getAddressSpace() == LangAS::opencl_constant) 7421 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7422 << "constant"; 7423 else 7424 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7425 << "local"; 7426 NewVD->setInvalidDecl(); 7427 return; 7428 } 7429 } 7430 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7431 // Do not allow other address spaces on automatic variable. 7432 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7433 NewVD->setInvalidDecl(); 7434 return; 7435 } 7436 } 7437 } 7438 7439 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7440 && !NewVD->hasAttr<BlocksAttr>()) { 7441 if (getLangOpts().getGC() != LangOptions::NonGC) 7442 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7443 else { 7444 assert(!getLangOpts().ObjCAutoRefCount); 7445 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7446 } 7447 } 7448 7449 bool isVM = T->isVariablyModifiedType(); 7450 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7451 NewVD->hasAttr<BlocksAttr>()) 7452 getCurFunction()->setHasBranchProtectedScope(); 7453 7454 if ((isVM && NewVD->hasLinkage()) || 7455 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7456 bool SizeIsNegative; 7457 llvm::APSInt Oversized; 7458 TypeSourceInfo *FixedTInfo = 7459 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7460 SizeIsNegative, Oversized); 7461 if (!FixedTInfo && T->isVariableArrayType()) { 7462 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7463 // FIXME: This won't give the correct result for 7464 // int a[10][n]; 7465 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7466 7467 if (NewVD->isFileVarDecl()) 7468 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7469 << SizeRange; 7470 else if (NewVD->isStaticLocal()) 7471 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7472 << SizeRange; 7473 else 7474 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7475 << SizeRange; 7476 NewVD->setInvalidDecl(); 7477 return; 7478 } 7479 7480 if (!FixedTInfo) { 7481 if (NewVD->isFileVarDecl()) 7482 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7483 else 7484 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7485 NewVD->setInvalidDecl(); 7486 return; 7487 } 7488 7489 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7490 NewVD->setType(FixedTInfo->getType()); 7491 NewVD->setTypeSourceInfo(FixedTInfo); 7492 } 7493 7494 if (T->isVoidType()) { 7495 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7496 // of objects and functions. 7497 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7498 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7499 << T; 7500 NewVD->setInvalidDecl(); 7501 return; 7502 } 7503 } 7504 7505 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7506 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7507 NewVD->setInvalidDecl(); 7508 return; 7509 } 7510 7511 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7512 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7513 NewVD->setInvalidDecl(); 7514 return; 7515 } 7516 7517 if (NewVD->isConstexpr() && !T->isDependentType() && 7518 RequireLiteralType(NewVD->getLocation(), T, 7519 diag::err_constexpr_var_non_literal)) { 7520 NewVD->setInvalidDecl(); 7521 return; 7522 } 7523 } 7524 7525 /// \brief Perform semantic checking on a newly-created variable 7526 /// declaration. 7527 /// 7528 /// This routine performs all of the type-checking required for a 7529 /// variable declaration once it has been built. It is used both to 7530 /// check variables after they have been parsed and their declarators 7531 /// have been translated into a declaration, and to check variables 7532 /// that have been instantiated from a template. 7533 /// 7534 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7535 /// 7536 /// Returns true if the variable declaration is a redeclaration. 7537 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7538 CheckVariableDeclarationType(NewVD); 7539 7540 // If the decl is already known invalid, don't check it. 7541 if (NewVD->isInvalidDecl()) 7542 return false; 7543 7544 // If we did not find anything by this name, look for a non-visible 7545 // extern "C" declaration with the same name. 7546 if (Previous.empty() && 7547 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7548 Previous.setShadowed(); 7549 7550 if (!Previous.empty()) { 7551 MergeVarDecl(NewVD, Previous); 7552 return true; 7553 } 7554 return false; 7555 } 7556 7557 namespace { 7558 struct FindOverriddenMethod { 7559 Sema *S; 7560 CXXMethodDecl *Method; 7561 7562 /// Member lookup function that determines whether a given C++ 7563 /// method overrides a method in a base class, to be used with 7564 /// CXXRecordDecl::lookupInBases(). 7565 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7566 RecordDecl *BaseRecord = 7567 Specifier->getType()->getAs<RecordType>()->getDecl(); 7568 7569 DeclarationName Name = Method->getDeclName(); 7570 7571 // FIXME: Do we care about other names here too? 7572 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7573 // We really want to find the base class destructor here. 7574 QualType T = S->Context.getTypeDeclType(BaseRecord); 7575 CanQualType CT = S->Context.getCanonicalType(T); 7576 7577 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7578 } 7579 7580 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7581 Path.Decls = Path.Decls.slice(1)) { 7582 NamedDecl *D = Path.Decls.front(); 7583 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7584 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7585 return true; 7586 } 7587 } 7588 7589 return false; 7590 } 7591 }; 7592 7593 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7594 } // end anonymous namespace 7595 7596 /// \brief Report an error regarding overriding, along with any relevant 7597 /// overriden methods. 7598 /// 7599 /// \param DiagID the primary error to report. 7600 /// \param MD the overriding method. 7601 /// \param OEK which overrides to include as notes. 7602 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7603 OverrideErrorKind OEK = OEK_All) { 7604 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7605 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 7606 E = MD->end_overridden_methods(); 7607 I != E; ++I) { 7608 // This check (& the OEK parameter) could be replaced by a predicate, but 7609 // without lambdas that would be overkill. This is still nicer than writing 7610 // out the diag loop 3 times. 7611 if ((OEK == OEK_All) || 7612 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 7613 (OEK == OEK_Deleted && (*I)->isDeleted())) 7614 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 7615 } 7616 } 7617 7618 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7619 /// and if so, check that it's a valid override and remember it. 7620 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7621 // Look for methods in base classes that this method might override. 7622 CXXBasePaths Paths; 7623 FindOverriddenMethod FOM; 7624 FOM.Method = MD; 7625 FOM.S = this; 7626 bool hasDeletedOverridenMethods = false; 7627 bool hasNonDeletedOverridenMethods = false; 7628 bool AddedAny = false; 7629 if (DC->lookupInBases(FOM, Paths)) { 7630 for (auto *I : Paths.found_decls()) { 7631 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7632 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7633 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7634 !CheckOverridingFunctionAttributes(MD, OldMD) && 7635 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7636 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7637 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7638 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7639 AddedAny = true; 7640 } 7641 } 7642 } 7643 } 7644 7645 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7646 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7647 } 7648 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7649 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7650 } 7651 7652 return AddedAny; 7653 } 7654 7655 namespace { 7656 // Struct for holding all of the extra arguments needed by 7657 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7658 struct ActOnFDArgs { 7659 Scope *S; 7660 Declarator &D; 7661 MultiTemplateParamsArg TemplateParamLists; 7662 bool AddToScope; 7663 }; 7664 } // end anonymous namespace 7665 7666 namespace { 7667 7668 // Callback to only accept typo corrections that have a non-zero edit distance. 7669 // Also only accept corrections that have the same parent decl. 7670 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7671 public: 7672 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7673 CXXRecordDecl *Parent) 7674 : Context(Context), OriginalFD(TypoFD), 7675 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7676 7677 bool ValidateCandidate(const TypoCorrection &candidate) override { 7678 if (candidate.getEditDistance() == 0) 7679 return false; 7680 7681 SmallVector<unsigned, 1> MismatchedParams; 7682 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7683 CDeclEnd = candidate.end(); 7684 CDecl != CDeclEnd; ++CDecl) { 7685 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7686 7687 if (FD && !FD->hasBody() && 7688 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7689 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7690 CXXRecordDecl *Parent = MD->getParent(); 7691 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7692 return true; 7693 } else if (!ExpectedParent) { 7694 return true; 7695 } 7696 } 7697 } 7698 7699 return false; 7700 } 7701 7702 private: 7703 ASTContext &Context; 7704 FunctionDecl *OriginalFD; 7705 CXXRecordDecl *ExpectedParent; 7706 }; 7707 7708 } // end anonymous namespace 7709 7710 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7711 TypoCorrectedFunctionDefinitions.insert(F); 7712 } 7713 7714 /// \brief Generate diagnostics for an invalid function redeclaration. 7715 /// 7716 /// This routine handles generating the diagnostic messages for an invalid 7717 /// function redeclaration, including finding possible similar declarations 7718 /// or performing typo correction if there are no previous declarations with 7719 /// the same name. 7720 /// 7721 /// Returns a NamedDecl iff typo correction was performed and substituting in 7722 /// the new declaration name does not cause new errors. 7723 static NamedDecl *DiagnoseInvalidRedeclaration( 7724 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7725 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7726 DeclarationName Name = NewFD->getDeclName(); 7727 DeclContext *NewDC = NewFD->getDeclContext(); 7728 SmallVector<unsigned, 1> MismatchedParams; 7729 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7730 TypoCorrection Correction; 7731 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7732 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7733 : diag::err_member_decl_does_not_match; 7734 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7735 IsLocalFriend ? Sema::LookupLocalFriendName 7736 : Sema::LookupOrdinaryName, 7737 Sema::ForVisibleRedeclaration); 7738 7739 NewFD->setInvalidDecl(); 7740 if (IsLocalFriend) 7741 SemaRef.LookupName(Prev, S); 7742 else 7743 SemaRef.LookupQualifiedName(Prev, NewDC); 7744 assert(!Prev.isAmbiguous() && 7745 "Cannot have an ambiguity in previous-declaration lookup"); 7746 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7747 if (!Prev.empty()) { 7748 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7749 Func != FuncEnd; ++Func) { 7750 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7751 if (FD && 7752 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7753 // Add 1 to the index so that 0 can mean the mismatch didn't 7754 // involve a parameter 7755 unsigned ParamNum = 7756 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7757 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7758 } 7759 } 7760 // If the qualified name lookup yielded nothing, try typo correction 7761 } else if ((Correction = SemaRef.CorrectTypo( 7762 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7763 &ExtraArgs.D.getCXXScopeSpec(), 7764 llvm::make_unique<DifferentNameValidatorCCC>( 7765 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7766 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7767 // Set up everything for the call to ActOnFunctionDeclarator 7768 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7769 ExtraArgs.D.getIdentifierLoc()); 7770 Previous.clear(); 7771 Previous.setLookupName(Correction.getCorrection()); 7772 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7773 CDeclEnd = Correction.end(); 7774 CDecl != CDeclEnd; ++CDecl) { 7775 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7776 if (FD && !FD->hasBody() && 7777 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7778 Previous.addDecl(FD); 7779 } 7780 } 7781 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7782 7783 NamedDecl *Result; 7784 // Retry building the function declaration with the new previous 7785 // declarations, and with errors suppressed. 7786 { 7787 // Trap errors. 7788 Sema::SFINAETrap Trap(SemaRef); 7789 7790 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7791 // pieces need to verify the typo-corrected C++ declaration and hopefully 7792 // eliminate the need for the parameter pack ExtraArgs. 7793 Result = SemaRef.ActOnFunctionDeclarator( 7794 ExtraArgs.S, ExtraArgs.D, 7795 Correction.getCorrectionDecl()->getDeclContext(), 7796 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7797 ExtraArgs.AddToScope); 7798 7799 if (Trap.hasErrorOccurred()) 7800 Result = nullptr; 7801 } 7802 7803 if (Result) { 7804 // Determine which correction we picked. 7805 Decl *Canonical = Result->getCanonicalDecl(); 7806 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7807 I != E; ++I) 7808 if ((*I)->getCanonicalDecl() == Canonical) 7809 Correction.setCorrectionDecl(*I); 7810 7811 // Let Sema know about the correction. 7812 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7813 SemaRef.diagnoseTypo( 7814 Correction, 7815 SemaRef.PDiag(IsLocalFriend 7816 ? diag::err_no_matching_local_friend_suggest 7817 : diag::err_member_decl_does_not_match_suggest) 7818 << Name << NewDC << IsDefinition); 7819 return Result; 7820 } 7821 7822 // Pretend the typo correction never occurred 7823 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7824 ExtraArgs.D.getIdentifierLoc()); 7825 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7826 Previous.clear(); 7827 Previous.setLookupName(Name); 7828 } 7829 7830 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7831 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7832 7833 bool NewFDisConst = false; 7834 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7835 NewFDisConst = NewMD->isConst(); 7836 7837 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7838 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7839 NearMatch != NearMatchEnd; ++NearMatch) { 7840 FunctionDecl *FD = NearMatch->first; 7841 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7842 bool FDisConst = MD && MD->isConst(); 7843 bool IsMember = MD || !IsLocalFriend; 7844 7845 // FIXME: These notes are poorly worded for the local friend case. 7846 if (unsigned Idx = NearMatch->second) { 7847 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7848 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7849 if (Loc.isInvalid()) Loc = FD->getLocation(); 7850 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7851 : diag::note_local_decl_close_param_match) 7852 << Idx << FDParam->getType() 7853 << NewFD->getParamDecl(Idx - 1)->getType(); 7854 } else if (FDisConst != NewFDisConst) { 7855 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7856 << NewFDisConst << FD->getSourceRange().getEnd(); 7857 } else 7858 SemaRef.Diag(FD->getLocation(), 7859 IsMember ? diag::note_member_def_close_match 7860 : diag::note_local_decl_close_match); 7861 } 7862 return nullptr; 7863 } 7864 7865 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7866 switch (D.getDeclSpec().getStorageClassSpec()) { 7867 default: llvm_unreachable("Unknown storage class!"); 7868 case DeclSpec::SCS_auto: 7869 case DeclSpec::SCS_register: 7870 case DeclSpec::SCS_mutable: 7871 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7872 diag::err_typecheck_sclass_func); 7873 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7874 D.setInvalidType(); 7875 break; 7876 case DeclSpec::SCS_unspecified: break; 7877 case DeclSpec::SCS_extern: 7878 if (D.getDeclSpec().isExternInLinkageSpec()) 7879 return SC_None; 7880 return SC_Extern; 7881 case DeclSpec::SCS_static: { 7882 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7883 // C99 6.7.1p5: 7884 // The declaration of an identifier for a function that has 7885 // block scope shall have no explicit storage-class specifier 7886 // other than extern 7887 // See also (C++ [dcl.stc]p4). 7888 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7889 diag::err_static_block_func); 7890 break; 7891 } else 7892 return SC_Static; 7893 } 7894 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7895 } 7896 7897 // No explicit storage class has already been returned 7898 return SC_None; 7899 } 7900 7901 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7902 DeclContext *DC, QualType &R, 7903 TypeSourceInfo *TInfo, 7904 StorageClass SC, 7905 bool &IsVirtualOkay) { 7906 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7907 DeclarationName Name = NameInfo.getName(); 7908 7909 FunctionDecl *NewFD = nullptr; 7910 bool isInline = D.getDeclSpec().isInlineSpecified(); 7911 7912 if (!SemaRef.getLangOpts().CPlusPlus) { 7913 // Determine whether the function was written with a 7914 // prototype. This true when: 7915 // - there is a prototype in the declarator, or 7916 // - the type R of the function is some kind of typedef or other non- 7917 // attributed reference to a type name (which eventually refers to a 7918 // function type). 7919 bool HasPrototype = 7920 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7921 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7922 7923 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7924 D.getLocStart(), NameInfo, R, 7925 TInfo, SC, isInline, 7926 HasPrototype, false); 7927 if (D.isInvalidType()) 7928 NewFD->setInvalidDecl(); 7929 7930 return NewFD; 7931 } 7932 7933 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7934 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7935 7936 // Check that the return type is not an abstract class type. 7937 // For record types, this is done by the AbstractClassUsageDiagnoser once 7938 // the class has been completely parsed. 7939 if (!DC->isRecord() && 7940 SemaRef.RequireNonAbstractType( 7941 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7942 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7943 D.setInvalidType(); 7944 7945 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7946 // This is a C++ constructor declaration. 7947 assert(DC->isRecord() && 7948 "Constructors can only be declared in a member context"); 7949 7950 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7951 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7952 D.getLocStart(), NameInfo, 7953 R, TInfo, isExplicit, isInline, 7954 /*isImplicitlyDeclared=*/false, 7955 isConstexpr); 7956 7957 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7958 // This is a C++ destructor declaration. 7959 if (DC->isRecord()) { 7960 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7961 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7962 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7963 SemaRef.Context, Record, 7964 D.getLocStart(), 7965 NameInfo, R, TInfo, isInline, 7966 /*isImplicitlyDeclared=*/false); 7967 7968 // If the class is complete, then we now create the implicit exception 7969 // specification. If the class is incomplete or dependent, we can't do 7970 // it yet. 7971 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7972 Record->getDefinition() && !Record->isBeingDefined() && 7973 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7974 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7975 } 7976 7977 IsVirtualOkay = true; 7978 return NewDD; 7979 7980 } else { 7981 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7982 D.setInvalidType(); 7983 7984 // Create a FunctionDecl to satisfy the function definition parsing 7985 // code path. 7986 return FunctionDecl::Create(SemaRef.Context, DC, 7987 D.getLocStart(), 7988 D.getIdentifierLoc(), Name, R, TInfo, 7989 SC, isInline, 7990 /*hasPrototype=*/true, isConstexpr); 7991 } 7992 7993 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7994 if (!DC->isRecord()) { 7995 SemaRef.Diag(D.getIdentifierLoc(), 7996 diag::err_conv_function_not_member); 7997 return nullptr; 7998 } 7999 8000 SemaRef.CheckConversionDeclarator(D, R, SC); 8001 IsVirtualOkay = true; 8002 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 8003 D.getLocStart(), NameInfo, 8004 R, TInfo, isInline, isExplicit, 8005 isConstexpr, SourceLocation()); 8006 8007 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8008 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8009 8010 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 8011 isExplicit, NameInfo, R, TInfo, 8012 D.getLocEnd()); 8013 } else if (DC->isRecord()) { 8014 // If the name of the function is the same as the name of the record, 8015 // then this must be an invalid constructor that has a return type. 8016 // (The parser checks for a return type and makes the declarator a 8017 // constructor if it has no return type). 8018 if (Name.getAsIdentifierInfo() && 8019 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8020 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8021 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8022 << SourceRange(D.getIdentifierLoc()); 8023 return nullptr; 8024 } 8025 8026 // This is a C++ method declaration. 8027 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 8028 cast<CXXRecordDecl>(DC), 8029 D.getLocStart(), NameInfo, R, 8030 TInfo, SC, isInline, 8031 isConstexpr, SourceLocation()); 8032 IsVirtualOkay = !Ret->isStatic(); 8033 return Ret; 8034 } else { 8035 bool isFriend = 8036 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8037 if (!isFriend && SemaRef.CurContext->isRecord()) 8038 return nullptr; 8039 8040 // Determine whether the function was written with a 8041 // prototype. This true when: 8042 // - we're in C++ (where every function has a prototype), 8043 return FunctionDecl::Create(SemaRef.Context, DC, 8044 D.getLocStart(), 8045 NameInfo, R, TInfo, SC, isInline, 8046 true/*HasPrototype*/, isConstexpr); 8047 } 8048 } 8049 8050 enum OpenCLParamType { 8051 ValidKernelParam, 8052 PtrPtrKernelParam, 8053 PtrKernelParam, 8054 InvalidAddrSpacePtrKernelParam, 8055 InvalidKernelParam, 8056 RecordKernelParam 8057 }; 8058 8059 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8060 if (PT->isPointerType()) { 8061 QualType PointeeType = PT->getPointeeType(); 8062 if (PointeeType->isPointerType()) 8063 return PtrPtrKernelParam; 8064 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8065 PointeeType.getAddressSpace() == LangAS::opencl_private || 8066 PointeeType.getAddressSpace() == LangAS::Default) 8067 return InvalidAddrSpacePtrKernelParam; 8068 return PtrKernelParam; 8069 } 8070 8071 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 8072 // be used as builtin types. 8073 8074 if (PT->isImageType()) 8075 return PtrKernelParam; 8076 8077 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8078 return InvalidKernelParam; 8079 8080 // OpenCL extension spec v1.2 s9.5: 8081 // This extension adds support for half scalar and vector types as built-in 8082 // types that can be used for arithmetic operations, conversions etc. 8083 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8084 return InvalidKernelParam; 8085 8086 if (PT->isRecordType()) 8087 return RecordKernelParam; 8088 8089 return ValidKernelParam; 8090 } 8091 8092 static void checkIsValidOpenCLKernelParameter( 8093 Sema &S, 8094 Declarator &D, 8095 ParmVarDecl *Param, 8096 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8097 QualType PT = Param->getType(); 8098 8099 // Cache the valid types we encounter to avoid rechecking structs that are 8100 // used again 8101 if (ValidTypes.count(PT.getTypePtr())) 8102 return; 8103 8104 switch (getOpenCLKernelParameterType(S, PT)) { 8105 case PtrPtrKernelParam: 8106 // OpenCL v1.2 s6.9.a: 8107 // A kernel function argument cannot be declared as a 8108 // pointer to a pointer type. 8109 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8110 D.setInvalidType(); 8111 return; 8112 8113 case InvalidAddrSpacePtrKernelParam: 8114 // OpenCL v1.0 s6.5: 8115 // __kernel function arguments declared to be a pointer of a type can point 8116 // to one of the following address spaces only : __global, __local or 8117 // __constant. 8118 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8119 D.setInvalidType(); 8120 return; 8121 8122 // OpenCL v1.2 s6.9.k: 8123 // Arguments to kernel functions in a program cannot be declared with the 8124 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8125 // uintptr_t or a struct and/or union that contain fields declared to be 8126 // one of these built-in scalar types. 8127 8128 case InvalidKernelParam: 8129 // OpenCL v1.2 s6.8 n: 8130 // A kernel function argument cannot be declared 8131 // of event_t type. 8132 // Do not diagnose half type since it is diagnosed as invalid argument 8133 // type for any function elsewhere. 8134 if (!PT->isHalfType()) 8135 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8136 D.setInvalidType(); 8137 return; 8138 8139 case PtrKernelParam: 8140 case ValidKernelParam: 8141 ValidTypes.insert(PT.getTypePtr()); 8142 return; 8143 8144 case RecordKernelParam: 8145 break; 8146 } 8147 8148 // Track nested structs we will inspect 8149 SmallVector<const Decl *, 4> VisitStack; 8150 8151 // Track where we are in the nested structs. Items will migrate from 8152 // VisitStack to HistoryStack as we do the DFS for bad field. 8153 SmallVector<const FieldDecl *, 4> HistoryStack; 8154 HistoryStack.push_back(nullptr); 8155 8156 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8157 VisitStack.push_back(PD); 8158 8159 assert(VisitStack.back() && "First decl null?"); 8160 8161 do { 8162 const Decl *Next = VisitStack.pop_back_val(); 8163 if (!Next) { 8164 assert(!HistoryStack.empty()); 8165 // Found a marker, we have gone up a level 8166 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8167 ValidTypes.insert(Hist->getType().getTypePtr()); 8168 8169 continue; 8170 } 8171 8172 // Adds everything except the original parameter declaration (which is not a 8173 // field itself) to the history stack. 8174 const RecordDecl *RD; 8175 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8176 HistoryStack.push_back(Field); 8177 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8178 } else { 8179 RD = cast<RecordDecl>(Next); 8180 } 8181 8182 // Add a null marker so we know when we've gone back up a level 8183 VisitStack.push_back(nullptr); 8184 8185 for (const auto *FD : RD->fields()) { 8186 QualType QT = FD->getType(); 8187 8188 if (ValidTypes.count(QT.getTypePtr())) 8189 continue; 8190 8191 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8192 if (ParamType == ValidKernelParam) 8193 continue; 8194 8195 if (ParamType == RecordKernelParam) { 8196 VisitStack.push_back(FD); 8197 continue; 8198 } 8199 8200 // OpenCL v1.2 s6.9.p: 8201 // Arguments to kernel functions that are declared to be a struct or union 8202 // do not allow OpenCL objects to be passed as elements of the struct or 8203 // union. 8204 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8205 ParamType == InvalidAddrSpacePtrKernelParam) { 8206 S.Diag(Param->getLocation(), 8207 diag::err_record_with_pointers_kernel_param) 8208 << PT->isUnionType() 8209 << PT; 8210 } else { 8211 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8212 } 8213 8214 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8215 << PD->getDeclName(); 8216 8217 // We have an error, now let's go back up through history and show where 8218 // the offending field came from 8219 for (ArrayRef<const FieldDecl *>::const_iterator 8220 I = HistoryStack.begin() + 1, 8221 E = HistoryStack.end(); 8222 I != E; ++I) { 8223 const FieldDecl *OuterField = *I; 8224 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8225 << OuterField->getType(); 8226 } 8227 8228 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8229 << QT->isPointerType() 8230 << QT; 8231 D.setInvalidType(); 8232 return; 8233 } 8234 } while (!VisitStack.empty()); 8235 } 8236 8237 /// Find the DeclContext in which a tag is implicitly declared if we see an 8238 /// elaborated type specifier in the specified context, and lookup finds 8239 /// nothing. 8240 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8241 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8242 DC = DC->getParent(); 8243 return DC; 8244 } 8245 8246 /// Find the Scope in which a tag is implicitly declared if we see an 8247 /// elaborated type specifier in the specified context, and lookup finds 8248 /// nothing. 8249 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8250 while (S->isClassScope() || 8251 (LangOpts.CPlusPlus && 8252 S->isFunctionPrototypeScope()) || 8253 ((S->getFlags() & Scope::DeclScope) == 0) || 8254 (S->getEntity() && S->getEntity()->isTransparentContext())) 8255 S = S->getParent(); 8256 return S; 8257 } 8258 8259 NamedDecl* 8260 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8261 TypeSourceInfo *TInfo, LookupResult &Previous, 8262 MultiTemplateParamsArg TemplateParamLists, 8263 bool &AddToScope) { 8264 QualType R = TInfo->getType(); 8265 8266 assert(R.getTypePtr()->isFunctionType()); 8267 8268 // TODO: consider using NameInfo for diagnostic. 8269 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8270 DeclarationName Name = NameInfo.getName(); 8271 StorageClass SC = getFunctionStorageClass(*this, D); 8272 8273 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8274 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8275 diag::err_invalid_thread) 8276 << DeclSpec::getSpecifierName(TSCS); 8277 8278 if (D.isFirstDeclarationOfMember()) 8279 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8280 D.getIdentifierLoc()); 8281 8282 bool isFriend = false; 8283 FunctionTemplateDecl *FunctionTemplate = nullptr; 8284 bool isMemberSpecialization = false; 8285 bool isFunctionTemplateSpecialization = false; 8286 8287 bool isDependentClassScopeExplicitSpecialization = false; 8288 bool HasExplicitTemplateArgs = false; 8289 TemplateArgumentListInfo TemplateArgs; 8290 8291 bool isVirtualOkay = false; 8292 8293 DeclContext *OriginalDC = DC; 8294 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8295 8296 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8297 isVirtualOkay); 8298 if (!NewFD) return nullptr; 8299 8300 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8301 NewFD->setTopLevelDeclInObjCContainer(); 8302 8303 // Set the lexical context. If this is a function-scope declaration, or has a 8304 // C++ scope specifier, or is the object of a friend declaration, the lexical 8305 // context will be different from the semantic context. 8306 NewFD->setLexicalDeclContext(CurContext); 8307 8308 if (IsLocalExternDecl) 8309 NewFD->setLocalExternDecl(); 8310 8311 if (getLangOpts().CPlusPlus) { 8312 bool isInline = D.getDeclSpec().isInlineSpecified(); 8313 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8314 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8315 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8316 bool isConcept = D.getDeclSpec().isConceptSpecified(); 8317 isFriend = D.getDeclSpec().isFriendSpecified(); 8318 if (isFriend && !isInline && D.isFunctionDefinition()) { 8319 // C++ [class.friend]p5 8320 // A function can be defined in a friend declaration of a 8321 // class . . . . Such a function is implicitly inline. 8322 NewFD->setImplicitlyInline(); 8323 } 8324 8325 // If this is a method defined in an __interface, and is not a constructor 8326 // or an overloaded operator, then set the pure flag (isVirtual will already 8327 // return true). 8328 if (const CXXRecordDecl *Parent = 8329 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8330 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8331 NewFD->setPure(true); 8332 8333 // C++ [class.union]p2 8334 // A union can have member functions, but not virtual functions. 8335 if (isVirtual && Parent->isUnion()) 8336 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8337 } 8338 8339 SetNestedNameSpecifier(NewFD, D); 8340 isMemberSpecialization = false; 8341 isFunctionTemplateSpecialization = false; 8342 if (D.isInvalidType()) 8343 NewFD->setInvalidDecl(); 8344 8345 // Match up the template parameter lists with the scope specifier, then 8346 // determine whether we have a template or a template specialization. 8347 bool Invalid = false; 8348 if (TemplateParameterList *TemplateParams = 8349 MatchTemplateParametersToScopeSpecifier( 8350 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8351 D.getCXXScopeSpec(), 8352 D.getName().getKind() == UnqualifiedId::IK_TemplateId 8353 ? D.getName().TemplateId 8354 : nullptr, 8355 TemplateParamLists, isFriend, isMemberSpecialization, 8356 Invalid)) { 8357 if (TemplateParams->size() > 0) { 8358 // This is a function template 8359 8360 // Check that we can declare a template here. 8361 if (CheckTemplateDeclScope(S, TemplateParams)) 8362 NewFD->setInvalidDecl(); 8363 8364 // A destructor cannot be a template. 8365 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8366 Diag(NewFD->getLocation(), diag::err_destructor_template); 8367 NewFD->setInvalidDecl(); 8368 } 8369 8370 // If we're adding a template to a dependent context, we may need to 8371 // rebuilding some of the types used within the template parameter list, 8372 // now that we know what the current instantiation is. 8373 if (DC->isDependentContext()) { 8374 ContextRAII SavedContext(*this, DC); 8375 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8376 Invalid = true; 8377 } 8378 8379 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8380 NewFD->getLocation(), 8381 Name, TemplateParams, 8382 NewFD); 8383 FunctionTemplate->setLexicalDeclContext(CurContext); 8384 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8385 8386 // For source fidelity, store the other template param lists. 8387 if (TemplateParamLists.size() > 1) { 8388 NewFD->setTemplateParameterListsInfo(Context, 8389 TemplateParamLists.drop_back(1)); 8390 } 8391 } else { 8392 // This is a function template specialization. 8393 isFunctionTemplateSpecialization = true; 8394 // For source fidelity, store all the template param lists. 8395 if (TemplateParamLists.size() > 0) 8396 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8397 8398 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8399 if (isFriend) { 8400 // We want to remove the "template<>", found here. 8401 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8402 8403 // If we remove the template<> and the name is not a 8404 // template-id, we're actually silently creating a problem: 8405 // the friend declaration will refer to an untemplated decl, 8406 // and clearly the user wants a template specialization. So 8407 // we need to insert '<>' after the name. 8408 SourceLocation InsertLoc; 8409 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 8410 InsertLoc = D.getName().getSourceRange().getEnd(); 8411 InsertLoc = getLocForEndOfToken(InsertLoc); 8412 } 8413 8414 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8415 << Name << RemoveRange 8416 << FixItHint::CreateRemoval(RemoveRange) 8417 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8418 } 8419 } 8420 } 8421 else { 8422 // All template param lists were matched against the scope specifier: 8423 // this is NOT (an explicit specialization of) a template. 8424 if (TemplateParamLists.size() > 0) 8425 // For source fidelity, store all the template param lists. 8426 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8427 } 8428 8429 if (Invalid) { 8430 NewFD->setInvalidDecl(); 8431 if (FunctionTemplate) 8432 FunctionTemplate->setInvalidDecl(); 8433 } 8434 8435 // C++ [dcl.fct.spec]p5: 8436 // The virtual specifier shall only be used in declarations of 8437 // nonstatic class member functions that appear within a 8438 // member-specification of a class declaration; see 10.3. 8439 // 8440 if (isVirtual && !NewFD->isInvalidDecl()) { 8441 if (!isVirtualOkay) { 8442 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8443 diag::err_virtual_non_function); 8444 } else if (!CurContext->isRecord()) { 8445 // 'virtual' was specified outside of the class. 8446 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8447 diag::err_virtual_out_of_class) 8448 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8449 } else if (NewFD->getDescribedFunctionTemplate()) { 8450 // C++ [temp.mem]p3: 8451 // A member function template shall not be virtual. 8452 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8453 diag::err_virtual_member_function_template) 8454 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8455 } else { 8456 // Okay: Add virtual to the method. 8457 NewFD->setVirtualAsWritten(true); 8458 } 8459 8460 if (getLangOpts().CPlusPlus14 && 8461 NewFD->getReturnType()->isUndeducedType()) 8462 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8463 } 8464 8465 if (getLangOpts().CPlusPlus14 && 8466 (NewFD->isDependentContext() || 8467 (isFriend && CurContext->isDependentContext())) && 8468 NewFD->getReturnType()->isUndeducedType()) { 8469 // If the function template is referenced directly (for instance, as a 8470 // member of the current instantiation), pretend it has a dependent type. 8471 // This is not really justified by the standard, but is the only sane 8472 // thing to do. 8473 // FIXME: For a friend function, we have not marked the function as being 8474 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8475 const FunctionProtoType *FPT = 8476 NewFD->getType()->castAs<FunctionProtoType>(); 8477 QualType Result = 8478 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8479 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8480 FPT->getExtProtoInfo())); 8481 } 8482 8483 // C++ [dcl.fct.spec]p3: 8484 // The inline specifier shall not appear on a block scope function 8485 // declaration. 8486 if (isInline && !NewFD->isInvalidDecl()) { 8487 if (CurContext->isFunctionOrMethod()) { 8488 // 'inline' is not allowed on block scope function declaration. 8489 Diag(D.getDeclSpec().getInlineSpecLoc(), 8490 diag::err_inline_declaration_block_scope) << Name 8491 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8492 } 8493 } 8494 8495 // C++ [dcl.fct.spec]p6: 8496 // The explicit specifier shall be used only in the declaration of a 8497 // constructor or conversion function within its class definition; 8498 // see 12.3.1 and 12.3.2. 8499 if (isExplicit && !NewFD->isInvalidDecl() && 8500 !isa<CXXDeductionGuideDecl>(NewFD)) { 8501 if (!CurContext->isRecord()) { 8502 // 'explicit' was specified outside of the class. 8503 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8504 diag::err_explicit_out_of_class) 8505 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8506 } else if (!isa<CXXConstructorDecl>(NewFD) && 8507 !isa<CXXConversionDecl>(NewFD)) { 8508 // 'explicit' was specified on a function that wasn't a constructor 8509 // or conversion function. 8510 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8511 diag::err_explicit_non_ctor_or_conv_function) 8512 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8513 } 8514 } 8515 8516 if (isConstexpr) { 8517 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8518 // are implicitly inline. 8519 NewFD->setImplicitlyInline(); 8520 8521 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8522 // be either constructors or to return a literal type. Therefore, 8523 // destructors cannot be declared constexpr. 8524 if (isa<CXXDestructorDecl>(NewFD)) 8525 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8526 } 8527 8528 if (isConcept) { 8529 // This is a function concept. 8530 if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate()) 8531 FTD->setConcept(); 8532 8533 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8534 // applied only to the definition of a function template [...] 8535 if (!D.isFunctionDefinition()) { 8536 Diag(D.getDeclSpec().getConceptSpecLoc(), 8537 diag::err_function_concept_not_defined); 8538 NewFD->setInvalidDecl(); 8539 } 8540 8541 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 8542 // have no exception-specification and is treated as if it were specified 8543 // with noexcept(true) (15.4). [...] 8544 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 8545 if (FPT->hasExceptionSpec()) { 8546 SourceRange Range; 8547 if (D.isFunctionDeclarator()) 8548 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 8549 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 8550 << FixItHint::CreateRemoval(Range); 8551 NewFD->setInvalidDecl(); 8552 } else { 8553 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 8554 } 8555 8556 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8557 // following restrictions: 8558 // - The declared return type shall have the type bool. 8559 if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) { 8560 Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret); 8561 NewFD->setInvalidDecl(); 8562 } 8563 8564 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 8565 // following restrictions: 8566 // - The declaration's parameter list shall be equivalent to an empty 8567 // parameter list. 8568 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 8569 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 8570 } 8571 8572 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 8573 // implicity defined to be a constexpr declaration (implicitly inline) 8574 NewFD->setImplicitlyInline(); 8575 8576 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 8577 // be declared with the thread_local, inline, friend, or constexpr 8578 // specifiers, [...] 8579 if (isInline) { 8580 Diag(D.getDeclSpec().getInlineSpecLoc(), 8581 diag::err_concept_decl_invalid_specifiers) 8582 << 1 << 1; 8583 NewFD->setInvalidDecl(true); 8584 } 8585 8586 if (isFriend) { 8587 Diag(D.getDeclSpec().getFriendSpecLoc(), 8588 diag::err_concept_decl_invalid_specifiers) 8589 << 1 << 2; 8590 NewFD->setInvalidDecl(true); 8591 } 8592 8593 if (isConstexpr) { 8594 Diag(D.getDeclSpec().getConstexprSpecLoc(), 8595 diag::err_concept_decl_invalid_specifiers) 8596 << 1 << 3; 8597 NewFD->setInvalidDecl(true); 8598 } 8599 8600 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 8601 // applied only to the definition of a function template or variable 8602 // template, declared in namespace scope. 8603 if (isFunctionTemplateSpecialization) { 8604 Diag(D.getDeclSpec().getConceptSpecLoc(), 8605 diag::err_concept_specified_specialization) << 1; 8606 NewFD->setInvalidDecl(true); 8607 return NewFD; 8608 } 8609 } 8610 8611 // If __module_private__ was specified, mark the function accordingly. 8612 if (D.getDeclSpec().isModulePrivateSpecified()) { 8613 if (isFunctionTemplateSpecialization) { 8614 SourceLocation ModulePrivateLoc 8615 = D.getDeclSpec().getModulePrivateSpecLoc(); 8616 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8617 << 0 8618 << FixItHint::CreateRemoval(ModulePrivateLoc); 8619 } else { 8620 NewFD->setModulePrivate(); 8621 if (FunctionTemplate) 8622 FunctionTemplate->setModulePrivate(); 8623 } 8624 } 8625 8626 if (isFriend) { 8627 if (FunctionTemplate) { 8628 FunctionTemplate->setObjectOfFriendDecl(); 8629 FunctionTemplate->setAccess(AS_public); 8630 } 8631 NewFD->setObjectOfFriendDecl(); 8632 NewFD->setAccess(AS_public); 8633 } 8634 8635 // If a function is defined as defaulted or deleted, mark it as such now. 8636 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8637 // definition kind to FDK_Definition. 8638 switch (D.getFunctionDefinitionKind()) { 8639 case FDK_Declaration: 8640 case FDK_Definition: 8641 break; 8642 8643 case FDK_Defaulted: 8644 NewFD->setDefaulted(); 8645 break; 8646 8647 case FDK_Deleted: 8648 NewFD->setDeletedAsWritten(); 8649 break; 8650 } 8651 8652 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8653 D.isFunctionDefinition()) { 8654 // C++ [class.mfct]p2: 8655 // A member function may be defined (8.4) in its class definition, in 8656 // which case it is an inline member function (7.1.2) 8657 NewFD->setImplicitlyInline(); 8658 } 8659 8660 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8661 !CurContext->isRecord()) { 8662 // C++ [class.static]p1: 8663 // A data or function member of a class may be declared static 8664 // in a class definition, in which case it is a static member of 8665 // the class. 8666 8667 // Complain about the 'static' specifier if it's on an out-of-line 8668 // member function definition. 8669 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8670 diag::err_static_out_of_line) 8671 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8672 } 8673 8674 // C++11 [except.spec]p15: 8675 // A deallocation function with no exception-specification is treated 8676 // as if it were specified with noexcept(true). 8677 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8678 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8679 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8680 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8681 NewFD->setType(Context.getFunctionType( 8682 FPT->getReturnType(), FPT->getParamTypes(), 8683 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8684 } 8685 8686 // Filter out previous declarations that don't match the scope. 8687 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8688 D.getCXXScopeSpec().isNotEmpty() || 8689 isMemberSpecialization || 8690 isFunctionTemplateSpecialization); 8691 8692 // Handle GNU asm-label extension (encoded as an attribute). 8693 if (Expr *E = (Expr*) D.getAsmLabel()) { 8694 // The parser guarantees this is a string. 8695 StringLiteral *SE = cast<StringLiteral>(E); 8696 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8697 SE->getString(), 0)); 8698 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8699 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8700 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8701 if (I != ExtnameUndeclaredIdentifiers.end()) { 8702 if (isDeclExternC(NewFD)) { 8703 NewFD->addAttr(I->second); 8704 ExtnameUndeclaredIdentifiers.erase(I); 8705 } else 8706 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8707 << /*Variable*/0 << NewFD; 8708 } 8709 } 8710 8711 // Copy the parameter declarations from the declarator D to the function 8712 // declaration NewFD, if they are available. First scavenge them into Params. 8713 SmallVector<ParmVarDecl*, 16> Params; 8714 unsigned FTIIdx; 8715 if (D.isFunctionDeclarator(FTIIdx)) { 8716 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8717 8718 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8719 // function that takes no arguments, not a function that takes a 8720 // single void argument. 8721 // We let through "const void" here because Sema::GetTypeForDeclarator 8722 // already checks for that case. 8723 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8724 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8725 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8726 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8727 Param->setDeclContext(NewFD); 8728 Params.push_back(Param); 8729 8730 if (Param->isInvalidDecl()) 8731 NewFD->setInvalidDecl(); 8732 } 8733 } 8734 8735 if (!getLangOpts().CPlusPlus) { 8736 // In C, find all the tag declarations from the prototype and move them 8737 // into the function DeclContext. Remove them from the surrounding tag 8738 // injection context of the function, which is typically but not always 8739 // the TU. 8740 DeclContext *PrototypeTagContext = 8741 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8742 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8743 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8744 8745 // We don't want to reparent enumerators. Look at their parent enum 8746 // instead. 8747 if (!TD) { 8748 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8749 TD = cast<EnumDecl>(ECD->getDeclContext()); 8750 } 8751 if (!TD) 8752 continue; 8753 DeclContext *TagDC = TD->getLexicalDeclContext(); 8754 if (!TagDC->containsDecl(TD)) 8755 continue; 8756 TagDC->removeDecl(TD); 8757 TD->setDeclContext(NewFD); 8758 NewFD->addDecl(TD); 8759 8760 // Preserve the lexical DeclContext if it is not the surrounding tag 8761 // injection context of the FD. In this example, the semantic context of 8762 // E will be f and the lexical context will be S, while both the 8763 // semantic and lexical contexts of S will be f: 8764 // void f(struct S { enum E { a } f; } s); 8765 if (TagDC != PrototypeTagContext) 8766 TD->setLexicalDeclContext(TagDC); 8767 } 8768 } 8769 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8770 // When we're declaring a function with a typedef, typeof, etc as in the 8771 // following example, we'll need to synthesize (unnamed) 8772 // parameters for use in the declaration. 8773 // 8774 // @code 8775 // typedef void fn(int); 8776 // fn f; 8777 // @endcode 8778 8779 // Synthesize a parameter for each argument type. 8780 for (const auto &AI : FT->param_types()) { 8781 ParmVarDecl *Param = 8782 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8783 Param->setScopeInfo(0, Params.size()); 8784 Params.push_back(Param); 8785 } 8786 } else { 8787 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8788 "Should not need args for typedef of non-prototype fn"); 8789 } 8790 8791 // Finally, we know we have the right number of parameters, install them. 8792 NewFD->setParams(Params); 8793 8794 if (D.getDeclSpec().isNoreturnSpecified()) 8795 NewFD->addAttr( 8796 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8797 Context, 0)); 8798 8799 // Functions returning a variably modified type violate C99 6.7.5.2p2 8800 // because all functions have linkage. 8801 if (!NewFD->isInvalidDecl() && 8802 NewFD->getReturnType()->isVariablyModifiedType()) { 8803 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8804 NewFD->setInvalidDecl(); 8805 } 8806 8807 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8808 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8809 !NewFD->hasAttr<SectionAttr>()) { 8810 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8811 PragmaClangTextSection.SectionName, 8812 PragmaClangTextSection.PragmaLocation)); 8813 } 8814 8815 // Apply an implicit SectionAttr if #pragma code_seg is active. 8816 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8817 !NewFD->hasAttr<SectionAttr>()) { 8818 NewFD->addAttr( 8819 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8820 CodeSegStack.CurrentValue->getString(), 8821 CodeSegStack.CurrentPragmaLocation)); 8822 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8823 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8824 ASTContext::PSF_Read, 8825 NewFD)) 8826 NewFD->dropAttr<SectionAttr>(); 8827 } 8828 8829 // Handle attributes. 8830 ProcessDeclAttributes(S, NewFD, D); 8831 8832 if (getLangOpts().OpenCL) { 8833 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8834 // type declaration will generate a compilation error. 8835 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 8836 if (AddressSpace != LangAS::Default) { 8837 Diag(NewFD->getLocation(), 8838 diag::err_opencl_return_value_with_address_space); 8839 NewFD->setInvalidDecl(); 8840 } 8841 } 8842 8843 if (!getLangOpts().CPlusPlus) { 8844 // Perform semantic checking on the function declaration. 8845 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8846 CheckMain(NewFD, D.getDeclSpec()); 8847 8848 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8849 CheckMSVCRTEntryPoint(NewFD); 8850 8851 if (!NewFD->isInvalidDecl()) 8852 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8853 isMemberSpecialization)); 8854 else if (!Previous.empty()) 8855 // Recover gracefully from an invalid redeclaration. 8856 D.setRedeclaration(true); 8857 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8858 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8859 "previous declaration set still overloaded"); 8860 8861 // Diagnose no-prototype function declarations with calling conventions that 8862 // don't support variadic calls. Only do this in C and do it after merging 8863 // possibly prototyped redeclarations. 8864 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8865 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8866 CallingConv CC = FT->getExtInfo().getCC(); 8867 if (!supportsVariadicCall(CC)) { 8868 // Windows system headers sometimes accidentally use stdcall without 8869 // (void) parameters, so we relax this to a warning. 8870 int DiagID = 8871 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8872 Diag(NewFD->getLocation(), DiagID) 8873 << FunctionType::getNameForCallConv(CC); 8874 } 8875 } 8876 } else { 8877 // C++11 [replacement.functions]p3: 8878 // The program's definitions shall not be specified as inline. 8879 // 8880 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8881 // 8882 // Suppress the diagnostic if the function is __attribute__((used)), since 8883 // that forces an external definition to be emitted. 8884 if (D.getDeclSpec().isInlineSpecified() && 8885 NewFD->isReplaceableGlobalAllocationFunction() && 8886 !NewFD->hasAttr<UsedAttr>()) 8887 Diag(D.getDeclSpec().getInlineSpecLoc(), 8888 diag::ext_operator_new_delete_declared_inline) 8889 << NewFD->getDeclName(); 8890 8891 // If the declarator is a template-id, translate the parser's template 8892 // argument list into our AST format. 8893 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 8894 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8895 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8896 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8897 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8898 TemplateId->NumArgs); 8899 translateTemplateArguments(TemplateArgsPtr, 8900 TemplateArgs); 8901 8902 HasExplicitTemplateArgs = true; 8903 8904 if (NewFD->isInvalidDecl()) { 8905 HasExplicitTemplateArgs = false; 8906 } else if (FunctionTemplate) { 8907 // Function template with explicit template arguments. 8908 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8909 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8910 8911 HasExplicitTemplateArgs = false; 8912 } else { 8913 assert((isFunctionTemplateSpecialization || 8914 D.getDeclSpec().isFriendSpecified()) && 8915 "should have a 'template<>' for this decl"); 8916 // "friend void foo<>(int);" is an implicit specialization decl. 8917 isFunctionTemplateSpecialization = true; 8918 } 8919 } else if (isFriend && isFunctionTemplateSpecialization) { 8920 // This combination is only possible in a recovery case; the user 8921 // wrote something like: 8922 // template <> friend void foo(int); 8923 // which we're recovering from as if the user had written: 8924 // friend void foo<>(int); 8925 // Go ahead and fake up a template id. 8926 HasExplicitTemplateArgs = true; 8927 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8928 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8929 } 8930 8931 // We do not add HD attributes to specializations here because 8932 // they may have different constexpr-ness compared to their 8933 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8934 // may end up with different effective targets. Instead, a 8935 // specialization inherits its target attributes from its template 8936 // in the CheckFunctionTemplateSpecialization() call below. 8937 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8938 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8939 8940 // If it's a friend (and only if it's a friend), it's possible 8941 // that either the specialized function type or the specialized 8942 // template is dependent, and therefore matching will fail. In 8943 // this case, don't check the specialization yet. 8944 bool InstantiationDependent = false; 8945 if (isFunctionTemplateSpecialization && isFriend && 8946 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8947 TemplateSpecializationType::anyDependentTemplateArguments( 8948 TemplateArgs, 8949 InstantiationDependent))) { 8950 assert(HasExplicitTemplateArgs && 8951 "friend function specialization without template args"); 8952 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8953 Previous)) 8954 NewFD->setInvalidDecl(); 8955 } else if (isFunctionTemplateSpecialization) { 8956 if (CurContext->isDependentContext() && CurContext->isRecord() 8957 && !isFriend) { 8958 isDependentClassScopeExplicitSpecialization = true; 8959 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 8960 diag::ext_function_specialization_in_class : 8961 diag::err_function_specialization_in_class) 8962 << NewFD->getDeclName(); 8963 } else if (CheckFunctionTemplateSpecialization(NewFD, 8964 (HasExplicitTemplateArgs ? &TemplateArgs 8965 : nullptr), 8966 Previous)) 8967 NewFD->setInvalidDecl(); 8968 8969 // C++ [dcl.stc]p1: 8970 // A storage-class-specifier shall not be specified in an explicit 8971 // specialization (14.7.3) 8972 FunctionTemplateSpecializationInfo *Info = 8973 NewFD->getTemplateSpecializationInfo(); 8974 if (Info && SC != SC_None) { 8975 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8976 Diag(NewFD->getLocation(), 8977 diag::err_explicit_specialization_inconsistent_storage_class) 8978 << SC 8979 << FixItHint::CreateRemoval( 8980 D.getDeclSpec().getStorageClassSpecLoc()); 8981 8982 else 8983 Diag(NewFD->getLocation(), 8984 diag::ext_explicit_specialization_storage_class) 8985 << FixItHint::CreateRemoval( 8986 D.getDeclSpec().getStorageClassSpecLoc()); 8987 } 8988 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8989 if (CheckMemberSpecialization(NewFD, Previous)) 8990 NewFD->setInvalidDecl(); 8991 } 8992 8993 // Perform semantic checking on the function declaration. 8994 if (!isDependentClassScopeExplicitSpecialization) { 8995 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8996 CheckMain(NewFD, D.getDeclSpec()); 8997 8998 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8999 CheckMSVCRTEntryPoint(NewFD); 9000 9001 if (!NewFD->isInvalidDecl()) 9002 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9003 isMemberSpecialization)); 9004 else if (!Previous.empty()) 9005 // Recover gracefully from an invalid redeclaration. 9006 D.setRedeclaration(true); 9007 } 9008 9009 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9010 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9011 "previous declaration set still overloaded"); 9012 9013 NamedDecl *PrincipalDecl = (FunctionTemplate 9014 ? cast<NamedDecl>(FunctionTemplate) 9015 : NewFD); 9016 9017 if (isFriend && NewFD->getPreviousDecl()) { 9018 AccessSpecifier Access = AS_public; 9019 if (!NewFD->isInvalidDecl()) 9020 Access = NewFD->getPreviousDecl()->getAccess(); 9021 9022 NewFD->setAccess(Access); 9023 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9024 } 9025 9026 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9027 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9028 PrincipalDecl->setNonMemberOperator(); 9029 9030 // If we have a function template, check the template parameter 9031 // list. This will check and merge default template arguments. 9032 if (FunctionTemplate) { 9033 FunctionTemplateDecl *PrevTemplate = 9034 FunctionTemplate->getPreviousDecl(); 9035 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9036 PrevTemplate ? PrevTemplate->getTemplateParameters() 9037 : nullptr, 9038 D.getDeclSpec().isFriendSpecified() 9039 ? (D.isFunctionDefinition() 9040 ? TPC_FriendFunctionTemplateDefinition 9041 : TPC_FriendFunctionTemplate) 9042 : (D.getCXXScopeSpec().isSet() && 9043 DC && DC->isRecord() && 9044 DC->isDependentContext()) 9045 ? TPC_ClassTemplateMember 9046 : TPC_FunctionTemplate); 9047 } 9048 9049 if (NewFD->isInvalidDecl()) { 9050 // Ignore all the rest of this. 9051 } else if (!D.isRedeclaration()) { 9052 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9053 AddToScope }; 9054 // Fake up an access specifier if it's supposed to be a class member. 9055 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9056 NewFD->setAccess(AS_public); 9057 9058 // Qualified decls generally require a previous declaration. 9059 if (D.getCXXScopeSpec().isSet()) { 9060 // ...with the major exception of templated-scope or 9061 // dependent-scope friend declarations. 9062 9063 // TODO: we currently also suppress this check in dependent 9064 // contexts because (1) the parameter depth will be off when 9065 // matching friend templates and (2) we might actually be 9066 // selecting a friend based on a dependent factor. But there 9067 // are situations where these conditions don't apply and we 9068 // can actually do this check immediately. 9069 if (isFriend && 9070 (TemplateParamLists.size() || 9071 D.getCXXScopeSpec().getScopeRep()->isDependent() || 9072 CurContext->isDependentContext())) { 9073 // ignore these 9074 } else { 9075 // The user tried to provide an out-of-line definition for a 9076 // function that is a member of a class or namespace, but there 9077 // was no such member function declared (C++ [class.mfct]p2, 9078 // C++ [namespace.memdef]p2). For example: 9079 // 9080 // class X { 9081 // void f() const; 9082 // }; 9083 // 9084 // void X::f() { } // ill-formed 9085 // 9086 // Complain about this problem, and attempt to suggest close 9087 // matches (e.g., those that differ only in cv-qualifiers and 9088 // whether the parameter types are references). 9089 9090 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9091 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9092 AddToScope = ExtraArgs.AddToScope; 9093 return Result; 9094 } 9095 } 9096 9097 // Unqualified local friend declarations are required to resolve 9098 // to something. 9099 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9100 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9101 *this, Previous, NewFD, ExtraArgs, true, S)) { 9102 AddToScope = ExtraArgs.AddToScope; 9103 return Result; 9104 } 9105 } 9106 } else if (!D.isFunctionDefinition() && 9107 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9108 !isFriend && !isFunctionTemplateSpecialization && 9109 !isMemberSpecialization) { 9110 // An out-of-line member function declaration must also be a 9111 // definition (C++ [class.mfct]p2). 9112 // Note that this is not the case for explicit specializations of 9113 // function templates or member functions of class templates, per 9114 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9115 // extension for compatibility with old SWIG code which likes to 9116 // generate them. 9117 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9118 << D.getCXXScopeSpec().getRange(); 9119 } 9120 } 9121 9122 ProcessPragmaWeak(S, NewFD); 9123 checkAttributesAfterMerging(*this, *NewFD); 9124 9125 AddKnownFunctionAttributes(NewFD); 9126 9127 if (NewFD->hasAttr<OverloadableAttr>() && 9128 !NewFD->getType()->getAs<FunctionProtoType>()) { 9129 Diag(NewFD->getLocation(), 9130 diag::err_attribute_overloadable_no_prototype) 9131 << NewFD; 9132 9133 // Turn this into a variadic function with no parameters. 9134 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9135 FunctionProtoType::ExtProtoInfo EPI( 9136 Context.getDefaultCallingConvention(true, false)); 9137 EPI.Variadic = true; 9138 EPI.ExtInfo = FT->getExtInfo(); 9139 9140 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9141 NewFD->setType(R); 9142 } 9143 9144 // If there's a #pragma GCC visibility in scope, and this isn't a class 9145 // member, set the visibility of this function. 9146 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9147 AddPushedVisibilityAttribute(NewFD); 9148 9149 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9150 // marking the function. 9151 AddCFAuditedAttribute(NewFD); 9152 9153 // If this is a function definition, check if we have to apply optnone due to 9154 // a pragma. 9155 if(D.isFunctionDefinition()) 9156 AddRangeBasedOptnone(NewFD); 9157 9158 // If this is the first declaration of an extern C variable, update 9159 // the map of such variables. 9160 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9161 isIncompleteDeclExternC(*this, NewFD)) 9162 RegisterLocallyScopedExternCDecl(NewFD, S); 9163 9164 // Set this FunctionDecl's range up to the right paren. 9165 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9166 9167 if (D.isRedeclaration() && !Previous.empty()) { 9168 checkDLLAttributeRedeclaration( 9169 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 9170 isMemberSpecialization || isFunctionTemplateSpecialization, 9171 D.isFunctionDefinition()); 9172 } 9173 9174 if (getLangOpts().CUDA) { 9175 IdentifierInfo *II = NewFD->getIdentifier(); 9176 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() && 9177 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9178 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9179 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9180 9181 Context.setcudaConfigureCallDecl(NewFD); 9182 } 9183 9184 // Variadic functions, other than a *declaration* of printf, are not allowed 9185 // in device-side CUDA code, unless someone passed 9186 // -fcuda-allow-variadic-functions. 9187 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9188 (NewFD->hasAttr<CUDADeviceAttr>() || 9189 NewFD->hasAttr<CUDAGlobalAttr>()) && 9190 !(II && II->isStr("printf") && NewFD->isExternC() && 9191 !D.isFunctionDefinition())) { 9192 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9193 } 9194 } 9195 9196 MarkUnusedFileScopedDecl(NewFD); 9197 9198 if (getLangOpts().CPlusPlus) { 9199 if (FunctionTemplate) { 9200 if (NewFD->isInvalidDecl()) 9201 FunctionTemplate->setInvalidDecl(); 9202 return FunctionTemplate; 9203 } 9204 9205 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9206 CompleteMemberSpecialization(NewFD, Previous); 9207 } 9208 9209 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9210 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9211 if ((getLangOpts().OpenCLVersion >= 120) 9212 && (SC == SC_Static)) { 9213 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9214 D.setInvalidType(); 9215 } 9216 9217 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9218 if (!NewFD->getReturnType()->isVoidType()) { 9219 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9220 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9221 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9222 : FixItHint()); 9223 D.setInvalidType(); 9224 } 9225 9226 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9227 for (auto Param : NewFD->parameters()) 9228 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9229 } 9230 for (const ParmVarDecl *Param : NewFD->parameters()) { 9231 QualType PT = Param->getType(); 9232 9233 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9234 // types. 9235 if (getLangOpts().OpenCLVersion >= 200) { 9236 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9237 QualType ElemTy = PipeTy->getElementType(); 9238 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9239 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9240 D.setInvalidType(); 9241 } 9242 } 9243 } 9244 } 9245 9246 // Here we have an function template explicit specialization at class scope. 9247 // The actually specialization will be postponed to template instatiation 9248 // time via the ClassScopeFunctionSpecializationDecl node. 9249 if (isDependentClassScopeExplicitSpecialization) { 9250 ClassScopeFunctionSpecializationDecl *NewSpec = 9251 ClassScopeFunctionSpecializationDecl::Create( 9252 Context, CurContext, SourceLocation(), 9253 cast<CXXMethodDecl>(NewFD), 9254 HasExplicitTemplateArgs, TemplateArgs); 9255 CurContext->addDecl(NewSpec); 9256 AddToScope = false; 9257 } 9258 9259 return NewFD; 9260 } 9261 9262 /// \brief Checks if the new declaration declared in dependent context must be 9263 /// put in the same redeclaration chain as the specified declaration. 9264 /// 9265 /// \param D Declaration that is checked. 9266 /// \param PrevDecl Previous declaration found with proper lookup method for the 9267 /// same declaration name. 9268 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9269 /// belongs to. 9270 /// 9271 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9272 // Any declarations should be put into redeclaration chains except for 9273 // friend declaration in a dependent context that names a function in 9274 // namespace scope. 9275 // 9276 // This allows to compile code like: 9277 // 9278 // void func(); 9279 // template<typename T> class C1 { friend void func() { } }; 9280 // template<typename T> class C2 { friend void func() { } }; 9281 // 9282 // This code snippet is a valid code unless both templates are instantiated. 9283 return !(D->getLexicalDeclContext()->isDependentContext() && 9284 D->getDeclContext()->isFileContext() && 9285 D->getFriendObjectKind() != Decl::FOK_None); 9286 } 9287 9288 /// \brief Perform semantic checking of a new function declaration. 9289 /// 9290 /// Performs semantic analysis of the new function declaration 9291 /// NewFD. This routine performs all semantic checking that does not 9292 /// require the actual declarator involved in the declaration, and is 9293 /// used both for the declaration of functions as they are parsed 9294 /// (called via ActOnDeclarator) and for the declaration of functions 9295 /// that have been instantiated via C++ template instantiation (called 9296 /// via InstantiateDecl). 9297 /// 9298 /// \param IsMemberSpecialization whether this new function declaration is 9299 /// a member specialization (that replaces any definition provided by the 9300 /// previous declaration). 9301 /// 9302 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9303 /// 9304 /// \returns true if the function declaration is a redeclaration. 9305 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9306 LookupResult &Previous, 9307 bool IsMemberSpecialization) { 9308 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9309 "Variably modified return types are not handled here"); 9310 9311 // Determine whether the type of this function should be merged with 9312 // a previous visible declaration. This never happens for functions in C++, 9313 // and always happens in C if the previous declaration was visible. 9314 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9315 !Previous.isShadowed(); 9316 9317 bool Redeclaration = false; 9318 NamedDecl *OldDecl = nullptr; 9319 bool MayNeedOverloadableChecks = false; 9320 9321 // Merge or overload the declaration with an existing declaration of 9322 // the same name, if appropriate. 9323 if (!Previous.empty()) { 9324 // Determine whether NewFD is an overload of PrevDecl or 9325 // a declaration that requires merging. If it's an overload, 9326 // there's no more work to do here; we'll just add the new 9327 // function to the scope. 9328 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9329 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9330 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9331 Redeclaration = true; 9332 OldDecl = Candidate; 9333 } 9334 } else { 9335 MayNeedOverloadableChecks = true; 9336 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9337 /*NewIsUsingDecl*/ false)) { 9338 case Ovl_Match: 9339 Redeclaration = true; 9340 break; 9341 9342 case Ovl_NonFunction: 9343 Redeclaration = true; 9344 break; 9345 9346 case Ovl_Overload: 9347 Redeclaration = false; 9348 break; 9349 } 9350 } 9351 } 9352 9353 // Check for a previous extern "C" declaration with this name. 9354 if (!Redeclaration && 9355 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9356 if (!Previous.empty()) { 9357 // This is an extern "C" declaration with the same name as a previous 9358 // declaration, and thus redeclares that entity... 9359 Redeclaration = true; 9360 OldDecl = Previous.getFoundDecl(); 9361 MergeTypeWithPrevious = false; 9362 9363 // ... except in the presence of __attribute__((overloadable)). 9364 if (OldDecl->hasAttr<OverloadableAttr>() || 9365 NewFD->hasAttr<OverloadableAttr>()) { 9366 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9367 MayNeedOverloadableChecks = true; 9368 Redeclaration = false; 9369 OldDecl = nullptr; 9370 } 9371 } 9372 } 9373 } 9374 9375 // C++11 [dcl.constexpr]p8: 9376 // A constexpr specifier for a non-static member function that is not 9377 // a constructor declares that member function to be const. 9378 // 9379 // This needs to be delayed until we know whether this is an out-of-line 9380 // definition of a static member function. 9381 // 9382 // This rule is not present in C++1y, so we produce a backwards 9383 // compatibility warning whenever it happens in C++11. 9384 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9385 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9386 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9387 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9388 CXXMethodDecl *OldMD = nullptr; 9389 if (OldDecl) 9390 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9391 if (!OldMD || !OldMD->isStatic()) { 9392 const FunctionProtoType *FPT = 9393 MD->getType()->castAs<FunctionProtoType>(); 9394 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9395 EPI.TypeQuals |= Qualifiers::Const; 9396 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9397 FPT->getParamTypes(), EPI)); 9398 9399 // Warn that we did this, if we're not performing template instantiation. 9400 // In that case, we'll have warned already when the template was defined. 9401 if (!inTemplateInstantiation()) { 9402 SourceLocation AddConstLoc; 9403 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9404 .IgnoreParens().getAs<FunctionTypeLoc>()) 9405 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9406 9407 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9408 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9409 } 9410 } 9411 } 9412 9413 if (Redeclaration) { 9414 // NewFD and OldDecl represent declarations that need to be 9415 // merged. 9416 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9417 NewFD->setInvalidDecl(); 9418 return Redeclaration; 9419 } 9420 9421 Previous.clear(); 9422 Previous.addDecl(OldDecl); 9423 9424 if (FunctionTemplateDecl *OldTemplateDecl 9425 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9426 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 9427 FunctionTemplateDecl *NewTemplateDecl 9428 = NewFD->getDescribedFunctionTemplate(); 9429 assert(NewTemplateDecl && "Template/non-template mismatch"); 9430 if (CXXMethodDecl *Method 9431 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 9432 Method->setAccess(OldTemplateDecl->getAccess()); 9433 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9434 } 9435 9436 // If this is an explicit specialization of a member that is a function 9437 // template, mark it as a member specialization. 9438 if (IsMemberSpecialization && 9439 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9440 NewTemplateDecl->setMemberSpecialization(); 9441 assert(OldTemplateDecl->isMemberSpecialization()); 9442 // Explicit specializations of a member template do not inherit deleted 9443 // status from the parent member template that they are specializing. 9444 if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) { 9445 FunctionDecl *const OldTemplatedDecl = 9446 OldTemplateDecl->getTemplatedDecl(); 9447 // FIXME: This assert will not hold in the presence of modules. 9448 assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl); 9449 // FIXME: We need an update record for this AST mutation. 9450 OldTemplatedDecl->setDeletedAsWritten(false); 9451 } 9452 } 9453 9454 } else { 9455 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9456 // This needs to happen first so that 'inline' propagates. 9457 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 9458 if (isa<CXXMethodDecl>(NewFD)) 9459 NewFD->setAccess(OldDecl->getAccess()); 9460 } 9461 } 9462 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9463 !NewFD->getAttr<OverloadableAttr>()) { 9464 assert((Previous.empty() || 9465 llvm::any_of(Previous, 9466 [](const NamedDecl *ND) { 9467 return ND->hasAttr<OverloadableAttr>(); 9468 })) && 9469 "Non-redecls shouldn't happen without overloadable present"); 9470 9471 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9472 const auto *FD = dyn_cast<FunctionDecl>(ND); 9473 return FD && !FD->hasAttr<OverloadableAttr>(); 9474 }); 9475 9476 if (OtherUnmarkedIter != Previous.end()) { 9477 Diag(NewFD->getLocation(), 9478 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9479 Diag((*OtherUnmarkedIter)->getLocation(), 9480 diag::note_attribute_overloadable_prev_overload) 9481 << false; 9482 9483 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9484 } 9485 } 9486 9487 // Semantic checking for this function declaration (in isolation). 9488 9489 if (getLangOpts().CPlusPlus) { 9490 // C++-specific checks. 9491 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9492 CheckConstructor(Constructor); 9493 } else if (CXXDestructorDecl *Destructor = 9494 dyn_cast<CXXDestructorDecl>(NewFD)) { 9495 CXXRecordDecl *Record = Destructor->getParent(); 9496 QualType ClassType = Context.getTypeDeclType(Record); 9497 9498 // FIXME: Shouldn't we be able to perform this check even when the class 9499 // type is dependent? Both gcc and edg can handle that. 9500 if (!ClassType->isDependentType()) { 9501 DeclarationName Name 9502 = Context.DeclarationNames.getCXXDestructorName( 9503 Context.getCanonicalType(ClassType)); 9504 if (NewFD->getDeclName() != Name) { 9505 Diag(NewFD->getLocation(), diag::err_destructor_name); 9506 NewFD->setInvalidDecl(); 9507 return Redeclaration; 9508 } 9509 } 9510 } else if (CXXConversionDecl *Conversion 9511 = dyn_cast<CXXConversionDecl>(NewFD)) { 9512 ActOnConversionDeclarator(Conversion); 9513 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9514 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9515 CheckDeductionGuideTemplate(TD); 9516 9517 // A deduction guide is not on the list of entities that can be 9518 // explicitly specialized. 9519 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9520 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9521 << /*explicit specialization*/ 1; 9522 } 9523 9524 // Find any virtual functions that this function overrides. 9525 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9526 if (!Method->isFunctionTemplateSpecialization() && 9527 !Method->getDescribedFunctionTemplate() && 9528 Method->isCanonicalDecl()) { 9529 if (AddOverriddenMethods(Method->getParent(), Method)) { 9530 // If the function was marked as "static", we have a problem. 9531 if (NewFD->getStorageClass() == SC_Static) { 9532 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9533 } 9534 } 9535 } 9536 9537 if (Method->isStatic()) 9538 checkThisInStaticMemberFunctionType(Method); 9539 } 9540 9541 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9542 if (NewFD->isOverloadedOperator() && 9543 CheckOverloadedOperatorDeclaration(NewFD)) { 9544 NewFD->setInvalidDecl(); 9545 return Redeclaration; 9546 } 9547 9548 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9549 if (NewFD->getLiteralIdentifier() && 9550 CheckLiteralOperatorDeclaration(NewFD)) { 9551 NewFD->setInvalidDecl(); 9552 return Redeclaration; 9553 } 9554 9555 // In C++, check default arguments now that we have merged decls. Unless 9556 // the lexical context is the class, because in this case this is done 9557 // during delayed parsing anyway. 9558 if (!CurContext->isRecord()) 9559 CheckCXXDefaultArguments(NewFD); 9560 9561 // If this function declares a builtin function, check the type of this 9562 // declaration against the expected type for the builtin. 9563 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9564 ASTContext::GetBuiltinTypeError Error; 9565 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9566 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9567 // If the type of the builtin differs only in its exception 9568 // specification, that's OK. 9569 // FIXME: If the types do differ in this way, it would be better to 9570 // retain the 'noexcept' form of the type. 9571 if (!T.isNull() && 9572 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9573 NewFD->getType())) 9574 // The type of this function differs from the type of the builtin, 9575 // so forget about the builtin entirely. 9576 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9577 } 9578 9579 // If this function is declared as being extern "C", then check to see if 9580 // the function returns a UDT (class, struct, or union type) that is not C 9581 // compatible, and if it does, warn the user. 9582 // But, issue any diagnostic on the first declaration only. 9583 if (Previous.empty() && NewFD->isExternC()) { 9584 QualType R = NewFD->getReturnType(); 9585 if (R->isIncompleteType() && !R->isVoidType()) 9586 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9587 << NewFD << R; 9588 else if (!R.isPODType(Context) && !R->isVoidType() && 9589 !R->isObjCObjectPointerType()) 9590 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9591 } 9592 9593 // C++1z [dcl.fct]p6: 9594 // [...] whether the function has a non-throwing exception-specification 9595 // [is] part of the function type 9596 // 9597 // This results in an ABI break between C++14 and C++17 for functions whose 9598 // declared type includes an exception-specification in a parameter or 9599 // return type. (Exception specifications on the function itself are OK in 9600 // most cases, and exception specifications are not permitted in most other 9601 // contexts where they could make it into a mangling.) 9602 if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) { 9603 auto HasNoexcept = [&](QualType T) -> bool { 9604 // Strip off declarator chunks that could be between us and a function 9605 // type. We don't need to look far, exception specifications are very 9606 // restricted prior to C++17. 9607 if (auto *RT = T->getAs<ReferenceType>()) 9608 T = RT->getPointeeType(); 9609 else if (T->isAnyPointerType()) 9610 T = T->getPointeeType(); 9611 else if (auto *MPT = T->getAs<MemberPointerType>()) 9612 T = MPT->getPointeeType(); 9613 if (auto *FPT = T->getAs<FunctionProtoType>()) 9614 if (FPT->isNothrow(Context)) 9615 return true; 9616 return false; 9617 }; 9618 9619 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9620 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9621 for (QualType T : FPT->param_types()) 9622 AnyNoexcept |= HasNoexcept(T); 9623 if (AnyNoexcept) 9624 Diag(NewFD->getLocation(), 9625 diag::warn_cxx17_compat_exception_spec_in_signature) 9626 << NewFD; 9627 } 9628 9629 if (!Redeclaration && LangOpts.CUDA) 9630 checkCUDATargetOverload(NewFD, Previous); 9631 } 9632 return Redeclaration; 9633 } 9634 9635 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9636 // C++11 [basic.start.main]p3: 9637 // A program that [...] declares main to be inline, static or 9638 // constexpr is ill-formed. 9639 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9640 // appear in a declaration of main. 9641 // static main is not an error under C99, but we should warn about it. 9642 // We accept _Noreturn main as an extension. 9643 if (FD->getStorageClass() == SC_Static) 9644 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9645 ? diag::err_static_main : diag::warn_static_main) 9646 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9647 if (FD->isInlineSpecified()) 9648 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9649 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9650 if (DS.isNoreturnSpecified()) { 9651 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9652 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9653 Diag(NoreturnLoc, diag::ext_noreturn_main); 9654 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9655 << FixItHint::CreateRemoval(NoreturnRange); 9656 } 9657 if (FD->isConstexpr()) { 9658 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9659 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9660 FD->setConstexpr(false); 9661 } 9662 9663 if (getLangOpts().OpenCL) { 9664 Diag(FD->getLocation(), diag::err_opencl_no_main) 9665 << FD->hasAttr<OpenCLKernelAttr>(); 9666 FD->setInvalidDecl(); 9667 return; 9668 } 9669 9670 QualType T = FD->getType(); 9671 assert(T->isFunctionType() && "function decl is not of function type"); 9672 const FunctionType* FT = T->castAs<FunctionType>(); 9673 9674 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9675 // In C with GNU extensions we allow main() to have non-integer return 9676 // type, but we should warn about the extension, and we disable the 9677 // implicit-return-zero rule. 9678 9679 // GCC in C mode accepts qualified 'int'. 9680 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9681 FD->setHasImplicitReturnZero(true); 9682 else { 9683 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9684 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9685 if (RTRange.isValid()) 9686 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9687 << FixItHint::CreateReplacement(RTRange, "int"); 9688 } 9689 } else { 9690 // In C and C++, main magically returns 0 if you fall off the end; 9691 // set the flag which tells us that. 9692 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9693 9694 // All the standards say that main() should return 'int'. 9695 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9696 FD->setHasImplicitReturnZero(true); 9697 else { 9698 // Otherwise, this is just a flat-out error. 9699 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9700 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9701 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9702 : FixItHint()); 9703 FD->setInvalidDecl(true); 9704 } 9705 } 9706 9707 // Treat protoless main() as nullary. 9708 if (isa<FunctionNoProtoType>(FT)) return; 9709 9710 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9711 unsigned nparams = FTP->getNumParams(); 9712 assert(FD->getNumParams() == nparams); 9713 9714 bool HasExtraParameters = (nparams > 3); 9715 9716 if (FTP->isVariadic()) { 9717 Diag(FD->getLocation(), diag::ext_variadic_main); 9718 // FIXME: if we had information about the location of the ellipsis, we 9719 // could add a FixIt hint to remove it as a parameter. 9720 } 9721 9722 // Darwin passes an undocumented fourth argument of type char**. If 9723 // other platforms start sprouting these, the logic below will start 9724 // getting shifty. 9725 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9726 HasExtraParameters = false; 9727 9728 if (HasExtraParameters) { 9729 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9730 FD->setInvalidDecl(true); 9731 nparams = 3; 9732 } 9733 9734 // FIXME: a lot of the following diagnostics would be improved 9735 // if we had some location information about types. 9736 9737 QualType CharPP = 9738 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9739 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9740 9741 for (unsigned i = 0; i < nparams; ++i) { 9742 QualType AT = FTP->getParamType(i); 9743 9744 bool mismatch = true; 9745 9746 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9747 mismatch = false; 9748 else if (Expected[i] == CharPP) { 9749 // As an extension, the following forms are okay: 9750 // char const ** 9751 // char const * const * 9752 // char * const * 9753 9754 QualifierCollector qs; 9755 const PointerType* PT; 9756 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9757 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9758 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 9759 Context.CharTy)) { 9760 qs.removeConst(); 9761 mismatch = !qs.empty(); 9762 } 9763 } 9764 9765 if (mismatch) { 9766 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 9767 // TODO: suggest replacing given type with expected type 9768 FD->setInvalidDecl(true); 9769 } 9770 } 9771 9772 if (nparams == 1 && !FD->isInvalidDecl()) { 9773 Diag(FD->getLocation(), diag::warn_main_one_arg); 9774 } 9775 9776 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9777 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9778 FD->setInvalidDecl(); 9779 } 9780 } 9781 9782 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 9783 QualType T = FD->getType(); 9784 assert(T->isFunctionType() && "function decl is not of function type"); 9785 const FunctionType *FT = T->castAs<FunctionType>(); 9786 9787 // Set an implicit return of 'zero' if the function can return some integral, 9788 // enumeration, pointer or nullptr type. 9789 if (FT->getReturnType()->isIntegralOrEnumerationType() || 9790 FT->getReturnType()->isAnyPointerType() || 9791 FT->getReturnType()->isNullPtrType()) 9792 // DllMain is exempt because a return value of zero means it failed. 9793 if (FD->getName() != "DllMain") 9794 FD->setHasImplicitReturnZero(true); 9795 9796 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 9797 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 9798 FD->setInvalidDecl(); 9799 } 9800 } 9801 9802 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 9803 // FIXME: Need strict checking. In C89, we need to check for 9804 // any assignment, increment, decrement, function-calls, or 9805 // commas outside of a sizeof. In C99, it's the same list, 9806 // except that the aforementioned are allowed in unevaluated 9807 // expressions. Everything else falls under the 9808 // "may accept other forms of constant expressions" exception. 9809 // (We never end up here for C++, so the constant expression 9810 // rules there don't matter.) 9811 const Expr *Culprit; 9812 if (Init->isConstantInitializer(Context, false, &Culprit)) 9813 return false; 9814 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 9815 << Culprit->getSourceRange(); 9816 return true; 9817 } 9818 9819 namespace { 9820 // Visits an initialization expression to see if OrigDecl is evaluated in 9821 // its own initialization and throws a warning if it does. 9822 class SelfReferenceChecker 9823 : public EvaluatedExprVisitor<SelfReferenceChecker> { 9824 Sema &S; 9825 Decl *OrigDecl; 9826 bool isRecordType; 9827 bool isPODType; 9828 bool isReferenceType; 9829 9830 bool isInitList; 9831 llvm::SmallVector<unsigned, 4> InitFieldIndex; 9832 9833 public: 9834 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 9835 9836 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 9837 S(S), OrigDecl(OrigDecl) { 9838 isPODType = false; 9839 isRecordType = false; 9840 isReferenceType = false; 9841 isInitList = false; 9842 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 9843 isPODType = VD->getType().isPODType(S.Context); 9844 isRecordType = VD->getType()->isRecordType(); 9845 isReferenceType = VD->getType()->isReferenceType(); 9846 } 9847 } 9848 9849 // For most expressions, just call the visitor. For initializer lists, 9850 // track the index of the field being initialized since fields are 9851 // initialized in order allowing use of previously initialized fields. 9852 void CheckExpr(Expr *E) { 9853 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 9854 if (!InitList) { 9855 Visit(E); 9856 return; 9857 } 9858 9859 // Track and increment the index here. 9860 isInitList = true; 9861 InitFieldIndex.push_back(0); 9862 for (auto Child : InitList->children()) { 9863 CheckExpr(cast<Expr>(Child)); 9864 ++InitFieldIndex.back(); 9865 } 9866 InitFieldIndex.pop_back(); 9867 } 9868 9869 // Returns true if MemberExpr is checked and no further checking is needed. 9870 // Returns false if additional checking is required. 9871 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 9872 llvm::SmallVector<FieldDecl*, 4> Fields; 9873 Expr *Base = E; 9874 bool ReferenceField = false; 9875 9876 // Get the field memebers used. 9877 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9878 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 9879 if (!FD) 9880 return false; 9881 Fields.push_back(FD); 9882 if (FD->getType()->isReferenceType()) 9883 ReferenceField = true; 9884 Base = ME->getBase()->IgnoreParenImpCasts(); 9885 } 9886 9887 // Keep checking only if the base Decl is the same. 9888 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 9889 if (!DRE || DRE->getDecl() != OrigDecl) 9890 return false; 9891 9892 // A reference field can be bound to an unininitialized field. 9893 if (CheckReference && !ReferenceField) 9894 return true; 9895 9896 // Convert FieldDecls to their index number. 9897 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 9898 for (const FieldDecl *I : llvm::reverse(Fields)) 9899 UsedFieldIndex.push_back(I->getFieldIndex()); 9900 9901 // See if a warning is needed by checking the first difference in index 9902 // numbers. If field being used has index less than the field being 9903 // initialized, then the use is safe. 9904 for (auto UsedIter = UsedFieldIndex.begin(), 9905 UsedEnd = UsedFieldIndex.end(), 9906 OrigIter = InitFieldIndex.begin(), 9907 OrigEnd = InitFieldIndex.end(); 9908 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 9909 if (*UsedIter < *OrigIter) 9910 return true; 9911 if (*UsedIter > *OrigIter) 9912 break; 9913 } 9914 9915 // TODO: Add a different warning which will print the field names. 9916 HandleDeclRefExpr(DRE); 9917 return true; 9918 } 9919 9920 // For most expressions, the cast is directly above the DeclRefExpr. 9921 // For conditional operators, the cast can be outside the conditional 9922 // operator if both expressions are DeclRefExpr's. 9923 void HandleValue(Expr *E) { 9924 E = E->IgnoreParens(); 9925 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 9926 HandleDeclRefExpr(DRE); 9927 return; 9928 } 9929 9930 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9931 Visit(CO->getCond()); 9932 HandleValue(CO->getTrueExpr()); 9933 HandleValue(CO->getFalseExpr()); 9934 return; 9935 } 9936 9937 if (BinaryConditionalOperator *BCO = 9938 dyn_cast<BinaryConditionalOperator>(E)) { 9939 Visit(BCO->getCond()); 9940 HandleValue(BCO->getFalseExpr()); 9941 return; 9942 } 9943 9944 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 9945 HandleValue(OVE->getSourceExpr()); 9946 return; 9947 } 9948 9949 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 9950 if (BO->getOpcode() == BO_Comma) { 9951 Visit(BO->getLHS()); 9952 HandleValue(BO->getRHS()); 9953 return; 9954 } 9955 } 9956 9957 if (isa<MemberExpr>(E)) { 9958 if (isInitList) { 9959 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 9960 false /*CheckReference*/)) 9961 return; 9962 } 9963 9964 Expr *Base = E->IgnoreParenImpCasts(); 9965 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 9966 // Check for static member variables and don't warn on them. 9967 if (!isa<FieldDecl>(ME->getMemberDecl())) 9968 return; 9969 Base = ME->getBase()->IgnoreParenImpCasts(); 9970 } 9971 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 9972 HandleDeclRefExpr(DRE); 9973 return; 9974 } 9975 9976 Visit(E); 9977 } 9978 9979 // Reference types not handled in HandleValue are handled here since all 9980 // uses of references are bad, not just r-value uses. 9981 void VisitDeclRefExpr(DeclRefExpr *E) { 9982 if (isReferenceType) 9983 HandleDeclRefExpr(E); 9984 } 9985 9986 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 9987 if (E->getCastKind() == CK_LValueToRValue) { 9988 HandleValue(E->getSubExpr()); 9989 return; 9990 } 9991 9992 Inherited::VisitImplicitCastExpr(E); 9993 } 9994 9995 void VisitMemberExpr(MemberExpr *E) { 9996 if (isInitList) { 9997 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 9998 return; 9999 } 10000 10001 // Don't warn on arrays since they can be treated as pointers. 10002 if (E->getType()->canDecayToPointerType()) return; 10003 10004 // Warn when a non-static method call is followed by non-static member 10005 // field accesses, which is followed by a DeclRefExpr. 10006 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10007 bool Warn = (MD && !MD->isStatic()); 10008 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10009 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10010 if (!isa<FieldDecl>(ME->getMemberDecl())) 10011 Warn = false; 10012 Base = ME->getBase()->IgnoreParenImpCasts(); 10013 } 10014 10015 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10016 if (Warn) 10017 HandleDeclRefExpr(DRE); 10018 return; 10019 } 10020 10021 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10022 // Visit that expression. 10023 Visit(Base); 10024 } 10025 10026 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10027 Expr *Callee = E->getCallee(); 10028 10029 if (isa<UnresolvedLookupExpr>(Callee)) 10030 return Inherited::VisitCXXOperatorCallExpr(E); 10031 10032 Visit(Callee); 10033 for (auto Arg: E->arguments()) 10034 HandleValue(Arg->IgnoreParenImpCasts()); 10035 } 10036 10037 void VisitUnaryOperator(UnaryOperator *E) { 10038 // For POD record types, addresses of its own members are well-defined. 10039 if (E->getOpcode() == UO_AddrOf && isRecordType && 10040 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10041 if (!isPODType) 10042 HandleValue(E->getSubExpr()); 10043 return; 10044 } 10045 10046 if (E->isIncrementDecrementOp()) { 10047 HandleValue(E->getSubExpr()); 10048 return; 10049 } 10050 10051 Inherited::VisitUnaryOperator(E); 10052 } 10053 10054 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10055 10056 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10057 if (E->getConstructor()->isCopyConstructor()) { 10058 Expr *ArgExpr = E->getArg(0); 10059 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10060 if (ILE->getNumInits() == 1) 10061 ArgExpr = ILE->getInit(0); 10062 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10063 if (ICE->getCastKind() == CK_NoOp) 10064 ArgExpr = ICE->getSubExpr(); 10065 HandleValue(ArgExpr); 10066 return; 10067 } 10068 Inherited::VisitCXXConstructExpr(E); 10069 } 10070 10071 void VisitCallExpr(CallExpr *E) { 10072 // Treat std::move as a use. 10073 if (E->isCallToStdMove()) { 10074 HandleValue(E->getArg(0)); 10075 return; 10076 } 10077 10078 Inherited::VisitCallExpr(E); 10079 } 10080 10081 void VisitBinaryOperator(BinaryOperator *E) { 10082 if (E->isCompoundAssignmentOp()) { 10083 HandleValue(E->getLHS()); 10084 Visit(E->getRHS()); 10085 return; 10086 } 10087 10088 Inherited::VisitBinaryOperator(E); 10089 } 10090 10091 // A custom visitor for BinaryConditionalOperator is needed because the 10092 // regular visitor would check the condition and true expression separately 10093 // but both point to the same place giving duplicate diagnostics. 10094 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10095 Visit(E->getCond()); 10096 Visit(E->getFalseExpr()); 10097 } 10098 10099 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10100 Decl* ReferenceDecl = DRE->getDecl(); 10101 if (OrigDecl != ReferenceDecl) return; 10102 unsigned diag; 10103 if (isReferenceType) { 10104 diag = diag::warn_uninit_self_reference_in_reference_init; 10105 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10106 diag = diag::warn_static_self_reference_in_init; 10107 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10108 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10109 DRE->getDecl()->getType()->isRecordType()) { 10110 diag = diag::warn_uninit_self_reference_in_init; 10111 } else { 10112 // Local variables will be handled by the CFG analysis. 10113 return; 10114 } 10115 10116 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10117 S.PDiag(diag) 10118 << DRE->getNameInfo().getName() 10119 << OrigDecl->getLocation() 10120 << DRE->getSourceRange()); 10121 } 10122 }; 10123 10124 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10125 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10126 bool DirectInit) { 10127 // Parameters arguments are occassionially constructed with itself, 10128 // for instance, in recursive functions. Skip them. 10129 if (isa<ParmVarDecl>(OrigDecl)) 10130 return; 10131 10132 E = E->IgnoreParens(); 10133 10134 // Skip checking T a = a where T is not a record or reference type. 10135 // Doing so is a way to silence uninitialized warnings. 10136 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10137 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10138 if (ICE->getCastKind() == CK_LValueToRValue) 10139 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10140 if (DRE->getDecl() == OrigDecl) 10141 return; 10142 10143 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10144 } 10145 } // end anonymous namespace 10146 10147 namespace { 10148 // Simple wrapper to add the name of a variable or (if no variable is 10149 // available) a DeclarationName into a diagnostic. 10150 struct VarDeclOrName { 10151 VarDecl *VDecl; 10152 DeclarationName Name; 10153 10154 friend const Sema::SemaDiagnosticBuilder & 10155 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10156 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10157 } 10158 }; 10159 } // end anonymous namespace 10160 10161 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10162 DeclarationName Name, QualType Type, 10163 TypeSourceInfo *TSI, 10164 SourceRange Range, bool DirectInit, 10165 Expr *Init) { 10166 bool IsInitCapture = !VDecl; 10167 assert((!VDecl || !VDecl->isInitCapture()) && 10168 "init captures are expected to be deduced prior to initialization"); 10169 10170 VarDeclOrName VN{VDecl, Name}; 10171 10172 DeducedType *Deduced = Type->getContainedDeducedType(); 10173 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10174 10175 // C++11 [dcl.spec.auto]p3 10176 if (!Init) { 10177 assert(VDecl && "no init for init capture deduction?"); 10178 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10179 << VDecl->getDeclName() << Type; 10180 return QualType(); 10181 } 10182 10183 ArrayRef<Expr*> DeduceInits = Init; 10184 if (DirectInit) { 10185 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10186 DeduceInits = PL->exprs(); 10187 } 10188 10189 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10190 assert(VDecl && "non-auto type for init capture deduction?"); 10191 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10192 InitializationKind Kind = InitializationKind::CreateForInit( 10193 VDecl->getLocation(), DirectInit, Init); 10194 // FIXME: Initialization should not be taking a mutable list of inits. 10195 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10196 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10197 InitsCopy); 10198 } 10199 10200 if (DirectInit) { 10201 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10202 DeduceInits = IL->inits(); 10203 } 10204 10205 // Deduction only works if we have exactly one source expression. 10206 if (DeduceInits.empty()) { 10207 // It isn't possible to write this directly, but it is possible to 10208 // end up in this situation with "auto x(some_pack...);" 10209 Diag(Init->getLocStart(), IsInitCapture 10210 ? diag::err_init_capture_no_expression 10211 : diag::err_auto_var_init_no_expression) 10212 << VN << Type << Range; 10213 return QualType(); 10214 } 10215 10216 if (DeduceInits.size() > 1) { 10217 Diag(DeduceInits[1]->getLocStart(), 10218 IsInitCapture ? diag::err_init_capture_multiple_expressions 10219 : diag::err_auto_var_init_multiple_expressions) 10220 << VN << Type << Range; 10221 return QualType(); 10222 } 10223 10224 Expr *DeduceInit = DeduceInits[0]; 10225 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10226 Diag(Init->getLocStart(), IsInitCapture 10227 ? diag::err_init_capture_paren_braces 10228 : diag::err_auto_var_init_paren_braces) 10229 << isa<InitListExpr>(Init) << VN << Type << Range; 10230 return QualType(); 10231 } 10232 10233 // Expressions default to 'id' when we're in a debugger. 10234 bool DefaultedAnyToId = false; 10235 if (getLangOpts().DebuggerCastResultToId && 10236 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10237 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10238 if (Result.isInvalid()) { 10239 return QualType(); 10240 } 10241 Init = Result.get(); 10242 DefaultedAnyToId = true; 10243 } 10244 10245 // C++ [dcl.decomp]p1: 10246 // If the assignment-expression [...] has array type A and no ref-qualifier 10247 // is present, e has type cv A 10248 if (VDecl && isa<DecompositionDecl>(VDecl) && 10249 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10250 DeduceInit->getType()->isConstantArrayType()) 10251 return Context.getQualifiedType(DeduceInit->getType(), 10252 Type.getQualifiers()); 10253 10254 QualType DeducedType; 10255 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10256 if (!IsInitCapture) 10257 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10258 else if (isa<InitListExpr>(Init)) 10259 Diag(Range.getBegin(), 10260 diag::err_init_capture_deduction_failure_from_init_list) 10261 << VN 10262 << (DeduceInit->getType().isNull() ? TSI->getType() 10263 : DeduceInit->getType()) 10264 << DeduceInit->getSourceRange(); 10265 else 10266 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10267 << VN << TSI->getType() 10268 << (DeduceInit->getType().isNull() ? TSI->getType() 10269 : DeduceInit->getType()) 10270 << DeduceInit->getSourceRange(); 10271 } 10272 10273 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10274 // 'id' instead of a specific object type prevents most of our usual 10275 // checks. 10276 // We only want to warn outside of template instantiations, though: 10277 // inside a template, the 'id' could have come from a parameter. 10278 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10279 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10280 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10281 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10282 } 10283 10284 return DeducedType; 10285 } 10286 10287 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10288 Expr *Init) { 10289 QualType DeducedType = deduceVarTypeFromInitializer( 10290 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10291 VDecl->getSourceRange(), DirectInit, Init); 10292 if (DeducedType.isNull()) { 10293 VDecl->setInvalidDecl(); 10294 return true; 10295 } 10296 10297 VDecl->setType(DeducedType); 10298 assert(VDecl->isLinkageValid()); 10299 10300 // In ARC, infer lifetime. 10301 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10302 VDecl->setInvalidDecl(); 10303 10304 // If this is a redeclaration, check that the type we just deduced matches 10305 // the previously declared type. 10306 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10307 // We never need to merge the type, because we cannot form an incomplete 10308 // array of auto, nor deduce such a type. 10309 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10310 } 10311 10312 // Check the deduced type is valid for a variable declaration. 10313 CheckVariableDeclarationType(VDecl); 10314 return VDecl->isInvalidDecl(); 10315 } 10316 10317 /// AddInitializerToDecl - Adds the initializer Init to the 10318 /// declaration dcl. If DirectInit is true, this is C++ direct 10319 /// initialization rather than copy initialization. 10320 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10321 // If there is no declaration, there was an error parsing it. Just ignore 10322 // the initializer. 10323 if (!RealDecl || RealDecl->isInvalidDecl()) { 10324 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10325 return; 10326 } 10327 10328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10329 // Pure-specifiers are handled in ActOnPureSpecifier. 10330 Diag(Method->getLocation(), diag::err_member_function_initialization) 10331 << Method->getDeclName() << Init->getSourceRange(); 10332 Method->setInvalidDecl(); 10333 return; 10334 } 10335 10336 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10337 if (!VDecl) { 10338 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10339 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10340 RealDecl->setInvalidDecl(); 10341 return; 10342 } 10343 10344 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10345 if (VDecl->getType()->isUndeducedType()) { 10346 // Attempt typo correction early so that the type of the init expression can 10347 // be deduced based on the chosen correction if the original init contains a 10348 // TypoExpr. 10349 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10350 if (!Res.isUsable()) { 10351 RealDecl->setInvalidDecl(); 10352 return; 10353 } 10354 Init = Res.get(); 10355 10356 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10357 return; 10358 } 10359 10360 // dllimport cannot be used on variable definitions. 10361 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10362 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10363 VDecl->setInvalidDecl(); 10364 return; 10365 } 10366 10367 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10368 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10369 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10370 VDecl->setInvalidDecl(); 10371 return; 10372 } 10373 10374 if (!VDecl->getType()->isDependentType()) { 10375 // A definition must end up with a complete type, which means it must be 10376 // complete with the restriction that an array type might be completed by 10377 // the initializer; note that later code assumes this restriction. 10378 QualType BaseDeclType = VDecl->getType(); 10379 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10380 BaseDeclType = Array->getElementType(); 10381 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10382 diag::err_typecheck_decl_incomplete_type)) { 10383 RealDecl->setInvalidDecl(); 10384 return; 10385 } 10386 10387 // The variable can not have an abstract class type. 10388 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10389 diag::err_abstract_type_in_decl, 10390 AbstractVariableType)) 10391 VDecl->setInvalidDecl(); 10392 } 10393 10394 // If adding the initializer will turn this declaration into a definition, 10395 // and we already have a definition for this variable, diagnose or otherwise 10396 // handle the situation. 10397 VarDecl *Def; 10398 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10399 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10400 !VDecl->isThisDeclarationADemotedDefinition() && 10401 checkVarDeclRedefinition(Def, VDecl)) 10402 return; 10403 10404 if (getLangOpts().CPlusPlus) { 10405 // C++ [class.static.data]p4 10406 // If a static data member is of const integral or const 10407 // enumeration type, its declaration in the class definition can 10408 // specify a constant-initializer which shall be an integral 10409 // constant expression (5.19). In that case, the member can appear 10410 // in integral constant expressions. The member shall still be 10411 // defined in a namespace scope if it is used in the program and the 10412 // namespace scope definition shall not contain an initializer. 10413 // 10414 // We already performed a redefinition check above, but for static 10415 // data members we also need to check whether there was an in-class 10416 // declaration with an initializer. 10417 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10418 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10419 << VDecl->getDeclName(); 10420 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10421 diag::note_previous_initializer) 10422 << 0; 10423 return; 10424 } 10425 10426 if (VDecl->hasLocalStorage()) 10427 getCurFunction()->setHasBranchProtectedScope(); 10428 10429 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10430 VDecl->setInvalidDecl(); 10431 return; 10432 } 10433 } 10434 10435 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10436 // a kernel function cannot be initialized." 10437 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10438 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10439 VDecl->setInvalidDecl(); 10440 return; 10441 } 10442 10443 // Get the decls type and save a reference for later, since 10444 // CheckInitializerTypes may change it. 10445 QualType DclT = VDecl->getType(), SavT = DclT; 10446 10447 // Expressions default to 'id' when we're in a debugger 10448 // and we are assigning it to a variable of Objective-C pointer type. 10449 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10450 Init->getType() == Context.UnknownAnyTy) { 10451 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10452 if (Result.isInvalid()) { 10453 VDecl->setInvalidDecl(); 10454 return; 10455 } 10456 Init = Result.get(); 10457 } 10458 10459 // Perform the initialization. 10460 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10461 if (!VDecl->isInvalidDecl()) { 10462 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10463 InitializationKind Kind = InitializationKind::CreateForInit( 10464 VDecl->getLocation(), DirectInit, Init); 10465 10466 MultiExprArg Args = Init; 10467 if (CXXDirectInit) 10468 Args = MultiExprArg(CXXDirectInit->getExprs(), 10469 CXXDirectInit->getNumExprs()); 10470 10471 // Try to correct any TypoExprs in the initialization arguments. 10472 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10473 ExprResult Res = CorrectDelayedTyposInExpr( 10474 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10475 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10476 return Init.Failed() ? ExprError() : E; 10477 }); 10478 if (Res.isInvalid()) { 10479 VDecl->setInvalidDecl(); 10480 } else if (Res.get() != Args[Idx]) { 10481 Args[Idx] = Res.get(); 10482 } 10483 } 10484 if (VDecl->isInvalidDecl()) 10485 return; 10486 10487 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10488 /*TopLevelOfInitList=*/false, 10489 /*TreatUnavailableAsInvalid=*/false); 10490 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10491 if (Result.isInvalid()) { 10492 VDecl->setInvalidDecl(); 10493 return; 10494 } 10495 10496 Init = Result.getAs<Expr>(); 10497 } 10498 10499 // Check for self-references within variable initializers. 10500 // Variables declared within a function/method body (except for references) 10501 // are handled by a dataflow analysis. 10502 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10503 VDecl->getType()->isReferenceType()) { 10504 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10505 } 10506 10507 // If the type changed, it means we had an incomplete type that was 10508 // completed by the initializer. For example: 10509 // int ary[] = { 1, 3, 5 }; 10510 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10511 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10512 VDecl->setType(DclT); 10513 10514 if (!VDecl->isInvalidDecl()) { 10515 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10516 10517 if (VDecl->hasAttr<BlocksAttr>()) 10518 checkRetainCycles(VDecl, Init); 10519 10520 // It is safe to assign a weak reference into a strong variable. 10521 // Although this code can still have problems: 10522 // id x = self.weakProp; 10523 // id y = self.weakProp; 10524 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10525 // paths through the function. This should be revisited if 10526 // -Wrepeated-use-of-weak is made flow-sensitive. 10527 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10528 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10529 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10530 Init->getLocStart())) 10531 getCurFunction()->markSafeWeakUse(Init); 10532 } 10533 10534 // The initialization is usually a full-expression. 10535 // 10536 // FIXME: If this is a braced initialization of an aggregate, it is not 10537 // an expression, and each individual field initializer is a separate 10538 // full-expression. For instance, in: 10539 // 10540 // struct Temp { ~Temp(); }; 10541 // struct S { S(Temp); }; 10542 // struct T { S a, b; } t = { Temp(), Temp() } 10543 // 10544 // we should destroy the first Temp before constructing the second. 10545 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10546 false, 10547 VDecl->isConstexpr()); 10548 if (Result.isInvalid()) { 10549 VDecl->setInvalidDecl(); 10550 return; 10551 } 10552 Init = Result.get(); 10553 10554 // Attach the initializer to the decl. 10555 VDecl->setInit(Init); 10556 10557 if (VDecl->isLocalVarDecl()) { 10558 // Don't check the initializer if the declaration is malformed. 10559 if (VDecl->isInvalidDecl()) { 10560 // do nothing 10561 10562 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10563 // This is true even in OpenCL C++. 10564 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10565 CheckForConstantInitializer(Init, DclT); 10566 10567 // Otherwise, C++ does not restrict the initializer. 10568 } else if (getLangOpts().CPlusPlus) { 10569 // do nothing 10570 10571 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10572 // static storage duration shall be constant expressions or string literals. 10573 } else if (VDecl->getStorageClass() == SC_Static) { 10574 CheckForConstantInitializer(Init, DclT); 10575 10576 // C89 is stricter than C99 for aggregate initializers. 10577 // C89 6.5.7p3: All the expressions [...] in an initializer list 10578 // for an object that has aggregate or union type shall be 10579 // constant expressions. 10580 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10581 isa<InitListExpr>(Init)) { 10582 const Expr *Culprit; 10583 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10584 Diag(Culprit->getExprLoc(), 10585 diag::ext_aggregate_init_not_constant) 10586 << Culprit->getSourceRange(); 10587 } 10588 } 10589 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10590 VDecl->getLexicalDeclContext()->isRecord()) { 10591 // This is an in-class initialization for a static data member, e.g., 10592 // 10593 // struct S { 10594 // static const int value = 17; 10595 // }; 10596 10597 // C++ [class.mem]p4: 10598 // A member-declarator can contain a constant-initializer only 10599 // if it declares a static member (9.4) of const integral or 10600 // const enumeration type, see 9.4.2. 10601 // 10602 // C++11 [class.static.data]p3: 10603 // If a non-volatile non-inline const static data member is of integral 10604 // or enumeration type, its declaration in the class definition can 10605 // specify a brace-or-equal-initializer in which every initializer-clause 10606 // that is an assignment-expression is a constant expression. A static 10607 // data member of literal type can be declared in the class definition 10608 // with the constexpr specifier; if so, its declaration shall specify a 10609 // brace-or-equal-initializer in which every initializer-clause that is 10610 // an assignment-expression is a constant expression. 10611 10612 // Do nothing on dependent types. 10613 if (DclT->isDependentType()) { 10614 10615 // Allow any 'static constexpr' members, whether or not they are of literal 10616 // type. We separately check that every constexpr variable is of literal 10617 // type. 10618 } else if (VDecl->isConstexpr()) { 10619 10620 // Require constness. 10621 } else if (!DclT.isConstQualified()) { 10622 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10623 << Init->getSourceRange(); 10624 VDecl->setInvalidDecl(); 10625 10626 // We allow integer constant expressions in all cases. 10627 } else if (DclT->isIntegralOrEnumerationType()) { 10628 // Check whether the expression is a constant expression. 10629 SourceLocation Loc; 10630 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10631 // In C++11, a non-constexpr const static data member with an 10632 // in-class initializer cannot be volatile. 10633 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10634 else if (Init->isValueDependent()) 10635 ; // Nothing to check. 10636 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10637 ; // Ok, it's an ICE! 10638 else if (Init->isEvaluatable(Context)) { 10639 // If we can constant fold the initializer through heroics, accept it, 10640 // but report this as a use of an extension for -pedantic. 10641 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10642 << Init->getSourceRange(); 10643 } else { 10644 // Otherwise, this is some crazy unknown case. Report the issue at the 10645 // location provided by the isIntegerConstantExpr failed check. 10646 Diag(Loc, diag::err_in_class_initializer_non_constant) 10647 << Init->getSourceRange(); 10648 VDecl->setInvalidDecl(); 10649 } 10650 10651 // We allow foldable floating-point constants as an extension. 10652 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10653 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10654 // it anyway and provide a fixit to add the 'constexpr'. 10655 if (getLangOpts().CPlusPlus11) { 10656 Diag(VDecl->getLocation(), 10657 diag::ext_in_class_initializer_float_type_cxx11) 10658 << DclT << Init->getSourceRange(); 10659 Diag(VDecl->getLocStart(), 10660 diag::note_in_class_initializer_float_type_cxx11) 10661 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10662 } else { 10663 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10664 << DclT << Init->getSourceRange(); 10665 10666 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10667 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10668 << Init->getSourceRange(); 10669 VDecl->setInvalidDecl(); 10670 } 10671 } 10672 10673 // Suggest adding 'constexpr' in C++11 for literal types. 10674 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10675 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10676 << DclT << Init->getSourceRange() 10677 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10678 VDecl->setConstexpr(true); 10679 10680 } else { 10681 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10682 << DclT << Init->getSourceRange(); 10683 VDecl->setInvalidDecl(); 10684 } 10685 } else if (VDecl->isFileVarDecl()) { 10686 // In C, extern is typically used to avoid tentative definitions when 10687 // declaring variables in headers, but adding an intializer makes it a 10688 // defintion. This is somewhat confusing, so GCC and Clang both warn on it. 10689 // In C++, extern is often used to give implictly static const variables 10690 // external linkage, so don't warn in that case. If selectany is present, 10691 // this might be header code intended for C and C++ inclusion, so apply the 10692 // C++ rules. 10693 if (VDecl->getStorageClass() == SC_Extern && 10694 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10695 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10696 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10697 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10698 Diag(VDecl->getLocation(), diag::warn_extern_init); 10699 10700 // C99 6.7.8p4. All file scoped initializers need to be constant. 10701 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10702 CheckForConstantInitializer(Init, DclT); 10703 } 10704 10705 // We will represent direct-initialization similarly to copy-initialization: 10706 // int x(1); -as-> int x = 1; 10707 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10708 // 10709 // Clients that want to distinguish between the two forms, can check for 10710 // direct initializer using VarDecl::getInitStyle(). 10711 // A major benefit is that clients that don't particularly care about which 10712 // exactly form was it (like the CodeGen) can handle both cases without 10713 // special case code. 10714 10715 // C++ 8.5p11: 10716 // The form of initialization (using parentheses or '=') is generally 10717 // insignificant, but does matter when the entity being initialized has a 10718 // class type. 10719 if (CXXDirectInit) { 10720 assert(DirectInit && "Call-style initializer must be direct init."); 10721 VDecl->setInitStyle(VarDecl::CallInit); 10722 } else if (DirectInit) { 10723 // This must be list-initialization. No other way is direct-initialization. 10724 VDecl->setInitStyle(VarDecl::ListInit); 10725 } 10726 10727 CheckCompleteVariableDeclaration(VDecl); 10728 } 10729 10730 /// ActOnInitializerError - Given that there was an error parsing an 10731 /// initializer for the given declaration, try to return to some form 10732 /// of sanity. 10733 void Sema::ActOnInitializerError(Decl *D) { 10734 // Our main concern here is re-establishing invariants like "a 10735 // variable's type is either dependent or complete". 10736 if (!D || D->isInvalidDecl()) return; 10737 10738 VarDecl *VD = dyn_cast<VarDecl>(D); 10739 if (!VD) return; 10740 10741 // Bindings are not usable if we can't make sense of the initializer. 10742 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10743 for (auto *BD : DD->bindings()) 10744 BD->setInvalidDecl(); 10745 10746 // Auto types are meaningless if we can't make sense of the initializer. 10747 if (ParsingInitForAutoVars.count(D)) { 10748 D->setInvalidDecl(); 10749 return; 10750 } 10751 10752 QualType Ty = VD->getType(); 10753 if (Ty->isDependentType()) return; 10754 10755 // Require a complete type. 10756 if (RequireCompleteType(VD->getLocation(), 10757 Context.getBaseElementType(Ty), 10758 diag::err_typecheck_decl_incomplete_type)) { 10759 VD->setInvalidDecl(); 10760 return; 10761 } 10762 10763 // Require a non-abstract type. 10764 if (RequireNonAbstractType(VD->getLocation(), Ty, 10765 diag::err_abstract_type_in_decl, 10766 AbstractVariableType)) { 10767 VD->setInvalidDecl(); 10768 return; 10769 } 10770 10771 // Don't bother complaining about constructors or destructors, 10772 // though. 10773 } 10774 10775 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 10776 // If there is no declaration, there was an error parsing it. Just ignore it. 10777 if (!RealDecl) 10778 return; 10779 10780 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 10781 QualType Type = Var->getType(); 10782 10783 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 10784 if (isa<DecompositionDecl>(RealDecl)) { 10785 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 10786 Var->setInvalidDecl(); 10787 return; 10788 } 10789 10790 if (Type->isUndeducedType() && 10791 DeduceVariableDeclarationType(Var, false, nullptr)) 10792 return; 10793 10794 // C++11 [class.static.data]p3: A static data member can be declared with 10795 // the constexpr specifier; if so, its declaration shall specify 10796 // a brace-or-equal-initializer. 10797 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 10798 // the definition of a variable [...] or the declaration of a static data 10799 // member. 10800 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 10801 !Var->isThisDeclarationADemotedDefinition()) { 10802 if (Var->isStaticDataMember()) { 10803 // C++1z removes the relevant rule; the in-class declaration is always 10804 // a definition there. 10805 if (!getLangOpts().CPlusPlus1z) { 10806 Diag(Var->getLocation(), 10807 diag::err_constexpr_static_mem_var_requires_init) 10808 << Var->getDeclName(); 10809 Var->setInvalidDecl(); 10810 return; 10811 } 10812 } else { 10813 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 10814 Var->setInvalidDecl(); 10815 return; 10816 } 10817 } 10818 10819 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 10820 // definition having the concept specifier is called a variable concept. A 10821 // concept definition refers to [...] a variable concept and its initializer. 10822 if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) { 10823 if (VTD->isConcept()) { 10824 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 10825 Var->setInvalidDecl(); 10826 return; 10827 } 10828 } 10829 10830 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 10831 // be initialized. 10832 if (!Var->isInvalidDecl() && 10833 Var->getType().getAddressSpace() == LangAS::opencl_constant && 10834 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 10835 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 10836 Var->setInvalidDecl(); 10837 return; 10838 } 10839 10840 switch (Var->isThisDeclarationADefinition()) { 10841 case VarDecl::Definition: 10842 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 10843 break; 10844 10845 // We have an out-of-line definition of a static data member 10846 // that has an in-class initializer, so we type-check this like 10847 // a declaration. 10848 // 10849 // Fall through 10850 10851 case VarDecl::DeclarationOnly: 10852 // It's only a declaration. 10853 10854 // Block scope. C99 6.7p7: If an identifier for an object is 10855 // declared with no linkage (C99 6.2.2p6), the type for the 10856 // object shall be complete. 10857 if (!Type->isDependentType() && Var->isLocalVarDecl() && 10858 !Var->hasLinkage() && !Var->isInvalidDecl() && 10859 RequireCompleteType(Var->getLocation(), Type, 10860 diag::err_typecheck_decl_incomplete_type)) 10861 Var->setInvalidDecl(); 10862 10863 // Make sure that the type is not abstract. 10864 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10865 RequireNonAbstractType(Var->getLocation(), Type, 10866 diag::err_abstract_type_in_decl, 10867 AbstractVariableType)) 10868 Var->setInvalidDecl(); 10869 if (!Type->isDependentType() && !Var->isInvalidDecl() && 10870 Var->getStorageClass() == SC_PrivateExtern) { 10871 Diag(Var->getLocation(), diag::warn_private_extern); 10872 Diag(Var->getLocation(), diag::note_private_extern); 10873 } 10874 10875 return; 10876 10877 case VarDecl::TentativeDefinition: 10878 // File scope. C99 6.9.2p2: A declaration of an identifier for an 10879 // object that has file scope without an initializer, and without a 10880 // storage-class specifier or with the storage-class specifier "static", 10881 // constitutes a tentative definition. Note: A tentative definition with 10882 // external linkage is valid (C99 6.2.2p5). 10883 if (!Var->isInvalidDecl()) { 10884 if (const IncompleteArrayType *ArrayT 10885 = Context.getAsIncompleteArrayType(Type)) { 10886 if (RequireCompleteType(Var->getLocation(), 10887 ArrayT->getElementType(), 10888 diag::err_illegal_decl_array_incomplete_type)) 10889 Var->setInvalidDecl(); 10890 } else if (Var->getStorageClass() == SC_Static) { 10891 // C99 6.9.2p3: If the declaration of an identifier for an object is 10892 // a tentative definition and has internal linkage (C99 6.2.2p3), the 10893 // declared type shall not be an incomplete type. 10894 // NOTE: code such as the following 10895 // static struct s; 10896 // struct s { int a; }; 10897 // is accepted by gcc. Hence here we issue a warning instead of 10898 // an error and we do not invalidate the static declaration. 10899 // NOTE: to avoid multiple warnings, only check the first declaration. 10900 if (Var->isFirstDecl()) 10901 RequireCompleteType(Var->getLocation(), Type, 10902 diag::ext_typecheck_decl_incomplete_type); 10903 } 10904 } 10905 10906 // Record the tentative definition; we're done. 10907 if (!Var->isInvalidDecl()) 10908 TentativeDefinitions.push_back(Var); 10909 return; 10910 } 10911 10912 // Provide a specific diagnostic for uninitialized variable 10913 // definitions with incomplete array type. 10914 if (Type->isIncompleteArrayType()) { 10915 Diag(Var->getLocation(), 10916 diag::err_typecheck_incomplete_array_needs_initializer); 10917 Var->setInvalidDecl(); 10918 return; 10919 } 10920 10921 // Provide a specific diagnostic for uninitialized variable 10922 // definitions with reference type. 10923 if (Type->isReferenceType()) { 10924 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 10925 << Var->getDeclName() 10926 << SourceRange(Var->getLocation(), Var->getLocation()); 10927 Var->setInvalidDecl(); 10928 return; 10929 } 10930 10931 // Do not attempt to type-check the default initializer for a 10932 // variable with dependent type. 10933 if (Type->isDependentType()) 10934 return; 10935 10936 if (Var->isInvalidDecl()) 10937 return; 10938 10939 if (!Var->hasAttr<AliasAttr>()) { 10940 if (RequireCompleteType(Var->getLocation(), 10941 Context.getBaseElementType(Type), 10942 diag::err_typecheck_decl_incomplete_type)) { 10943 Var->setInvalidDecl(); 10944 return; 10945 } 10946 } else { 10947 return; 10948 } 10949 10950 // The variable can not have an abstract class type. 10951 if (RequireNonAbstractType(Var->getLocation(), Type, 10952 diag::err_abstract_type_in_decl, 10953 AbstractVariableType)) { 10954 Var->setInvalidDecl(); 10955 return; 10956 } 10957 10958 // Check for jumps past the implicit initializer. C++0x 10959 // clarifies that this applies to a "variable with automatic 10960 // storage duration", not a "local variable". 10961 // C++11 [stmt.dcl]p3 10962 // A program that jumps from a point where a variable with automatic 10963 // storage duration is not in scope to a point where it is in scope is 10964 // ill-formed unless the variable has scalar type, class type with a 10965 // trivial default constructor and a trivial destructor, a cv-qualified 10966 // version of one of these types, or an array of one of the preceding 10967 // types and is declared without an initializer. 10968 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 10969 if (const RecordType *Record 10970 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 10971 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 10972 // Mark the function for further checking even if the looser rules of 10973 // C++11 do not require such checks, so that we can diagnose 10974 // incompatibilities with C++98. 10975 if (!CXXRecord->isPOD()) 10976 getCurFunction()->setHasBranchProtectedScope(); 10977 } 10978 } 10979 10980 // C++03 [dcl.init]p9: 10981 // If no initializer is specified for an object, and the 10982 // object is of (possibly cv-qualified) non-POD class type (or 10983 // array thereof), the object shall be default-initialized; if 10984 // the object is of const-qualified type, the underlying class 10985 // type shall have a user-declared default 10986 // constructor. Otherwise, if no initializer is specified for 10987 // a non- static object, the object and its subobjects, if 10988 // any, have an indeterminate initial value); if the object 10989 // or any of its subobjects are of const-qualified type, the 10990 // program is ill-formed. 10991 // C++0x [dcl.init]p11: 10992 // If no initializer is specified for an object, the object is 10993 // default-initialized; [...]. 10994 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 10995 InitializationKind Kind 10996 = InitializationKind::CreateDefault(Var->getLocation()); 10997 10998 InitializationSequence InitSeq(*this, Entity, Kind, None); 10999 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11000 if (Init.isInvalid()) 11001 Var->setInvalidDecl(); 11002 else if (Init.get()) { 11003 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11004 // This is important for template substitution. 11005 Var->setInitStyle(VarDecl::CallInit); 11006 } 11007 11008 CheckCompleteVariableDeclaration(Var); 11009 } 11010 } 11011 11012 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11013 // If there is no declaration, there was an error parsing it. Ignore it. 11014 if (!D) 11015 return; 11016 11017 VarDecl *VD = dyn_cast<VarDecl>(D); 11018 if (!VD) { 11019 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11020 D->setInvalidDecl(); 11021 return; 11022 } 11023 11024 VD->setCXXForRangeDecl(true); 11025 11026 // for-range-declaration cannot be given a storage class specifier. 11027 int Error = -1; 11028 switch (VD->getStorageClass()) { 11029 case SC_None: 11030 break; 11031 case SC_Extern: 11032 Error = 0; 11033 break; 11034 case SC_Static: 11035 Error = 1; 11036 break; 11037 case SC_PrivateExtern: 11038 Error = 2; 11039 break; 11040 case SC_Auto: 11041 Error = 3; 11042 break; 11043 case SC_Register: 11044 Error = 4; 11045 break; 11046 } 11047 if (Error != -1) { 11048 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11049 << VD->getDeclName() << Error; 11050 D->setInvalidDecl(); 11051 } 11052 } 11053 11054 StmtResult 11055 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11056 IdentifierInfo *Ident, 11057 ParsedAttributes &Attrs, 11058 SourceLocation AttrEnd) { 11059 // C++1y [stmt.iter]p1: 11060 // A range-based for statement of the form 11061 // for ( for-range-identifier : for-range-initializer ) statement 11062 // is equivalent to 11063 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11064 DeclSpec DS(Attrs.getPool().getFactory()); 11065 11066 const char *PrevSpec; 11067 unsigned DiagID; 11068 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11069 getPrintingPolicy()); 11070 11071 Declarator D(DS, Declarator::ForContext); 11072 D.SetIdentifier(Ident, IdentLoc); 11073 D.takeAttributes(Attrs, AttrEnd); 11074 11075 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11076 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 11077 EmptyAttrs, IdentLoc); 11078 Decl *Var = ActOnDeclarator(S, D); 11079 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11080 FinalizeDeclaration(Var); 11081 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11082 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11083 } 11084 11085 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11086 if (var->isInvalidDecl()) return; 11087 11088 if (getLangOpts().OpenCL) { 11089 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11090 // initialiser 11091 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11092 !var->hasInit()) { 11093 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11094 << 1 /*Init*/; 11095 var->setInvalidDecl(); 11096 return; 11097 } 11098 } 11099 11100 // In Objective-C, don't allow jumps past the implicit initialization of a 11101 // local retaining variable. 11102 if (getLangOpts().ObjC1 && 11103 var->hasLocalStorage()) { 11104 switch (var->getType().getObjCLifetime()) { 11105 case Qualifiers::OCL_None: 11106 case Qualifiers::OCL_ExplicitNone: 11107 case Qualifiers::OCL_Autoreleasing: 11108 break; 11109 11110 case Qualifiers::OCL_Weak: 11111 case Qualifiers::OCL_Strong: 11112 getCurFunction()->setHasBranchProtectedScope(); 11113 break; 11114 } 11115 } 11116 11117 // Warn about externally-visible variables being defined without a 11118 // prior declaration. We only want to do this for global 11119 // declarations, but we also specifically need to avoid doing it for 11120 // class members because the linkage of an anonymous class can 11121 // change if it's later given a typedef name. 11122 if (var->isThisDeclarationADefinition() && 11123 var->getDeclContext()->getRedeclContext()->isFileContext() && 11124 var->isExternallyVisible() && var->hasLinkage() && 11125 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11126 var->getLocation())) { 11127 // Find a previous declaration that's not a definition. 11128 VarDecl *prev = var->getPreviousDecl(); 11129 while (prev && prev->isThisDeclarationADefinition()) 11130 prev = prev->getPreviousDecl(); 11131 11132 if (!prev) 11133 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11134 } 11135 11136 // Cache the result of checking for constant initialization. 11137 Optional<bool> CacheHasConstInit; 11138 const Expr *CacheCulprit; 11139 auto checkConstInit = [&]() mutable { 11140 if (!CacheHasConstInit) 11141 CacheHasConstInit = var->getInit()->isConstantInitializer( 11142 Context, var->getType()->isReferenceType(), &CacheCulprit); 11143 return *CacheHasConstInit; 11144 }; 11145 11146 if (var->getTLSKind() == VarDecl::TLS_Static) { 11147 if (var->getType().isDestructedType()) { 11148 // GNU C++98 edits for __thread, [basic.start.term]p3: 11149 // The type of an object with thread storage duration shall not 11150 // have a non-trivial destructor. 11151 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11152 if (getLangOpts().CPlusPlus11) 11153 Diag(var->getLocation(), diag::note_use_thread_local); 11154 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11155 if (!checkConstInit()) { 11156 // GNU C++98 edits for __thread, [basic.start.init]p4: 11157 // An object of thread storage duration shall not require dynamic 11158 // initialization. 11159 // FIXME: Need strict checking here. 11160 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11161 << CacheCulprit->getSourceRange(); 11162 if (getLangOpts().CPlusPlus11) 11163 Diag(var->getLocation(), diag::note_use_thread_local); 11164 } 11165 } 11166 } 11167 11168 // Apply section attributes and pragmas to global variables. 11169 bool GlobalStorage = var->hasGlobalStorage(); 11170 if (GlobalStorage && var->isThisDeclarationADefinition() && 11171 !inTemplateInstantiation()) { 11172 PragmaStack<StringLiteral *> *Stack = nullptr; 11173 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11174 if (var->getType().isConstQualified()) 11175 Stack = &ConstSegStack; 11176 else if (!var->getInit()) { 11177 Stack = &BSSSegStack; 11178 SectionFlags |= ASTContext::PSF_Write; 11179 } else { 11180 Stack = &DataSegStack; 11181 SectionFlags |= ASTContext::PSF_Write; 11182 } 11183 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11184 var->addAttr(SectionAttr::CreateImplicit( 11185 Context, SectionAttr::Declspec_allocate, 11186 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11187 } 11188 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11189 if (UnifySection(SA->getName(), SectionFlags, var)) 11190 var->dropAttr<SectionAttr>(); 11191 11192 // Apply the init_seg attribute if this has an initializer. If the 11193 // initializer turns out to not be dynamic, we'll end up ignoring this 11194 // attribute. 11195 if (CurInitSeg && var->getInit()) 11196 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11197 CurInitSegLoc)); 11198 } 11199 11200 // All the following checks are C++ only. 11201 if (!getLangOpts().CPlusPlus) { 11202 // If this variable must be emitted, add it as an initializer for the 11203 // current module. 11204 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11205 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11206 return; 11207 } 11208 11209 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11210 CheckCompleteDecompositionDeclaration(DD); 11211 11212 QualType type = var->getType(); 11213 if (type->isDependentType()) return; 11214 11215 // __block variables might require us to capture a copy-initializer. 11216 if (var->hasAttr<BlocksAttr>()) { 11217 // It's currently invalid to ever have a __block variable with an 11218 // array type; should we diagnose that here? 11219 11220 // Regardless, we don't want to ignore array nesting when 11221 // constructing this copy. 11222 if (type->isStructureOrClassType()) { 11223 EnterExpressionEvaluationContext scope( 11224 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11225 SourceLocation poi = var->getLocation(); 11226 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11227 ExprResult result 11228 = PerformMoveOrCopyInitialization( 11229 InitializedEntity::InitializeBlock(poi, type, false), 11230 var, var->getType(), varRef, /*AllowNRVO=*/true); 11231 if (!result.isInvalid()) { 11232 result = MaybeCreateExprWithCleanups(result); 11233 Expr *init = result.getAs<Expr>(); 11234 Context.setBlockVarCopyInits(var, init); 11235 } 11236 } 11237 } 11238 11239 Expr *Init = var->getInit(); 11240 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11241 QualType baseType = Context.getBaseElementType(type); 11242 11243 if (Init && !Init->isValueDependent()) { 11244 if (var->isConstexpr()) { 11245 SmallVector<PartialDiagnosticAt, 8> Notes; 11246 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11247 SourceLocation DiagLoc = var->getLocation(); 11248 // If the note doesn't add any useful information other than a source 11249 // location, fold it into the primary diagnostic. 11250 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11251 diag::note_invalid_subexpr_in_const_expr) { 11252 DiagLoc = Notes[0].first; 11253 Notes.clear(); 11254 } 11255 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11256 << var << Init->getSourceRange(); 11257 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11258 Diag(Notes[I].first, Notes[I].second); 11259 } 11260 } else if (var->isUsableInConstantExpressions(Context)) { 11261 // Check whether the initializer of a const variable of integral or 11262 // enumeration type is an ICE now, since we can't tell whether it was 11263 // initialized by a constant expression if we check later. 11264 var->checkInitIsICE(); 11265 } 11266 11267 // Don't emit further diagnostics about constexpr globals since they 11268 // were just diagnosed. 11269 if (!var->isConstexpr() && GlobalStorage && 11270 var->hasAttr<RequireConstantInitAttr>()) { 11271 // FIXME: Need strict checking in C++03 here. 11272 bool DiagErr = getLangOpts().CPlusPlus11 11273 ? !var->checkInitIsICE() : !checkConstInit(); 11274 if (DiagErr) { 11275 auto attr = var->getAttr<RequireConstantInitAttr>(); 11276 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11277 << Init->getSourceRange(); 11278 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11279 << attr->getRange(); 11280 if (getLangOpts().CPlusPlus11) { 11281 APValue Value; 11282 SmallVector<PartialDiagnosticAt, 8> Notes; 11283 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11284 for (auto &it : Notes) 11285 Diag(it.first, it.second); 11286 } else { 11287 Diag(CacheCulprit->getExprLoc(), 11288 diag::note_invalid_subexpr_in_const_expr) 11289 << CacheCulprit->getSourceRange(); 11290 } 11291 } 11292 } 11293 else if (!var->isConstexpr() && IsGlobal && 11294 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11295 var->getLocation())) { 11296 // Warn about globals which don't have a constant initializer. Don't 11297 // warn about globals with a non-trivial destructor because we already 11298 // warned about them. 11299 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11300 if (!(RD && !RD->hasTrivialDestructor())) { 11301 if (!checkConstInit()) 11302 Diag(var->getLocation(), diag::warn_global_constructor) 11303 << Init->getSourceRange(); 11304 } 11305 } 11306 } 11307 11308 // Require the destructor. 11309 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11310 FinalizeVarWithDestructor(var, recordType); 11311 11312 // If this variable must be emitted, add it as an initializer for the current 11313 // module. 11314 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11315 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11316 } 11317 11318 /// \brief Determines if a variable's alignment is dependent. 11319 static bool hasDependentAlignment(VarDecl *VD) { 11320 if (VD->getType()->isDependentType()) 11321 return true; 11322 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11323 if (I->isAlignmentDependent()) 11324 return true; 11325 return false; 11326 } 11327 11328 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11329 /// any semantic actions necessary after any initializer has been attached. 11330 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11331 // Note that we are no longer parsing the initializer for this declaration. 11332 ParsingInitForAutoVars.erase(ThisDecl); 11333 11334 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11335 if (!VD) 11336 return; 11337 11338 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11339 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11340 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11341 if (PragmaClangBSSSection.Valid) 11342 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11343 PragmaClangBSSSection.SectionName, 11344 PragmaClangBSSSection.PragmaLocation)); 11345 if (PragmaClangDataSection.Valid) 11346 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11347 PragmaClangDataSection.SectionName, 11348 PragmaClangDataSection.PragmaLocation)); 11349 if (PragmaClangRodataSection.Valid) 11350 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11351 PragmaClangRodataSection.SectionName, 11352 PragmaClangRodataSection.PragmaLocation)); 11353 } 11354 11355 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11356 for (auto *BD : DD->bindings()) { 11357 FinalizeDeclaration(BD); 11358 } 11359 } 11360 11361 checkAttributesAfterMerging(*this, *VD); 11362 11363 // Perform TLS alignment check here after attributes attached to the variable 11364 // which may affect the alignment have been processed. Only perform the check 11365 // if the target has a maximum TLS alignment (zero means no constraints). 11366 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11367 // Protect the check so that it's not performed on dependent types and 11368 // dependent alignments (we can't determine the alignment in that case). 11369 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11370 !VD->isInvalidDecl()) { 11371 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11372 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11373 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11374 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11375 << (unsigned)MaxAlignChars.getQuantity(); 11376 } 11377 } 11378 } 11379 11380 if (VD->isStaticLocal()) { 11381 if (FunctionDecl *FD = 11382 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11383 // Static locals inherit dll attributes from their function. 11384 if (Attr *A = getDLLAttr(FD)) { 11385 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11386 NewAttr->setInherited(true); 11387 VD->addAttr(NewAttr); 11388 } 11389 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11390 // function, only __shared__ variables may be declared with 11391 // static storage class. 11392 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11393 CUDADiagIfDeviceCode(VD->getLocation(), 11394 diag::err_device_static_local_var) 11395 << CurrentCUDATarget()) 11396 VD->setInvalidDecl(); 11397 } 11398 } 11399 11400 // Perform check for initializers of device-side global variables. 11401 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11402 // 7.5). We must also apply the same checks to all __shared__ 11403 // variables whether they are local or not. CUDA also allows 11404 // constant initializers for __constant__ and __device__ variables. 11405 if (getLangOpts().CUDA) { 11406 const Expr *Init = VD->getInit(); 11407 if (Init && VD->hasGlobalStorage()) { 11408 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11409 VD->hasAttr<CUDASharedAttr>()) { 11410 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11411 bool AllowedInit = false; 11412 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11413 AllowedInit = 11414 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11415 // We'll allow constant initializers even if it's a non-empty 11416 // constructor according to CUDA rules. This deviates from NVCC, 11417 // but allows us to handle things like constexpr constructors. 11418 if (!AllowedInit && 11419 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11420 AllowedInit = VD->getInit()->isConstantInitializer( 11421 Context, VD->getType()->isReferenceType()); 11422 11423 // Also make sure that destructor, if there is one, is empty. 11424 if (AllowedInit) 11425 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11426 AllowedInit = 11427 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11428 11429 if (!AllowedInit) { 11430 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11431 ? diag::err_shared_var_init 11432 : diag::err_dynamic_var_init) 11433 << Init->getSourceRange(); 11434 VD->setInvalidDecl(); 11435 } 11436 } else { 11437 // This is a host-side global variable. Check that the initializer is 11438 // callable from the host side. 11439 const FunctionDecl *InitFn = nullptr; 11440 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11441 InitFn = CE->getConstructor(); 11442 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11443 InitFn = CE->getDirectCallee(); 11444 } 11445 if (InitFn) { 11446 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11447 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11448 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11449 << InitFnTarget << InitFn; 11450 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11451 VD->setInvalidDecl(); 11452 } 11453 } 11454 } 11455 } 11456 } 11457 11458 // Grab the dllimport or dllexport attribute off of the VarDecl. 11459 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11460 11461 // Imported static data members cannot be defined out-of-line. 11462 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11463 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11464 VD->isThisDeclarationADefinition()) { 11465 // We allow definitions of dllimport class template static data members 11466 // with a warning. 11467 CXXRecordDecl *Context = 11468 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11469 bool IsClassTemplateMember = 11470 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11471 Context->getDescribedClassTemplate(); 11472 11473 Diag(VD->getLocation(), 11474 IsClassTemplateMember 11475 ? diag::warn_attribute_dllimport_static_field_definition 11476 : diag::err_attribute_dllimport_static_field_definition); 11477 Diag(IA->getLocation(), diag::note_attribute); 11478 if (!IsClassTemplateMember) 11479 VD->setInvalidDecl(); 11480 } 11481 } 11482 11483 // dllimport/dllexport variables cannot be thread local, their TLS index 11484 // isn't exported with the variable. 11485 if (DLLAttr && VD->getTLSKind()) { 11486 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11487 if (F && getDLLAttr(F)) { 11488 assert(VD->isStaticLocal()); 11489 // But if this is a static local in a dlimport/dllexport function, the 11490 // function will never be inlined, which means the var would never be 11491 // imported, so having it marked import/export is safe. 11492 } else { 11493 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11494 << DLLAttr; 11495 VD->setInvalidDecl(); 11496 } 11497 } 11498 11499 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11500 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11501 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11502 VD->dropAttr<UsedAttr>(); 11503 } 11504 } 11505 11506 const DeclContext *DC = VD->getDeclContext(); 11507 // If there's a #pragma GCC visibility in scope, and this isn't a class 11508 // member, set the visibility of this variable. 11509 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11510 AddPushedVisibilityAttribute(VD); 11511 11512 // FIXME: Warn on unused var template partial specializations. 11513 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11514 MarkUnusedFileScopedDecl(VD); 11515 11516 // Now we have parsed the initializer and can update the table of magic 11517 // tag values. 11518 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11519 !VD->getType()->isIntegralOrEnumerationType()) 11520 return; 11521 11522 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11523 const Expr *MagicValueExpr = VD->getInit(); 11524 if (!MagicValueExpr) { 11525 continue; 11526 } 11527 llvm::APSInt MagicValueInt; 11528 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11529 Diag(I->getRange().getBegin(), 11530 diag::err_type_tag_for_datatype_not_ice) 11531 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11532 continue; 11533 } 11534 if (MagicValueInt.getActiveBits() > 64) { 11535 Diag(I->getRange().getBegin(), 11536 diag::err_type_tag_for_datatype_too_large) 11537 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11538 continue; 11539 } 11540 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11541 RegisterTypeTagForDatatype(I->getArgumentKind(), 11542 MagicValue, 11543 I->getMatchingCType(), 11544 I->getLayoutCompatible(), 11545 I->getMustBeNull()); 11546 } 11547 } 11548 11549 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11550 auto *VD = dyn_cast<VarDecl>(DD); 11551 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11552 } 11553 11554 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11555 ArrayRef<Decl *> Group) { 11556 SmallVector<Decl*, 8> Decls; 11557 11558 if (DS.isTypeSpecOwned()) 11559 Decls.push_back(DS.getRepAsDecl()); 11560 11561 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11562 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11563 bool DiagnosedMultipleDecomps = false; 11564 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11565 bool DiagnosedNonDeducedAuto = false; 11566 11567 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11568 if (Decl *D = Group[i]) { 11569 // For declarators, there are some additional syntactic-ish checks we need 11570 // to perform. 11571 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11572 if (!FirstDeclaratorInGroup) 11573 FirstDeclaratorInGroup = DD; 11574 if (!FirstDecompDeclaratorInGroup) 11575 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11576 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11577 !hasDeducedAuto(DD)) 11578 FirstNonDeducedAutoInGroup = DD; 11579 11580 if (FirstDeclaratorInGroup != DD) { 11581 // A decomposition declaration cannot be combined with any other 11582 // declaration in the same group. 11583 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11584 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11585 diag::err_decomp_decl_not_alone) 11586 << FirstDeclaratorInGroup->getSourceRange() 11587 << DD->getSourceRange(); 11588 DiagnosedMultipleDecomps = true; 11589 } 11590 11591 // A declarator that uses 'auto' in any way other than to declare a 11592 // variable with a deduced type cannot be combined with any other 11593 // declarator in the same group. 11594 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11595 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11596 diag::err_auto_non_deduced_not_alone) 11597 << FirstNonDeducedAutoInGroup->getType() 11598 ->hasAutoForTrailingReturnType() 11599 << FirstDeclaratorInGroup->getSourceRange() 11600 << DD->getSourceRange(); 11601 DiagnosedNonDeducedAuto = true; 11602 } 11603 } 11604 } 11605 11606 Decls.push_back(D); 11607 } 11608 } 11609 11610 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11611 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11612 handleTagNumbering(Tag, S); 11613 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11614 getLangOpts().CPlusPlus) 11615 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11616 } 11617 } 11618 11619 return BuildDeclaratorGroup(Decls); 11620 } 11621 11622 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11623 /// group, performing any necessary semantic checking. 11624 Sema::DeclGroupPtrTy 11625 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11626 // C++14 [dcl.spec.auto]p7: (DR1347) 11627 // If the type that replaces the placeholder type is not the same in each 11628 // deduction, the program is ill-formed. 11629 if (Group.size() > 1) { 11630 QualType Deduced; 11631 VarDecl *DeducedDecl = nullptr; 11632 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11633 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11634 if (!D || D->isInvalidDecl()) 11635 break; 11636 DeducedType *DT = D->getType()->getContainedDeducedType(); 11637 if (!DT || DT->getDeducedType().isNull()) 11638 continue; 11639 if (Deduced.isNull()) { 11640 Deduced = DT->getDeducedType(); 11641 DeducedDecl = D; 11642 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11643 auto *AT = dyn_cast<AutoType>(DT); 11644 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11645 diag::err_auto_different_deductions) 11646 << (AT ? (unsigned)AT->getKeyword() : 3) 11647 << Deduced << DeducedDecl->getDeclName() 11648 << DT->getDeducedType() << D->getDeclName() 11649 << DeducedDecl->getInit()->getSourceRange() 11650 << D->getInit()->getSourceRange(); 11651 D->setInvalidDecl(); 11652 break; 11653 } 11654 } 11655 } 11656 11657 ActOnDocumentableDecls(Group); 11658 11659 return DeclGroupPtrTy::make( 11660 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11661 } 11662 11663 void Sema::ActOnDocumentableDecl(Decl *D) { 11664 ActOnDocumentableDecls(D); 11665 } 11666 11667 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11668 // Don't parse the comment if Doxygen diagnostics are ignored. 11669 if (Group.empty() || !Group[0]) 11670 return; 11671 11672 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11673 Group[0]->getLocation()) && 11674 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11675 Group[0]->getLocation())) 11676 return; 11677 11678 if (Group.size() >= 2) { 11679 // This is a decl group. Normally it will contain only declarations 11680 // produced from declarator list. But in case we have any definitions or 11681 // additional declaration references: 11682 // 'typedef struct S {} S;' 11683 // 'typedef struct S *S;' 11684 // 'struct S *pS;' 11685 // FinalizeDeclaratorGroup adds these as separate declarations. 11686 Decl *MaybeTagDecl = Group[0]; 11687 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11688 Group = Group.slice(1); 11689 } 11690 } 11691 11692 // See if there are any new comments that are not attached to a decl. 11693 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11694 if (!Comments.empty() && 11695 !Comments.back()->isAttached()) { 11696 // There is at least one comment that not attached to a decl. 11697 // Maybe it should be attached to one of these decls? 11698 // 11699 // Note that this way we pick up not only comments that precede the 11700 // declaration, but also comments that *follow* the declaration -- thanks to 11701 // the lookahead in the lexer: we've consumed the semicolon and looked 11702 // ahead through comments. 11703 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11704 Context.getCommentForDecl(Group[i], &PP); 11705 } 11706 } 11707 11708 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11709 /// to introduce parameters into function prototype scope. 11710 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11711 const DeclSpec &DS = D.getDeclSpec(); 11712 11713 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11714 11715 // C++03 [dcl.stc]p2 also permits 'auto'. 11716 StorageClass SC = SC_None; 11717 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11718 SC = SC_Register; 11719 } else if (getLangOpts().CPlusPlus && 11720 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11721 SC = SC_Auto; 11722 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11723 Diag(DS.getStorageClassSpecLoc(), 11724 diag::err_invalid_storage_class_in_func_decl); 11725 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11726 } 11727 11728 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11729 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11730 << DeclSpec::getSpecifierName(TSCS); 11731 if (DS.isInlineSpecified()) 11732 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11733 << getLangOpts().CPlusPlus1z; 11734 if (DS.isConstexprSpecified()) 11735 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11736 << 0; 11737 if (DS.isConceptSpecified()) 11738 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 11739 11740 DiagnoseFunctionSpecifiers(DS); 11741 11742 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11743 QualType parmDeclType = TInfo->getType(); 11744 11745 if (getLangOpts().CPlusPlus) { 11746 // Check that there are no default arguments inside the type of this 11747 // parameter. 11748 CheckExtraCXXDefaultArguments(D); 11749 11750 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 11751 if (D.getCXXScopeSpec().isSet()) { 11752 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 11753 << D.getCXXScopeSpec().getRange(); 11754 D.getCXXScopeSpec().clear(); 11755 } 11756 } 11757 11758 // Ensure we have a valid name 11759 IdentifierInfo *II = nullptr; 11760 if (D.hasName()) { 11761 II = D.getIdentifier(); 11762 if (!II) { 11763 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 11764 << GetNameForDeclarator(D).getName(); 11765 D.setInvalidType(true); 11766 } 11767 } 11768 11769 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 11770 if (II) { 11771 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 11772 ForVisibleRedeclaration); 11773 LookupName(R, S); 11774 if (R.isSingleResult()) { 11775 NamedDecl *PrevDecl = R.getFoundDecl(); 11776 if (PrevDecl->isTemplateParameter()) { 11777 // Maybe we will complain about the shadowed template parameter. 11778 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 11779 // Just pretend that we didn't see the previous declaration. 11780 PrevDecl = nullptr; 11781 } else if (S->isDeclScope(PrevDecl)) { 11782 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 11783 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 11784 11785 // Recover by removing the name 11786 II = nullptr; 11787 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 11788 D.setInvalidType(true); 11789 } 11790 } 11791 } 11792 11793 // Temporarily put parameter variables in the translation unit, not 11794 // the enclosing context. This prevents them from accidentally 11795 // looking like class members in C++. 11796 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 11797 D.getLocStart(), 11798 D.getIdentifierLoc(), II, 11799 parmDeclType, TInfo, 11800 SC); 11801 11802 if (D.isInvalidType()) 11803 New->setInvalidDecl(); 11804 11805 assert(S->isFunctionPrototypeScope()); 11806 assert(S->getFunctionPrototypeDepth() >= 1); 11807 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 11808 S->getNextFunctionPrototypeIndex()); 11809 11810 // Add the parameter declaration into this scope. 11811 S->AddDecl(New); 11812 if (II) 11813 IdResolver.AddDecl(New); 11814 11815 ProcessDeclAttributes(S, New, D); 11816 11817 if (D.getDeclSpec().isModulePrivateSpecified()) 11818 Diag(New->getLocation(), diag::err_module_private_local) 11819 << 1 << New->getDeclName() 11820 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11821 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11822 11823 if (New->hasAttr<BlocksAttr>()) { 11824 Diag(New->getLocation(), diag::err_block_on_nonlocal); 11825 } 11826 return New; 11827 } 11828 11829 /// \brief Synthesizes a variable for a parameter arising from a 11830 /// typedef. 11831 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 11832 SourceLocation Loc, 11833 QualType T) { 11834 /* FIXME: setting StartLoc == Loc. 11835 Would it be worth to modify callers so as to provide proper source 11836 location for the unnamed parameters, embedding the parameter's type? */ 11837 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 11838 T, Context.getTrivialTypeSourceInfo(T, Loc), 11839 SC_None, nullptr); 11840 Param->setImplicit(); 11841 return Param; 11842 } 11843 11844 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 11845 // Don't diagnose unused-parameter errors in template instantiations; we 11846 // will already have done so in the template itself. 11847 if (inTemplateInstantiation()) 11848 return; 11849 11850 for (const ParmVarDecl *Parameter : Parameters) { 11851 if (!Parameter->isReferenced() && Parameter->getDeclName() && 11852 !Parameter->hasAttr<UnusedAttr>()) { 11853 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 11854 << Parameter->getDeclName(); 11855 } 11856 } 11857 } 11858 11859 void Sema::DiagnoseSizeOfParametersAndReturnValue( 11860 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 11861 if (LangOpts.NumLargeByValueCopy == 0) // No check. 11862 return; 11863 11864 // Warn if the return value is pass-by-value and larger than the specified 11865 // threshold. 11866 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 11867 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 11868 if (Size > LangOpts.NumLargeByValueCopy) 11869 Diag(D->getLocation(), diag::warn_return_value_size) 11870 << D->getDeclName() << Size; 11871 } 11872 11873 // Warn if any parameter is pass-by-value and larger than the specified 11874 // threshold. 11875 for (const ParmVarDecl *Parameter : Parameters) { 11876 QualType T = Parameter->getType(); 11877 if (T->isDependentType() || !T.isPODType(Context)) 11878 continue; 11879 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 11880 if (Size > LangOpts.NumLargeByValueCopy) 11881 Diag(Parameter->getLocation(), diag::warn_parameter_size) 11882 << Parameter->getDeclName() << Size; 11883 } 11884 } 11885 11886 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 11887 SourceLocation NameLoc, IdentifierInfo *Name, 11888 QualType T, TypeSourceInfo *TSInfo, 11889 StorageClass SC) { 11890 // In ARC, infer a lifetime qualifier for appropriate parameter types. 11891 if (getLangOpts().ObjCAutoRefCount && 11892 T.getObjCLifetime() == Qualifiers::OCL_None && 11893 T->isObjCLifetimeType()) { 11894 11895 Qualifiers::ObjCLifetime lifetime; 11896 11897 // Special cases for arrays: 11898 // - if it's const, use __unsafe_unretained 11899 // - otherwise, it's an error 11900 if (T->isArrayType()) { 11901 if (!T.isConstQualified()) { 11902 DelayedDiagnostics.add( 11903 sema::DelayedDiagnostic::makeForbiddenType( 11904 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 11905 } 11906 lifetime = Qualifiers::OCL_ExplicitNone; 11907 } else { 11908 lifetime = T->getObjCARCImplicitLifetime(); 11909 } 11910 T = Context.getLifetimeQualifiedType(T, lifetime); 11911 } 11912 11913 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 11914 Context.getAdjustedParameterType(T), 11915 TSInfo, SC, nullptr); 11916 11917 // Parameters can not be abstract class types. 11918 // For record types, this is done by the AbstractClassUsageDiagnoser once 11919 // the class has been completely parsed. 11920 if (!CurContext->isRecord() && 11921 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 11922 AbstractParamType)) 11923 New->setInvalidDecl(); 11924 11925 // Parameter declarators cannot be interface types. All ObjC objects are 11926 // passed by reference. 11927 if (T->isObjCObjectType()) { 11928 SourceLocation TypeEndLoc = 11929 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 11930 Diag(NameLoc, 11931 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 11932 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 11933 T = Context.getObjCObjectPointerType(T); 11934 New->setType(T); 11935 } 11936 11937 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 11938 // duration shall not be qualified by an address-space qualifier." 11939 // Since all parameters have automatic store duration, they can not have 11940 // an address space. 11941 if (T.getAddressSpace() != LangAS::Default && 11942 // OpenCL allows function arguments declared to be an array of a type 11943 // to be qualified with an address space. 11944 !(getLangOpts().OpenCL && 11945 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 11946 Diag(NameLoc, diag::err_arg_with_address_space); 11947 New->setInvalidDecl(); 11948 } 11949 11950 return New; 11951 } 11952 11953 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 11954 SourceLocation LocAfterDecls) { 11955 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 11956 11957 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 11958 // for a K&R function. 11959 if (!FTI.hasPrototype) { 11960 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 11961 --i; 11962 if (FTI.Params[i].Param == nullptr) { 11963 SmallString<256> Code; 11964 llvm::raw_svector_ostream(Code) 11965 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 11966 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 11967 << FTI.Params[i].Ident 11968 << FixItHint::CreateInsertion(LocAfterDecls, Code); 11969 11970 // Implicitly declare the argument as type 'int' for lack of a better 11971 // type. 11972 AttributeFactory attrs; 11973 DeclSpec DS(attrs); 11974 const char* PrevSpec; // unused 11975 unsigned DiagID; // unused 11976 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 11977 DiagID, Context.getPrintingPolicy()); 11978 // Use the identifier location for the type source range. 11979 DS.SetRangeStart(FTI.Params[i].IdentLoc); 11980 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 11981 Declarator ParamD(DS, Declarator::KNRTypeListContext); 11982 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 11983 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 11984 } 11985 } 11986 } 11987 } 11988 11989 Decl * 11990 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 11991 MultiTemplateParamsArg TemplateParameterLists, 11992 SkipBodyInfo *SkipBody) { 11993 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 11994 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 11995 Scope *ParentScope = FnBodyScope->getParent(); 11996 11997 D.setFunctionDefinitionKind(FDK_Definition); 11998 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 11999 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12000 } 12001 12002 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12003 Consumer.HandleInlineFunctionDefinition(D); 12004 } 12005 12006 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12007 const FunctionDecl*& PossibleZeroParamPrototype) { 12008 // Don't warn about invalid declarations. 12009 if (FD->isInvalidDecl()) 12010 return false; 12011 12012 // Or declarations that aren't global. 12013 if (!FD->isGlobal()) 12014 return false; 12015 12016 // Don't warn about C++ member functions. 12017 if (isa<CXXMethodDecl>(FD)) 12018 return false; 12019 12020 // Don't warn about 'main'. 12021 if (FD->isMain()) 12022 return false; 12023 12024 // Don't warn about inline functions. 12025 if (FD->isInlined()) 12026 return false; 12027 12028 // Don't warn about function templates. 12029 if (FD->getDescribedFunctionTemplate()) 12030 return false; 12031 12032 // Don't warn about function template specializations. 12033 if (FD->isFunctionTemplateSpecialization()) 12034 return false; 12035 12036 // Don't warn for OpenCL kernels. 12037 if (FD->hasAttr<OpenCLKernelAttr>()) 12038 return false; 12039 12040 // Don't warn on explicitly deleted functions. 12041 if (FD->isDeleted()) 12042 return false; 12043 12044 bool MissingPrototype = true; 12045 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12046 Prev; Prev = Prev->getPreviousDecl()) { 12047 // Ignore any declarations that occur in function or method 12048 // scope, because they aren't visible from the header. 12049 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12050 continue; 12051 12052 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12053 if (FD->getNumParams() == 0) 12054 PossibleZeroParamPrototype = Prev; 12055 break; 12056 } 12057 12058 return MissingPrototype; 12059 } 12060 12061 void 12062 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12063 const FunctionDecl *EffectiveDefinition, 12064 SkipBodyInfo *SkipBody) { 12065 const FunctionDecl *Definition = EffectiveDefinition; 12066 if (!Definition) 12067 if (!FD->isDefined(Definition)) 12068 return; 12069 12070 if (canRedefineFunction(Definition, getLangOpts())) 12071 return; 12072 12073 // Don't emit an error when this is redefinition of a typo-corrected 12074 // definition. 12075 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12076 return; 12077 12078 // If we don't have a visible definition of the function, and it's inline or 12079 // a template, skip the new definition. 12080 if (SkipBody && !hasVisibleDefinition(Definition) && 12081 (Definition->getFormalLinkage() == InternalLinkage || 12082 Definition->isInlined() || 12083 Definition->getDescribedFunctionTemplate() || 12084 Definition->getNumTemplateParameterLists())) { 12085 SkipBody->ShouldSkip = true; 12086 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12087 makeMergedDefinitionVisible(TD); 12088 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12089 return; 12090 } 12091 12092 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12093 Definition->getStorageClass() == SC_Extern) 12094 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12095 << FD->getDeclName() << getLangOpts().CPlusPlus; 12096 else 12097 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12098 12099 Diag(Definition->getLocation(), diag::note_previous_definition); 12100 FD->setInvalidDecl(); 12101 } 12102 12103 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12104 Sema &S) { 12105 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12106 12107 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12108 LSI->CallOperator = CallOperator; 12109 LSI->Lambda = LambdaClass; 12110 LSI->ReturnType = CallOperator->getReturnType(); 12111 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12112 12113 if (LCD == LCD_None) 12114 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12115 else if (LCD == LCD_ByCopy) 12116 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12117 else if (LCD == LCD_ByRef) 12118 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12119 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12120 12121 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12122 LSI->Mutable = !CallOperator->isConst(); 12123 12124 // Add the captures to the LSI so they can be noted as already 12125 // captured within tryCaptureVar. 12126 auto I = LambdaClass->field_begin(); 12127 for (const auto &C : LambdaClass->captures()) { 12128 if (C.capturesVariable()) { 12129 VarDecl *VD = C.getCapturedVar(); 12130 if (VD->isInitCapture()) 12131 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12132 QualType CaptureType = VD->getType(); 12133 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12134 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12135 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12136 /*EllipsisLoc*/C.isPackExpansion() 12137 ? C.getEllipsisLoc() : SourceLocation(), 12138 CaptureType, /*Expr*/ nullptr); 12139 12140 } else if (C.capturesThis()) { 12141 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12142 /*Expr*/ nullptr, 12143 C.getCaptureKind() == LCK_StarThis); 12144 } else { 12145 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12146 } 12147 ++I; 12148 } 12149 } 12150 12151 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12152 SkipBodyInfo *SkipBody) { 12153 if (!D) 12154 return D; 12155 FunctionDecl *FD = nullptr; 12156 12157 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12158 FD = FunTmpl->getTemplatedDecl(); 12159 else 12160 FD = cast<FunctionDecl>(D); 12161 12162 // Check for defining attributes before the check for redefinition. 12163 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12164 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12165 FD->dropAttr<AliasAttr>(); 12166 FD->setInvalidDecl(); 12167 } 12168 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12169 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12170 FD->dropAttr<IFuncAttr>(); 12171 FD->setInvalidDecl(); 12172 } 12173 12174 // See if this is a redefinition. If 'will have body' is already set, then 12175 // these checks were already performed when it was set. 12176 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12177 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12178 12179 // If we're skipping the body, we're done. Don't enter the scope. 12180 if (SkipBody && SkipBody->ShouldSkip) 12181 return D; 12182 } 12183 12184 // Mark this function as "will have a body eventually". This lets users to 12185 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12186 // this function. 12187 FD->setWillHaveBody(); 12188 12189 // If we are instantiating a generic lambda call operator, push 12190 // a LambdaScopeInfo onto the function stack. But use the information 12191 // that's already been calculated (ActOnLambdaExpr) to prime the current 12192 // LambdaScopeInfo. 12193 // When the template operator is being specialized, the LambdaScopeInfo, 12194 // has to be properly restored so that tryCaptureVariable doesn't try 12195 // and capture any new variables. In addition when calculating potential 12196 // captures during transformation of nested lambdas, it is necessary to 12197 // have the LSI properly restored. 12198 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12199 assert(inTemplateInstantiation() && 12200 "There should be an active template instantiation on the stack " 12201 "when instantiating a generic lambda!"); 12202 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12203 } else { 12204 // Enter a new function scope 12205 PushFunctionScope(); 12206 } 12207 12208 // Builtin functions cannot be defined. 12209 if (unsigned BuiltinID = FD->getBuiltinID()) { 12210 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12211 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12212 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12213 FD->setInvalidDecl(); 12214 } 12215 } 12216 12217 // The return type of a function definition must be complete 12218 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12219 QualType ResultType = FD->getReturnType(); 12220 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12221 !FD->isInvalidDecl() && 12222 RequireCompleteType(FD->getLocation(), ResultType, 12223 diag::err_func_def_incomplete_result)) 12224 FD->setInvalidDecl(); 12225 12226 if (FnBodyScope) 12227 PushDeclContext(FnBodyScope, FD); 12228 12229 // Check the validity of our function parameters 12230 CheckParmsForFunctionDef(FD->parameters(), 12231 /*CheckParameterNames=*/true); 12232 12233 // Add non-parameter declarations already in the function to the current 12234 // scope. 12235 if (FnBodyScope) { 12236 for (Decl *NPD : FD->decls()) { 12237 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12238 if (!NonParmDecl) 12239 continue; 12240 assert(!isa<ParmVarDecl>(NonParmDecl) && 12241 "parameters should not be in newly created FD yet"); 12242 12243 // If the decl has a name, make it accessible in the current scope. 12244 if (NonParmDecl->getDeclName()) 12245 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12246 12247 // Similarly, dive into enums and fish their constants out, making them 12248 // accessible in this scope. 12249 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12250 for (auto *EI : ED->enumerators()) 12251 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12252 } 12253 } 12254 } 12255 12256 // Introduce our parameters into the function scope 12257 for (auto Param : FD->parameters()) { 12258 Param->setOwningFunction(FD); 12259 12260 // If this has an identifier, add it to the scope stack. 12261 if (Param->getIdentifier() && FnBodyScope) { 12262 CheckShadow(FnBodyScope, Param); 12263 12264 PushOnScopeChains(Param, FnBodyScope); 12265 } 12266 } 12267 12268 // Ensure that the function's exception specification is instantiated. 12269 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12270 ResolveExceptionSpec(D->getLocation(), FPT); 12271 12272 // dllimport cannot be applied to non-inline function definitions. 12273 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12274 !FD->isTemplateInstantiation()) { 12275 assert(!FD->hasAttr<DLLExportAttr>()); 12276 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12277 FD->setInvalidDecl(); 12278 return D; 12279 } 12280 // We want to attach documentation to original Decl (which might be 12281 // a function template). 12282 ActOnDocumentableDecl(D); 12283 if (getCurLexicalContext()->isObjCContainer() && 12284 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12285 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12286 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12287 12288 return D; 12289 } 12290 12291 /// \brief Given the set of return statements within a function body, 12292 /// compute the variables that are subject to the named return value 12293 /// optimization. 12294 /// 12295 /// Each of the variables that is subject to the named return value 12296 /// optimization will be marked as NRVO variables in the AST, and any 12297 /// return statement that has a marked NRVO variable as its NRVO candidate can 12298 /// use the named return value optimization. 12299 /// 12300 /// This function applies a very simplistic algorithm for NRVO: if every return 12301 /// statement in the scope of a variable has the same NRVO candidate, that 12302 /// candidate is an NRVO variable. 12303 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12304 ReturnStmt **Returns = Scope->Returns.data(); 12305 12306 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12307 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12308 if (!NRVOCandidate->isNRVOVariable()) 12309 Returns[I]->setNRVOCandidate(nullptr); 12310 } 12311 } 12312 } 12313 12314 bool Sema::canDelayFunctionBody(const Declarator &D) { 12315 // We can't delay parsing the body of a constexpr function template (yet). 12316 if (D.getDeclSpec().isConstexprSpecified()) 12317 return false; 12318 12319 // We can't delay parsing the body of a function template with a deduced 12320 // return type (yet). 12321 if (D.getDeclSpec().hasAutoTypeSpec()) { 12322 // If the placeholder introduces a non-deduced trailing return type, 12323 // we can still delay parsing it. 12324 if (D.getNumTypeObjects()) { 12325 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12326 if (Outer.Kind == DeclaratorChunk::Function && 12327 Outer.Fun.hasTrailingReturnType()) { 12328 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12329 return Ty.isNull() || !Ty->isUndeducedType(); 12330 } 12331 } 12332 return false; 12333 } 12334 12335 return true; 12336 } 12337 12338 bool Sema::canSkipFunctionBody(Decl *D) { 12339 // We cannot skip the body of a function (or function template) which is 12340 // constexpr, since we may need to evaluate its body in order to parse the 12341 // rest of the file. 12342 // We cannot skip the body of a function with an undeduced return type, 12343 // because any callers of that function need to know the type. 12344 if (const FunctionDecl *FD = D->getAsFunction()) 12345 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12346 return false; 12347 return Consumer.shouldSkipFunctionBody(D); 12348 } 12349 12350 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12351 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 12352 FD->setHasSkippedBody(); 12353 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 12354 MD->setHasSkippedBody(); 12355 return Decl; 12356 } 12357 12358 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12359 return ActOnFinishFunctionBody(D, BodyArg, false); 12360 } 12361 12362 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12363 bool IsInstantiation) { 12364 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12365 12366 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12367 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12368 12369 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12370 CheckCompletedCoroutineBody(FD, Body); 12371 12372 if (FD) { 12373 FD->setBody(Body); 12374 FD->setWillHaveBody(false); 12375 12376 if (getLangOpts().CPlusPlus14) { 12377 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12378 FD->getReturnType()->isUndeducedType()) { 12379 // If the function has a deduced result type but contains no 'return' 12380 // statements, the result type as written must be exactly 'auto', and 12381 // the deduced result type is 'void'. 12382 if (!FD->getReturnType()->getAs<AutoType>()) { 12383 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12384 << FD->getReturnType(); 12385 FD->setInvalidDecl(); 12386 } else { 12387 // Substitute 'void' for the 'auto' in the type. 12388 TypeLoc ResultType = getReturnTypeLoc(FD); 12389 Context.adjustDeducedFunctionResultType( 12390 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12391 } 12392 } 12393 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12394 // In C++11, we don't use 'auto' deduction rules for lambda call 12395 // operators because we don't support return type deduction. 12396 auto *LSI = getCurLambda(); 12397 if (LSI->HasImplicitReturnType) { 12398 deduceClosureReturnType(*LSI); 12399 12400 // C++11 [expr.prim.lambda]p4: 12401 // [...] if there are no return statements in the compound-statement 12402 // [the deduced type is] the type void 12403 QualType RetType = 12404 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12405 12406 // Update the return type to the deduced type. 12407 const FunctionProtoType *Proto = 12408 FD->getType()->getAs<FunctionProtoType>(); 12409 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12410 Proto->getExtProtoInfo())); 12411 } 12412 } 12413 12414 // If the function implicitly returns zero (like 'main') or is naked, 12415 // don't complain about missing return statements. 12416 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12417 WP.disableCheckFallThrough(); 12418 12419 // MSVC permits the use of pure specifier (=0) on function definition, 12420 // defined at class scope, warn about this non-standard construct. 12421 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12422 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12423 12424 if (!FD->isInvalidDecl()) { 12425 // Don't diagnose unused parameters of defaulted or deleted functions. 12426 if (!FD->isDeleted() && !FD->isDefaulted()) 12427 DiagnoseUnusedParameters(FD->parameters()); 12428 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12429 FD->getReturnType(), FD); 12430 12431 // If this is a structor, we need a vtable. 12432 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12433 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12434 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12435 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12436 12437 // Try to apply the named return value optimization. We have to check 12438 // if we can do this here because lambdas keep return statements around 12439 // to deduce an implicit return type. 12440 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 12441 !FD->isDependentContext()) 12442 computeNRVO(Body, getCurFunction()); 12443 } 12444 12445 // GNU warning -Wmissing-prototypes: 12446 // Warn if a global function is defined without a previous 12447 // prototype declaration. This warning is issued even if the 12448 // definition itself provides a prototype. The aim is to detect 12449 // global functions that fail to be declared in header files. 12450 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12451 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12452 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12453 12454 if (PossibleZeroParamPrototype) { 12455 // We found a declaration that is not a prototype, 12456 // but that could be a zero-parameter prototype 12457 if (TypeSourceInfo *TI = 12458 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12459 TypeLoc TL = TI->getTypeLoc(); 12460 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12461 Diag(PossibleZeroParamPrototype->getLocation(), 12462 diag::note_declaration_not_a_prototype) 12463 << PossibleZeroParamPrototype 12464 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12465 } 12466 } 12467 12468 // GNU warning -Wstrict-prototypes 12469 // Warn if K&R function is defined without a previous declaration. 12470 // This warning is issued only if the definition itself does not provide 12471 // a prototype. Only K&R definitions do not provide a prototype. 12472 // An empty list in a function declarator that is part of a definition 12473 // of that function specifies that the function has no parameters 12474 // (C99 6.7.5.3p14) 12475 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12476 !LangOpts.CPlusPlus) { 12477 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12478 TypeLoc TL = TI->getTypeLoc(); 12479 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12480 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12481 } 12482 } 12483 12484 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12485 const CXXMethodDecl *KeyFunction; 12486 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12487 MD->isVirtual() && 12488 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12489 MD == KeyFunction->getCanonicalDecl()) { 12490 // Update the key-function state if necessary for this ABI. 12491 if (FD->isInlined() && 12492 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12493 Context.setNonKeyFunction(MD); 12494 12495 // If the newly-chosen key function is already defined, then we 12496 // need to mark the vtable as used retroactively. 12497 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12498 const FunctionDecl *Definition; 12499 if (KeyFunction && KeyFunction->isDefined(Definition)) 12500 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12501 } else { 12502 // We just defined they key function; mark the vtable as used. 12503 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12504 } 12505 } 12506 } 12507 12508 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12509 "Function parsing confused"); 12510 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12511 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12512 MD->setBody(Body); 12513 if (!MD->isInvalidDecl()) { 12514 DiagnoseUnusedParameters(MD->parameters()); 12515 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12516 MD->getReturnType(), MD); 12517 12518 if (Body) 12519 computeNRVO(Body, getCurFunction()); 12520 } 12521 if (getCurFunction()->ObjCShouldCallSuper) { 12522 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12523 << MD->getSelector().getAsString(); 12524 getCurFunction()->ObjCShouldCallSuper = false; 12525 } 12526 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12527 const ObjCMethodDecl *InitMethod = nullptr; 12528 bool isDesignated = 12529 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12530 assert(isDesignated && InitMethod); 12531 (void)isDesignated; 12532 12533 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12534 auto IFace = MD->getClassInterface(); 12535 if (!IFace) 12536 return false; 12537 auto SuperD = IFace->getSuperClass(); 12538 if (!SuperD) 12539 return false; 12540 return SuperD->getIdentifier() == 12541 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12542 }; 12543 // Don't issue this warning for unavailable inits or direct subclasses 12544 // of NSObject. 12545 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12546 Diag(MD->getLocation(), 12547 diag::warn_objc_designated_init_missing_super_call); 12548 Diag(InitMethod->getLocation(), 12549 diag::note_objc_designated_init_marked_here); 12550 } 12551 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12552 } 12553 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12554 // Don't issue this warning for unavaialable inits. 12555 if (!MD->isUnavailable()) 12556 Diag(MD->getLocation(), 12557 diag::warn_objc_secondary_init_missing_init_call); 12558 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12559 } 12560 } else { 12561 return nullptr; 12562 } 12563 12564 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12565 DiagnoseUnguardedAvailabilityViolations(dcl); 12566 12567 assert(!getCurFunction()->ObjCShouldCallSuper && 12568 "This should only be set for ObjC methods, which should have been " 12569 "handled in the block above."); 12570 12571 // Verify and clean out per-function state. 12572 if (Body && (!FD || !FD->isDefaulted())) { 12573 // C++ constructors that have function-try-blocks can't have return 12574 // statements in the handlers of that block. (C++ [except.handle]p14) 12575 // Verify this. 12576 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12577 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12578 12579 // Verify that gotos and switch cases don't jump into scopes illegally. 12580 if (getCurFunction()->NeedsScopeChecking() && 12581 !PP.isCodeCompletionEnabled()) 12582 DiagnoseInvalidJumps(Body); 12583 12584 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12585 if (!Destructor->getParent()->isDependentType()) 12586 CheckDestructor(Destructor); 12587 12588 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12589 Destructor->getParent()); 12590 } 12591 12592 // If any errors have occurred, clear out any temporaries that may have 12593 // been leftover. This ensures that these temporaries won't be picked up for 12594 // deletion in some later function. 12595 if (getDiagnostics().hasErrorOccurred() || 12596 getDiagnostics().getSuppressAllDiagnostics()) { 12597 DiscardCleanupsInEvaluationContext(); 12598 } 12599 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12600 !isa<FunctionTemplateDecl>(dcl)) { 12601 // Since the body is valid, issue any analysis-based warnings that are 12602 // enabled. 12603 ActivePolicy = &WP; 12604 } 12605 12606 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12607 (!CheckConstexprFunctionDecl(FD) || 12608 !CheckConstexprFunctionBody(FD, Body))) 12609 FD->setInvalidDecl(); 12610 12611 if (FD && FD->hasAttr<NakedAttr>()) { 12612 for (const Stmt *S : Body->children()) { 12613 // Allow local register variables without initializer as they don't 12614 // require prologue. 12615 bool RegisterVariables = false; 12616 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12617 for (const auto *Decl : DS->decls()) { 12618 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12619 RegisterVariables = 12620 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12621 if (!RegisterVariables) 12622 break; 12623 } 12624 } 12625 } 12626 if (RegisterVariables) 12627 continue; 12628 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12629 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12630 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12631 FD->setInvalidDecl(); 12632 break; 12633 } 12634 } 12635 } 12636 12637 assert(ExprCleanupObjects.size() == 12638 ExprEvalContexts.back().NumCleanupObjects && 12639 "Leftover temporaries in function"); 12640 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12641 assert(MaybeODRUseExprs.empty() && 12642 "Leftover expressions for odr-use checking"); 12643 } 12644 12645 if (!IsInstantiation) 12646 PopDeclContext(); 12647 12648 PopFunctionScopeInfo(ActivePolicy, dcl); 12649 // If any errors have occurred, clear out any temporaries that may have 12650 // been leftover. This ensures that these temporaries won't be picked up for 12651 // deletion in some later function. 12652 if (getDiagnostics().hasErrorOccurred()) { 12653 DiscardCleanupsInEvaluationContext(); 12654 } 12655 12656 return dcl; 12657 } 12658 12659 /// When we finish delayed parsing of an attribute, we must attach it to the 12660 /// relevant Decl. 12661 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12662 ParsedAttributes &Attrs) { 12663 // Always attach attributes to the underlying decl. 12664 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12665 D = TD->getTemplatedDecl(); 12666 ProcessDeclAttributeList(S, D, Attrs.getList()); 12667 12668 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12669 if (Method->isStatic()) 12670 checkThisInStaticMemberFunctionAttributes(Method); 12671 } 12672 12673 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12674 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12675 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12676 IdentifierInfo &II, Scope *S) { 12677 Scope *BlockScope = S; 12678 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 12679 BlockScope = BlockScope->getParent(); 12680 12681 // Before we produce a declaration for an implicitly defined 12682 // function, see whether there was a locally-scoped declaration of 12683 // this name as a function or variable. If so, use that 12684 // (non-visible) declaration, and complain about it. 12685 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 12686 if (ExternCPrev) { 12687 // We still need to inject the function into the enclosing block scope so 12688 // that later (non-call) uses can see it. 12689 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 12690 12691 // C89 footnote 38: 12692 // If in fact it is not defined as having type "function returning int", 12693 // the behavior is undefined. 12694 if (!isa<FunctionDecl>(ExternCPrev) || 12695 !Context.typesAreCompatible( 12696 cast<FunctionDecl>(ExternCPrev)->getType(), 12697 Context.getFunctionNoProtoType(Context.IntTy))) { 12698 Diag(Loc, diag::ext_use_out_of_scope_declaration) 12699 << ExternCPrev << !getLangOpts().C99; 12700 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 12701 return ExternCPrev; 12702 } 12703 } 12704 12705 // Extension in C99. Legal in C90, but warn about it. 12706 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 12707 unsigned diag_id; 12708 if (II.getName().startswith("__builtin_")) 12709 diag_id = diag::warn_builtin_unknown; 12710 else if (getLangOpts().C99 || getLangOpts().OpenCL) 12711 diag_id = diag::ext_implicit_function_decl; 12712 else 12713 diag_id = diag::warn_implicit_function_decl; 12714 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL; 12715 12716 // If we found a prior declaration of this function, don't bother building 12717 // another one. We've already pushed that one into scope, so there's nothing 12718 // more to do. 12719 if (ExternCPrev) 12720 return ExternCPrev; 12721 12722 // Because typo correction is expensive, only do it if the implicit 12723 // function declaration is going to be treated as an error. 12724 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 12725 TypoCorrection Corrected; 12726 if (S && 12727 (Corrected = CorrectTypo( 12728 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 12729 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 12730 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 12731 /*ErrorRecovery*/false); 12732 } 12733 12734 // Set a Declarator for the implicit definition: int foo(); 12735 const char *Dummy; 12736 AttributeFactory attrFactory; 12737 DeclSpec DS(attrFactory); 12738 unsigned DiagID; 12739 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 12740 Context.getPrintingPolicy()); 12741 (void)Error; // Silence warning. 12742 assert(!Error && "Error setting up implicit decl!"); 12743 SourceLocation NoLoc; 12744 Declarator D(DS, Declarator::BlockContext); 12745 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 12746 /*IsAmbiguous=*/false, 12747 /*LParenLoc=*/NoLoc, 12748 /*Params=*/nullptr, 12749 /*NumParams=*/0, 12750 /*EllipsisLoc=*/NoLoc, 12751 /*RParenLoc=*/NoLoc, 12752 /*TypeQuals=*/0, 12753 /*RefQualifierIsLvalueRef=*/true, 12754 /*RefQualifierLoc=*/NoLoc, 12755 /*ConstQualifierLoc=*/NoLoc, 12756 /*VolatileQualifierLoc=*/NoLoc, 12757 /*RestrictQualifierLoc=*/NoLoc, 12758 /*MutableLoc=*/NoLoc, 12759 EST_None, 12760 /*ESpecRange=*/SourceRange(), 12761 /*Exceptions=*/nullptr, 12762 /*ExceptionRanges=*/nullptr, 12763 /*NumExceptions=*/0, 12764 /*NoexceptExpr=*/nullptr, 12765 /*ExceptionSpecTokens=*/nullptr, 12766 /*DeclsInPrototype=*/None, 12767 Loc, Loc, D), 12768 DS.getAttributes(), 12769 SourceLocation()); 12770 D.SetIdentifier(&II, Loc); 12771 12772 // Insert this function into the enclosing block scope. 12773 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 12774 FD->setImplicit(); 12775 12776 AddKnownFunctionAttributes(FD); 12777 12778 return FD; 12779 } 12780 12781 /// \brief Adds any function attributes that we know a priori based on 12782 /// the declaration of this function. 12783 /// 12784 /// These attributes can apply both to implicitly-declared builtins 12785 /// (like __builtin___printf_chk) or to library-declared functions 12786 /// like NSLog or printf. 12787 /// 12788 /// We need to check for duplicate attributes both here and where user-written 12789 /// attributes are applied to declarations. 12790 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 12791 if (FD->isInvalidDecl()) 12792 return; 12793 12794 // If this is a built-in function, map its builtin attributes to 12795 // actual attributes. 12796 if (unsigned BuiltinID = FD->getBuiltinID()) { 12797 // Handle printf-formatting attributes. 12798 unsigned FormatIdx; 12799 bool HasVAListArg; 12800 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 12801 if (!FD->hasAttr<FormatAttr>()) { 12802 const char *fmt = "printf"; 12803 unsigned int NumParams = FD->getNumParams(); 12804 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 12805 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 12806 fmt = "NSString"; 12807 FD->addAttr(FormatAttr::CreateImplicit(Context, 12808 &Context.Idents.get(fmt), 12809 FormatIdx+1, 12810 HasVAListArg ? 0 : FormatIdx+2, 12811 FD->getLocation())); 12812 } 12813 } 12814 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 12815 HasVAListArg)) { 12816 if (!FD->hasAttr<FormatAttr>()) 12817 FD->addAttr(FormatAttr::CreateImplicit(Context, 12818 &Context.Idents.get("scanf"), 12819 FormatIdx+1, 12820 HasVAListArg ? 0 : FormatIdx+2, 12821 FD->getLocation())); 12822 } 12823 12824 // Mark const if we don't care about errno and that is the only 12825 // thing preventing the function from being const. This allows 12826 // IRgen to use LLVM intrinsics for such functions. 12827 if (!getLangOpts().MathErrno && 12828 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 12829 if (!FD->hasAttr<ConstAttr>()) 12830 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12831 } 12832 12833 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 12834 !FD->hasAttr<ReturnsTwiceAttr>()) 12835 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 12836 FD->getLocation())); 12837 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 12838 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12839 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 12840 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 12841 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 12842 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 12843 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 12844 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 12845 // Add the appropriate attribute, depending on the CUDA compilation mode 12846 // and which target the builtin belongs to. For example, during host 12847 // compilation, aux builtins are __device__, while the rest are __host__. 12848 if (getLangOpts().CUDAIsDevice != 12849 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 12850 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 12851 else 12852 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 12853 } 12854 } 12855 12856 // If C++ exceptions are enabled but we are told extern "C" functions cannot 12857 // throw, add an implicit nothrow attribute to any extern "C" function we come 12858 // across. 12859 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 12860 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 12861 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 12862 if (!FPT || FPT->getExceptionSpecType() == EST_None) 12863 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 12864 } 12865 12866 IdentifierInfo *Name = FD->getIdentifier(); 12867 if (!Name) 12868 return; 12869 if ((!getLangOpts().CPlusPlus && 12870 FD->getDeclContext()->isTranslationUnit()) || 12871 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 12872 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 12873 LinkageSpecDecl::lang_c)) { 12874 // Okay: this could be a libc/libm/Objective-C function we know 12875 // about. 12876 } else 12877 return; 12878 12879 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 12880 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 12881 // target-specific builtins, perhaps? 12882 if (!FD->hasAttr<FormatAttr>()) 12883 FD->addAttr(FormatAttr::CreateImplicit(Context, 12884 &Context.Idents.get("printf"), 2, 12885 Name->isStr("vasprintf") ? 0 : 3, 12886 FD->getLocation())); 12887 } 12888 12889 if (Name->isStr("__CFStringMakeConstantString")) { 12890 // We already have a __builtin___CFStringMakeConstantString, 12891 // but builds that use -fno-constant-cfstrings don't go through that. 12892 if (!FD->hasAttr<FormatArgAttr>()) 12893 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 12894 FD->getLocation())); 12895 } 12896 } 12897 12898 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 12899 TypeSourceInfo *TInfo) { 12900 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 12901 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 12902 12903 if (!TInfo) { 12904 assert(D.isInvalidType() && "no declarator info for valid type"); 12905 TInfo = Context.getTrivialTypeSourceInfo(T); 12906 } 12907 12908 // Scope manipulation handled by caller. 12909 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 12910 D.getLocStart(), 12911 D.getIdentifierLoc(), 12912 D.getIdentifier(), 12913 TInfo); 12914 12915 // Bail out immediately if we have an invalid declaration. 12916 if (D.isInvalidType()) { 12917 NewTD->setInvalidDecl(); 12918 return NewTD; 12919 } 12920 12921 if (D.getDeclSpec().isModulePrivateSpecified()) { 12922 if (CurContext->isFunctionOrMethod()) 12923 Diag(NewTD->getLocation(), diag::err_module_private_local) 12924 << 2 << NewTD->getDeclName() 12925 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12926 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12927 else 12928 NewTD->setModulePrivate(); 12929 } 12930 12931 // C++ [dcl.typedef]p8: 12932 // If the typedef declaration defines an unnamed class (or 12933 // enum), the first typedef-name declared by the declaration 12934 // to be that class type (or enum type) is used to denote the 12935 // class type (or enum type) for linkage purposes only. 12936 // We need to check whether the type was declared in the declaration. 12937 switch (D.getDeclSpec().getTypeSpecType()) { 12938 case TST_enum: 12939 case TST_struct: 12940 case TST_interface: 12941 case TST_union: 12942 case TST_class: { 12943 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 12944 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 12945 break; 12946 } 12947 12948 default: 12949 break; 12950 } 12951 12952 return NewTD; 12953 } 12954 12955 /// \brief Check that this is a valid underlying type for an enum declaration. 12956 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 12957 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 12958 QualType T = TI->getType(); 12959 12960 if (T->isDependentType()) 12961 return false; 12962 12963 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 12964 if (BT->isInteger()) 12965 return false; 12966 12967 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 12968 return true; 12969 } 12970 12971 /// Check whether this is a valid redeclaration of a previous enumeration. 12972 /// \return true if the redeclaration was invalid. 12973 bool Sema::CheckEnumRedeclaration( 12974 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 12975 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 12976 bool IsFixed = !EnumUnderlyingTy.isNull(); 12977 12978 if (IsScoped != Prev->isScoped()) { 12979 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 12980 << Prev->isScoped(); 12981 Diag(Prev->getLocation(), diag::note_previous_declaration); 12982 return true; 12983 } 12984 12985 if (IsFixed && Prev->isFixed()) { 12986 if (!EnumUnderlyingTy->isDependentType() && 12987 !Prev->getIntegerType()->isDependentType() && 12988 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 12989 Prev->getIntegerType())) { 12990 // TODO: Highlight the underlying type of the redeclaration. 12991 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 12992 << EnumUnderlyingTy << Prev->getIntegerType(); 12993 Diag(Prev->getLocation(), diag::note_previous_declaration) 12994 << Prev->getIntegerTypeRange(); 12995 return true; 12996 } 12997 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 12998 ; 12999 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 13000 ; 13001 } else if (IsFixed != Prev->isFixed()) { 13002 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13003 << Prev->isFixed(); 13004 Diag(Prev->getLocation(), diag::note_previous_declaration); 13005 return true; 13006 } 13007 13008 return false; 13009 } 13010 13011 /// \brief Get diagnostic %select index for tag kind for 13012 /// redeclaration diagnostic message. 13013 /// WARNING: Indexes apply to particular diagnostics only! 13014 /// 13015 /// \returns diagnostic %select index. 13016 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13017 switch (Tag) { 13018 case TTK_Struct: return 0; 13019 case TTK_Interface: return 1; 13020 case TTK_Class: return 2; 13021 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13022 } 13023 } 13024 13025 /// \brief Determine if tag kind is a class-key compatible with 13026 /// class for redeclaration (class, struct, or __interface). 13027 /// 13028 /// \returns true iff the tag kind is compatible. 13029 static bool isClassCompatTagKind(TagTypeKind Tag) 13030 { 13031 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13032 } 13033 13034 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13035 TagTypeKind TTK) { 13036 if (isa<TypedefDecl>(PrevDecl)) 13037 return NTK_Typedef; 13038 else if (isa<TypeAliasDecl>(PrevDecl)) 13039 return NTK_TypeAlias; 13040 else if (isa<ClassTemplateDecl>(PrevDecl)) 13041 return NTK_Template; 13042 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13043 return NTK_TypeAliasTemplate; 13044 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13045 return NTK_TemplateTemplateArgument; 13046 switch (TTK) { 13047 case TTK_Struct: 13048 case TTK_Interface: 13049 case TTK_Class: 13050 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13051 case TTK_Union: 13052 return NTK_NonUnion; 13053 case TTK_Enum: 13054 return NTK_NonEnum; 13055 } 13056 llvm_unreachable("invalid TTK"); 13057 } 13058 13059 /// \brief Determine whether a tag with a given kind is acceptable 13060 /// as a redeclaration of the given tag declaration. 13061 /// 13062 /// \returns true if the new tag kind is acceptable, false otherwise. 13063 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13064 TagTypeKind NewTag, bool isDefinition, 13065 SourceLocation NewTagLoc, 13066 const IdentifierInfo *Name) { 13067 // C++ [dcl.type.elab]p3: 13068 // The class-key or enum keyword present in the 13069 // elaborated-type-specifier shall agree in kind with the 13070 // declaration to which the name in the elaborated-type-specifier 13071 // refers. This rule also applies to the form of 13072 // elaborated-type-specifier that declares a class-name or 13073 // friend class since it can be construed as referring to the 13074 // definition of the class. Thus, in any 13075 // elaborated-type-specifier, the enum keyword shall be used to 13076 // refer to an enumeration (7.2), the union class-key shall be 13077 // used to refer to a union (clause 9), and either the class or 13078 // struct class-key shall be used to refer to a class (clause 9) 13079 // declared using the class or struct class-key. 13080 TagTypeKind OldTag = Previous->getTagKind(); 13081 if (!isDefinition || !isClassCompatTagKind(NewTag)) 13082 if (OldTag == NewTag) 13083 return true; 13084 13085 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13086 // Warn about the struct/class tag mismatch. 13087 bool isTemplate = false; 13088 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13089 isTemplate = Record->getDescribedClassTemplate(); 13090 13091 if (inTemplateInstantiation()) { 13092 // In a template instantiation, do not offer fix-its for tag mismatches 13093 // since they usually mess up the template instead of fixing the problem. 13094 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13095 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13096 << getRedeclDiagFromTagKind(OldTag); 13097 return true; 13098 } 13099 13100 if (isDefinition) { 13101 // On definitions, check previous tags and issue a fix-it for each 13102 // one that doesn't match the current tag. 13103 if (Previous->getDefinition()) { 13104 // Don't suggest fix-its for redefinitions. 13105 return true; 13106 } 13107 13108 bool previousMismatch = false; 13109 for (auto I : Previous->redecls()) { 13110 if (I->getTagKind() != NewTag) { 13111 if (!previousMismatch) { 13112 previousMismatch = true; 13113 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13114 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13115 << getRedeclDiagFromTagKind(I->getTagKind()); 13116 } 13117 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13118 << getRedeclDiagFromTagKind(NewTag) 13119 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13120 TypeWithKeyword::getTagTypeKindName(NewTag)); 13121 } 13122 } 13123 return true; 13124 } 13125 13126 // Check for a previous definition. If current tag and definition 13127 // are same type, do nothing. If no definition, but disagree with 13128 // with previous tag type, give a warning, but no fix-it. 13129 const TagDecl *Redecl = Previous->getDefinition() ? 13130 Previous->getDefinition() : Previous; 13131 if (Redecl->getTagKind() == NewTag) { 13132 return true; 13133 } 13134 13135 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13136 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13137 << getRedeclDiagFromTagKind(OldTag); 13138 Diag(Redecl->getLocation(), diag::note_previous_use); 13139 13140 // If there is a previous definition, suggest a fix-it. 13141 if (Previous->getDefinition()) { 13142 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13143 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13144 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13145 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13146 } 13147 13148 return true; 13149 } 13150 return false; 13151 } 13152 13153 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13154 /// from an outer enclosing namespace or file scope inside a friend declaration. 13155 /// This should provide the commented out code in the following snippet: 13156 /// namespace N { 13157 /// struct X; 13158 /// namespace M { 13159 /// struct Y { friend struct /*N::*/ X; }; 13160 /// } 13161 /// } 13162 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13163 SourceLocation NameLoc) { 13164 // While the decl is in a namespace, do repeated lookup of that name and see 13165 // if we get the same namespace back. If we do not, continue until 13166 // translation unit scope, at which point we have a fully qualified NNS. 13167 SmallVector<IdentifierInfo *, 4> Namespaces; 13168 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13169 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13170 // This tag should be declared in a namespace, which can only be enclosed by 13171 // other namespaces. Bail if there's an anonymous namespace in the chain. 13172 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13173 if (!Namespace || Namespace->isAnonymousNamespace()) 13174 return FixItHint(); 13175 IdentifierInfo *II = Namespace->getIdentifier(); 13176 Namespaces.push_back(II); 13177 NamedDecl *Lookup = SemaRef.LookupSingleName( 13178 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13179 if (Lookup == Namespace) 13180 break; 13181 } 13182 13183 // Once we have all the namespaces, reverse them to go outermost first, and 13184 // build an NNS. 13185 SmallString<64> Insertion; 13186 llvm::raw_svector_ostream OS(Insertion); 13187 if (DC->isTranslationUnit()) 13188 OS << "::"; 13189 std::reverse(Namespaces.begin(), Namespaces.end()); 13190 for (auto *II : Namespaces) 13191 OS << II->getName() << "::"; 13192 return FixItHint::CreateInsertion(NameLoc, Insertion); 13193 } 13194 13195 /// \brief Determine whether a tag originally declared in context \p OldDC can 13196 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 13197 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13198 /// using-declaration). 13199 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13200 DeclContext *NewDC) { 13201 OldDC = OldDC->getRedeclContext(); 13202 NewDC = NewDC->getRedeclContext(); 13203 13204 if (OldDC->Equals(NewDC)) 13205 return true; 13206 13207 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13208 // encloses the other). 13209 if (S.getLangOpts().MSVCCompat && 13210 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13211 return true; 13212 13213 return false; 13214 } 13215 13216 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13217 /// former case, Name will be non-null. In the later case, Name will be null. 13218 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13219 /// reference/declaration/definition of a tag. 13220 /// 13221 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13222 /// trailing-type-specifier) other than one in an alias-declaration. 13223 /// 13224 /// \param SkipBody If non-null, will be set to indicate if the caller should 13225 /// skip the definition of this tag and treat it as if it were a declaration. 13226 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13227 SourceLocation KWLoc, CXXScopeSpec &SS, 13228 IdentifierInfo *Name, SourceLocation NameLoc, 13229 AttributeList *Attr, AccessSpecifier AS, 13230 SourceLocation ModulePrivateLoc, 13231 MultiTemplateParamsArg TemplateParameterLists, 13232 bool &OwnedDecl, bool &IsDependent, 13233 SourceLocation ScopedEnumKWLoc, 13234 bool ScopedEnumUsesClassTag, 13235 TypeResult UnderlyingType, 13236 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13237 SkipBodyInfo *SkipBody) { 13238 // If this is not a definition, it must have a name. 13239 IdentifierInfo *OrigName = Name; 13240 assert((Name != nullptr || TUK == TUK_Definition) && 13241 "Nameless record must be a definition!"); 13242 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13243 13244 OwnedDecl = false; 13245 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13246 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13247 13248 // FIXME: Check member specializations more carefully. 13249 bool isMemberSpecialization = false; 13250 bool Invalid = false; 13251 13252 // We only need to do this matching if we have template parameters 13253 // or a scope specifier, which also conveniently avoids this work 13254 // for non-C++ cases. 13255 if (TemplateParameterLists.size() > 0 || 13256 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13257 if (TemplateParameterList *TemplateParams = 13258 MatchTemplateParametersToScopeSpecifier( 13259 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13260 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13261 if (Kind == TTK_Enum) { 13262 Diag(KWLoc, diag::err_enum_template); 13263 return nullptr; 13264 } 13265 13266 if (TemplateParams->size() > 0) { 13267 // This is a declaration or definition of a class template (which may 13268 // be a member of another template). 13269 13270 if (Invalid) 13271 return nullptr; 13272 13273 OwnedDecl = false; 13274 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13275 SS, Name, NameLoc, Attr, 13276 TemplateParams, AS, 13277 ModulePrivateLoc, 13278 /*FriendLoc*/SourceLocation(), 13279 TemplateParameterLists.size()-1, 13280 TemplateParameterLists.data(), 13281 SkipBody); 13282 return Result.get(); 13283 } else { 13284 // The "template<>" header is extraneous. 13285 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13286 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13287 isMemberSpecialization = true; 13288 } 13289 } 13290 } 13291 13292 // Figure out the underlying type if this a enum declaration. We need to do 13293 // this early, because it's needed to detect if this is an incompatible 13294 // redeclaration. 13295 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13296 bool EnumUnderlyingIsImplicit = false; 13297 13298 if (Kind == TTK_Enum) { 13299 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 13300 // No underlying type explicitly specified, or we failed to parse the 13301 // type, default to int. 13302 EnumUnderlying = Context.IntTy.getTypePtr(); 13303 else if (UnderlyingType.get()) { 13304 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13305 // integral type; any cv-qualification is ignored. 13306 TypeSourceInfo *TI = nullptr; 13307 GetTypeFromParser(UnderlyingType.get(), &TI); 13308 EnumUnderlying = TI; 13309 13310 if (CheckEnumUnderlyingType(TI)) 13311 // Recover by falling back to int. 13312 EnumUnderlying = Context.IntTy.getTypePtr(); 13313 13314 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13315 UPPC_FixedUnderlyingType)) 13316 EnumUnderlying = Context.IntTy.getTypePtr(); 13317 13318 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13319 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 13320 // Microsoft enums are always of int type. 13321 EnumUnderlying = Context.IntTy.getTypePtr(); 13322 EnumUnderlyingIsImplicit = true; 13323 } 13324 } 13325 } 13326 13327 DeclContext *SearchDC = CurContext; 13328 DeclContext *DC = CurContext; 13329 bool isStdBadAlloc = false; 13330 bool isStdAlignValT = false; 13331 13332 RedeclarationKind Redecl = forRedeclarationInCurContext(); 13333 if (TUK == TUK_Friend || TUK == TUK_Reference) 13334 Redecl = NotForRedeclaration; 13335 13336 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13337 /// implemented asks for structural equivalence checking, the returned decl 13338 /// here is passed back to the parser, allowing the tag body to be parsed. 13339 auto createTagFromNewDecl = [&]() -> TagDecl * { 13340 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13341 // If there is an identifier, use the location of the identifier as the 13342 // location of the decl, otherwise use the location of the struct/union 13343 // keyword. 13344 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13345 TagDecl *New = nullptr; 13346 13347 if (Kind == TTK_Enum) { 13348 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13349 ScopedEnum, ScopedEnumUsesClassTag, 13350 !EnumUnderlying.isNull()); 13351 // If this is an undefined enum, bail. 13352 if (TUK != TUK_Definition && !Invalid) 13353 return nullptr; 13354 if (EnumUnderlying) { 13355 EnumDecl *ED = cast<EnumDecl>(New); 13356 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13357 ED->setIntegerTypeSourceInfo(TI); 13358 else 13359 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13360 ED->setPromotionType(ED->getIntegerType()); 13361 } 13362 } else { // struct/union 13363 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13364 nullptr); 13365 } 13366 13367 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13368 // Add alignment attributes if necessary; these attributes are checked 13369 // when the ASTContext lays out the structure. 13370 // 13371 // It is important for implementing the correct semantics that this 13372 // happen here (in ActOnTag). The #pragma pack stack is 13373 // maintained as a result of parser callbacks which can occur at 13374 // many points during the parsing of a struct declaration (because 13375 // the #pragma tokens are effectively skipped over during the 13376 // parsing of the struct). 13377 if (TUK == TUK_Definition) { 13378 AddAlignmentAttributesForRecord(RD); 13379 AddMsStructLayoutForRecord(RD); 13380 } 13381 } 13382 New->setLexicalDeclContext(CurContext); 13383 return New; 13384 }; 13385 13386 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13387 if (Name && SS.isNotEmpty()) { 13388 // We have a nested-name tag ('struct foo::bar'). 13389 13390 // Check for invalid 'foo::'. 13391 if (SS.isInvalid()) { 13392 Name = nullptr; 13393 goto CreateNewDecl; 13394 } 13395 13396 // If this is a friend or a reference to a class in a dependent 13397 // context, don't try to make a decl for it. 13398 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13399 DC = computeDeclContext(SS, false); 13400 if (!DC) { 13401 IsDependent = true; 13402 return nullptr; 13403 } 13404 } else { 13405 DC = computeDeclContext(SS, true); 13406 if (!DC) { 13407 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13408 << SS.getRange(); 13409 return nullptr; 13410 } 13411 } 13412 13413 if (RequireCompleteDeclContext(SS, DC)) 13414 return nullptr; 13415 13416 SearchDC = DC; 13417 // Look-up name inside 'foo::'. 13418 LookupQualifiedName(Previous, DC); 13419 13420 if (Previous.isAmbiguous()) 13421 return nullptr; 13422 13423 if (Previous.empty()) { 13424 // Name lookup did not find anything. However, if the 13425 // nested-name-specifier refers to the current instantiation, 13426 // and that current instantiation has any dependent base 13427 // classes, we might find something at instantiation time: treat 13428 // this as a dependent elaborated-type-specifier. 13429 // But this only makes any sense for reference-like lookups. 13430 if (Previous.wasNotFoundInCurrentInstantiation() && 13431 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13432 IsDependent = true; 13433 return nullptr; 13434 } 13435 13436 // A tag 'foo::bar' must already exist. 13437 Diag(NameLoc, diag::err_not_tag_in_scope) 13438 << Kind << Name << DC << SS.getRange(); 13439 Name = nullptr; 13440 Invalid = true; 13441 goto CreateNewDecl; 13442 } 13443 } else if (Name) { 13444 // C++14 [class.mem]p14: 13445 // If T is the name of a class, then each of the following shall have a 13446 // name different from T: 13447 // -- every member of class T that is itself a type 13448 if (TUK != TUK_Reference && TUK != TUK_Friend && 13449 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13450 return nullptr; 13451 13452 // If this is a named struct, check to see if there was a previous forward 13453 // declaration or definition. 13454 // FIXME: We're looking into outer scopes here, even when we 13455 // shouldn't be. Doing so can result in ambiguities that we 13456 // shouldn't be diagnosing. 13457 LookupName(Previous, S); 13458 13459 // When declaring or defining a tag, ignore ambiguities introduced 13460 // by types using'ed into this scope. 13461 if (Previous.isAmbiguous() && 13462 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13463 LookupResult::Filter F = Previous.makeFilter(); 13464 while (F.hasNext()) { 13465 NamedDecl *ND = F.next(); 13466 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13467 SearchDC->getRedeclContext())) 13468 F.erase(); 13469 } 13470 F.done(); 13471 } 13472 13473 // C++11 [namespace.memdef]p3: 13474 // If the name in a friend declaration is neither qualified nor 13475 // a template-id and the declaration is a function or an 13476 // elaborated-type-specifier, the lookup to determine whether 13477 // the entity has been previously declared shall not consider 13478 // any scopes outside the innermost enclosing namespace. 13479 // 13480 // MSVC doesn't implement the above rule for types, so a friend tag 13481 // declaration may be a redeclaration of a type declared in an enclosing 13482 // scope. They do implement this rule for friend functions. 13483 // 13484 // Does it matter that this should be by scope instead of by 13485 // semantic context? 13486 if (!Previous.empty() && TUK == TUK_Friend) { 13487 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13488 LookupResult::Filter F = Previous.makeFilter(); 13489 bool FriendSawTagOutsideEnclosingNamespace = false; 13490 while (F.hasNext()) { 13491 NamedDecl *ND = F.next(); 13492 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13493 if (DC->isFileContext() && 13494 !EnclosingNS->Encloses(ND->getDeclContext())) { 13495 if (getLangOpts().MSVCCompat) 13496 FriendSawTagOutsideEnclosingNamespace = true; 13497 else 13498 F.erase(); 13499 } 13500 } 13501 F.done(); 13502 13503 // Diagnose this MSVC extension in the easy case where lookup would have 13504 // unambiguously found something outside the enclosing namespace. 13505 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13506 NamedDecl *ND = Previous.getFoundDecl(); 13507 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13508 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13509 } 13510 } 13511 13512 // Note: there used to be some attempt at recovery here. 13513 if (Previous.isAmbiguous()) 13514 return nullptr; 13515 13516 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13517 // FIXME: This makes sure that we ignore the contexts associated 13518 // with C structs, unions, and enums when looking for a matching 13519 // tag declaration or definition. See the similar lookup tweak 13520 // in Sema::LookupName; is there a better way to deal with this? 13521 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13522 SearchDC = SearchDC->getParent(); 13523 } 13524 } 13525 13526 if (Previous.isSingleResult() && 13527 Previous.getFoundDecl()->isTemplateParameter()) { 13528 // Maybe we will complain about the shadowed template parameter. 13529 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13530 // Just pretend that we didn't see the previous declaration. 13531 Previous.clear(); 13532 } 13533 13534 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13535 DC->Equals(getStdNamespace())) { 13536 if (Name->isStr("bad_alloc")) { 13537 // This is a declaration of or a reference to "std::bad_alloc". 13538 isStdBadAlloc = true; 13539 13540 // If std::bad_alloc has been implicitly declared (but made invisible to 13541 // name lookup), fill in this implicit declaration as the previous 13542 // declaration, so that the declarations get chained appropriately. 13543 if (Previous.empty() && StdBadAlloc) 13544 Previous.addDecl(getStdBadAlloc()); 13545 } else if (Name->isStr("align_val_t")) { 13546 isStdAlignValT = true; 13547 if (Previous.empty() && StdAlignValT) 13548 Previous.addDecl(getStdAlignValT()); 13549 } 13550 } 13551 13552 // If we didn't find a previous declaration, and this is a reference 13553 // (or friend reference), move to the correct scope. In C++, we 13554 // also need to do a redeclaration lookup there, just in case 13555 // there's a shadow friend decl. 13556 if (Name && Previous.empty() && 13557 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13558 if (Invalid) goto CreateNewDecl; 13559 assert(SS.isEmpty()); 13560 13561 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13562 // C++ [basic.scope.pdecl]p5: 13563 // -- for an elaborated-type-specifier of the form 13564 // 13565 // class-key identifier 13566 // 13567 // if the elaborated-type-specifier is used in the 13568 // decl-specifier-seq or parameter-declaration-clause of a 13569 // function defined in namespace scope, the identifier is 13570 // declared as a class-name in the namespace that contains 13571 // the declaration; otherwise, except as a friend 13572 // declaration, the identifier is declared in the smallest 13573 // non-class, non-function-prototype scope that contains the 13574 // declaration. 13575 // 13576 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13577 // C structs and unions. 13578 // 13579 // It is an error in C++ to declare (rather than define) an enum 13580 // type, including via an elaborated type specifier. We'll 13581 // diagnose that later; for now, declare the enum in the same 13582 // scope as we would have picked for any other tag type. 13583 // 13584 // GNU C also supports this behavior as part of its incomplete 13585 // enum types extension, while GNU C++ does not. 13586 // 13587 // Find the context where we'll be declaring the tag. 13588 // FIXME: We would like to maintain the current DeclContext as the 13589 // lexical context, 13590 SearchDC = getTagInjectionContext(SearchDC); 13591 13592 // Find the scope where we'll be declaring the tag. 13593 S = getTagInjectionScope(S, getLangOpts()); 13594 } else { 13595 assert(TUK == TUK_Friend); 13596 // C++ [namespace.memdef]p3: 13597 // If a friend declaration in a non-local class first declares a 13598 // class or function, the friend class or function is a member of 13599 // the innermost enclosing namespace. 13600 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13601 } 13602 13603 // In C++, we need to do a redeclaration lookup to properly 13604 // diagnose some problems. 13605 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13606 // hidden declaration so that we don't get ambiguity errors when using a 13607 // type declared by an elaborated-type-specifier. In C that is not correct 13608 // and we should instead merge compatible types found by lookup. 13609 if (getLangOpts().CPlusPlus) { 13610 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13611 LookupQualifiedName(Previous, SearchDC); 13612 } else { 13613 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13614 LookupName(Previous, S); 13615 } 13616 } 13617 13618 // If we have a known previous declaration to use, then use it. 13619 if (Previous.empty() && SkipBody && SkipBody->Previous) 13620 Previous.addDecl(SkipBody->Previous); 13621 13622 if (!Previous.empty()) { 13623 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13624 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13625 13626 // It's okay to have a tag decl in the same scope as a typedef 13627 // which hides a tag decl in the same scope. Finding this 13628 // insanity with a redeclaration lookup can only actually happen 13629 // in C++. 13630 // 13631 // This is also okay for elaborated-type-specifiers, which is 13632 // technically forbidden by the current standard but which is 13633 // okay according to the likely resolution of an open issue; 13634 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13635 if (getLangOpts().CPlusPlus) { 13636 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13637 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13638 TagDecl *Tag = TT->getDecl(); 13639 if (Tag->getDeclName() == Name && 13640 Tag->getDeclContext()->getRedeclContext() 13641 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13642 PrevDecl = Tag; 13643 Previous.clear(); 13644 Previous.addDecl(Tag); 13645 Previous.resolveKind(); 13646 } 13647 } 13648 } 13649 } 13650 13651 // If this is a redeclaration of a using shadow declaration, it must 13652 // declare a tag in the same context. In MSVC mode, we allow a 13653 // redefinition if either context is within the other. 13654 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13655 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13656 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13657 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13658 !(OldTag && isAcceptableTagRedeclContext( 13659 *this, OldTag->getDeclContext(), SearchDC))) { 13660 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13661 Diag(Shadow->getTargetDecl()->getLocation(), 13662 diag::note_using_decl_target); 13663 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13664 << 0; 13665 // Recover by ignoring the old declaration. 13666 Previous.clear(); 13667 goto CreateNewDecl; 13668 } 13669 } 13670 13671 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13672 // If this is a use of a previous tag, or if the tag is already declared 13673 // in the same scope (so that the definition/declaration completes or 13674 // rementions the tag), reuse the decl. 13675 if (TUK == TUK_Reference || TUK == TUK_Friend || 13676 isDeclInScope(DirectPrevDecl, SearchDC, S, 13677 SS.isNotEmpty() || isMemberSpecialization)) { 13678 // Make sure that this wasn't declared as an enum and now used as a 13679 // struct or something similar. 13680 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 13681 TUK == TUK_Definition, KWLoc, 13682 Name)) { 13683 bool SafeToContinue 13684 = (PrevTagDecl->getTagKind() != TTK_Enum && 13685 Kind != TTK_Enum); 13686 if (SafeToContinue) 13687 Diag(KWLoc, diag::err_use_with_wrong_tag) 13688 << Name 13689 << FixItHint::CreateReplacement(SourceRange(KWLoc), 13690 PrevTagDecl->getKindName()); 13691 else 13692 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 13693 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 13694 13695 if (SafeToContinue) 13696 Kind = PrevTagDecl->getTagKind(); 13697 else { 13698 // Recover by making this an anonymous redefinition. 13699 Name = nullptr; 13700 Previous.clear(); 13701 Invalid = true; 13702 } 13703 } 13704 13705 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 13706 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 13707 13708 // If this is an elaborated-type-specifier for a scoped enumeration, 13709 // the 'class' keyword is not necessary and not permitted. 13710 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13711 if (ScopedEnum) 13712 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 13713 << PrevEnum->isScoped() 13714 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 13715 return PrevTagDecl; 13716 } 13717 13718 QualType EnumUnderlyingTy; 13719 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13720 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 13721 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 13722 EnumUnderlyingTy = QualType(T, 0); 13723 13724 // All conflicts with previous declarations are recovered by 13725 // returning the previous declaration, unless this is a definition, 13726 // in which case we want the caller to bail out. 13727 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 13728 ScopedEnum, EnumUnderlyingTy, 13729 EnumUnderlyingIsImplicit, PrevEnum)) 13730 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 13731 } 13732 13733 // C++11 [class.mem]p1: 13734 // A member shall not be declared twice in the member-specification, 13735 // except that a nested class or member class template can be declared 13736 // and then later defined. 13737 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 13738 S->isDeclScope(PrevDecl)) { 13739 Diag(NameLoc, diag::ext_member_redeclared); 13740 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 13741 } 13742 13743 if (!Invalid) { 13744 // If this is a use, just return the declaration we found, unless 13745 // we have attributes. 13746 if (TUK == TUK_Reference || TUK == TUK_Friend) { 13747 if (Attr) { 13748 // FIXME: Diagnose these attributes. For now, we create a new 13749 // declaration to hold them. 13750 } else if (TUK == TUK_Reference && 13751 (PrevTagDecl->getFriendObjectKind() == 13752 Decl::FOK_Undeclared || 13753 PrevDecl->getOwningModule() != getCurrentModule()) && 13754 SS.isEmpty()) { 13755 // This declaration is a reference to an existing entity, but 13756 // has different visibility from that entity: it either makes 13757 // a friend visible or it makes a type visible in a new module. 13758 // In either case, create a new declaration. We only do this if 13759 // the declaration would have meant the same thing if no prior 13760 // declaration were found, that is, if it was found in the same 13761 // scope where we would have injected a declaration. 13762 if (!getTagInjectionContext(CurContext)->getRedeclContext() 13763 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 13764 return PrevTagDecl; 13765 // This is in the injected scope, create a new declaration in 13766 // that scope. 13767 S = getTagInjectionScope(S, getLangOpts()); 13768 } else { 13769 return PrevTagDecl; 13770 } 13771 } 13772 13773 // Diagnose attempts to redefine a tag. 13774 if (TUK == TUK_Definition) { 13775 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 13776 // If we're defining a specialization and the previous definition 13777 // is from an implicit instantiation, don't emit an error 13778 // here; we'll catch this in the general case below. 13779 bool IsExplicitSpecializationAfterInstantiation = false; 13780 if (isMemberSpecialization) { 13781 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 13782 IsExplicitSpecializationAfterInstantiation = 13783 RD->getTemplateSpecializationKind() != 13784 TSK_ExplicitSpecialization; 13785 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 13786 IsExplicitSpecializationAfterInstantiation = 13787 ED->getTemplateSpecializationKind() != 13788 TSK_ExplicitSpecialization; 13789 } 13790 13791 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 13792 // not keep more that one definition around (merge them). However, 13793 // ensure the decl passes the structural compatibility check in 13794 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 13795 NamedDecl *Hidden = nullptr; 13796 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 13797 // There is a definition of this tag, but it is not visible. We 13798 // explicitly make use of C++'s one definition rule here, and 13799 // assume that this definition is identical to the hidden one 13800 // we already have. Make the existing definition visible and 13801 // use it in place of this one. 13802 if (!getLangOpts().CPlusPlus) { 13803 // Postpone making the old definition visible until after we 13804 // complete parsing the new one and do the structural 13805 // comparison. 13806 SkipBody->CheckSameAsPrevious = true; 13807 SkipBody->New = createTagFromNewDecl(); 13808 SkipBody->Previous = Hidden; 13809 } else { 13810 SkipBody->ShouldSkip = true; 13811 makeMergedDefinitionVisible(Hidden); 13812 } 13813 return Def; 13814 } else if (!IsExplicitSpecializationAfterInstantiation) { 13815 // A redeclaration in function prototype scope in C isn't 13816 // visible elsewhere, so merely issue a warning. 13817 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 13818 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 13819 else 13820 Diag(NameLoc, diag::err_redefinition) << Name; 13821 notePreviousDefinition(Def, 13822 NameLoc.isValid() ? NameLoc : KWLoc); 13823 // If this is a redefinition, recover by making this 13824 // struct be anonymous, which will make any later 13825 // references get the previous definition. 13826 Name = nullptr; 13827 Previous.clear(); 13828 Invalid = true; 13829 } 13830 } else { 13831 // If the type is currently being defined, complain 13832 // about a nested redefinition. 13833 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 13834 if (TD->isBeingDefined()) { 13835 Diag(NameLoc, diag::err_nested_redefinition) << Name; 13836 Diag(PrevTagDecl->getLocation(), 13837 diag::note_previous_definition); 13838 Name = nullptr; 13839 Previous.clear(); 13840 Invalid = true; 13841 } 13842 } 13843 13844 // Okay, this is definition of a previously declared or referenced 13845 // tag. We're going to create a new Decl for it. 13846 } 13847 13848 // Okay, we're going to make a redeclaration. If this is some kind 13849 // of reference, make sure we build the redeclaration in the same DC 13850 // as the original, and ignore the current access specifier. 13851 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13852 SearchDC = PrevTagDecl->getDeclContext(); 13853 AS = AS_none; 13854 } 13855 } 13856 // If we get here we have (another) forward declaration or we 13857 // have a definition. Just create a new decl. 13858 13859 } else { 13860 // If we get here, this is a definition of a new tag type in a nested 13861 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 13862 // new decl/type. We set PrevDecl to NULL so that the entities 13863 // have distinct types. 13864 Previous.clear(); 13865 } 13866 // If we get here, we're going to create a new Decl. If PrevDecl 13867 // is non-NULL, it's a definition of the tag declared by 13868 // PrevDecl. If it's NULL, we have a new definition. 13869 13870 // Otherwise, PrevDecl is not a tag, but was found with tag 13871 // lookup. This is only actually possible in C++, where a few 13872 // things like templates still live in the tag namespace. 13873 } else { 13874 // Use a better diagnostic if an elaborated-type-specifier 13875 // found the wrong kind of type on the first 13876 // (non-redeclaration) lookup. 13877 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 13878 !Previous.isForRedeclaration()) { 13879 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13880 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 13881 << Kind; 13882 Diag(PrevDecl->getLocation(), diag::note_declared_at); 13883 Invalid = true; 13884 13885 // Otherwise, only diagnose if the declaration is in scope. 13886 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 13887 SS.isNotEmpty() || isMemberSpecialization)) { 13888 // do nothing 13889 13890 // Diagnose implicit declarations introduced by elaborated types. 13891 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 13892 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 13893 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 13894 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13895 Invalid = true; 13896 13897 // Otherwise it's a declaration. Call out a particularly common 13898 // case here. 13899 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13900 unsigned Kind = 0; 13901 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 13902 Diag(NameLoc, diag::err_tag_definition_of_typedef) 13903 << Name << Kind << TND->getUnderlyingType(); 13904 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 13905 Invalid = true; 13906 13907 // Otherwise, diagnose. 13908 } else { 13909 // The tag name clashes with something else in the target scope, 13910 // issue an error and recover by making this tag be anonymous. 13911 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 13912 notePreviousDefinition(PrevDecl, NameLoc); 13913 Name = nullptr; 13914 Invalid = true; 13915 } 13916 13917 // The existing declaration isn't relevant to us; we're in a 13918 // new scope, so clear out the previous declaration. 13919 Previous.clear(); 13920 } 13921 } 13922 13923 CreateNewDecl: 13924 13925 TagDecl *PrevDecl = nullptr; 13926 if (Previous.isSingleResult()) 13927 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 13928 13929 // If there is an identifier, use the location of the identifier as the 13930 // location of the decl, otherwise use the location of the struct/union 13931 // keyword. 13932 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13933 13934 // Otherwise, create a new declaration. If there is a previous 13935 // declaration of the same entity, the two will be linked via 13936 // PrevDecl. 13937 TagDecl *New; 13938 13939 bool IsForwardReference = false; 13940 if (Kind == TTK_Enum) { 13941 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13942 // enum X { A, B, C } D; D should chain to X. 13943 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 13944 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 13945 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 13946 13947 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 13948 StdAlignValT = cast<EnumDecl>(New); 13949 13950 // If this is an undefined enum, warn. 13951 if (TUK != TUK_Definition && !Invalid) { 13952 TagDecl *Def; 13953 if (!EnumUnderlyingIsImplicit && 13954 (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 13955 cast<EnumDecl>(New)->isFixed()) { 13956 // C++0x: 7.2p2: opaque-enum-declaration. 13957 // Conflicts are diagnosed above. Do nothing. 13958 } 13959 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 13960 Diag(Loc, diag::ext_forward_ref_enum_def) 13961 << New; 13962 Diag(Def->getLocation(), diag::note_previous_definition); 13963 } else { 13964 unsigned DiagID = diag::ext_forward_ref_enum; 13965 if (getLangOpts().MSVCCompat) 13966 DiagID = diag::ext_ms_forward_ref_enum; 13967 else if (getLangOpts().CPlusPlus) 13968 DiagID = diag::err_forward_ref_enum; 13969 Diag(Loc, DiagID); 13970 13971 // If this is a forward-declared reference to an enumeration, make a 13972 // note of it; we won't actually be introducing the declaration into 13973 // the declaration context. 13974 if (TUK == TUK_Reference) 13975 IsForwardReference = true; 13976 } 13977 } 13978 13979 if (EnumUnderlying) { 13980 EnumDecl *ED = cast<EnumDecl>(New); 13981 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 13982 ED->setIntegerTypeSourceInfo(TI); 13983 else 13984 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 13985 ED->setPromotionType(ED->getIntegerType()); 13986 } 13987 } else { 13988 // struct/union/class 13989 13990 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 13991 // struct X { int A; } D; D should chain to X. 13992 if (getLangOpts().CPlusPlus) { 13993 // FIXME: Look for a way to use RecordDecl for simple structs. 13994 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13995 cast_or_null<CXXRecordDecl>(PrevDecl)); 13996 13997 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 13998 StdBadAlloc = cast<CXXRecordDecl>(New); 13999 } else 14000 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14001 cast_or_null<RecordDecl>(PrevDecl)); 14002 } 14003 14004 // C++11 [dcl.type]p3: 14005 // A type-specifier-seq shall not define a class or enumeration [...]. 14006 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14007 TUK == TUK_Definition) { 14008 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14009 << Context.getTagDeclType(New); 14010 Invalid = true; 14011 } 14012 14013 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14014 DC->getDeclKind() == Decl::Enum) { 14015 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14016 << Context.getTagDeclType(New); 14017 Invalid = true; 14018 } 14019 14020 // Maybe add qualifier info. 14021 if (SS.isNotEmpty()) { 14022 if (SS.isSet()) { 14023 // If this is either a declaration or a definition, check the 14024 // nested-name-specifier against the current context. We don't do this 14025 // for explicit specializations, because they have similar checking 14026 // (with more specific diagnostics) in the call to 14027 // CheckMemberSpecialization, below. 14028 if (!isMemberSpecialization && 14029 (TUK == TUK_Definition || TUK == TUK_Declaration) && 14030 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 14031 Invalid = true; 14032 14033 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14034 if (TemplateParameterLists.size() > 0) { 14035 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14036 } 14037 } 14038 else 14039 Invalid = true; 14040 } 14041 14042 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14043 // Add alignment attributes if necessary; these attributes are checked when 14044 // the ASTContext lays out the structure. 14045 // 14046 // It is important for implementing the correct semantics that this 14047 // happen here (in ActOnTag). The #pragma pack stack is 14048 // maintained as a result of parser callbacks which can occur at 14049 // many points during the parsing of a struct declaration (because 14050 // the #pragma tokens are effectively skipped over during the 14051 // parsing of the struct). 14052 if (TUK == TUK_Definition) { 14053 AddAlignmentAttributesForRecord(RD); 14054 AddMsStructLayoutForRecord(RD); 14055 } 14056 } 14057 14058 if (ModulePrivateLoc.isValid()) { 14059 if (isMemberSpecialization) 14060 Diag(New->getLocation(), diag::err_module_private_specialization) 14061 << 2 14062 << FixItHint::CreateRemoval(ModulePrivateLoc); 14063 // __module_private__ does not apply to local classes. However, we only 14064 // diagnose this as an error when the declaration specifiers are 14065 // freestanding. Here, we just ignore the __module_private__. 14066 else if (!SearchDC->isFunctionOrMethod()) 14067 New->setModulePrivate(); 14068 } 14069 14070 // If this is a specialization of a member class (of a class template), 14071 // check the specialization. 14072 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14073 Invalid = true; 14074 14075 // If we're declaring or defining a tag in function prototype scope in C, 14076 // note that this type can only be used within the function and add it to 14077 // the list of decls to inject into the function definition scope. 14078 if ((Name || Kind == TTK_Enum) && 14079 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14080 if (getLangOpts().CPlusPlus) { 14081 // C++ [dcl.fct]p6: 14082 // Types shall not be defined in return or parameter types. 14083 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14084 Diag(Loc, diag::err_type_defined_in_param_type) 14085 << Name; 14086 Invalid = true; 14087 } 14088 } else if (!PrevDecl) { 14089 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14090 } 14091 } 14092 14093 if (Invalid) 14094 New->setInvalidDecl(); 14095 14096 // Set the lexical context. If the tag has a C++ scope specifier, the 14097 // lexical context will be different from the semantic context. 14098 New->setLexicalDeclContext(CurContext); 14099 14100 // Mark this as a friend decl if applicable. 14101 // In Microsoft mode, a friend declaration also acts as a forward 14102 // declaration so we always pass true to setObjectOfFriendDecl to make 14103 // the tag name visible. 14104 if (TUK == TUK_Friend) 14105 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14106 14107 // Set the access specifier. 14108 if (!Invalid && SearchDC->isRecord()) 14109 SetMemberAccessSpecifier(New, PrevDecl, AS); 14110 14111 if (PrevDecl) 14112 CheckRedeclarationModuleOwnership(New, PrevDecl); 14113 14114 if (TUK == TUK_Definition) 14115 New->startDefinition(); 14116 14117 if (Attr) 14118 ProcessDeclAttributeList(S, New, Attr); 14119 AddPragmaAttributes(S, New); 14120 14121 // If this has an identifier, add it to the scope stack. 14122 if (TUK == TUK_Friend) { 14123 // We might be replacing an existing declaration in the lookup tables; 14124 // if so, borrow its access specifier. 14125 if (PrevDecl) 14126 New->setAccess(PrevDecl->getAccess()); 14127 14128 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14129 DC->makeDeclVisibleInContext(New); 14130 if (Name) // can be null along some error paths 14131 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14132 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14133 } else if (Name) { 14134 S = getNonFieldDeclScope(S); 14135 PushOnScopeChains(New, S, !IsForwardReference); 14136 if (IsForwardReference) 14137 SearchDC->makeDeclVisibleInContext(New); 14138 } else { 14139 CurContext->addDecl(New); 14140 } 14141 14142 // If this is the C FILE type, notify the AST context. 14143 if (IdentifierInfo *II = New->getIdentifier()) 14144 if (!New->isInvalidDecl() && 14145 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14146 II->isStr("FILE")) 14147 Context.setFILEDecl(New); 14148 14149 if (PrevDecl) 14150 mergeDeclAttributes(New, PrevDecl); 14151 14152 // If there's a #pragma GCC visibility in scope, set the visibility of this 14153 // record. 14154 AddPushedVisibilityAttribute(New); 14155 14156 if (isMemberSpecialization && !New->isInvalidDecl()) 14157 CompleteMemberSpecialization(New, Previous); 14158 14159 OwnedDecl = true; 14160 // In C++, don't return an invalid declaration. We can't recover well from 14161 // the cases where we make the type anonymous. 14162 if (Invalid && getLangOpts().CPlusPlus) { 14163 if (New->isBeingDefined()) 14164 if (auto RD = dyn_cast<RecordDecl>(New)) 14165 RD->completeDefinition(); 14166 return nullptr; 14167 } else { 14168 return New; 14169 } 14170 } 14171 14172 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14173 AdjustDeclIfTemplate(TagD); 14174 TagDecl *Tag = cast<TagDecl>(TagD); 14175 14176 // Enter the tag context. 14177 PushDeclContext(S, Tag); 14178 14179 ActOnDocumentableDecl(TagD); 14180 14181 // If there's a #pragma GCC visibility in scope, set the visibility of this 14182 // record. 14183 AddPushedVisibilityAttribute(Tag); 14184 } 14185 14186 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14187 SkipBodyInfo &SkipBody) { 14188 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14189 return false; 14190 14191 // Make the previous decl visible. 14192 makeMergedDefinitionVisible(SkipBody.Previous); 14193 return true; 14194 } 14195 14196 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14197 assert(isa<ObjCContainerDecl>(IDecl) && 14198 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14199 DeclContext *OCD = cast<DeclContext>(IDecl); 14200 assert(getContainingDC(OCD) == CurContext && 14201 "The next DeclContext should be lexically contained in the current one."); 14202 CurContext = OCD; 14203 return IDecl; 14204 } 14205 14206 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14207 SourceLocation FinalLoc, 14208 bool IsFinalSpelledSealed, 14209 SourceLocation LBraceLoc) { 14210 AdjustDeclIfTemplate(TagD); 14211 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14212 14213 FieldCollector->StartClass(); 14214 14215 if (!Record->getIdentifier()) 14216 return; 14217 14218 if (FinalLoc.isValid()) 14219 Record->addAttr(new (Context) 14220 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14221 14222 // C++ [class]p2: 14223 // [...] The class-name is also inserted into the scope of the 14224 // class itself; this is known as the injected-class-name. For 14225 // purposes of access checking, the injected-class-name is treated 14226 // as if it were a public member name. 14227 CXXRecordDecl *InjectedClassName 14228 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14229 Record->getLocStart(), Record->getLocation(), 14230 Record->getIdentifier(), 14231 /*PrevDecl=*/nullptr, 14232 /*DelayTypeCreation=*/true); 14233 Context.getTypeDeclType(InjectedClassName, Record); 14234 InjectedClassName->setImplicit(); 14235 InjectedClassName->setAccess(AS_public); 14236 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14237 InjectedClassName->setDescribedClassTemplate(Template); 14238 PushOnScopeChains(InjectedClassName, S); 14239 assert(InjectedClassName->isInjectedClassName() && 14240 "Broken injected-class-name"); 14241 } 14242 14243 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14244 SourceRange BraceRange) { 14245 AdjustDeclIfTemplate(TagD); 14246 TagDecl *Tag = cast<TagDecl>(TagD); 14247 Tag->setBraceRange(BraceRange); 14248 14249 // Make sure we "complete" the definition even it is invalid. 14250 if (Tag->isBeingDefined()) { 14251 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14252 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14253 RD->completeDefinition(); 14254 } 14255 14256 if (isa<CXXRecordDecl>(Tag)) { 14257 FieldCollector->FinishClass(); 14258 } 14259 14260 // Exit this scope of this tag's definition. 14261 PopDeclContext(); 14262 14263 if (getCurLexicalContext()->isObjCContainer() && 14264 Tag->getDeclContext()->isFileContext()) 14265 Tag->setTopLevelDeclInObjCContainer(); 14266 14267 // Notify the consumer that we've defined a tag. 14268 if (!Tag->isInvalidDecl()) 14269 Consumer.HandleTagDeclDefinition(Tag); 14270 } 14271 14272 void Sema::ActOnObjCContainerFinishDefinition() { 14273 // Exit this scope of this interface definition. 14274 PopDeclContext(); 14275 } 14276 14277 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14278 assert(DC == CurContext && "Mismatch of container contexts"); 14279 OriginalLexicalContext = DC; 14280 ActOnObjCContainerFinishDefinition(); 14281 } 14282 14283 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14284 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14285 OriginalLexicalContext = nullptr; 14286 } 14287 14288 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14289 AdjustDeclIfTemplate(TagD); 14290 TagDecl *Tag = cast<TagDecl>(TagD); 14291 Tag->setInvalidDecl(); 14292 14293 // Make sure we "complete" the definition even it is invalid. 14294 if (Tag->isBeingDefined()) { 14295 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14296 RD->completeDefinition(); 14297 } 14298 14299 // We're undoing ActOnTagStartDefinition here, not 14300 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14301 // the FieldCollector. 14302 14303 PopDeclContext(); 14304 } 14305 14306 // Note that FieldName may be null for anonymous bitfields. 14307 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14308 IdentifierInfo *FieldName, 14309 QualType FieldTy, bool IsMsStruct, 14310 Expr *BitWidth, bool *ZeroWidth) { 14311 // Default to true; that shouldn't confuse checks for emptiness 14312 if (ZeroWidth) 14313 *ZeroWidth = true; 14314 14315 // C99 6.7.2.1p4 - verify the field type. 14316 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14317 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14318 // Handle incomplete types with specific error. 14319 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14320 return ExprError(); 14321 if (FieldName) 14322 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14323 << FieldName << FieldTy << BitWidth->getSourceRange(); 14324 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14325 << FieldTy << BitWidth->getSourceRange(); 14326 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14327 UPPC_BitFieldWidth)) 14328 return ExprError(); 14329 14330 // If the bit-width is type- or value-dependent, don't try to check 14331 // it now. 14332 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14333 return BitWidth; 14334 14335 llvm::APSInt Value; 14336 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14337 if (ICE.isInvalid()) 14338 return ICE; 14339 BitWidth = ICE.get(); 14340 14341 if (Value != 0 && ZeroWidth) 14342 *ZeroWidth = false; 14343 14344 // Zero-width bitfield is ok for anonymous field. 14345 if (Value == 0 && FieldName) 14346 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14347 14348 if (Value.isSigned() && Value.isNegative()) { 14349 if (FieldName) 14350 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14351 << FieldName << Value.toString(10); 14352 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14353 << Value.toString(10); 14354 } 14355 14356 if (!FieldTy->isDependentType()) { 14357 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14358 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14359 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14360 14361 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14362 // ABI. 14363 bool CStdConstraintViolation = 14364 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14365 bool MSBitfieldViolation = 14366 Value.ugt(TypeStorageSize) && 14367 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14368 if (CStdConstraintViolation || MSBitfieldViolation) { 14369 unsigned DiagWidth = 14370 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14371 if (FieldName) 14372 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14373 << FieldName << (unsigned)Value.getZExtValue() 14374 << !CStdConstraintViolation << DiagWidth; 14375 14376 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14377 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14378 << DiagWidth; 14379 } 14380 14381 // Warn on types where the user might conceivably expect to get all 14382 // specified bits as value bits: that's all integral types other than 14383 // 'bool'. 14384 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14385 if (FieldName) 14386 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14387 << FieldName << (unsigned)Value.getZExtValue() 14388 << (unsigned)TypeWidth; 14389 else 14390 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14391 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14392 } 14393 } 14394 14395 return BitWidth; 14396 } 14397 14398 /// ActOnField - Each field of a C struct/union is passed into this in order 14399 /// to create a FieldDecl object for it. 14400 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14401 Declarator &D, Expr *BitfieldWidth) { 14402 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14403 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14404 /*InitStyle=*/ICIS_NoInit, AS_public); 14405 return Res; 14406 } 14407 14408 /// HandleField - Analyze a field of a C struct or a C++ data member. 14409 /// 14410 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14411 SourceLocation DeclStart, 14412 Declarator &D, Expr *BitWidth, 14413 InClassInitStyle InitStyle, 14414 AccessSpecifier AS) { 14415 if (D.isDecompositionDeclarator()) { 14416 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14417 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14418 << Decomp.getSourceRange(); 14419 return nullptr; 14420 } 14421 14422 IdentifierInfo *II = D.getIdentifier(); 14423 SourceLocation Loc = DeclStart; 14424 if (II) Loc = D.getIdentifierLoc(); 14425 14426 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14427 QualType T = TInfo->getType(); 14428 if (getLangOpts().CPlusPlus) { 14429 CheckExtraCXXDefaultArguments(D); 14430 14431 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14432 UPPC_DataMemberType)) { 14433 D.setInvalidType(); 14434 T = Context.IntTy; 14435 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14436 } 14437 } 14438 14439 // TR 18037 does not allow fields to be declared with address spaces. 14440 if (T.getQualifiers().hasAddressSpace() || 14441 T->isDependentAddressSpaceType() || 14442 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 14443 Diag(Loc, diag::err_field_with_address_space); 14444 D.setInvalidType(); 14445 } 14446 14447 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14448 // used as structure or union field: image, sampler, event or block types. 14449 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14450 T->isSamplerT() || T->isBlockPointerType())) { 14451 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14452 D.setInvalidType(); 14453 } 14454 14455 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14456 14457 if (D.getDeclSpec().isInlineSpecified()) 14458 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14459 << getLangOpts().CPlusPlus1z; 14460 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14461 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14462 diag::err_invalid_thread) 14463 << DeclSpec::getSpecifierName(TSCS); 14464 14465 // Check to see if this name was declared as a member previously 14466 NamedDecl *PrevDecl = nullptr; 14467 LookupResult Previous(*this, II, Loc, LookupMemberName, 14468 ForVisibleRedeclaration); 14469 LookupName(Previous, S); 14470 switch (Previous.getResultKind()) { 14471 case LookupResult::Found: 14472 case LookupResult::FoundUnresolvedValue: 14473 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14474 break; 14475 14476 case LookupResult::FoundOverloaded: 14477 PrevDecl = Previous.getRepresentativeDecl(); 14478 break; 14479 14480 case LookupResult::NotFound: 14481 case LookupResult::NotFoundInCurrentInstantiation: 14482 case LookupResult::Ambiguous: 14483 break; 14484 } 14485 Previous.suppressDiagnostics(); 14486 14487 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14488 // Maybe we will complain about the shadowed template parameter. 14489 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14490 // Just pretend that we didn't see the previous declaration. 14491 PrevDecl = nullptr; 14492 } 14493 14494 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14495 PrevDecl = nullptr; 14496 14497 bool Mutable 14498 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14499 SourceLocation TSSL = D.getLocStart(); 14500 FieldDecl *NewFD 14501 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14502 TSSL, AS, PrevDecl, &D); 14503 14504 if (NewFD->isInvalidDecl()) 14505 Record->setInvalidDecl(); 14506 14507 if (D.getDeclSpec().isModulePrivateSpecified()) 14508 NewFD->setModulePrivate(); 14509 14510 if (NewFD->isInvalidDecl() && PrevDecl) { 14511 // Don't introduce NewFD into scope; there's already something 14512 // with the same name in the same scope. 14513 } else if (II) { 14514 PushOnScopeChains(NewFD, S); 14515 } else 14516 Record->addDecl(NewFD); 14517 14518 return NewFD; 14519 } 14520 14521 /// \brief Build a new FieldDecl and check its well-formedness. 14522 /// 14523 /// This routine builds a new FieldDecl given the fields name, type, 14524 /// record, etc. \p PrevDecl should refer to any previous declaration 14525 /// with the same name and in the same scope as the field to be 14526 /// created. 14527 /// 14528 /// \returns a new FieldDecl. 14529 /// 14530 /// \todo The Declarator argument is a hack. It will be removed once 14531 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14532 TypeSourceInfo *TInfo, 14533 RecordDecl *Record, SourceLocation Loc, 14534 bool Mutable, Expr *BitWidth, 14535 InClassInitStyle InitStyle, 14536 SourceLocation TSSL, 14537 AccessSpecifier AS, NamedDecl *PrevDecl, 14538 Declarator *D) { 14539 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14540 bool InvalidDecl = false; 14541 if (D) InvalidDecl = D->isInvalidType(); 14542 14543 // If we receive a broken type, recover by assuming 'int' and 14544 // marking this declaration as invalid. 14545 if (T.isNull()) { 14546 InvalidDecl = true; 14547 T = Context.IntTy; 14548 } 14549 14550 QualType EltTy = Context.getBaseElementType(T); 14551 if (!EltTy->isDependentType()) { 14552 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14553 // Fields of incomplete type force their record to be invalid. 14554 Record->setInvalidDecl(); 14555 InvalidDecl = true; 14556 } else { 14557 NamedDecl *Def; 14558 EltTy->isIncompleteType(&Def); 14559 if (Def && Def->isInvalidDecl()) { 14560 Record->setInvalidDecl(); 14561 InvalidDecl = true; 14562 } 14563 } 14564 } 14565 14566 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14567 if (BitWidth && getLangOpts().OpenCL) { 14568 Diag(Loc, diag::err_opencl_bitfields); 14569 InvalidDecl = true; 14570 } 14571 14572 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14573 // than a variably modified type. 14574 if (!InvalidDecl && T->isVariablyModifiedType()) { 14575 bool SizeIsNegative; 14576 llvm::APSInt Oversized; 14577 14578 TypeSourceInfo *FixedTInfo = 14579 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14580 SizeIsNegative, 14581 Oversized); 14582 if (FixedTInfo) { 14583 Diag(Loc, diag::warn_illegal_constant_array_size); 14584 TInfo = FixedTInfo; 14585 T = FixedTInfo->getType(); 14586 } else { 14587 if (SizeIsNegative) 14588 Diag(Loc, diag::err_typecheck_negative_array_size); 14589 else if (Oversized.getBoolValue()) 14590 Diag(Loc, diag::err_array_too_large) 14591 << Oversized.toString(10); 14592 else 14593 Diag(Loc, diag::err_typecheck_field_variable_size); 14594 InvalidDecl = true; 14595 } 14596 } 14597 14598 // Fields can not have abstract class types 14599 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14600 diag::err_abstract_type_in_decl, 14601 AbstractFieldType)) 14602 InvalidDecl = true; 14603 14604 bool ZeroWidth = false; 14605 if (InvalidDecl) 14606 BitWidth = nullptr; 14607 // If this is declared as a bit-field, check the bit-field. 14608 if (BitWidth) { 14609 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14610 &ZeroWidth).get(); 14611 if (!BitWidth) { 14612 InvalidDecl = true; 14613 BitWidth = nullptr; 14614 ZeroWidth = false; 14615 } 14616 } 14617 14618 // Check that 'mutable' is consistent with the type of the declaration. 14619 if (!InvalidDecl && Mutable) { 14620 unsigned DiagID = 0; 14621 if (T->isReferenceType()) 14622 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14623 : diag::err_mutable_reference; 14624 else if (T.isConstQualified()) 14625 DiagID = diag::err_mutable_const; 14626 14627 if (DiagID) { 14628 SourceLocation ErrLoc = Loc; 14629 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14630 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14631 Diag(ErrLoc, DiagID); 14632 if (DiagID != diag::ext_mutable_reference) { 14633 Mutable = false; 14634 InvalidDecl = true; 14635 } 14636 } 14637 } 14638 14639 // C++11 [class.union]p8 (DR1460): 14640 // At most one variant member of a union may have a 14641 // brace-or-equal-initializer. 14642 if (InitStyle != ICIS_NoInit) 14643 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14644 14645 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14646 BitWidth, Mutable, InitStyle); 14647 if (InvalidDecl) 14648 NewFD->setInvalidDecl(); 14649 14650 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14651 Diag(Loc, diag::err_duplicate_member) << II; 14652 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14653 NewFD->setInvalidDecl(); 14654 } 14655 14656 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14657 if (Record->isUnion()) { 14658 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14659 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14660 if (RDecl->getDefinition()) { 14661 // C++ [class.union]p1: An object of a class with a non-trivial 14662 // constructor, a non-trivial copy constructor, a non-trivial 14663 // destructor, or a non-trivial copy assignment operator 14664 // cannot be a member of a union, nor can an array of such 14665 // objects. 14666 if (CheckNontrivialField(NewFD)) 14667 NewFD->setInvalidDecl(); 14668 } 14669 } 14670 14671 // C++ [class.union]p1: If a union contains a member of reference type, 14672 // the program is ill-formed, except when compiling with MSVC extensions 14673 // enabled. 14674 if (EltTy->isReferenceType()) { 14675 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 14676 diag::ext_union_member_of_reference_type : 14677 diag::err_union_member_of_reference_type) 14678 << NewFD->getDeclName() << EltTy; 14679 if (!getLangOpts().MicrosoftExt) 14680 NewFD->setInvalidDecl(); 14681 } 14682 } 14683 } 14684 14685 // FIXME: We need to pass in the attributes given an AST 14686 // representation, not a parser representation. 14687 if (D) { 14688 // FIXME: The current scope is almost... but not entirely... correct here. 14689 ProcessDeclAttributes(getCurScope(), NewFD, *D); 14690 14691 if (NewFD->hasAttrs()) 14692 CheckAlignasUnderalignment(NewFD); 14693 } 14694 14695 // In auto-retain/release, infer strong retension for fields of 14696 // retainable type. 14697 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 14698 NewFD->setInvalidDecl(); 14699 14700 if (T.isObjCGCWeak()) 14701 Diag(Loc, diag::warn_attribute_weak_on_field); 14702 14703 NewFD->setAccess(AS); 14704 return NewFD; 14705 } 14706 14707 bool Sema::CheckNontrivialField(FieldDecl *FD) { 14708 assert(FD); 14709 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 14710 14711 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 14712 return false; 14713 14714 QualType EltTy = Context.getBaseElementType(FD->getType()); 14715 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14716 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14717 if (RDecl->getDefinition()) { 14718 // We check for copy constructors before constructors 14719 // because otherwise we'll never get complaints about 14720 // copy constructors. 14721 14722 CXXSpecialMember member = CXXInvalid; 14723 // We're required to check for any non-trivial constructors. Since the 14724 // implicit default constructor is suppressed if there are any 14725 // user-declared constructors, we just need to check that there is a 14726 // trivial default constructor and a trivial copy constructor. (We don't 14727 // worry about move constructors here, since this is a C++98 check.) 14728 if (RDecl->hasNonTrivialCopyConstructor()) 14729 member = CXXCopyConstructor; 14730 else if (!RDecl->hasTrivialDefaultConstructor()) 14731 member = CXXDefaultConstructor; 14732 else if (RDecl->hasNonTrivialCopyAssignment()) 14733 member = CXXCopyAssignment; 14734 else if (RDecl->hasNonTrivialDestructor()) 14735 member = CXXDestructor; 14736 14737 if (member != CXXInvalid) { 14738 if (!getLangOpts().CPlusPlus11 && 14739 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 14740 // Objective-C++ ARC: it is an error to have a non-trivial field of 14741 // a union. However, system headers in Objective-C programs 14742 // occasionally have Objective-C lifetime objects within unions, 14743 // and rather than cause the program to fail, we make those 14744 // members unavailable. 14745 SourceLocation Loc = FD->getLocation(); 14746 if (getSourceManager().isInSystemHeader(Loc)) { 14747 if (!FD->hasAttr<UnavailableAttr>()) 14748 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 14749 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 14750 return false; 14751 } 14752 } 14753 14754 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 14755 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 14756 diag::err_illegal_union_or_anon_struct_member) 14757 << FD->getParent()->isUnion() << FD->getDeclName() << member; 14758 DiagnoseNontrivial(RDecl, member); 14759 return !getLangOpts().CPlusPlus11; 14760 } 14761 } 14762 } 14763 14764 return false; 14765 } 14766 14767 /// TranslateIvarVisibility - Translate visibility from a token ID to an 14768 /// AST enum value. 14769 static ObjCIvarDecl::AccessControl 14770 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 14771 switch (ivarVisibility) { 14772 default: llvm_unreachable("Unknown visitibility kind"); 14773 case tok::objc_private: return ObjCIvarDecl::Private; 14774 case tok::objc_public: return ObjCIvarDecl::Public; 14775 case tok::objc_protected: return ObjCIvarDecl::Protected; 14776 case tok::objc_package: return ObjCIvarDecl::Package; 14777 } 14778 } 14779 14780 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 14781 /// in order to create an IvarDecl object for it. 14782 Decl *Sema::ActOnIvar(Scope *S, 14783 SourceLocation DeclStart, 14784 Declarator &D, Expr *BitfieldWidth, 14785 tok::ObjCKeywordKind Visibility) { 14786 14787 IdentifierInfo *II = D.getIdentifier(); 14788 Expr *BitWidth = (Expr*)BitfieldWidth; 14789 SourceLocation Loc = DeclStart; 14790 if (II) Loc = D.getIdentifierLoc(); 14791 14792 // FIXME: Unnamed fields can be handled in various different ways, for 14793 // example, unnamed unions inject all members into the struct namespace! 14794 14795 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14796 QualType T = TInfo->getType(); 14797 14798 if (BitWidth) { 14799 // 6.7.2.1p3, 6.7.2.1p4 14800 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 14801 if (!BitWidth) 14802 D.setInvalidType(); 14803 } else { 14804 // Not a bitfield. 14805 14806 // validate II. 14807 14808 } 14809 if (T->isReferenceType()) { 14810 Diag(Loc, diag::err_ivar_reference_type); 14811 D.setInvalidType(); 14812 } 14813 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14814 // than a variably modified type. 14815 else if (T->isVariablyModifiedType()) { 14816 Diag(Loc, diag::err_typecheck_ivar_variable_size); 14817 D.setInvalidType(); 14818 } 14819 14820 // Get the visibility (access control) for this ivar. 14821 ObjCIvarDecl::AccessControl ac = 14822 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 14823 : ObjCIvarDecl::None; 14824 // Must set ivar's DeclContext to its enclosing interface. 14825 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 14826 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 14827 return nullptr; 14828 ObjCContainerDecl *EnclosingContext; 14829 if (ObjCImplementationDecl *IMPDecl = 14830 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 14831 if (LangOpts.ObjCRuntime.isFragile()) { 14832 // Case of ivar declared in an implementation. Context is that of its class. 14833 EnclosingContext = IMPDecl->getClassInterface(); 14834 assert(EnclosingContext && "Implementation has no class interface!"); 14835 } 14836 else 14837 EnclosingContext = EnclosingDecl; 14838 } else { 14839 if (ObjCCategoryDecl *CDecl = 14840 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 14841 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 14842 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 14843 return nullptr; 14844 } 14845 } 14846 EnclosingContext = EnclosingDecl; 14847 } 14848 14849 // Construct the decl. 14850 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 14851 DeclStart, Loc, II, T, 14852 TInfo, ac, (Expr *)BitfieldWidth); 14853 14854 if (II) { 14855 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 14856 ForVisibleRedeclaration); 14857 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 14858 && !isa<TagDecl>(PrevDecl)) { 14859 Diag(Loc, diag::err_duplicate_member) << II; 14860 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14861 NewID->setInvalidDecl(); 14862 } 14863 } 14864 14865 // Process attributes attached to the ivar. 14866 ProcessDeclAttributes(S, NewID, D); 14867 14868 if (D.isInvalidType()) 14869 NewID->setInvalidDecl(); 14870 14871 // In ARC, infer 'retaining' for ivars of retainable type. 14872 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 14873 NewID->setInvalidDecl(); 14874 14875 if (D.getDeclSpec().isModulePrivateSpecified()) 14876 NewID->setModulePrivate(); 14877 14878 if (II) { 14879 // FIXME: When interfaces are DeclContexts, we'll need to add 14880 // these to the interface. 14881 S->AddDecl(NewID); 14882 IdResolver.AddDecl(NewID); 14883 } 14884 14885 if (LangOpts.ObjCRuntime.isNonFragile() && 14886 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 14887 Diag(Loc, diag::warn_ivars_in_interface); 14888 14889 return NewID; 14890 } 14891 14892 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 14893 /// class and class extensions. For every class \@interface and class 14894 /// extension \@interface, if the last ivar is a bitfield of any type, 14895 /// then add an implicit `char :0` ivar to the end of that interface. 14896 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 14897 SmallVectorImpl<Decl *> &AllIvarDecls) { 14898 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 14899 return; 14900 14901 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 14902 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 14903 14904 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 14905 return; 14906 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 14907 if (!ID) { 14908 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 14909 if (!CD->IsClassExtension()) 14910 return; 14911 } 14912 // No need to add this to end of @implementation. 14913 else 14914 return; 14915 } 14916 // All conditions are met. Add a new bitfield to the tail end of ivars. 14917 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 14918 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 14919 14920 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 14921 DeclLoc, DeclLoc, nullptr, 14922 Context.CharTy, 14923 Context.getTrivialTypeSourceInfo(Context.CharTy, 14924 DeclLoc), 14925 ObjCIvarDecl::Private, BW, 14926 true); 14927 AllIvarDecls.push_back(Ivar); 14928 } 14929 14930 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 14931 ArrayRef<Decl *> Fields, SourceLocation LBrac, 14932 SourceLocation RBrac, AttributeList *Attr) { 14933 assert(EnclosingDecl && "missing record or interface decl"); 14934 14935 // If this is an Objective-C @implementation or category and we have 14936 // new fields here we should reset the layout of the interface since 14937 // it will now change. 14938 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 14939 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 14940 switch (DC->getKind()) { 14941 default: break; 14942 case Decl::ObjCCategory: 14943 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 14944 break; 14945 case Decl::ObjCImplementation: 14946 Context. 14947 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 14948 break; 14949 } 14950 } 14951 14952 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 14953 14954 // Start counting up the number of named members; make sure to include 14955 // members of anonymous structs and unions in the total. 14956 unsigned NumNamedMembers = 0; 14957 if (Record) { 14958 for (const auto *I : Record->decls()) { 14959 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 14960 if (IFD->getDeclName()) 14961 ++NumNamedMembers; 14962 } 14963 } 14964 14965 // Verify that all the fields are okay. 14966 SmallVector<FieldDecl*, 32> RecFields; 14967 14968 bool ObjCFieldLifetimeErrReported = false; 14969 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 14970 i != end; ++i) { 14971 FieldDecl *FD = cast<FieldDecl>(*i); 14972 14973 // Get the type for the field. 14974 const Type *FDTy = FD->getType().getTypePtr(); 14975 14976 if (!FD->isAnonymousStructOrUnion()) { 14977 // Remember all fields written by the user. 14978 RecFields.push_back(FD); 14979 } 14980 14981 // If the field is already invalid for some reason, don't emit more 14982 // diagnostics about it. 14983 if (FD->isInvalidDecl()) { 14984 EnclosingDecl->setInvalidDecl(); 14985 continue; 14986 } 14987 14988 // C99 6.7.2.1p2: 14989 // A structure or union shall not contain a member with 14990 // incomplete or function type (hence, a structure shall not 14991 // contain an instance of itself, but may contain a pointer to 14992 // an instance of itself), except that the last member of a 14993 // structure with more than one named member may have incomplete 14994 // array type; such a structure (and any union containing, 14995 // possibly recursively, a member that is such a structure) 14996 // shall not be a member of a structure or an element of an 14997 // array. 14998 if (FDTy->isFunctionType()) { 14999 // Field declared as a function. 15000 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15001 << FD->getDeclName(); 15002 FD->setInvalidDecl(); 15003 EnclosingDecl->setInvalidDecl(); 15004 continue; 15005 } else if (FDTy->isIncompleteArrayType() && Record && 15006 ((i + 1 == Fields.end() && !Record->isUnion()) || 15007 ((getLangOpts().MicrosoftExt || 15008 getLangOpts().CPlusPlus) && 15009 (i + 1 == Fields.end() || Record->isUnion())))) { 15010 // Flexible array member. 15011 // Microsoft and g++ is more permissive regarding flexible array. 15012 // It will accept flexible array in union and also 15013 // as the sole element of a struct/class. 15014 unsigned DiagID = 0; 15015 if (Record->isUnion()) 15016 DiagID = getLangOpts().MicrosoftExt 15017 ? diag::ext_flexible_array_union_ms 15018 : getLangOpts().CPlusPlus 15019 ? diag::ext_flexible_array_union_gnu 15020 : diag::err_flexible_array_union; 15021 else if (NumNamedMembers < 1) 15022 DiagID = getLangOpts().MicrosoftExt 15023 ? diag::ext_flexible_array_empty_aggregate_ms 15024 : getLangOpts().CPlusPlus 15025 ? diag::ext_flexible_array_empty_aggregate_gnu 15026 : diag::err_flexible_array_empty_aggregate; 15027 15028 if (DiagID) 15029 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15030 << Record->getTagKind(); 15031 // While the layout of types that contain virtual bases is not specified 15032 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15033 // virtual bases after the derived members. This would make a flexible 15034 // array member declared at the end of an object not adjacent to the end 15035 // of the type. 15036 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 15037 if (RD->getNumVBases() != 0) 15038 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15039 << FD->getDeclName() << Record->getTagKind(); 15040 if (!getLangOpts().C99) 15041 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15042 << FD->getDeclName() << Record->getTagKind(); 15043 15044 // If the element type has a non-trivial destructor, we would not 15045 // implicitly destroy the elements, so disallow it for now. 15046 // 15047 // FIXME: GCC allows this. We should probably either implicitly delete 15048 // the destructor of the containing class, or just allow this. 15049 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15050 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15051 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15052 << FD->getDeclName() << FD->getType(); 15053 FD->setInvalidDecl(); 15054 EnclosingDecl->setInvalidDecl(); 15055 continue; 15056 } 15057 // Okay, we have a legal flexible array member at the end of the struct. 15058 Record->setHasFlexibleArrayMember(true); 15059 } else if (!FDTy->isDependentType() && 15060 RequireCompleteType(FD->getLocation(), FD->getType(), 15061 diag::err_field_incomplete)) { 15062 // Incomplete type 15063 FD->setInvalidDecl(); 15064 EnclosingDecl->setInvalidDecl(); 15065 continue; 15066 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15067 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15068 // A type which contains a flexible array member is considered to be a 15069 // flexible array member. 15070 Record->setHasFlexibleArrayMember(true); 15071 if (!Record->isUnion()) { 15072 // If this is a struct/class and this is not the last element, reject 15073 // it. Note that GCC supports variable sized arrays in the middle of 15074 // structures. 15075 if (i + 1 != Fields.end()) 15076 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15077 << FD->getDeclName() << FD->getType(); 15078 else { 15079 // We support flexible arrays at the end of structs in 15080 // other structs as an extension. 15081 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15082 << FD->getDeclName(); 15083 } 15084 } 15085 } 15086 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15087 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15088 diag::err_abstract_type_in_decl, 15089 AbstractIvarType)) { 15090 // Ivars can not have abstract class types 15091 FD->setInvalidDecl(); 15092 } 15093 if (Record && FDTTy->getDecl()->hasObjectMember()) 15094 Record->setHasObjectMember(true); 15095 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15096 Record->setHasVolatileMember(true); 15097 } else if (FDTy->isObjCObjectType()) { 15098 /// A field cannot be an Objective-c object 15099 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15100 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15101 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15102 FD->setType(T); 15103 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15104 Record && !ObjCFieldLifetimeErrReported && 15105 (!getLangOpts().CPlusPlus || Record->isUnion())) { 15106 // It's an error in ARC or Weak if a field has lifetime. 15107 // We don't want to report this in a system header, though, 15108 // so we just make the field unavailable. 15109 // FIXME: that's really not sufficient; we need to make the type 15110 // itself invalid to, say, initialize or copy. 15111 QualType T = FD->getType(); 15112 if (T.hasNonTrivialObjCLifetime()) { 15113 SourceLocation loc = FD->getLocation(); 15114 if (getSourceManager().isInSystemHeader(loc)) { 15115 if (!FD->hasAttr<UnavailableAttr>()) { 15116 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15117 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15118 } 15119 } else { 15120 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15121 << T->isBlockPointerType() << Record->getTagKind(); 15122 } 15123 ObjCFieldLifetimeErrReported = true; 15124 } 15125 } else if (getLangOpts().ObjC1 && 15126 getLangOpts().getGC() != LangOptions::NonGC && 15127 Record && !Record->hasObjectMember()) { 15128 if (FD->getType()->isObjCObjectPointerType() || 15129 FD->getType().isObjCGCStrong()) 15130 Record->setHasObjectMember(true); 15131 else if (Context.getAsArrayType(FD->getType())) { 15132 QualType BaseType = Context.getBaseElementType(FD->getType()); 15133 if (BaseType->isRecordType() && 15134 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15135 Record->setHasObjectMember(true); 15136 else if (BaseType->isObjCObjectPointerType() || 15137 BaseType.isObjCGCStrong()) 15138 Record->setHasObjectMember(true); 15139 } 15140 } 15141 if (Record && FD->getType().isVolatileQualified()) 15142 Record->setHasVolatileMember(true); 15143 // Keep track of the number of named members. 15144 if (FD->getIdentifier()) 15145 ++NumNamedMembers; 15146 } 15147 15148 // Okay, we successfully defined 'Record'. 15149 if (Record) { 15150 bool Completed = false; 15151 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15152 if (!CXXRecord->isInvalidDecl()) { 15153 // Set access bits correctly on the directly-declared conversions. 15154 for (CXXRecordDecl::conversion_iterator 15155 I = CXXRecord->conversion_begin(), 15156 E = CXXRecord->conversion_end(); I != E; ++I) 15157 I.setAccess((*I)->getAccess()); 15158 } 15159 15160 if (!CXXRecord->isDependentType()) { 15161 if (CXXRecord->hasUserDeclaredDestructor()) { 15162 // Adjust user-defined destructor exception spec. 15163 if (getLangOpts().CPlusPlus11) 15164 AdjustDestructorExceptionSpec(CXXRecord, 15165 CXXRecord->getDestructor()); 15166 } 15167 15168 if (!CXXRecord->isInvalidDecl()) { 15169 // Add any implicitly-declared members to this class. 15170 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15171 15172 // If we have virtual base classes, we may end up finding multiple 15173 // final overriders for a given virtual function. Check for this 15174 // problem now. 15175 if (CXXRecord->getNumVBases()) { 15176 CXXFinalOverriderMap FinalOverriders; 15177 CXXRecord->getFinalOverriders(FinalOverriders); 15178 15179 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15180 MEnd = FinalOverriders.end(); 15181 M != MEnd; ++M) { 15182 for (OverridingMethods::iterator SO = M->second.begin(), 15183 SOEnd = M->second.end(); 15184 SO != SOEnd; ++SO) { 15185 assert(SO->second.size() > 0 && 15186 "Virtual function without overridding functions?"); 15187 if (SO->second.size() == 1) 15188 continue; 15189 15190 // C++ [class.virtual]p2: 15191 // In a derived class, if a virtual member function of a base 15192 // class subobject has more than one final overrider the 15193 // program is ill-formed. 15194 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15195 << (const NamedDecl *)M->first << Record; 15196 Diag(M->first->getLocation(), 15197 diag::note_overridden_virtual_function); 15198 for (OverridingMethods::overriding_iterator 15199 OM = SO->second.begin(), 15200 OMEnd = SO->second.end(); 15201 OM != OMEnd; ++OM) 15202 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15203 << (const NamedDecl *)M->first << OM->Method->getParent(); 15204 15205 Record->setInvalidDecl(); 15206 } 15207 } 15208 CXXRecord->completeDefinition(&FinalOverriders); 15209 Completed = true; 15210 } 15211 } 15212 } 15213 } 15214 15215 if (!Completed) 15216 Record->completeDefinition(); 15217 15218 // We may have deferred checking for a deleted destructor. Check now. 15219 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15220 auto *Dtor = CXXRecord->getDestructor(); 15221 if (Dtor && Dtor->isImplicit() && 15222 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 15223 CXXRecord->setImplicitDestructorIsDeleted(); 15224 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15225 } 15226 } 15227 15228 if (Record->hasAttrs()) { 15229 CheckAlignasUnderalignment(Record); 15230 15231 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15232 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15233 IA->getRange(), IA->getBestCase(), 15234 IA->getSemanticSpelling()); 15235 } 15236 15237 // Check if the structure/union declaration is a type that can have zero 15238 // size in C. For C this is a language extension, for C++ it may cause 15239 // compatibility problems. 15240 bool CheckForZeroSize; 15241 if (!getLangOpts().CPlusPlus) { 15242 CheckForZeroSize = true; 15243 } else { 15244 // For C++ filter out types that cannot be referenced in C code. 15245 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15246 CheckForZeroSize = 15247 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15248 !CXXRecord->isDependentType() && 15249 CXXRecord->isCLike(); 15250 } 15251 if (CheckForZeroSize) { 15252 bool ZeroSize = true; 15253 bool IsEmpty = true; 15254 unsigned NonBitFields = 0; 15255 for (RecordDecl::field_iterator I = Record->field_begin(), 15256 E = Record->field_end(); 15257 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15258 IsEmpty = false; 15259 if (I->isUnnamedBitfield()) { 15260 if (I->getBitWidthValue(Context) > 0) 15261 ZeroSize = false; 15262 } else { 15263 ++NonBitFields; 15264 QualType FieldType = I->getType(); 15265 if (FieldType->isIncompleteType() || 15266 !Context.getTypeSizeInChars(FieldType).isZero()) 15267 ZeroSize = false; 15268 } 15269 } 15270 15271 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15272 // allowed in C++, but warn if its declaration is inside 15273 // extern "C" block. 15274 if (ZeroSize) { 15275 Diag(RecLoc, getLangOpts().CPlusPlus ? 15276 diag::warn_zero_size_struct_union_in_extern_c : 15277 diag::warn_zero_size_struct_union_compat) 15278 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15279 } 15280 15281 // Structs without named members are extension in C (C99 6.7.2.1p7), 15282 // but are accepted by GCC. 15283 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15284 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15285 diag::ext_no_named_members_in_struct_union) 15286 << Record->isUnion(); 15287 } 15288 } 15289 } else { 15290 ObjCIvarDecl **ClsFields = 15291 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15292 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15293 ID->setEndOfDefinitionLoc(RBrac); 15294 // Add ivar's to class's DeclContext. 15295 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15296 ClsFields[i]->setLexicalDeclContext(ID); 15297 ID->addDecl(ClsFields[i]); 15298 } 15299 // Must enforce the rule that ivars in the base classes may not be 15300 // duplicates. 15301 if (ID->getSuperClass()) 15302 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15303 } else if (ObjCImplementationDecl *IMPDecl = 15304 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15305 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15306 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15307 // Ivar declared in @implementation never belongs to the implementation. 15308 // Only it is in implementation's lexical context. 15309 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15310 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15311 IMPDecl->setIvarLBraceLoc(LBrac); 15312 IMPDecl->setIvarRBraceLoc(RBrac); 15313 } else if (ObjCCategoryDecl *CDecl = 15314 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15315 // case of ivars in class extension; all other cases have been 15316 // reported as errors elsewhere. 15317 // FIXME. Class extension does not have a LocEnd field. 15318 // CDecl->setLocEnd(RBrac); 15319 // Add ivar's to class extension's DeclContext. 15320 // Diagnose redeclaration of private ivars. 15321 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15322 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15323 if (IDecl) { 15324 if (const ObjCIvarDecl *ClsIvar = 15325 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15326 Diag(ClsFields[i]->getLocation(), 15327 diag::err_duplicate_ivar_declaration); 15328 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15329 continue; 15330 } 15331 for (const auto *Ext : IDecl->known_extensions()) { 15332 if (const ObjCIvarDecl *ClsExtIvar 15333 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15334 Diag(ClsFields[i]->getLocation(), 15335 diag::err_duplicate_ivar_declaration); 15336 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15337 continue; 15338 } 15339 } 15340 } 15341 ClsFields[i]->setLexicalDeclContext(CDecl); 15342 CDecl->addDecl(ClsFields[i]); 15343 } 15344 CDecl->setIvarLBraceLoc(LBrac); 15345 CDecl->setIvarRBraceLoc(RBrac); 15346 } 15347 } 15348 15349 if (Attr) 15350 ProcessDeclAttributeList(S, Record, Attr); 15351 } 15352 15353 /// \brief Determine whether the given integral value is representable within 15354 /// the given type T. 15355 static bool isRepresentableIntegerValue(ASTContext &Context, 15356 llvm::APSInt &Value, 15357 QualType T) { 15358 assert(T->isIntegralType(Context) && "Integral type required!"); 15359 unsigned BitWidth = Context.getIntWidth(T); 15360 15361 if (Value.isUnsigned() || Value.isNonNegative()) { 15362 if (T->isSignedIntegerOrEnumerationType()) 15363 --BitWidth; 15364 return Value.getActiveBits() <= BitWidth; 15365 } 15366 return Value.getMinSignedBits() <= BitWidth; 15367 } 15368 15369 // \brief Given an integral type, return the next larger integral type 15370 // (or a NULL type of no such type exists). 15371 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15372 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15373 // enum checking below. 15374 assert(T->isIntegralType(Context) && "Integral type required!"); 15375 const unsigned NumTypes = 4; 15376 QualType SignedIntegralTypes[NumTypes] = { 15377 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15378 }; 15379 QualType UnsignedIntegralTypes[NumTypes] = { 15380 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15381 Context.UnsignedLongLongTy 15382 }; 15383 15384 unsigned BitWidth = Context.getTypeSize(T); 15385 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15386 : UnsignedIntegralTypes; 15387 for (unsigned I = 0; I != NumTypes; ++I) 15388 if (Context.getTypeSize(Types[I]) > BitWidth) 15389 return Types[I]; 15390 15391 return QualType(); 15392 } 15393 15394 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15395 EnumConstantDecl *LastEnumConst, 15396 SourceLocation IdLoc, 15397 IdentifierInfo *Id, 15398 Expr *Val) { 15399 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15400 llvm::APSInt EnumVal(IntWidth); 15401 QualType EltTy; 15402 15403 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15404 Val = nullptr; 15405 15406 if (Val) 15407 Val = DefaultLvalueConversion(Val).get(); 15408 15409 if (Val) { 15410 if (Enum->isDependentType() || Val->isTypeDependent()) 15411 EltTy = Context.DependentTy; 15412 else { 15413 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15414 !getLangOpts().MSVCCompat) { 15415 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15416 // constant-expression in the enumerator-definition shall be a converted 15417 // constant expression of the underlying type. 15418 EltTy = Enum->getIntegerType(); 15419 ExprResult Converted = 15420 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15421 CCEK_Enumerator); 15422 if (Converted.isInvalid()) 15423 Val = nullptr; 15424 else 15425 Val = Converted.get(); 15426 } else if (!Val->isValueDependent() && 15427 !(Val = VerifyIntegerConstantExpression(Val, 15428 &EnumVal).get())) { 15429 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15430 } else { 15431 if (Enum->isFixed()) { 15432 EltTy = Enum->getIntegerType(); 15433 15434 // In Obj-C and Microsoft mode, require the enumeration value to be 15435 // representable in the underlying type of the enumeration. In C++11, 15436 // we perform a non-narrowing conversion as part of converted constant 15437 // expression checking. 15438 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15439 if (getLangOpts().MSVCCompat) { 15440 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15441 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15442 } else 15443 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15444 } else 15445 Val = ImpCastExprToType(Val, EltTy, 15446 EltTy->isBooleanType() ? 15447 CK_IntegralToBoolean : CK_IntegralCast) 15448 .get(); 15449 } else if (getLangOpts().CPlusPlus) { 15450 // C++11 [dcl.enum]p5: 15451 // If the underlying type is not fixed, the type of each enumerator 15452 // is the type of its initializing value: 15453 // - If an initializer is specified for an enumerator, the 15454 // initializing value has the same type as the expression. 15455 EltTy = Val->getType(); 15456 } else { 15457 // C99 6.7.2.2p2: 15458 // The expression that defines the value of an enumeration constant 15459 // shall be an integer constant expression that has a value 15460 // representable as an int. 15461 15462 // Complain if the value is not representable in an int. 15463 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15464 Diag(IdLoc, diag::ext_enum_value_not_int) 15465 << EnumVal.toString(10) << Val->getSourceRange() 15466 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15467 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15468 // Force the type of the expression to 'int'. 15469 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15470 } 15471 EltTy = Val->getType(); 15472 } 15473 } 15474 } 15475 } 15476 15477 if (!Val) { 15478 if (Enum->isDependentType()) 15479 EltTy = Context.DependentTy; 15480 else if (!LastEnumConst) { 15481 // C++0x [dcl.enum]p5: 15482 // If the underlying type is not fixed, the type of each enumerator 15483 // is the type of its initializing value: 15484 // - If no initializer is specified for the first enumerator, the 15485 // initializing value has an unspecified integral type. 15486 // 15487 // GCC uses 'int' for its unspecified integral type, as does 15488 // C99 6.7.2.2p3. 15489 if (Enum->isFixed()) { 15490 EltTy = Enum->getIntegerType(); 15491 } 15492 else { 15493 EltTy = Context.IntTy; 15494 } 15495 } else { 15496 // Assign the last value + 1. 15497 EnumVal = LastEnumConst->getInitVal(); 15498 ++EnumVal; 15499 EltTy = LastEnumConst->getType(); 15500 15501 // Check for overflow on increment. 15502 if (EnumVal < LastEnumConst->getInitVal()) { 15503 // C++0x [dcl.enum]p5: 15504 // If the underlying type is not fixed, the type of each enumerator 15505 // is the type of its initializing value: 15506 // 15507 // - Otherwise the type of the initializing value is the same as 15508 // the type of the initializing value of the preceding enumerator 15509 // unless the incremented value is not representable in that type, 15510 // in which case the type is an unspecified integral type 15511 // sufficient to contain the incremented value. If no such type 15512 // exists, the program is ill-formed. 15513 QualType T = getNextLargerIntegralType(Context, EltTy); 15514 if (T.isNull() || Enum->isFixed()) { 15515 // There is no integral type larger enough to represent this 15516 // value. Complain, then allow the value to wrap around. 15517 EnumVal = LastEnumConst->getInitVal(); 15518 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15519 ++EnumVal; 15520 if (Enum->isFixed()) 15521 // When the underlying type is fixed, this is ill-formed. 15522 Diag(IdLoc, diag::err_enumerator_wrapped) 15523 << EnumVal.toString(10) 15524 << EltTy; 15525 else 15526 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15527 << EnumVal.toString(10); 15528 } else { 15529 EltTy = T; 15530 } 15531 15532 // Retrieve the last enumerator's value, extent that type to the 15533 // type that is supposed to be large enough to represent the incremented 15534 // value, then increment. 15535 EnumVal = LastEnumConst->getInitVal(); 15536 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15537 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15538 ++EnumVal; 15539 15540 // If we're not in C++, diagnose the overflow of enumerator values, 15541 // which in C99 means that the enumerator value is not representable in 15542 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15543 // permits enumerator values that are representable in some larger 15544 // integral type. 15545 if (!getLangOpts().CPlusPlus && !T.isNull()) 15546 Diag(IdLoc, diag::warn_enum_value_overflow); 15547 } else if (!getLangOpts().CPlusPlus && 15548 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15549 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15550 Diag(IdLoc, diag::ext_enum_value_not_int) 15551 << EnumVal.toString(10) << 1; 15552 } 15553 } 15554 } 15555 15556 if (!EltTy->isDependentType()) { 15557 // Make the enumerator value match the signedness and size of the 15558 // enumerator's type. 15559 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15560 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15561 } 15562 15563 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15564 Val, EnumVal); 15565 } 15566 15567 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15568 SourceLocation IILoc) { 15569 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15570 !getLangOpts().CPlusPlus) 15571 return SkipBodyInfo(); 15572 15573 // We have an anonymous enum definition. Look up the first enumerator to 15574 // determine if we should merge the definition with an existing one and 15575 // skip the body. 15576 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15577 forRedeclarationInCurContext()); 15578 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15579 if (!PrevECD) 15580 return SkipBodyInfo(); 15581 15582 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15583 NamedDecl *Hidden; 15584 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15585 SkipBodyInfo Skip; 15586 Skip.Previous = Hidden; 15587 return Skip; 15588 } 15589 15590 return SkipBodyInfo(); 15591 } 15592 15593 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15594 SourceLocation IdLoc, IdentifierInfo *Id, 15595 AttributeList *Attr, 15596 SourceLocation EqualLoc, Expr *Val) { 15597 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15598 EnumConstantDecl *LastEnumConst = 15599 cast_or_null<EnumConstantDecl>(lastEnumConst); 15600 15601 // The scope passed in may not be a decl scope. Zip up the scope tree until 15602 // we find one that is. 15603 S = getNonFieldDeclScope(S); 15604 15605 // Verify that there isn't already something declared with this name in this 15606 // scope. 15607 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15608 ForVisibleRedeclaration); 15609 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15610 // Maybe we will complain about the shadowed template parameter. 15611 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15612 // Just pretend that we didn't see the previous declaration. 15613 PrevDecl = nullptr; 15614 } 15615 15616 // C++ [class.mem]p15: 15617 // If T is the name of a class, then each of the following shall have a name 15618 // different from T: 15619 // - every enumerator of every member of class T that is an unscoped 15620 // enumerated type 15621 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 15622 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15623 DeclarationNameInfo(Id, IdLoc)); 15624 15625 EnumConstantDecl *New = 15626 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15627 if (!New) 15628 return nullptr; 15629 15630 if (PrevDecl) { 15631 // When in C++, we may get a TagDecl with the same name; in this case the 15632 // enum constant will 'hide' the tag. 15633 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15634 "Received TagDecl when not in C++!"); 15635 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 15636 if (isa<EnumConstantDecl>(PrevDecl)) 15637 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15638 else 15639 Diag(IdLoc, diag::err_redefinition) << Id; 15640 notePreviousDefinition(PrevDecl, IdLoc); 15641 return nullptr; 15642 } 15643 } 15644 15645 // Process attributes. 15646 if (Attr) ProcessDeclAttributeList(S, New, Attr); 15647 AddPragmaAttributes(S, New); 15648 15649 // Register this decl in the current scope stack. 15650 New->setAccess(TheEnumDecl->getAccess()); 15651 PushOnScopeChains(New, S); 15652 15653 ActOnDocumentableDecl(New); 15654 15655 return New; 15656 } 15657 15658 // Returns true when the enum initial expression does not trigger the 15659 // duplicate enum warning. A few common cases are exempted as follows: 15660 // Element2 = Element1 15661 // Element2 = Element1 + 1 15662 // Element2 = Element1 - 1 15663 // Where Element2 and Element1 are from the same enum. 15664 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 15665 Expr *InitExpr = ECD->getInitExpr(); 15666 if (!InitExpr) 15667 return true; 15668 InitExpr = InitExpr->IgnoreImpCasts(); 15669 15670 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 15671 if (!BO->isAdditiveOp()) 15672 return true; 15673 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 15674 if (!IL) 15675 return true; 15676 if (IL->getValue() != 1) 15677 return true; 15678 15679 InitExpr = BO->getLHS(); 15680 } 15681 15682 // This checks if the elements are from the same enum. 15683 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 15684 if (!DRE) 15685 return true; 15686 15687 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 15688 if (!EnumConstant) 15689 return true; 15690 15691 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 15692 Enum) 15693 return true; 15694 15695 return false; 15696 } 15697 15698 namespace { 15699 struct DupKey { 15700 int64_t val; 15701 bool isTombstoneOrEmptyKey; 15702 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 15703 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 15704 }; 15705 15706 static DupKey GetDupKey(const llvm::APSInt& Val) { 15707 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 15708 false); 15709 } 15710 15711 struct DenseMapInfoDupKey { 15712 static DupKey getEmptyKey() { return DupKey(0, true); } 15713 static DupKey getTombstoneKey() { return DupKey(1, true); } 15714 static unsigned getHashValue(const DupKey Key) { 15715 return (unsigned)(Key.val * 37); 15716 } 15717 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 15718 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 15719 LHS.val == RHS.val; 15720 } 15721 }; 15722 } // end anonymous namespace 15723 15724 // Emits a warning when an element is implicitly set a value that 15725 // a previous element has already been set to. 15726 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 15727 EnumDecl *Enum, 15728 QualType EnumType) { 15729 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 15730 return; 15731 // Avoid anonymous enums 15732 if (!Enum->getIdentifier()) 15733 return; 15734 15735 // Only check for small enums. 15736 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 15737 return; 15738 15739 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 15740 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 15741 15742 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 15743 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 15744 ValueToVectorMap; 15745 15746 DuplicatesVector DupVector; 15747 ValueToVectorMap EnumMap; 15748 15749 // Populate the EnumMap with all values represented by enum constants without 15750 // an initialier. 15751 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15752 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 15753 15754 // Null EnumConstantDecl means a previous diagnostic has been emitted for 15755 // this constant. Skip this enum since it may be ill-formed. 15756 if (!ECD) { 15757 return; 15758 } 15759 15760 if (ECD->getInitExpr()) 15761 continue; 15762 15763 DupKey Key = GetDupKey(ECD->getInitVal()); 15764 DeclOrVector &Entry = EnumMap[Key]; 15765 15766 // First time encountering this value. 15767 if (Entry.isNull()) 15768 Entry = ECD; 15769 } 15770 15771 // Create vectors for any values that has duplicates. 15772 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15773 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 15774 if (!ValidDuplicateEnum(ECD, Enum)) 15775 continue; 15776 15777 DupKey Key = GetDupKey(ECD->getInitVal()); 15778 15779 DeclOrVector& Entry = EnumMap[Key]; 15780 if (Entry.isNull()) 15781 continue; 15782 15783 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 15784 // Ensure constants are different. 15785 if (D == ECD) 15786 continue; 15787 15788 // Create new vector and push values onto it. 15789 ECDVector *Vec = new ECDVector(); 15790 Vec->push_back(D); 15791 Vec->push_back(ECD); 15792 15793 // Update entry to point to the duplicates vector. 15794 Entry = Vec; 15795 15796 // Store the vector somewhere we can consult later for quick emission of 15797 // diagnostics. 15798 DupVector.push_back(Vec); 15799 continue; 15800 } 15801 15802 ECDVector *Vec = Entry.get<ECDVector*>(); 15803 // Make sure constants are not added more than once. 15804 if (*Vec->begin() == ECD) 15805 continue; 15806 15807 Vec->push_back(ECD); 15808 } 15809 15810 // Emit diagnostics. 15811 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 15812 DupVectorEnd = DupVector.end(); 15813 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 15814 ECDVector *Vec = *DupVectorIter; 15815 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 15816 15817 // Emit warning for one enum constant. 15818 ECDVector::iterator I = Vec->begin(); 15819 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 15820 << (*I)->getName() << (*I)->getInitVal().toString(10) 15821 << (*I)->getSourceRange(); 15822 ++I; 15823 15824 // Emit one note for each of the remaining enum constants with 15825 // the same value. 15826 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 15827 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 15828 << (*I)->getName() << (*I)->getInitVal().toString(10) 15829 << (*I)->getSourceRange(); 15830 delete Vec; 15831 } 15832 } 15833 15834 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 15835 bool AllowMask) const { 15836 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 15837 assert(ED->isCompleteDefinition() && "expected enum definition"); 15838 15839 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 15840 llvm::APInt &FlagBits = R.first->second; 15841 15842 if (R.second) { 15843 for (auto *E : ED->enumerators()) { 15844 const auto &EVal = E->getInitVal(); 15845 // Only single-bit enumerators introduce new flag values. 15846 if (EVal.isPowerOf2()) 15847 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 15848 } 15849 } 15850 15851 // A value is in a flag enum if either its bits are a subset of the enum's 15852 // flag bits (the first condition) or we are allowing masks and the same is 15853 // true of its complement (the second condition). When masks are allowed, we 15854 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 15855 // 15856 // While it's true that any value could be used as a mask, the assumption is 15857 // that a mask will have all of the insignificant bits set. Anything else is 15858 // likely a logic error. 15859 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 15860 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 15861 } 15862 15863 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 15864 Decl *EnumDeclX, 15865 ArrayRef<Decl *> Elements, 15866 Scope *S, AttributeList *Attr) { 15867 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 15868 QualType EnumType = Context.getTypeDeclType(Enum); 15869 15870 if (Attr) 15871 ProcessDeclAttributeList(S, Enum, Attr); 15872 15873 if (Enum->isDependentType()) { 15874 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15875 EnumConstantDecl *ECD = 15876 cast_or_null<EnumConstantDecl>(Elements[i]); 15877 if (!ECD) continue; 15878 15879 ECD->setType(EnumType); 15880 } 15881 15882 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 15883 return; 15884 } 15885 15886 // TODO: If the result value doesn't fit in an int, it must be a long or long 15887 // long value. ISO C does not support this, but GCC does as an extension, 15888 // emit a warning. 15889 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15890 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 15891 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 15892 15893 // Verify that all the values are okay, compute the size of the values, and 15894 // reverse the list. 15895 unsigned NumNegativeBits = 0; 15896 unsigned NumPositiveBits = 0; 15897 15898 // Keep track of whether all elements have type int. 15899 bool AllElementsInt = true; 15900 15901 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 15902 EnumConstantDecl *ECD = 15903 cast_or_null<EnumConstantDecl>(Elements[i]); 15904 if (!ECD) continue; // Already issued a diagnostic. 15905 15906 const llvm::APSInt &InitVal = ECD->getInitVal(); 15907 15908 // Keep track of the size of positive and negative values. 15909 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 15910 NumPositiveBits = std::max(NumPositiveBits, 15911 (unsigned)InitVal.getActiveBits()); 15912 else 15913 NumNegativeBits = std::max(NumNegativeBits, 15914 (unsigned)InitVal.getMinSignedBits()); 15915 15916 // Keep track of whether every enum element has type int (very commmon). 15917 if (AllElementsInt) 15918 AllElementsInt = ECD->getType() == Context.IntTy; 15919 } 15920 15921 // Figure out the type that should be used for this enum. 15922 QualType BestType; 15923 unsigned BestWidth; 15924 15925 // C++0x N3000 [conv.prom]p3: 15926 // An rvalue of an unscoped enumeration type whose underlying 15927 // type is not fixed can be converted to an rvalue of the first 15928 // of the following types that can represent all the values of 15929 // the enumeration: int, unsigned int, long int, unsigned long 15930 // int, long long int, or unsigned long long int. 15931 // C99 6.4.4.3p2: 15932 // An identifier declared as an enumeration constant has type int. 15933 // The C99 rule is modified by a gcc extension 15934 QualType BestPromotionType; 15935 15936 bool Packed = Enum->hasAttr<PackedAttr>(); 15937 // -fshort-enums is the equivalent to specifying the packed attribute on all 15938 // enum definitions. 15939 if (LangOpts.ShortEnums) 15940 Packed = true; 15941 15942 if (Enum->isFixed()) { 15943 BestType = Enum->getIntegerType(); 15944 if (BestType->isPromotableIntegerType()) 15945 BestPromotionType = Context.getPromotedIntegerType(BestType); 15946 else 15947 BestPromotionType = BestType; 15948 15949 BestWidth = Context.getIntWidth(BestType); 15950 } 15951 else if (NumNegativeBits) { 15952 // If there is a negative value, figure out the smallest integer type (of 15953 // int/long/longlong) that fits. 15954 // If it's packed, check also if it fits a char or a short. 15955 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 15956 BestType = Context.SignedCharTy; 15957 BestWidth = CharWidth; 15958 } else if (Packed && NumNegativeBits <= ShortWidth && 15959 NumPositiveBits < ShortWidth) { 15960 BestType = Context.ShortTy; 15961 BestWidth = ShortWidth; 15962 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 15963 BestType = Context.IntTy; 15964 BestWidth = IntWidth; 15965 } else { 15966 BestWidth = Context.getTargetInfo().getLongWidth(); 15967 15968 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 15969 BestType = Context.LongTy; 15970 } else { 15971 BestWidth = Context.getTargetInfo().getLongLongWidth(); 15972 15973 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 15974 Diag(Enum->getLocation(), diag::ext_enum_too_large); 15975 BestType = Context.LongLongTy; 15976 } 15977 } 15978 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 15979 } else { 15980 // If there is no negative value, figure out the smallest type that fits 15981 // all of the enumerator values. 15982 // If it's packed, check also if it fits a char or a short. 15983 if (Packed && NumPositiveBits <= CharWidth) { 15984 BestType = Context.UnsignedCharTy; 15985 BestPromotionType = Context.IntTy; 15986 BestWidth = CharWidth; 15987 } else if (Packed && NumPositiveBits <= ShortWidth) { 15988 BestType = Context.UnsignedShortTy; 15989 BestPromotionType = Context.IntTy; 15990 BestWidth = ShortWidth; 15991 } else if (NumPositiveBits <= IntWidth) { 15992 BestType = Context.UnsignedIntTy; 15993 BestWidth = IntWidth; 15994 BestPromotionType 15995 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 15996 ? Context.UnsignedIntTy : Context.IntTy; 15997 } else if (NumPositiveBits <= 15998 (BestWidth = Context.getTargetInfo().getLongWidth())) { 15999 BestType = Context.UnsignedLongTy; 16000 BestPromotionType 16001 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16002 ? Context.UnsignedLongTy : Context.LongTy; 16003 } else { 16004 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16005 assert(NumPositiveBits <= BestWidth && 16006 "How could an initializer get larger than ULL?"); 16007 BestType = Context.UnsignedLongLongTy; 16008 BestPromotionType 16009 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16010 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16011 } 16012 } 16013 16014 // Loop over all of the enumerator constants, changing their types to match 16015 // the type of the enum if needed. 16016 for (auto *D : Elements) { 16017 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16018 if (!ECD) continue; // Already issued a diagnostic. 16019 16020 // Standard C says the enumerators have int type, but we allow, as an 16021 // extension, the enumerators to be larger than int size. If each 16022 // enumerator value fits in an int, type it as an int, otherwise type it the 16023 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16024 // that X has type 'int', not 'unsigned'. 16025 16026 // Determine whether the value fits into an int. 16027 llvm::APSInt InitVal = ECD->getInitVal(); 16028 16029 // If it fits into an integer type, force it. Otherwise force it to match 16030 // the enum decl type. 16031 QualType NewTy; 16032 unsigned NewWidth; 16033 bool NewSign; 16034 if (!getLangOpts().CPlusPlus && 16035 !Enum->isFixed() && 16036 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16037 NewTy = Context.IntTy; 16038 NewWidth = IntWidth; 16039 NewSign = true; 16040 } else if (ECD->getType() == BestType) { 16041 // Already the right type! 16042 if (getLangOpts().CPlusPlus) 16043 // C++ [dcl.enum]p4: Following the closing brace of an 16044 // enum-specifier, each enumerator has the type of its 16045 // enumeration. 16046 ECD->setType(EnumType); 16047 continue; 16048 } else { 16049 NewTy = BestType; 16050 NewWidth = BestWidth; 16051 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16052 } 16053 16054 // Adjust the APSInt value. 16055 InitVal = InitVal.extOrTrunc(NewWidth); 16056 InitVal.setIsSigned(NewSign); 16057 ECD->setInitVal(InitVal); 16058 16059 // Adjust the Expr initializer and type. 16060 if (ECD->getInitExpr() && 16061 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16062 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16063 CK_IntegralCast, 16064 ECD->getInitExpr(), 16065 /*base paths*/ nullptr, 16066 VK_RValue)); 16067 if (getLangOpts().CPlusPlus) 16068 // C++ [dcl.enum]p4: Following the closing brace of an 16069 // enum-specifier, each enumerator has the type of its 16070 // enumeration. 16071 ECD->setType(EnumType); 16072 else 16073 ECD->setType(NewTy); 16074 } 16075 16076 Enum->completeDefinition(BestType, BestPromotionType, 16077 NumPositiveBits, NumNegativeBits); 16078 16079 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16080 16081 if (Enum->isClosedFlag()) { 16082 for (Decl *D : Elements) { 16083 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16084 if (!ECD) continue; // Already issued a diagnostic. 16085 16086 llvm::APSInt InitVal = ECD->getInitVal(); 16087 if (InitVal != 0 && !InitVal.isPowerOf2() && 16088 !IsValueInFlagEnum(Enum, InitVal, true)) 16089 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16090 << ECD << Enum; 16091 } 16092 } 16093 16094 // Now that the enum type is defined, ensure it's not been underaligned. 16095 if (Enum->hasAttrs()) 16096 CheckAlignasUnderalignment(Enum); 16097 } 16098 16099 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16100 SourceLocation StartLoc, 16101 SourceLocation EndLoc) { 16102 StringLiteral *AsmString = cast<StringLiteral>(expr); 16103 16104 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16105 AsmString, StartLoc, 16106 EndLoc); 16107 CurContext->addDecl(New); 16108 return New; 16109 } 16110 16111 static void checkModuleImportContext(Sema &S, Module *M, 16112 SourceLocation ImportLoc, DeclContext *DC, 16113 bool FromInclude = false) { 16114 SourceLocation ExternCLoc; 16115 16116 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16117 switch (LSD->getLanguage()) { 16118 case LinkageSpecDecl::lang_c: 16119 if (ExternCLoc.isInvalid()) 16120 ExternCLoc = LSD->getLocStart(); 16121 break; 16122 case LinkageSpecDecl::lang_cxx: 16123 break; 16124 } 16125 DC = LSD->getParent(); 16126 } 16127 16128 while (isa<LinkageSpecDecl>(DC)) 16129 DC = DC->getParent(); 16130 16131 if (!isa<TranslationUnitDecl>(DC)) { 16132 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16133 ? diag::ext_module_import_not_at_top_level_noop 16134 : diag::err_module_import_not_at_top_level_fatal) 16135 << M->getFullModuleName() << DC; 16136 S.Diag(cast<Decl>(DC)->getLocStart(), 16137 diag::note_module_import_not_at_top_level) << DC; 16138 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16139 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16140 << M->getFullModuleName(); 16141 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16142 } 16143 } 16144 16145 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16146 SourceLocation ModuleLoc, 16147 ModuleDeclKind MDK, 16148 ModuleIdPath Path) { 16149 assert(getLangOpts().ModulesTS && 16150 "should only have module decl in modules TS"); 16151 16152 // A module implementation unit requires that we are not compiling a module 16153 // of any kind. A module interface unit requires that we are not compiling a 16154 // module map. 16155 switch (getLangOpts().getCompilingModule()) { 16156 case LangOptions::CMK_None: 16157 // It's OK to compile a module interface as a normal translation unit. 16158 break; 16159 16160 case LangOptions::CMK_ModuleInterface: 16161 if (MDK != ModuleDeclKind::Implementation) 16162 break; 16163 16164 // We were asked to compile a module interface unit but this is a module 16165 // implementation unit. That indicates the 'export' is missing. 16166 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16167 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16168 MDK = ModuleDeclKind::Interface; 16169 break; 16170 16171 case LangOptions::CMK_ModuleMap: 16172 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16173 return nullptr; 16174 } 16175 16176 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16177 16178 // FIXME: Most of this work should be done by the preprocessor rather than 16179 // here, in order to support macro import. 16180 16181 // Only one module-declaration is permitted per source file. 16182 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16183 Diag(ModuleLoc, diag::err_module_redeclaration); 16184 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16185 diag::note_prev_module_declaration); 16186 return nullptr; 16187 } 16188 16189 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16190 // modules, the dots here are just another character that can appear in a 16191 // module name. 16192 std::string ModuleName; 16193 for (auto &Piece : Path) { 16194 if (!ModuleName.empty()) 16195 ModuleName += "."; 16196 ModuleName += Piece.first->getName(); 16197 } 16198 16199 // If a module name was explicitly specified on the command line, it must be 16200 // correct. 16201 if (!getLangOpts().CurrentModule.empty() && 16202 getLangOpts().CurrentModule != ModuleName) { 16203 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16204 << SourceRange(Path.front().second, Path.back().second) 16205 << getLangOpts().CurrentModule; 16206 return nullptr; 16207 } 16208 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16209 16210 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16211 Module *Mod; 16212 16213 switch (MDK) { 16214 case ModuleDeclKind::Interface: { 16215 // We can't have parsed or imported a definition of this module or parsed a 16216 // module map defining it already. 16217 if (auto *M = Map.findModule(ModuleName)) { 16218 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16219 if (M->DefinitionLoc.isValid()) 16220 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16221 else if (const auto *FE = M->getASTFile()) 16222 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16223 << FE->getName(); 16224 Mod = M; 16225 break; 16226 } 16227 16228 // Create a Module for the module that we're defining. 16229 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16230 ModuleScopes.front().Module); 16231 assert(Mod && "module creation should not fail"); 16232 break; 16233 } 16234 16235 case ModuleDeclKind::Partition: 16236 // FIXME: Check we are in a submodule of the named module. 16237 return nullptr; 16238 16239 case ModuleDeclKind::Implementation: 16240 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16241 PP.getIdentifierInfo(ModuleName), Path[0].second); 16242 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16243 /*IsIncludeDirective=*/false); 16244 if (!Mod) { 16245 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 16246 // Create an empty module interface unit for error recovery. 16247 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16248 ModuleScopes.front().Module); 16249 } 16250 break; 16251 } 16252 16253 // Switch from the global module to the named module. 16254 ModuleScopes.back().Module = Mod; 16255 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 16256 VisibleModules.setVisible(Mod, ModuleLoc); 16257 16258 // From now on, we have an owning module for all declarations we see. 16259 // However, those declarations are module-private unless explicitly 16260 // exported. 16261 auto *TU = Context.getTranslationUnitDecl(); 16262 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16263 TU->setLocalOwningModule(Mod); 16264 16265 // FIXME: Create a ModuleDecl. 16266 return nullptr; 16267 } 16268 16269 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16270 SourceLocation ImportLoc, 16271 ModuleIdPath Path) { 16272 Module *Mod = 16273 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16274 /*IsIncludeDirective=*/false); 16275 if (!Mod) 16276 return true; 16277 16278 VisibleModules.setVisible(Mod, ImportLoc); 16279 16280 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16281 16282 // FIXME: we should support importing a submodule within a different submodule 16283 // of the same top-level module. Until we do, make it an error rather than 16284 // silently ignoring the import. 16285 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16286 // warn on a redundant import of the current module? 16287 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16288 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16289 Diag(ImportLoc, getLangOpts().isCompilingModule() 16290 ? diag::err_module_self_import 16291 : diag::err_module_import_in_implementation) 16292 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16293 16294 SmallVector<SourceLocation, 2> IdentifierLocs; 16295 Module *ModCheck = Mod; 16296 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16297 // If we've run out of module parents, just drop the remaining identifiers. 16298 // We need the length to be consistent. 16299 if (!ModCheck) 16300 break; 16301 ModCheck = ModCheck->Parent; 16302 16303 IdentifierLocs.push_back(Path[I].second); 16304 } 16305 16306 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16307 ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc, 16308 Mod, IdentifierLocs); 16309 if (!ModuleScopes.empty()) 16310 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16311 TU->addDecl(Import); 16312 return Import; 16313 } 16314 16315 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16316 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16317 BuildModuleInclude(DirectiveLoc, Mod); 16318 } 16319 16320 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16321 // Determine whether we're in the #include buffer for a module. The #includes 16322 // in that buffer do not qualify as module imports; they're just an 16323 // implementation detail of us building the module. 16324 // 16325 // FIXME: Should we even get ActOnModuleInclude calls for those? 16326 bool IsInModuleIncludes = 16327 TUKind == TU_Module && 16328 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16329 16330 bool ShouldAddImport = !IsInModuleIncludes; 16331 16332 // If this module import was due to an inclusion directive, create an 16333 // implicit import declaration to capture it in the AST. 16334 if (ShouldAddImport) { 16335 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16336 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16337 DirectiveLoc, Mod, 16338 DirectiveLoc); 16339 if (!ModuleScopes.empty()) 16340 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16341 TU->addDecl(ImportD); 16342 Consumer.HandleImplicitImportDecl(ImportD); 16343 } 16344 16345 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16346 VisibleModules.setVisible(Mod, DirectiveLoc); 16347 } 16348 16349 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16350 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16351 16352 ModuleScopes.push_back({}); 16353 ModuleScopes.back().Module = Mod; 16354 if (getLangOpts().ModulesLocalVisibility) 16355 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16356 16357 VisibleModules.setVisible(Mod, DirectiveLoc); 16358 16359 // The enclosing context is now part of this module. 16360 // FIXME: Consider creating a child DeclContext to hold the entities 16361 // lexically within the module. 16362 if (getLangOpts().trackLocalOwningModule()) { 16363 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16364 cast<Decl>(DC)->setModuleOwnershipKind( 16365 getLangOpts().ModulesLocalVisibility 16366 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16367 : Decl::ModuleOwnershipKind::Visible); 16368 cast<Decl>(DC)->setLocalOwningModule(Mod); 16369 } 16370 } 16371 } 16372 16373 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16374 if (getLangOpts().ModulesLocalVisibility) { 16375 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16376 // Leaving a module hides namespace names, so our visible namespace cache 16377 // is now out of date. 16378 VisibleNamespaceCache.clear(); 16379 } 16380 16381 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16382 "left the wrong module scope"); 16383 ModuleScopes.pop_back(); 16384 16385 // We got to the end of processing a local module. Create an 16386 // ImportDecl as we would for an imported module. 16387 FileID File = getSourceManager().getFileID(EomLoc); 16388 SourceLocation DirectiveLoc; 16389 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16390 // We reached the end of a #included module header. Use the #include loc. 16391 assert(File != getSourceManager().getMainFileID() && 16392 "end of submodule in main source file"); 16393 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16394 } else { 16395 // We reached an EOM pragma. Use the pragma location. 16396 DirectiveLoc = EomLoc; 16397 } 16398 BuildModuleInclude(DirectiveLoc, Mod); 16399 16400 // Any further declarations are in whatever module we returned to. 16401 if (getLangOpts().trackLocalOwningModule()) { 16402 // The parser guarantees that this is the same context that we entered 16403 // the module within. 16404 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16405 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16406 if (!getCurrentModule()) 16407 cast<Decl>(DC)->setModuleOwnershipKind( 16408 Decl::ModuleOwnershipKind::Unowned); 16409 } 16410 } 16411 } 16412 16413 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16414 Module *Mod) { 16415 // Bail if we're not allowed to implicitly import a module here. 16416 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16417 VisibleModules.isVisible(Mod)) 16418 return; 16419 16420 // Create the implicit import declaration. 16421 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16422 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16423 Loc, Mod, Loc); 16424 TU->addDecl(ImportD); 16425 Consumer.HandleImplicitImportDecl(ImportD); 16426 16427 // Make the module visible. 16428 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16429 VisibleModules.setVisible(Mod, Loc); 16430 } 16431 16432 /// We have parsed the start of an export declaration, including the '{' 16433 /// (if present). 16434 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16435 SourceLocation LBraceLoc) { 16436 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16437 16438 // C++ Modules TS draft: 16439 // An export-declaration shall appear in the purview of a module other than 16440 // the global module. 16441 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 16442 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16443 16444 // An export-declaration [...] shall not contain more than one 16445 // export keyword. 16446 // 16447 // The intent here is that an export-declaration cannot appear within another 16448 // export-declaration. 16449 if (D->isExported()) 16450 Diag(ExportLoc, diag::err_export_within_export); 16451 16452 CurContext->addDecl(D); 16453 PushDeclContext(S, D); 16454 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16455 return D; 16456 } 16457 16458 /// Complete the definition of an export declaration. 16459 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16460 auto *ED = cast<ExportDecl>(D); 16461 if (RBraceLoc.isValid()) 16462 ED->setRBraceLoc(RBraceLoc); 16463 16464 // FIXME: Diagnose export of internal-linkage declaration (including 16465 // anonymous namespace). 16466 16467 PopDeclContext(); 16468 return D; 16469 } 16470 16471 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16472 IdentifierInfo* AliasName, 16473 SourceLocation PragmaLoc, 16474 SourceLocation NameLoc, 16475 SourceLocation AliasNameLoc) { 16476 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16477 LookupOrdinaryName); 16478 AsmLabelAttr *Attr = 16479 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16480 16481 // If a declaration that: 16482 // 1) declares a function or a variable 16483 // 2) has external linkage 16484 // already exists, add a label attribute to it. 16485 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16486 if (isDeclExternC(PrevDecl)) 16487 PrevDecl->addAttr(Attr); 16488 else 16489 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16490 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16491 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16492 } else 16493 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16494 } 16495 16496 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16497 SourceLocation PragmaLoc, 16498 SourceLocation NameLoc) { 16499 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16500 16501 if (PrevDecl) { 16502 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16503 } else { 16504 (void)WeakUndeclaredIdentifiers.insert( 16505 std::pair<IdentifierInfo*,WeakInfo> 16506 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16507 } 16508 } 16509 16510 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16511 IdentifierInfo* AliasName, 16512 SourceLocation PragmaLoc, 16513 SourceLocation NameLoc, 16514 SourceLocation AliasNameLoc) { 16515 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16516 LookupOrdinaryName); 16517 WeakInfo W = WeakInfo(Name, NameLoc); 16518 16519 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16520 if (!PrevDecl->hasAttr<AliasAttr>()) 16521 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16522 DeclApplyPragmaWeak(TUScope, ND, W); 16523 } else { 16524 (void)WeakUndeclaredIdentifiers.insert( 16525 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16526 } 16527 } 16528 16529 Decl *Sema::getObjCDeclContext() const { 16530 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16531 } 16532