1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw__Float16: 136 case tok::kw___float128: 137 case tok::kw_wchar_t: 138 case tok::kw_bool: 139 case tok::kw___underlying_type: 140 case tok::kw___auto_type: 141 return true; 142 143 case tok::annot_typename: 144 case tok::kw_char16_t: 145 case tok::kw_char32_t: 146 case tok::kw_typeof: 147 case tok::annot_decltype: 148 case tok::kw_decltype: 149 return getLangOpts().CPlusPlus; 150 151 case tok::kw_char8_t: 152 return getLangOpts().Char8; 153 154 default: 155 break; 156 } 157 158 return false; 159 } 160 161 namespace { 162 enum class UnqualifiedTypeNameLookupResult { 163 NotFound, 164 FoundNonType, 165 FoundType 166 }; 167 } // end anonymous namespace 168 169 /// Tries to perform unqualified lookup of the type decls in bases for 170 /// dependent class. 171 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 172 /// type decl, \a FoundType if only type decls are found. 173 static UnqualifiedTypeNameLookupResult 174 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 175 SourceLocation NameLoc, 176 const CXXRecordDecl *RD) { 177 if (!RD->hasDefinition()) 178 return UnqualifiedTypeNameLookupResult::NotFound; 179 // Look for type decls in base classes. 180 UnqualifiedTypeNameLookupResult FoundTypeDecl = 181 UnqualifiedTypeNameLookupResult::NotFound; 182 for (const auto &Base : RD->bases()) { 183 const CXXRecordDecl *BaseRD = nullptr; 184 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 185 BaseRD = BaseTT->getAsCXXRecordDecl(); 186 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 187 // Look for type decls in dependent base classes that have known primary 188 // templates. 189 if (!TST || !TST->isDependentType()) 190 continue; 191 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 192 if (!TD) 193 continue; 194 if (auto *BasePrimaryTemplate = 195 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 196 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 197 BaseRD = BasePrimaryTemplate; 198 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 199 if (const ClassTemplatePartialSpecializationDecl *PS = 200 CTD->findPartialSpecialization(Base.getType())) 201 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 202 BaseRD = PS; 203 } 204 } 205 } 206 if (BaseRD) { 207 for (NamedDecl *ND : BaseRD->lookup(&II)) { 208 if (!isa<TypeDecl>(ND)) 209 return UnqualifiedTypeNameLookupResult::FoundNonType; 210 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 211 } 212 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 213 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 214 case UnqualifiedTypeNameLookupResult::FoundNonType: 215 return UnqualifiedTypeNameLookupResult::FoundNonType; 216 case UnqualifiedTypeNameLookupResult::FoundType: 217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 218 break; 219 case UnqualifiedTypeNameLookupResult::NotFound: 220 break; 221 } 222 } 223 } 224 } 225 226 return FoundTypeDecl; 227 } 228 229 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 230 const IdentifierInfo &II, 231 SourceLocation NameLoc) { 232 // Lookup in the parent class template context, if any. 233 const CXXRecordDecl *RD = nullptr; 234 UnqualifiedTypeNameLookupResult FoundTypeDecl = 235 UnqualifiedTypeNameLookupResult::NotFound; 236 for (DeclContext *DC = S.CurContext; 237 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 238 DC = DC->getParent()) { 239 // Look for type decls in dependent base classes that have known primary 240 // templates. 241 RD = dyn_cast<CXXRecordDecl>(DC); 242 if (RD && RD->getDescribedClassTemplate()) 243 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 244 } 245 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 246 return nullptr; 247 248 // We found some types in dependent base classes. Recover as if the user 249 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 250 // lookup during template instantiation. 251 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 252 253 ASTContext &Context = S.Context; 254 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 255 cast<Type>(Context.getRecordType(RD))); 256 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 257 258 CXXScopeSpec SS; 259 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 260 261 TypeLocBuilder Builder; 262 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 263 DepTL.setNameLoc(NameLoc); 264 DepTL.setElaboratedKeywordLoc(SourceLocation()); 265 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 266 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 267 } 268 269 /// If the identifier refers to a type name within this scope, 270 /// return the declaration of that type. 271 /// 272 /// This routine performs ordinary name lookup of the identifier II 273 /// within the given scope, with optional C++ scope specifier SS, to 274 /// determine whether the name refers to a type. If so, returns an 275 /// opaque pointer (actually a QualType) corresponding to that 276 /// type. Otherwise, returns NULL. 277 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 278 Scope *S, CXXScopeSpec *SS, 279 bool isClassName, bool HasTrailingDot, 280 ParsedType ObjectTypePtr, 281 bool IsCtorOrDtorName, 282 bool WantNontrivialTypeSourceInfo, 283 bool IsClassTemplateDeductionContext, 284 IdentifierInfo **CorrectedII) { 285 // FIXME: Consider allowing this outside C++1z mode as an extension. 286 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 287 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 288 !isClassName && !HasTrailingDot; 289 290 // Determine where we will perform name lookup. 291 DeclContext *LookupCtx = nullptr; 292 if (ObjectTypePtr) { 293 QualType ObjectType = ObjectTypePtr.get(); 294 if (ObjectType->isRecordType()) 295 LookupCtx = computeDeclContext(ObjectType); 296 } else if (SS && SS->isNotEmpty()) { 297 LookupCtx = computeDeclContext(*SS, false); 298 299 if (!LookupCtx) { 300 if (isDependentScopeSpecifier(*SS)) { 301 // C++ [temp.res]p3: 302 // A qualified-id that refers to a type and in which the 303 // nested-name-specifier depends on a template-parameter (14.6.2) 304 // shall be prefixed by the keyword typename to indicate that the 305 // qualified-id denotes a type, forming an 306 // elaborated-type-specifier (7.1.5.3). 307 // 308 // We therefore do not perform any name lookup if the result would 309 // refer to a member of an unknown specialization. 310 if (!isClassName && !IsCtorOrDtorName) 311 return nullptr; 312 313 // We know from the grammar that this name refers to a type, 314 // so build a dependent node to describe the type. 315 if (WantNontrivialTypeSourceInfo) 316 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 317 318 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 319 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 320 II, NameLoc); 321 return ParsedType::make(T); 322 } 323 324 return nullptr; 325 } 326 327 if (!LookupCtx->isDependentContext() && 328 RequireCompleteDeclContext(*SS, LookupCtx)) 329 return nullptr; 330 } 331 332 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 333 // lookup for class-names. 334 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 335 LookupOrdinaryName; 336 LookupResult Result(*this, &II, NameLoc, Kind); 337 if (LookupCtx) { 338 // Perform "qualified" name lookup into the declaration context we 339 // computed, which is either the type of the base of a member access 340 // expression or the declaration context associated with a prior 341 // nested-name-specifier. 342 LookupQualifiedName(Result, LookupCtx); 343 344 if (ObjectTypePtr && Result.empty()) { 345 // C++ [basic.lookup.classref]p3: 346 // If the unqualified-id is ~type-name, the type-name is looked up 347 // in the context of the entire postfix-expression. If the type T of 348 // the object expression is of a class type C, the type-name is also 349 // looked up in the scope of class C. At least one of the lookups shall 350 // find a name that refers to (possibly cv-qualified) T. 351 LookupName(Result, S); 352 } 353 } else { 354 // Perform unqualified name lookup. 355 LookupName(Result, S); 356 357 // For unqualified lookup in a class template in MSVC mode, look into 358 // dependent base classes where the primary class template is known. 359 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 360 if (ParsedType TypeInBase = 361 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 362 return TypeInBase; 363 } 364 } 365 366 NamedDecl *IIDecl = nullptr; 367 switch (Result.getResultKind()) { 368 case LookupResult::NotFound: 369 case LookupResult::NotFoundInCurrentInstantiation: 370 if (CorrectedII) { 371 TypoCorrection Correction = 372 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 373 llvm::make_unique<TypeNameValidatorCCC>( 374 true, isClassName, AllowDeducedTemplate), 375 CTK_ErrorRecovery); 376 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 377 TemplateTy Template; 378 bool MemberOfUnknownSpecialization; 379 UnqualifiedId TemplateName; 380 TemplateName.setIdentifier(NewII, NameLoc); 381 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 382 CXXScopeSpec NewSS, *NewSSPtr = SS; 383 if (SS && NNS) { 384 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 385 NewSSPtr = &NewSS; 386 } 387 if (Correction && (NNS || NewII != &II) && 388 // Ignore a correction to a template type as the to-be-corrected 389 // identifier is not a template (typo correction for template names 390 // is handled elsewhere). 391 !(getLangOpts().CPlusPlus && NewSSPtr && 392 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 393 Template, MemberOfUnknownSpecialization))) { 394 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 395 isClassName, HasTrailingDot, ObjectTypePtr, 396 IsCtorOrDtorName, 397 WantNontrivialTypeSourceInfo, 398 IsClassTemplateDeductionContext); 399 if (Ty) { 400 diagnoseTypo(Correction, 401 PDiag(diag::err_unknown_type_or_class_name_suggest) 402 << Result.getLookupName() << isClassName); 403 if (SS && NNS) 404 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 405 *CorrectedII = NewII; 406 return Ty; 407 } 408 } 409 } 410 // If typo correction failed or was not performed, fall through 411 LLVM_FALLTHROUGH; 412 case LookupResult::FoundOverloaded: 413 case LookupResult::FoundUnresolvedValue: 414 Result.suppressDiagnostics(); 415 return nullptr; 416 417 case LookupResult::Ambiguous: 418 // Recover from type-hiding ambiguities by hiding the type. We'll 419 // do the lookup again when looking for an object, and we can 420 // diagnose the error then. If we don't do this, then the error 421 // about hiding the type will be immediately followed by an error 422 // that only makes sense if the identifier was treated like a type. 423 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 424 Result.suppressDiagnostics(); 425 return nullptr; 426 } 427 428 // Look to see if we have a type anywhere in the list of results. 429 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 430 Res != ResEnd; ++Res) { 431 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 432 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 433 if (!IIDecl || 434 (*Res)->getLocation().getRawEncoding() < 435 IIDecl->getLocation().getRawEncoding()) 436 IIDecl = *Res; 437 } 438 } 439 440 if (!IIDecl) { 441 // None of the entities we found is a type, so there is no way 442 // to even assume that the result is a type. In this case, don't 443 // complain about the ambiguity. The parser will either try to 444 // perform this lookup again (e.g., as an object name), which 445 // will produce the ambiguity, or will complain that it expected 446 // a type name. 447 Result.suppressDiagnostics(); 448 return nullptr; 449 } 450 451 // We found a type within the ambiguous lookup; diagnose the 452 // ambiguity and then return that type. This might be the right 453 // answer, or it might not be, but it suppresses any attempt to 454 // perform the name lookup again. 455 break; 456 457 case LookupResult::Found: 458 IIDecl = Result.getFoundDecl(); 459 break; 460 } 461 462 assert(IIDecl && "Didn't find decl"); 463 464 QualType T; 465 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 466 // C++ [class.qual]p2: A lookup that would find the injected-class-name 467 // instead names the constructors of the class, except when naming a class. 468 // This is ill-formed when we're not actually forming a ctor or dtor name. 469 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 470 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 471 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 472 FoundRD->isInjectedClassName() && 473 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 474 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 475 << &II << /*Type*/1; 476 477 DiagnoseUseOfDecl(IIDecl, NameLoc); 478 479 T = Context.getTypeDeclType(TD); 480 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 481 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 482 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 483 if (!HasTrailingDot) 484 T = Context.getObjCInterfaceType(IDecl); 485 } else if (AllowDeducedTemplate) { 486 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 487 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 488 QualType(), false); 489 } 490 491 if (T.isNull()) { 492 // If it's not plausibly a type, suppress diagnostics. 493 Result.suppressDiagnostics(); 494 return nullptr; 495 } 496 497 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 498 // constructor or destructor name (in such a case, the scope specifier 499 // will be attached to the enclosing Expr or Decl node). 500 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 501 !isa<ObjCInterfaceDecl>(IIDecl)) { 502 if (WantNontrivialTypeSourceInfo) { 503 // Construct a type with type-source information. 504 TypeLocBuilder Builder; 505 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 506 507 T = getElaboratedType(ETK_None, *SS, T); 508 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 509 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 510 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 511 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 512 } else { 513 T = getElaboratedType(ETK_None, *SS, T); 514 } 515 } 516 517 return ParsedType::make(T); 518 } 519 520 // Builds a fake NNS for the given decl context. 521 static NestedNameSpecifier * 522 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 523 for (;; DC = DC->getLookupParent()) { 524 DC = DC->getPrimaryContext(); 525 auto *ND = dyn_cast<NamespaceDecl>(DC); 526 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 527 return NestedNameSpecifier::Create(Context, nullptr, ND); 528 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 529 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 530 RD->getTypeForDecl()); 531 else if (isa<TranslationUnitDecl>(DC)) 532 return NestedNameSpecifier::GlobalSpecifier(Context); 533 } 534 llvm_unreachable("something isn't in TU scope?"); 535 } 536 537 /// Find the parent class with dependent bases of the innermost enclosing method 538 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 539 /// up allowing unqualified dependent type names at class-level, which MSVC 540 /// correctly rejects. 541 static const CXXRecordDecl * 542 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 543 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 544 DC = DC->getPrimaryContext(); 545 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 546 if (MD->getParent()->hasAnyDependentBases()) 547 return MD->getParent(); 548 } 549 return nullptr; 550 } 551 552 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 553 SourceLocation NameLoc, 554 bool IsTemplateTypeArg) { 555 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 556 557 NestedNameSpecifier *NNS = nullptr; 558 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 559 // If we weren't able to parse a default template argument, delay lookup 560 // until instantiation time by making a non-dependent DependentTypeName. We 561 // pretend we saw a NestedNameSpecifier referring to the current scope, and 562 // lookup is retried. 563 // FIXME: This hurts our diagnostic quality, since we get errors like "no 564 // type named 'Foo' in 'current_namespace'" when the user didn't write any 565 // name specifiers. 566 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 567 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 568 } else if (const CXXRecordDecl *RD = 569 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 570 // Build a DependentNameType that will perform lookup into RD at 571 // instantiation time. 572 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 573 RD->getTypeForDecl()); 574 575 // Diagnose that this identifier was undeclared, and retry the lookup during 576 // template instantiation. 577 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 578 << RD; 579 } else { 580 // This is not a situation that we should recover from. 581 return ParsedType(); 582 } 583 584 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 585 586 // Build type location information. We synthesized the qualifier, so we have 587 // to build a fake NestedNameSpecifierLoc. 588 NestedNameSpecifierLocBuilder NNSLocBuilder; 589 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 590 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 591 592 TypeLocBuilder Builder; 593 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 594 DepTL.setNameLoc(NameLoc); 595 DepTL.setElaboratedKeywordLoc(SourceLocation()); 596 DepTL.setQualifierLoc(QualifierLoc); 597 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 598 } 599 600 /// isTagName() - This method is called *for error recovery purposes only* 601 /// to determine if the specified name is a valid tag name ("struct foo"). If 602 /// so, this returns the TST for the tag corresponding to it (TST_enum, 603 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 604 /// cases in C where the user forgot to specify the tag. 605 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 606 // Do a tag name lookup in this scope. 607 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 608 LookupName(R, S, false); 609 R.suppressDiagnostics(); 610 if (R.getResultKind() == LookupResult::Found) 611 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 612 switch (TD->getTagKind()) { 613 case TTK_Struct: return DeclSpec::TST_struct; 614 case TTK_Interface: return DeclSpec::TST_interface; 615 case TTK_Union: return DeclSpec::TST_union; 616 case TTK_Class: return DeclSpec::TST_class; 617 case TTK_Enum: return DeclSpec::TST_enum; 618 } 619 } 620 621 return DeclSpec::TST_unspecified; 622 } 623 624 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 625 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 626 /// then downgrade the missing typename error to a warning. 627 /// This is needed for MSVC compatibility; Example: 628 /// @code 629 /// template<class T> class A { 630 /// public: 631 /// typedef int TYPE; 632 /// }; 633 /// template<class T> class B : public A<T> { 634 /// public: 635 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 636 /// }; 637 /// @endcode 638 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 639 if (CurContext->isRecord()) { 640 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 641 return true; 642 643 const Type *Ty = SS->getScopeRep()->getAsType(); 644 645 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 646 for (const auto &Base : RD->bases()) 647 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 648 return true; 649 return S->isFunctionPrototypeScope(); 650 } 651 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 652 } 653 654 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 655 SourceLocation IILoc, 656 Scope *S, 657 CXXScopeSpec *SS, 658 ParsedType &SuggestedType, 659 bool IsTemplateName) { 660 // Don't report typename errors for editor placeholders. 661 if (II->isEditorPlaceholder()) 662 return; 663 // We don't have anything to suggest (yet). 664 SuggestedType = nullptr; 665 666 // There may have been a typo in the name of the type. Look up typo 667 // results, in case we have something that we can suggest. 668 if (TypoCorrection Corrected = 669 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 670 llvm::make_unique<TypeNameValidatorCCC>( 671 false, false, IsTemplateName, !IsTemplateName), 672 CTK_ErrorRecovery)) { 673 // FIXME: Support error recovery for the template-name case. 674 bool CanRecover = !IsTemplateName; 675 if (Corrected.isKeyword()) { 676 // We corrected to a keyword. 677 diagnoseTypo(Corrected, 678 PDiag(IsTemplateName ? diag::err_no_template_suggest 679 : diag::err_unknown_typename_suggest) 680 << II); 681 II = Corrected.getCorrectionAsIdentifierInfo(); 682 } else { 683 // We found a similarly-named type or interface; suggest that. 684 if (!SS || !SS->isSet()) { 685 diagnoseTypo(Corrected, 686 PDiag(IsTemplateName ? diag::err_no_template_suggest 687 : diag::err_unknown_typename_suggest) 688 << II, CanRecover); 689 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 690 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 691 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 692 II->getName().equals(CorrectedStr); 693 diagnoseTypo(Corrected, 694 PDiag(IsTemplateName 695 ? diag::err_no_member_template_suggest 696 : diag::err_unknown_nested_typename_suggest) 697 << II << DC << DroppedSpecifier << SS->getRange(), 698 CanRecover); 699 } else { 700 llvm_unreachable("could not have corrected a typo here"); 701 } 702 703 if (!CanRecover) 704 return; 705 706 CXXScopeSpec tmpSS; 707 if (Corrected.getCorrectionSpecifier()) 708 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 709 SourceRange(IILoc)); 710 // FIXME: Support class template argument deduction here. 711 SuggestedType = 712 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 713 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 714 /*IsCtorOrDtorName=*/false, 715 /*NonTrivialTypeSourceInfo=*/true); 716 } 717 return; 718 } 719 720 if (getLangOpts().CPlusPlus && !IsTemplateName) { 721 // See if II is a class template that the user forgot to pass arguments to. 722 UnqualifiedId Name; 723 Name.setIdentifier(II, IILoc); 724 CXXScopeSpec EmptySS; 725 TemplateTy TemplateResult; 726 bool MemberOfUnknownSpecialization; 727 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 728 Name, nullptr, true, TemplateResult, 729 MemberOfUnknownSpecialization) == TNK_Type_template) { 730 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 731 return; 732 } 733 } 734 735 // FIXME: Should we move the logic that tries to recover from a missing tag 736 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 737 738 if (!SS || (!SS->isSet() && !SS->isInvalid())) 739 Diag(IILoc, IsTemplateName ? diag::err_no_template 740 : diag::err_unknown_typename) 741 << II; 742 else if (DeclContext *DC = computeDeclContext(*SS, false)) 743 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 744 : diag::err_typename_nested_not_found) 745 << II << DC << SS->getRange(); 746 else if (isDependentScopeSpecifier(*SS)) { 747 unsigned DiagID = diag::err_typename_missing; 748 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 749 DiagID = diag::ext_typename_missing; 750 751 Diag(SS->getRange().getBegin(), DiagID) 752 << SS->getScopeRep() << II->getName() 753 << SourceRange(SS->getRange().getBegin(), IILoc) 754 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 755 SuggestedType = ActOnTypenameType(S, SourceLocation(), 756 *SS, *II, IILoc).get(); 757 } else { 758 assert(SS && SS->isInvalid() && 759 "Invalid scope specifier has already been diagnosed"); 760 } 761 } 762 763 /// Determine whether the given result set contains either a type name 764 /// or 765 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 766 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 767 NextToken.is(tok::less); 768 769 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 770 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 771 return true; 772 773 if (CheckTemplate && isa<TemplateDecl>(*I)) 774 return true; 775 } 776 777 return false; 778 } 779 780 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 781 Scope *S, CXXScopeSpec &SS, 782 IdentifierInfo *&Name, 783 SourceLocation NameLoc) { 784 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 785 SemaRef.LookupParsedName(R, S, &SS); 786 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 787 StringRef FixItTagName; 788 switch (Tag->getTagKind()) { 789 case TTK_Class: 790 FixItTagName = "class "; 791 break; 792 793 case TTK_Enum: 794 FixItTagName = "enum "; 795 break; 796 797 case TTK_Struct: 798 FixItTagName = "struct "; 799 break; 800 801 case TTK_Interface: 802 FixItTagName = "__interface "; 803 break; 804 805 case TTK_Union: 806 FixItTagName = "union "; 807 break; 808 } 809 810 StringRef TagName = FixItTagName.drop_back(); 811 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 812 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 813 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 814 815 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 816 I != IEnd; ++I) 817 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 818 << Name << TagName; 819 820 // Replace lookup results with just the tag decl. 821 Result.clear(Sema::LookupTagName); 822 SemaRef.LookupParsedName(Result, S, &SS); 823 return true; 824 } 825 826 return false; 827 } 828 829 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 830 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 831 QualType T, SourceLocation NameLoc) { 832 ASTContext &Context = S.Context; 833 834 TypeLocBuilder Builder; 835 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 836 837 T = S.getElaboratedType(ETK_None, SS, T); 838 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 839 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 840 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 841 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 842 } 843 844 Sema::NameClassification 845 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 846 SourceLocation NameLoc, const Token &NextToken, 847 bool IsAddressOfOperand, 848 std::unique_ptr<CorrectionCandidateCallback> CCC) { 849 DeclarationNameInfo NameInfo(Name, NameLoc); 850 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 851 852 if (NextToken.is(tok::coloncolon)) { 853 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 854 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 855 } else if (getLangOpts().CPlusPlus && SS.isSet() && 856 isCurrentClassName(*Name, S, &SS)) { 857 // Per [class.qual]p2, this names the constructors of SS, not the 858 // injected-class-name. We don't have a classification for that. 859 // There's not much point caching this result, since the parser 860 // will reject it later. 861 return NameClassification::Unknown(); 862 } 863 864 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 865 LookupParsedName(Result, S, &SS, !CurMethod); 866 867 // For unqualified lookup in a class template in MSVC mode, look into 868 // dependent base classes where the primary class template is known. 869 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 870 if (ParsedType TypeInBase = 871 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 872 return TypeInBase; 873 } 874 875 // Perform lookup for Objective-C instance variables (including automatically 876 // synthesized instance variables), if we're in an Objective-C method. 877 // FIXME: This lookup really, really needs to be folded in to the normal 878 // unqualified lookup mechanism. 879 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 880 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 881 if (E.get() || E.isInvalid()) 882 return E; 883 } 884 885 bool SecondTry = false; 886 bool IsFilteredTemplateName = false; 887 888 Corrected: 889 switch (Result.getResultKind()) { 890 case LookupResult::NotFound: 891 // If an unqualified-id is followed by a '(', then we have a function 892 // call. 893 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 894 // In C++, this is an ADL-only call. 895 // FIXME: Reference? 896 if (getLangOpts().CPlusPlus) 897 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 898 899 // C90 6.3.2.2: 900 // If the expression that precedes the parenthesized argument list in a 901 // function call consists solely of an identifier, and if no 902 // declaration is visible for this identifier, the identifier is 903 // implicitly declared exactly as if, in the innermost block containing 904 // the function call, the declaration 905 // 906 // extern int identifier (); 907 // 908 // appeared. 909 // 910 // We also allow this in C99 as an extension. 911 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 912 Result.addDecl(D); 913 Result.resolveKind(); 914 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 915 } 916 } 917 918 // In C, we first see whether there is a tag type by the same name, in 919 // which case it's likely that the user just forgot to write "enum", 920 // "struct", or "union". 921 if (!getLangOpts().CPlusPlus && !SecondTry && 922 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 923 break; 924 } 925 926 // Perform typo correction to determine if there is another name that is 927 // close to this name. 928 if (!SecondTry && CCC) { 929 SecondTry = true; 930 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 931 Result.getLookupKind(), S, 932 &SS, std::move(CCC), 933 CTK_ErrorRecovery)) { 934 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 935 unsigned QualifiedDiag = diag::err_no_member_suggest; 936 937 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 938 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 939 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 940 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 941 UnqualifiedDiag = diag::err_no_template_suggest; 942 QualifiedDiag = diag::err_no_member_template_suggest; 943 } else if (UnderlyingFirstDecl && 944 (isa<TypeDecl>(UnderlyingFirstDecl) || 945 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 946 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 947 UnqualifiedDiag = diag::err_unknown_typename_suggest; 948 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 949 } 950 951 if (SS.isEmpty()) { 952 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 953 } else {// FIXME: is this even reachable? Test it. 954 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 955 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 956 Name->getName().equals(CorrectedStr); 957 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 958 << Name << computeDeclContext(SS, false) 959 << DroppedSpecifier << SS.getRange()); 960 } 961 962 // Update the name, so that the caller has the new name. 963 Name = Corrected.getCorrectionAsIdentifierInfo(); 964 965 // Typo correction corrected to a keyword. 966 if (Corrected.isKeyword()) 967 return Name; 968 969 // Also update the LookupResult... 970 // FIXME: This should probably go away at some point 971 Result.clear(); 972 Result.setLookupName(Corrected.getCorrection()); 973 if (FirstDecl) 974 Result.addDecl(FirstDecl); 975 976 // If we found an Objective-C instance variable, let 977 // LookupInObjCMethod build the appropriate expression to 978 // reference the ivar. 979 // FIXME: This is a gross hack. 980 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 981 Result.clear(); 982 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 983 return E; 984 } 985 986 goto Corrected; 987 } 988 } 989 990 // We failed to correct; just fall through and let the parser deal with it. 991 Result.suppressDiagnostics(); 992 return NameClassification::Unknown(); 993 994 case LookupResult::NotFoundInCurrentInstantiation: { 995 // We performed name lookup into the current instantiation, and there were 996 // dependent bases, so we treat this result the same way as any other 997 // dependent nested-name-specifier. 998 999 // C++ [temp.res]p2: 1000 // A name used in a template declaration or definition and that is 1001 // dependent on a template-parameter is assumed not to name a type 1002 // unless the applicable name lookup finds a type name or the name is 1003 // qualified by the keyword typename. 1004 // 1005 // FIXME: If the next token is '<', we might want to ask the parser to 1006 // perform some heroics to see if we actually have a 1007 // template-argument-list, which would indicate a missing 'template' 1008 // keyword here. 1009 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1010 NameInfo, IsAddressOfOperand, 1011 /*TemplateArgs=*/nullptr); 1012 } 1013 1014 case LookupResult::Found: 1015 case LookupResult::FoundOverloaded: 1016 case LookupResult::FoundUnresolvedValue: 1017 break; 1018 1019 case LookupResult::Ambiguous: 1020 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1021 hasAnyAcceptableTemplateNames(Result)) { 1022 // C++ [temp.local]p3: 1023 // A lookup that finds an injected-class-name (10.2) can result in an 1024 // ambiguity in certain cases (for example, if it is found in more than 1025 // one base class). If all of the injected-class-names that are found 1026 // refer to specializations of the same class template, and if the name 1027 // is followed by a template-argument-list, the reference refers to the 1028 // class template itself and not a specialization thereof, and is not 1029 // ambiguous. 1030 // 1031 // This filtering can make an ambiguous result into an unambiguous one, 1032 // so try again after filtering out template names. 1033 FilterAcceptableTemplateNames(Result); 1034 if (!Result.isAmbiguous()) { 1035 IsFilteredTemplateName = true; 1036 break; 1037 } 1038 } 1039 1040 // Diagnose the ambiguity and return an error. 1041 return NameClassification::Error(); 1042 } 1043 1044 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1045 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1046 // C++ [temp.names]p3: 1047 // After name lookup (3.4) finds that a name is a template-name or that 1048 // an operator-function-id or a literal- operator-id refers to a set of 1049 // overloaded functions any member of which is a function template if 1050 // this is followed by a <, the < is always taken as the delimiter of a 1051 // template-argument-list and never as the less-than operator. 1052 if (!IsFilteredTemplateName) 1053 FilterAcceptableTemplateNames(Result); 1054 1055 if (!Result.empty()) { 1056 bool IsFunctionTemplate; 1057 bool IsVarTemplate; 1058 TemplateName Template; 1059 if (Result.end() - Result.begin() > 1) { 1060 IsFunctionTemplate = true; 1061 Template = Context.getOverloadedTemplateName(Result.begin(), 1062 Result.end()); 1063 } else { 1064 TemplateDecl *TD 1065 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1066 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1067 IsVarTemplate = isa<VarTemplateDecl>(TD); 1068 1069 if (SS.isSet() && !SS.isInvalid()) 1070 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1071 /*TemplateKeyword=*/false, 1072 TD); 1073 else 1074 Template = TemplateName(TD); 1075 } 1076 1077 if (IsFunctionTemplate) { 1078 // Function templates always go through overload resolution, at which 1079 // point we'll perform the various checks (e.g., accessibility) we need 1080 // to based on which function we selected. 1081 Result.suppressDiagnostics(); 1082 1083 return NameClassification::FunctionTemplate(Template); 1084 } 1085 1086 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1087 : NameClassification::TypeTemplate(Template); 1088 } 1089 } 1090 1091 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1092 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1093 DiagnoseUseOfDecl(Type, NameLoc); 1094 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1095 QualType T = Context.getTypeDeclType(Type); 1096 if (SS.isNotEmpty()) 1097 return buildNestedType(*this, SS, T, NameLoc); 1098 return ParsedType::make(T); 1099 } 1100 1101 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1102 if (!Class) { 1103 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1104 if (ObjCCompatibleAliasDecl *Alias = 1105 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1106 Class = Alias->getClassInterface(); 1107 } 1108 1109 if (Class) { 1110 DiagnoseUseOfDecl(Class, NameLoc); 1111 1112 if (NextToken.is(tok::period)) { 1113 // Interface. <something> is parsed as a property reference expression. 1114 // Just return "unknown" as a fall-through for now. 1115 Result.suppressDiagnostics(); 1116 return NameClassification::Unknown(); 1117 } 1118 1119 QualType T = Context.getObjCInterfaceType(Class); 1120 return ParsedType::make(T); 1121 } 1122 1123 // We can have a type template here if we're classifying a template argument. 1124 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1125 !isa<VarTemplateDecl>(FirstDecl)) 1126 return NameClassification::TypeTemplate( 1127 TemplateName(cast<TemplateDecl>(FirstDecl))); 1128 1129 // Check for a tag type hidden by a non-type decl in a few cases where it 1130 // seems likely a type is wanted instead of the non-type that was found. 1131 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1132 if ((NextToken.is(tok::identifier) || 1133 (NextIsOp && 1134 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1135 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1136 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1137 DiagnoseUseOfDecl(Type, NameLoc); 1138 QualType T = Context.getTypeDeclType(Type); 1139 if (SS.isNotEmpty()) 1140 return buildNestedType(*this, SS, T, NameLoc); 1141 return ParsedType::make(T); 1142 } 1143 1144 if (FirstDecl->isCXXClassMember()) 1145 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1146 nullptr, S); 1147 1148 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1149 return BuildDeclarationNameExpr(SS, Result, ADL); 1150 } 1151 1152 Sema::TemplateNameKindForDiagnostics 1153 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1154 auto *TD = Name.getAsTemplateDecl(); 1155 if (!TD) 1156 return TemplateNameKindForDiagnostics::DependentTemplate; 1157 if (isa<ClassTemplateDecl>(TD)) 1158 return TemplateNameKindForDiagnostics::ClassTemplate; 1159 if (isa<FunctionTemplateDecl>(TD)) 1160 return TemplateNameKindForDiagnostics::FunctionTemplate; 1161 if (isa<VarTemplateDecl>(TD)) 1162 return TemplateNameKindForDiagnostics::VarTemplate; 1163 if (isa<TypeAliasTemplateDecl>(TD)) 1164 return TemplateNameKindForDiagnostics::AliasTemplate; 1165 if (isa<TemplateTemplateParmDecl>(TD)) 1166 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1167 return TemplateNameKindForDiagnostics::DependentTemplate; 1168 } 1169 1170 // Determines the context to return to after temporarily entering a 1171 // context. This depends in an unnecessarily complicated way on the 1172 // exact ordering of callbacks from the parser. 1173 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1174 1175 // Functions defined inline within classes aren't parsed until we've 1176 // finished parsing the top-level class, so the top-level class is 1177 // the context we'll need to return to. 1178 // A Lambda call operator whose parent is a class must not be treated 1179 // as an inline member function. A Lambda can be used legally 1180 // either as an in-class member initializer or a default argument. These 1181 // are parsed once the class has been marked complete and so the containing 1182 // context would be the nested class (when the lambda is defined in one); 1183 // If the class is not complete, then the lambda is being used in an 1184 // ill-formed fashion (such as to specify the width of a bit-field, or 1185 // in an array-bound) - in which case we still want to return the 1186 // lexically containing DC (which could be a nested class). 1187 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1188 DC = DC->getLexicalParent(); 1189 1190 // A function not defined within a class will always return to its 1191 // lexical context. 1192 if (!isa<CXXRecordDecl>(DC)) 1193 return DC; 1194 1195 // A C++ inline method/friend is parsed *after* the topmost class 1196 // it was declared in is fully parsed ("complete"); the topmost 1197 // class is the context we need to return to. 1198 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1199 DC = RD; 1200 1201 // Return the declaration context of the topmost class the inline method is 1202 // declared in. 1203 return DC; 1204 } 1205 1206 return DC->getLexicalParent(); 1207 } 1208 1209 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1210 assert(getContainingDC(DC) == CurContext && 1211 "The next DeclContext should be lexically contained in the current one."); 1212 CurContext = DC; 1213 S->setEntity(DC); 1214 } 1215 1216 void Sema::PopDeclContext() { 1217 assert(CurContext && "DeclContext imbalance!"); 1218 1219 CurContext = getContainingDC(CurContext); 1220 assert(CurContext && "Popped translation unit!"); 1221 } 1222 1223 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1224 Decl *D) { 1225 // Unlike PushDeclContext, the context to which we return is not necessarily 1226 // the containing DC of TD, because the new context will be some pre-existing 1227 // TagDecl definition instead of a fresh one. 1228 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1229 CurContext = cast<TagDecl>(D)->getDefinition(); 1230 assert(CurContext && "skipping definition of undefined tag"); 1231 // Start lookups from the parent of the current context; we don't want to look 1232 // into the pre-existing complete definition. 1233 S->setEntity(CurContext->getLookupParent()); 1234 return Result; 1235 } 1236 1237 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1238 CurContext = static_cast<decltype(CurContext)>(Context); 1239 } 1240 1241 /// EnterDeclaratorContext - Used when we must lookup names in the context 1242 /// of a declarator's nested name specifier. 1243 /// 1244 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1245 // C++0x [basic.lookup.unqual]p13: 1246 // A name used in the definition of a static data member of class 1247 // X (after the qualified-id of the static member) is looked up as 1248 // if the name was used in a member function of X. 1249 // C++0x [basic.lookup.unqual]p14: 1250 // If a variable member of a namespace is defined outside of the 1251 // scope of its namespace then any name used in the definition of 1252 // the variable member (after the declarator-id) is looked up as 1253 // if the definition of the variable member occurred in its 1254 // namespace. 1255 // Both of these imply that we should push a scope whose context 1256 // is the semantic context of the declaration. We can't use 1257 // PushDeclContext here because that context is not necessarily 1258 // lexically contained in the current context. Fortunately, 1259 // the containing scope should have the appropriate information. 1260 1261 assert(!S->getEntity() && "scope already has entity"); 1262 1263 #ifndef NDEBUG 1264 Scope *Ancestor = S->getParent(); 1265 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1266 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1267 #endif 1268 1269 CurContext = DC; 1270 S->setEntity(DC); 1271 } 1272 1273 void Sema::ExitDeclaratorContext(Scope *S) { 1274 assert(S->getEntity() == CurContext && "Context imbalance!"); 1275 1276 // Switch back to the lexical context. The safety of this is 1277 // enforced by an assert in EnterDeclaratorContext. 1278 Scope *Ancestor = S->getParent(); 1279 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1280 CurContext = Ancestor->getEntity(); 1281 1282 // We don't need to do anything with the scope, which is going to 1283 // disappear. 1284 } 1285 1286 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1287 // We assume that the caller has already called 1288 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1289 FunctionDecl *FD = D->getAsFunction(); 1290 if (!FD) 1291 return; 1292 1293 // Same implementation as PushDeclContext, but enters the context 1294 // from the lexical parent, rather than the top-level class. 1295 assert(CurContext == FD->getLexicalParent() && 1296 "The next DeclContext should be lexically contained in the current one."); 1297 CurContext = FD; 1298 S->setEntity(CurContext); 1299 1300 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1301 ParmVarDecl *Param = FD->getParamDecl(P); 1302 // If the parameter has an identifier, then add it to the scope 1303 if (Param->getIdentifier()) { 1304 S->AddDecl(Param); 1305 IdResolver.AddDecl(Param); 1306 } 1307 } 1308 } 1309 1310 void Sema::ActOnExitFunctionContext() { 1311 // Same implementation as PopDeclContext, but returns to the lexical parent, 1312 // rather than the top-level class. 1313 assert(CurContext && "DeclContext imbalance!"); 1314 CurContext = CurContext->getLexicalParent(); 1315 assert(CurContext && "Popped translation unit!"); 1316 } 1317 1318 /// Determine whether we allow overloading of the function 1319 /// PrevDecl with another declaration. 1320 /// 1321 /// This routine determines whether overloading is possible, not 1322 /// whether some new function is actually an overload. It will return 1323 /// true in C++ (where we can always provide overloads) or, as an 1324 /// extension, in C when the previous function is already an 1325 /// overloaded function declaration or has the "overloadable" 1326 /// attribute. 1327 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1328 ASTContext &Context, 1329 const FunctionDecl *New) { 1330 if (Context.getLangOpts().CPlusPlus) 1331 return true; 1332 1333 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1334 return true; 1335 1336 return Previous.getResultKind() == LookupResult::Found && 1337 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1338 New->hasAttr<OverloadableAttr>()); 1339 } 1340 1341 /// Add this decl to the scope shadowed decl chains. 1342 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1343 // Move up the scope chain until we find the nearest enclosing 1344 // non-transparent context. The declaration will be introduced into this 1345 // scope. 1346 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1347 S = S->getParent(); 1348 1349 // Add scoped declarations into their context, so that they can be 1350 // found later. Declarations without a context won't be inserted 1351 // into any context. 1352 if (AddToContext) 1353 CurContext->addDecl(D); 1354 1355 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1356 // are function-local declarations. 1357 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1358 !D->getDeclContext()->getRedeclContext()->Equals( 1359 D->getLexicalDeclContext()->getRedeclContext()) && 1360 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1361 return; 1362 1363 // Template instantiations should also not be pushed into scope. 1364 if (isa<FunctionDecl>(D) && 1365 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1366 return; 1367 1368 // If this replaces anything in the current scope, 1369 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1370 IEnd = IdResolver.end(); 1371 for (; I != IEnd; ++I) { 1372 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1373 S->RemoveDecl(*I); 1374 IdResolver.RemoveDecl(*I); 1375 1376 // Should only need to replace one decl. 1377 break; 1378 } 1379 } 1380 1381 S->AddDecl(D); 1382 1383 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1384 // Implicitly-generated labels may end up getting generated in an order that 1385 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1386 // the label at the appropriate place in the identifier chain. 1387 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1388 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1389 if (IDC == CurContext) { 1390 if (!S->isDeclScope(*I)) 1391 continue; 1392 } else if (IDC->Encloses(CurContext)) 1393 break; 1394 } 1395 1396 IdResolver.InsertDeclAfter(I, D); 1397 } else { 1398 IdResolver.AddDecl(D); 1399 } 1400 } 1401 1402 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1403 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1404 TUScope->AddDecl(D); 1405 } 1406 1407 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1408 bool AllowInlineNamespace) { 1409 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1410 } 1411 1412 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1413 DeclContext *TargetDC = DC->getPrimaryContext(); 1414 do { 1415 if (DeclContext *ScopeDC = S->getEntity()) 1416 if (ScopeDC->getPrimaryContext() == TargetDC) 1417 return S; 1418 } while ((S = S->getParent())); 1419 1420 return nullptr; 1421 } 1422 1423 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1424 DeclContext*, 1425 ASTContext&); 1426 1427 /// Filters out lookup results that don't fall within the given scope 1428 /// as determined by isDeclInScope. 1429 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1430 bool ConsiderLinkage, 1431 bool AllowInlineNamespace) { 1432 LookupResult::Filter F = R.makeFilter(); 1433 while (F.hasNext()) { 1434 NamedDecl *D = F.next(); 1435 1436 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1437 continue; 1438 1439 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1440 continue; 1441 1442 F.erase(); 1443 } 1444 1445 F.done(); 1446 } 1447 1448 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1449 /// have compatible owning modules. 1450 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1451 // FIXME: The Modules TS is not clear about how friend declarations are 1452 // to be treated. It's not meaningful to have different owning modules for 1453 // linkage in redeclarations of the same entity, so for now allow the 1454 // redeclaration and change the owning modules to match. 1455 if (New->getFriendObjectKind() && 1456 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1457 New->setLocalOwningModule(Old->getOwningModule()); 1458 makeMergedDefinitionVisible(New); 1459 return false; 1460 } 1461 1462 Module *NewM = New->getOwningModule(); 1463 Module *OldM = Old->getOwningModule(); 1464 if (NewM == OldM) 1465 return false; 1466 1467 // FIXME: Check proclaimed-ownership-declarations here too. 1468 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit; 1469 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit; 1470 if (NewIsModuleInterface || OldIsModuleInterface) { 1471 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1472 // if a declaration of D [...] appears in the purview of a module, all 1473 // other such declarations shall appear in the purview of the same module 1474 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1475 << New 1476 << NewIsModuleInterface 1477 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1478 << OldIsModuleInterface 1479 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1480 Diag(Old->getLocation(), diag::note_previous_declaration); 1481 New->setInvalidDecl(); 1482 return true; 1483 } 1484 1485 return false; 1486 } 1487 1488 static bool isUsingDecl(NamedDecl *D) { 1489 return isa<UsingShadowDecl>(D) || 1490 isa<UnresolvedUsingTypenameDecl>(D) || 1491 isa<UnresolvedUsingValueDecl>(D); 1492 } 1493 1494 /// Removes using shadow declarations from the lookup results. 1495 static void RemoveUsingDecls(LookupResult &R) { 1496 LookupResult::Filter F = R.makeFilter(); 1497 while (F.hasNext()) 1498 if (isUsingDecl(F.next())) 1499 F.erase(); 1500 1501 F.done(); 1502 } 1503 1504 /// Check for this common pattern: 1505 /// @code 1506 /// class S { 1507 /// S(const S&); // DO NOT IMPLEMENT 1508 /// void operator=(const S&); // DO NOT IMPLEMENT 1509 /// }; 1510 /// @endcode 1511 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1512 // FIXME: Should check for private access too but access is set after we get 1513 // the decl here. 1514 if (D->doesThisDeclarationHaveABody()) 1515 return false; 1516 1517 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1518 return CD->isCopyConstructor(); 1519 return D->isCopyAssignmentOperator(); 1520 } 1521 1522 // We need this to handle 1523 // 1524 // typedef struct { 1525 // void *foo() { return 0; } 1526 // } A; 1527 // 1528 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1529 // for example. If 'A', foo will have external linkage. If we have '*A', 1530 // foo will have no linkage. Since we can't know until we get to the end 1531 // of the typedef, this function finds out if D might have non-external linkage. 1532 // Callers should verify at the end of the TU if it D has external linkage or 1533 // not. 1534 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1535 const DeclContext *DC = D->getDeclContext(); 1536 while (!DC->isTranslationUnit()) { 1537 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1538 if (!RD->hasNameForLinkage()) 1539 return true; 1540 } 1541 DC = DC->getParent(); 1542 } 1543 1544 return !D->isExternallyVisible(); 1545 } 1546 1547 // FIXME: This needs to be refactored; some other isInMainFile users want 1548 // these semantics. 1549 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1550 if (S.TUKind != TU_Complete) 1551 return false; 1552 return S.SourceMgr.isInMainFile(Loc); 1553 } 1554 1555 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1556 assert(D); 1557 1558 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1559 return false; 1560 1561 // Ignore all entities declared within templates, and out-of-line definitions 1562 // of members of class templates. 1563 if (D->getDeclContext()->isDependentContext() || 1564 D->getLexicalDeclContext()->isDependentContext()) 1565 return false; 1566 1567 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1568 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1569 return false; 1570 // A non-out-of-line declaration of a member specialization was implicitly 1571 // instantiated; it's the out-of-line declaration that we're interested in. 1572 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1573 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1574 return false; 1575 1576 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1577 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1578 return false; 1579 } else { 1580 // 'static inline' functions are defined in headers; don't warn. 1581 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1582 return false; 1583 } 1584 1585 if (FD->doesThisDeclarationHaveABody() && 1586 Context.DeclMustBeEmitted(FD)) 1587 return false; 1588 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1589 // Constants and utility variables are defined in headers with internal 1590 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1591 // like "inline".) 1592 if (!isMainFileLoc(*this, VD->getLocation())) 1593 return false; 1594 1595 if (Context.DeclMustBeEmitted(VD)) 1596 return false; 1597 1598 if (VD->isStaticDataMember() && 1599 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1600 return false; 1601 if (VD->isStaticDataMember() && 1602 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1603 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1604 return false; 1605 1606 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1607 return false; 1608 } else { 1609 return false; 1610 } 1611 1612 // Only warn for unused decls internal to the translation unit. 1613 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1614 // for inline functions defined in the main source file, for instance. 1615 return mightHaveNonExternalLinkage(D); 1616 } 1617 1618 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1619 if (!D) 1620 return; 1621 1622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1623 const FunctionDecl *First = FD->getFirstDecl(); 1624 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1625 return; // First should already be in the vector. 1626 } 1627 1628 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1629 const VarDecl *First = VD->getFirstDecl(); 1630 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1631 return; // First should already be in the vector. 1632 } 1633 1634 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1635 UnusedFileScopedDecls.push_back(D); 1636 } 1637 1638 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1639 if (D->isInvalidDecl()) 1640 return false; 1641 1642 bool Referenced = false; 1643 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1644 // For a decomposition declaration, warn if none of the bindings are 1645 // referenced, instead of if the variable itself is referenced (which 1646 // it is, by the bindings' expressions). 1647 for (auto *BD : DD->bindings()) { 1648 if (BD->isReferenced()) { 1649 Referenced = true; 1650 break; 1651 } 1652 } 1653 } else if (!D->getDeclName()) { 1654 return false; 1655 } else if (D->isReferenced() || D->isUsed()) { 1656 Referenced = true; 1657 } 1658 1659 if (Referenced || D->hasAttr<UnusedAttr>() || 1660 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1661 return false; 1662 1663 if (isa<LabelDecl>(D)) 1664 return true; 1665 1666 // Except for labels, we only care about unused decls that are local to 1667 // functions. 1668 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1669 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1670 // For dependent types, the diagnostic is deferred. 1671 WithinFunction = 1672 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1673 if (!WithinFunction) 1674 return false; 1675 1676 if (isa<TypedefNameDecl>(D)) 1677 return true; 1678 1679 // White-list anything that isn't a local variable. 1680 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1681 return false; 1682 1683 // Types of valid local variables should be complete, so this should succeed. 1684 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1685 1686 // White-list anything with an __attribute__((unused)) type. 1687 const auto *Ty = VD->getType().getTypePtr(); 1688 1689 // Only look at the outermost level of typedef. 1690 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1691 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1692 return false; 1693 } 1694 1695 // If we failed to complete the type for some reason, or if the type is 1696 // dependent, don't diagnose the variable. 1697 if (Ty->isIncompleteType() || Ty->isDependentType()) 1698 return false; 1699 1700 // Look at the element type to ensure that the warning behaviour is 1701 // consistent for both scalars and arrays. 1702 Ty = Ty->getBaseElementTypeUnsafe(); 1703 1704 if (const TagType *TT = Ty->getAs<TagType>()) { 1705 const TagDecl *Tag = TT->getDecl(); 1706 if (Tag->hasAttr<UnusedAttr>()) 1707 return false; 1708 1709 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1710 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1711 return false; 1712 1713 if (const Expr *Init = VD->getInit()) { 1714 if (const ExprWithCleanups *Cleanups = 1715 dyn_cast<ExprWithCleanups>(Init)) 1716 Init = Cleanups->getSubExpr(); 1717 const CXXConstructExpr *Construct = 1718 dyn_cast<CXXConstructExpr>(Init); 1719 if (Construct && !Construct->isElidable()) { 1720 CXXConstructorDecl *CD = Construct->getConstructor(); 1721 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1722 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1723 return false; 1724 } 1725 } 1726 } 1727 } 1728 1729 // TODO: __attribute__((unused)) templates? 1730 } 1731 1732 return true; 1733 } 1734 1735 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1736 FixItHint &Hint) { 1737 if (isa<LabelDecl>(D)) { 1738 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1739 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1740 if (AfterColon.isInvalid()) 1741 return; 1742 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1743 getCharRange(D->getLocStart(), AfterColon)); 1744 } 1745 } 1746 1747 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1748 if (D->getTypeForDecl()->isDependentType()) 1749 return; 1750 1751 for (auto *TmpD : D->decls()) { 1752 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1753 DiagnoseUnusedDecl(T); 1754 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1755 DiagnoseUnusedNestedTypedefs(R); 1756 } 1757 } 1758 1759 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1760 /// unless they are marked attr(unused). 1761 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1762 if (!ShouldDiagnoseUnusedDecl(D)) 1763 return; 1764 1765 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1766 // typedefs can be referenced later on, so the diagnostics are emitted 1767 // at end-of-translation-unit. 1768 UnusedLocalTypedefNameCandidates.insert(TD); 1769 return; 1770 } 1771 1772 FixItHint Hint; 1773 GenerateFixForUnusedDecl(D, Context, Hint); 1774 1775 unsigned DiagID; 1776 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1777 DiagID = diag::warn_unused_exception_param; 1778 else if (isa<LabelDecl>(D)) 1779 DiagID = diag::warn_unused_label; 1780 else 1781 DiagID = diag::warn_unused_variable; 1782 1783 Diag(D->getLocation(), DiagID) << D << Hint; 1784 } 1785 1786 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1787 // Verify that we have no forward references left. If so, there was a goto 1788 // or address of a label taken, but no definition of it. Label fwd 1789 // definitions are indicated with a null substmt which is also not a resolved 1790 // MS inline assembly label name. 1791 bool Diagnose = false; 1792 if (L->isMSAsmLabel()) 1793 Diagnose = !L->isResolvedMSAsmLabel(); 1794 else 1795 Diagnose = L->getStmt() == nullptr; 1796 if (Diagnose) 1797 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1798 } 1799 1800 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1801 S->mergeNRVOIntoParent(); 1802 1803 if (S->decl_empty()) return; 1804 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1805 "Scope shouldn't contain decls!"); 1806 1807 for (auto *TmpD : S->decls()) { 1808 assert(TmpD && "This decl didn't get pushed??"); 1809 1810 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1811 NamedDecl *D = cast<NamedDecl>(TmpD); 1812 1813 // Diagnose unused variables in this scope. 1814 if (!S->hasUnrecoverableErrorOccurred()) { 1815 DiagnoseUnusedDecl(D); 1816 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1817 DiagnoseUnusedNestedTypedefs(RD); 1818 } 1819 1820 if (!D->getDeclName()) continue; 1821 1822 // If this was a forward reference to a label, verify it was defined. 1823 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1824 CheckPoppedLabel(LD, *this); 1825 1826 // Remove this name from our lexical scope, and warn on it if we haven't 1827 // already. 1828 IdResolver.RemoveDecl(D); 1829 auto ShadowI = ShadowingDecls.find(D); 1830 if (ShadowI != ShadowingDecls.end()) { 1831 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1832 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1833 << D << FD << FD->getParent(); 1834 Diag(FD->getLocation(), diag::note_previous_declaration); 1835 } 1836 ShadowingDecls.erase(ShadowI); 1837 } 1838 } 1839 } 1840 1841 /// Look for an Objective-C class in the translation unit. 1842 /// 1843 /// \param Id The name of the Objective-C class we're looking for. If 1844 /// typo-correction fixes this name, the Id will be updated 1845 /// to the fixed name. 1846 /// 1847 /// \param IdLoc The location of the name in the translation unit. 1848 /// 1849 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1850 /// if there is no class with the given name. 1851 /// 1852 /// \returns The declaration of the named Objective-C class, or NULL if the 1853 /// class could not be found. 1854 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1855 SourceLocation IdLoc, 1856 bool DoTypoCorrection) { 1857 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1858 // creation from this context. 1859 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1860 1861 if (!IDecl && DoTypoCorrection) { 1862 // Perform typo correction at the given location, but only if we 1863 // find an Objective-C class name. 1864 if (TypoCorrection C = CorrectTypo( 1865 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1866 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1867 CTK_ErrorRecovery)) { 1868 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1869 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1870 Id = IDecl->getIdentifier(); 1871 } 1872 } 1873 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1874 // This routine must always return a class definition, if any. 1875 if (Def && Def->getDefinition()) 1876 Def = Def->getDefinition(); 1877 return Def; 1878 } 1879 1880 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1881 /// from S, where a non-field would be declared. This routine copes 1882 /// with the difference between C and C++ scoping rules in structs and 1883 /// unions. For example, the following code is well-formed in C but 1884 /// ill-formed in C++: 1885 /// @code 1886 /// struct S6 { 1887 /// enum { BAR } e; 1888 /// }; 1889 /// 1890 /// void test_S6() { 1891 /// struct S6 a; 1892 /// a.e = BAR; 1893 /// } 1894 /// @endcode 1895 /// For the declaration of BAR, this routine will return a different 1896 /// scope. The scope S will be the scope of the unnamed enumeration 1897 /// within S6. In C++, this routine will return the scope associated 1898 /// with S6, because the enumeration's scope is a transparent 1899 /// context but structures can contain non-field names. In C, this 1900 /// routine will return the translation unit scope, since the 1901 /// enumeration's scope is a transparent context and structures cannot 1902 /// contain non-field names. 1903 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1904 while (((S->getFlags() & Scope::DeclScope) == 0) || 1905 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1906 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1907 S = S->getParent(); 1908 return S; 1909 } 1910 1911 /// Looks up the declaration of "struct objc_super" and 1912 /// saves it for later use in building builtin declaration of 1913 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1914 /// pre-existing declaration exists no action takes place. 1915 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1916 IdentifierInfo *II) { 1917 if (!II->isStr("objc_msgSendSuper")) 1918 return; 1919 ASTContext &Context = ThisSema.Context; 1920 1921 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1922 SourceLocation(), Sema::LookupTagName); 1923 ThisSema.LookupName(Result, S); 1924 if (Result.getResultKind() == LookupResult::Found) 1925 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1926 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1927 } 1928 1929 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1930 switch (Error) { 1931 case ASTContext::GE_None: 1932 return ""; 1933 case ASTContext::GE_Missing_stdio: 1934 return "stdio.h"; 1935 case ASTContext::GE_Missing_setjmp: 1936 return "setjmp.h"; 1937 case ASTContext::GE_Missing_ucontext: 1938 return "ucontext.h"; 1939 } 1940 llvm_unreachable("unhandled error kind"); 1941 } 1942 1943 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1944 /// file scope. lazily create a decl for it. ForRedeclaration is true 1945 /// if we're creating this built-in in anticipation of redeclaring the 1946 /// built-in. 1947 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1948 Scope *S, bool ForRedeclaration, 1949 SourceLocation Loc) { 1950 LookupPredefedObjCSuperType(*this, S, II); 1951 1952 ASTContext::GetBuiltinTypeError Error; 1953 QualType R = Context.GetBuiltinType(ID, Error); 1954 if (Error) { 1955 if (ForRedeclaration) 1956 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1957 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1958 return nullptr; 1959 } 1960 1961 if (!ForRedeclaration && 1962 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1963 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1964 Diag(Loc, diag::ext_implicit_lib_function_decl) 1965 << Context.BuiltinInfo.getName(ID) << R; 1966 if (Context.BuiltinInfo.getHeaderName(ID) && 1967 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1968 Diag(Loc, diag::note_include_header_or_declare) 1969 << Context.BuiltinInfo.getHeaderName(ID) 1970 << Context.BuiltinInfo.getName(ID); 1971 } 1972 1973 if (R.isNull()) 1974 return nullptr; 1975 1976 DeclContext *Parent = Context.getTranslationUnitDecl(); 1977 if (getLangOpts().CPlusPlus) { 1978 LinkageSpecDecl *CLinkageDecl = 1979 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1980 LinkageSpecDecl::lang_c, false); 1981 CLinkageDecl->setImplicit(); 1982 Parent->addDecl(CLinkageDecl); 1983 Parent = CLinkageDecl; 1984 } 1985 1986 FunctionDecl *New = FunctionDecl::Create(Context, 1987 Parent, 1988 Loc, Loc, II, R, /*TInfo=*/nullptr, 1989 SC_Extern, 1990 false, 1991 R->isFunctionProtoType()); 1992 New->setImplicit(); 1993 1994 // Create Decl objects for each parameter, adding them to the 1995 // FunctionDecl. 1996 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1997 SmallVector<ParmVarDecl*, 16> Params; 1998 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1999 ParmVarDecl *parm = 2000 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2001 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2002 SC_None, nullptr); 2003 parm->setScopeInfo(0, i); 2004 Params.push_back(parm); 2005 } 2006 New->setParams(Params); 2007 } 2008 2009 AddKnownFunctionAttributes(New); 2010 RegisterLocallyScopedExternCDecl(New, S); 2011 2012 // TUScope is the translation-unit scope to insert this function into. 2013 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2014 // relate Scopes to DeclContexts, and probably eliminate CurContext 2015 // entirely, but we're not there yet. 2016 DeclContext *SavedContext = CurContext; 2017 CurContext = Parent; 2018 PushOnScopeChains(New, TUScope); 2019 CurContext = SavedContext; 2020 return New; 2021 } 2022 2023 /// Typedef declarations don't have linkage, but they still denote the same 2024 /// entity if their types are the same. 2025 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2026 /// isSameEntity. 2027 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2028 TypedefNameDecl *Decl, 2029 LookupResult &Previous) { 2030 // This is only interesting when modules are enabled. 2031 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2032 return; 2033 2034 // Empty sets are uninteresting. 2035 if (Previous.empty()) 2036 return; 2037 2038 LookupResult::Filter Filter = Previous.makeFilter(); 2039 while (Filter.hasNext()) { 2040 NamedDecl *Old = Filter.next(); 2041 2042 // Non-hidden declarations are never ignored. 2043 if (S.isVisible(Old)) 2044 continue; 2045 2046 // Declarations of the same entity are not ignored, even if they have 2047 // different linkages. 2048 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2049 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2050 Decl->getUnderlyingType())) 2051 continue; 2052 2053 // If both declarations give a tag declaration a typedef name for linkage 2054 // purposes, then they declare the same entity. 2055 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2056 Decl->getAnonDeclWithTypedefName()) 2057 continue; 2058 } 2059 2060 Filter.erase(); 2061 } 2062 2063 Filter.done(); 2064 } 2065 2066 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2067 QualType OldType; 2068 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2069 OldType = OldTypedef->getUnderlyingType(); 2070 else 2071 OldType = Context.getTypeDeclType(Old); 2072 QualType NewType = New->getUnderlyingType(); 2073 2074 if (NewType->isVariablyModifiedType()) { 2075 // Must not redefine a typedef with a variably-modified type. 2076 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2077 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2078 << Kind << NewType; 2079 if (Old->getLocation().isValid()) 2080 notePreviousDefinition(Old, New->getLocation()); 2081 New->setInvalidDecl(); 2082 return true; 2083 } 2084 2085 if (OldType != NewType && 2086 !OldType->isDependentType() && 2087 !NewType->isDependentType() && 2088 !Context.hasSameType(OldType, NewType)) { 2089 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2090 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2091 << Kind << NewType << OldType; 2092 if (Old->getLocation().isValid()) 2093 notePreviousDefinition(Old, New->getLocation()); 2094 New->setInvalidDecl(); 2095 return true; 2096 } 2097 return false; 2098 } 2099 2100 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2101 /// same name and scope as a previous declaration 'Old'. Figure out 2102 /// how to resolve this situation, merging decls or emitting 2103 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2104 /// 2105 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2106 LookupResult &OldDecls) { 2107 // If the new decl is known invalid already, don't bother doing any 2108 // merging checks. 2109 if (New->isInvalidDecl()) return; 2110 2111 // Allow multiple definitions for ObjC built-in typedefs. 2112 // FIXME: Verify the underlying types are equivalent! 2113 if (getLangOpts().ObjC1) { 2114 const IdentifierInfo *TypeID = New->getIdentifier(); 2115 switch (TypeID->getLength()) { 2116 default: break; 2117 case 2: 2118 { 2119 if (!TypeID->isStr("id")) 2120 break; 2121 QualType T = New->getUnderlyingType(); 2122 if (!T->isPointerType()) 2123 break; 2124 if (!T->isVoidPointerType()) { 2125 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2126 if (!PT->isStructureType()) 2127 break; 2128 } 2129 Context.setObjCIdRedefinitionType(T); 2130 // Install the built-in type for 'id', ignoring the current definition. 2131 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2132 return; 2133 } 2134 case 5: 2135 if (!TypeID->isStr("Class")) 2136 break; 2137 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2138 // Install the built-in type for 'Class', ignoring the current definition. 2139 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2140 return; 2141 case 3: 2142 if (!TypeID->isStr("SEL")) 2143 break; 2144 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2145 // Install the built-in type for 'SEL', ignoring the current definition. 2146 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2147 return; 2148 } 2149 // Fall through - the typedef name was not a builtin type. 2150 } 2151 2152 // Verify the old decl was also a type. 2153 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2154 if (!Old) { 2155 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2156 << New->getDeclName(); 2157 2158 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2159 if (OldD->getLocation().isValid()) 2160 notePreviousDefinition(OldD, New->getLocation()); 2161 2162 return New->setInvalidDecl(); 2163 } 2164 2165 // If the old declaration is invalid, just give up here. 2166 if (Old->isInvalidDecl()) 2167 return New->setInvalidDecl(); 2168 2169 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2170 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2171 auto *NewTag = New->getAnonDeclWithTypedefName(); 2172 NamedDecl *Hidden = nullptr; 2173 if (OldTag && NewTag && 2174 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2175 !hasVisibleDefinition(OldTag, &Hidden)) { 2176 // There is a definition of this tag, but it is not visible. Use it 2177 // instead of our tag. 2178 New->setTypeForDecl(OldTD->getTypeForDecl()); 2179 if (OldTD->isModed()) 2180 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2181 OldTD->getUnderlyingType()); 2182 else 2183 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2184 2185 // Make the old tag definition visible. 2186 makeMergedDefinitionVisible(Hidden); 2187 2188 // If this was an unscoped enumeration, yank all of its enumerators 2189 // out of the scope. 2190 if (isa<EnumDecl>(NewTag)) { 2191 Scope *EnumScope = getNonFieldDeclScope(S); 2192 for (auto *D : NewTag->decls()) { 2193 auto *ED = cast<EnumConstantDecl>(D); 2194 assert(EnumScope->isDeclScope(ED)); 2195 EnumScope->RemoveDecl(ED); 2196 IdResolver.RemoveDecl(ED); 2197 ED->getLexicalDeclContext()->removeDecl(ED); 2198 } 2199 } 2200 } 2201 } 2202 2203 // If the typedef types are not identical, reject them in all languages and 2204 // with any extensions enabled. 2205 if (isIncompatibleTypedef(Old, New)) 2206 return; 2207 2208 // The types match. Link up the redeclaration chain and merge attributes if 2209 // the old declaration was a typedef. 2210 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2211 New->setPreviousDecl(Typedef); 2212 mergeDeclAttributes(New, Old); 2213 } 2214 2215 if (getLangOpts().MicrosoftExt) 2216 return; 2217 2218 if (getLangOpts().CPlusPlus) { 2219 // C++ [dcl.typedef]p2: 2220 // In a given non-class scope, a typedef specifier can be used to 2221 // redefine the name of any type declared in that scope to refer 2222 // to the type to which it already refers. 2223 if (!isa<CXXRecordDecl>(CurContext)) 2224 return; 2225 2226 // C++0x [dcl.typedef]p4: 2227 // In a given class scope, a typedef specifier can be used to redefine 2228 // any class-name declared in that scope that is not also a typedef-name 2229 // to refer to the type to which it already refers. 2230 // 2231 // This wording came in via DR424, which was a correction to the 2232 // wording in DR56, which accidentally banned code like: 2233 // 2234 // struct S { 2235 // typedef struct A { } A; 2236 // }; 2237 // 2238 // in the C++03 standard. We implement the C++0x semantics, which 2239 // allow the above but disallow 2240 // 2241 // struct S { 2242 // typedef int I; 2243 // typedef int I; 2244 // }; 2245 // 2246 // since that was the intent of DR56. 2247 if (!isa<TypedefNameDecl>(Old)) 2248 return; 2249 2250 Diag(New->getLocation(), diag::err_redefinition) 2251 << New->getDeclName(); 2252 notePreviousDefinition(Old, New->getLocation()); 2253 return New->setInvalidDecl(); 2254 } 2255 2256 // Modules always permit redefinition of typedefs, as does C11. 2257 if (getLangOpts().Modules || getLangOpts().C11) 2258 return; 2259 2260 // If we have a redefinition of a typedef in C, emit a warning. This warning 2261 // is normally mapped to an error, but can be controlled with 2262 // -Wtypedef-redefinition. If either the original or the redefinition is 2263 // in a system header, don't emit this for compatibility with GCC. 2264 if (getDiagnostics().getSuppressSystemWarnings() && 2265 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2266 (Old->isImplicit() || 2267 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2268 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2269 return; 2270 2271 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2272 << New->getDeclName(); 2273 notePreviousDefinition(Old, New->getLocation()); 2274 } 2275 2276 /// DeclhasAttr - returns true if decl Declaration already has the target 2277 /// attribute. 2278 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2279 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2280 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2281 for (const auto *i : D->attrs()) 2282 if (i->getKind() == A->getKind()) { 2283 if (Ann) { 2284 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2285 return true; 2286 continue; 2287 } 2288 // FIXME: Don't hardcode this check 2289 if (OA && isa<OwnershipAttr>(i)) 2290 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2291 return true; 2292 } 2293 2294 return false; 2295 } 2296 2297 static bool isAttributeTargetADefinition(Decl *D) { 2298 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2299 return VD->isThisDeclarationADefinition(); 2300 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2301 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2302 return true; 2303 } 2304 2305 /// Merge alignment attributes from \p Old to \p New, taking into account the 2306 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2307 /// 2308 /// \return \c true if any attributes were added to \p New. 2309 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2310 // Look for alignas attributes on Old, and pick out whichever attribute 2311 // specifies the strictest alignment requirement. 2312 AlignedAttr *OldAlignasAttr = nullptr; 2313 AlignedAttr *OldStrictestAlignAttr = nullptr; 2314 unsigned OldAlign = 0; 2315 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2316 // FIXME: We have no way of representing inherited dependent alignments 2317 // in a case like: 2318 // template<int A, int B> struct alignas(A) X; 2319 // template<int A, int B> struct alignas(B) X {}; 2320 // For now, we just ignore any alignas attributes which are not on the 2321 // definition in such a case. 2322 if (I->isAlignmentDependent()) 2323 return false; 2324 2325 if (I->isAlignas()) 2326 OldAlignasAttr = I; 2327 2328 unsigned Align = I->getAlignment(S.Context); 2329 if (Align > OldAlign) { 2330 OldAlign = Align; 2331 OldStrictestAlignAttr = I; 2332 } 2333 } 2334 2335 // Look for alignas attributes on New. 2336 AlignedAttr *NewAlignasAttr = nullptr; 2337 unsigned NewAlign = 0; 2338 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2339 if (I->isAlignmentDependent()) 2340 return false; 2341 2342 if (I->isAlignas()) 2343 NewAlignasAttr = I; 2344 2345 unsigned Align = I->getAlignment(S.Context); 2346 if (Align > NewAlign) 2347 NewAlign = Align; 2348 } 2349 2350 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2351 // Both declarations have 'alignas' attributes. We require them to match. 2352 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2353 // fall short. (If two declarations both have alignas, they must both match 2354 // every definition, and so must match each other if there is a definition.) 2355 2356 // If either declaration only contains 'alignas(0)' specifiers, then it 2357 // specifies the natural alignment for the type. 2358 if (OldAlign == 0 || NewAlign == 0) { 2359 QualType Ty; 2360 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2361 Ty = VD->getType(); 2362 else 2363 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2364 2365 if (OldAlign == 0) 2366 OldAlign = S.Context.getTypeAlign(Ty); 2367 if (NewAlign == 0) 2368 NewAlign = S.Context.getTypeAlign(Ty); 2369 } 2370 2371 if (OldAlign != NewAlign) { 2372 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2373 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2374 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2375 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2376 } 2377 } 2378 2379 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2380 // C++11 [dcl.align]p6: 2381 // if any declaration of an entity has an alignment-specifier, 2382 // every defining declaration of that entity shall specify an 2383 // equivalent alignment. 2384 // C11 6.7.5/7: 2385 // If the definition of an object does not have an alignment 2386 // specifier, any other declaration of that object shall also 2387 // have no alignment specifier. 2388 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2389 << OldAlignasAttr; 2390 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2391 << OldAlignasAttr; 2392 } 2393 2394 bool AnyAdded = false; 2395 2396 // Ensure we have an attribute representing the strictest alignment. 2397 if (OldAlign > NewAlign) { 2398 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2399 Clone->setInherited(true); 2400 New->addAttr(Clone); 2401 AnyAdded = true; 2402 } 2403 2404 // Ensure we have an alignas attribute if the old declaration had one. 2405 if (OldAlignasAttr && !NewAlignasAttr && 2406 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2407 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2408 Clone->setInherited(true); 2409 New->addAttr(Clone); 2410 AnyAdded = true; 2411 } 2412 2413 return AnyAdded; 2414 } 2415 2416 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2417 const InheritableAttr *Attr, 2418 Sema::AvailabilityMergeKind AMK) { 2419 // This function copies an attribute Attr from a previous declaration to the 2420 // new declaration D if the new declaration doesn't itself have that attribute 2421 // yet or if that attribute allows duplicates. 2422 // If you're adding a new attribute that requires logic different from 2423 // "use explicit attribute on decl if present, else use attribute from 2424 // previous decl", for example if the attribute needs to be consistent 2425 // between redeclarations, you need to call a custom merge function here. 2426 InheritableAttr *NewAttr = nullptr; 2427 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2428 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2429 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2430 AA->isImplicit(), AA->getIntroduced(), 2431 AA->getDeprecated(), 2432 AA->getObsoleted(), AA->getUnavailable(), 2433 AA->getMessage(), AA->getStrict(), 2434 AA->getReplacement(), AMK, 2435 AttrSpellingListIndex); 2436 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2437 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2438 AttrSpellingListIndex); 2439 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2440 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2441 AttrSpellingListIndex); 2442 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2443 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2444 AttrSpellingListIndex); 2445 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2446 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2447 AttrSpellingListIndex); 2448 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2449 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2450 FA->getFormatIdx(), FA->getFirstArg(), 2451 AttrSpellingListIndex); 2452 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2453 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2454 AttrSpellingListIndex); 2455 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2456 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2457 AttrSpellingListIndex, 2458 IA->getSemanticSpelling()); 2459 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2460 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2461 &S.Context.Idents.get(AA->getSpelling()), 2462 AttrSpellingListIndex); 2463 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2464 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2465 isa<CUDAGlobalAttr>(Attr))) { 2466 // CUDA target attributes are part of function signature for 2467 // overloading purposes and must not be merged. 2468 return false; 2469 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2470 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2471 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2472 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2473 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2474 NewAttr = S.mergeInternalLinkageAttr( 2475 D, InternalLinkageA->getRange(), 2476 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2477 AttrSpellingListIndex); 2478 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2479 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2480 &S.Context.Idents.get(CommonA->getSpelling()), 2481 AttrSpellingListIndex); 2482 else if (isa<AlignedAttr>(Attr)) 2483 // AlignedAttrs are handled separately, because we need to handle all 2484 // such attributes on a declaration at the same time. 2485 NewAttr = nullptr; 2486 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2487 (AMK == Sema::AMK_Override || 2488 AMK == Sema::AMK_ProtocolImplementation)) 2489 NewAttr = nullptr; 2490 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2491 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2492 UA->getGuid()); 2493 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2494 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2495 2496 if (NewAttr) { 2497 NewAttr->setInherited(true); 2498 D->addAttr(NewAttr); 2499 if (isa<MSInheritanceAttr>(NewAttr)) 2500 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2501 return true; 2502 } 2503 2504 return false; 2505 } 2506 2507 static const NamedDecl *getDefinition(const Decl *D) { 2508 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2509 return TD->getDefinition(); 2510 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2511 const VarDecl *Def = VD->getDefinition(); 2512 if (Def) 2513 return Def; 2514 return VD->getActingDefinition(); 2515 } 2516 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2517 return FD->getDefinition(); 2518 return nullptr; 2519 } 2520 2521 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2522 for (const auto *Attribute : D->attrs()) 2523 if (Attribute->getKind() == Kind) 2524 return true; 2525 return false; 2526 } 2527 2528 /// checkNewAttributesAfterDef - If we already have a definition, check that 2529 /// there are no new attributes in this declaration. 2530 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2531 if (!New->hasAttrs()) 2532 return; 2533 2534 const NamedDecl *Def = getDefinition(Old); 2535 if (!Def || Def == New) 2536 return; 2537 2538 AttrVec &NewAttributes = New->getAttrs(); 2539 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2540 const Attr *NewAttribute = NewAttributes[I]; 2541 2542 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2543 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2544 Sema::SkipBodyInfo SkipBody; 2545 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2546 2547 // If we're skipping this definition, drop the "alias" attribute. 2548 if (SkipBody.ShouldSkip) { 2549 NewAttributes.erase(NewAttributes.begin() + I); 2550 --E; 2551 continue; 2552 } 2553 } else { 2554 VarDecl *VD = cast<VarDecl>(New); 2555 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2556 VarDecl::TentativeDefinition 2557 ? diag::err_alias_after_tentative 2558 : diag::err_redefinition; 2559 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2560 if (Diag == diag::err_redefinition) 2561 S.notePreviousDefinition(Def, VD->getLocation()); 2562 else 2563 S.Diag(Def->getLocation(), diag::note_previous_definition); 2564 VD->setInvalidDecl(); 2565 } 2566 ++I; 2567 continue; 2568 } 2569 2570 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2571 // Tentative definitions are only interesting for the alias check above. 2572 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2573 ++I; 2574 continue; 2575 } 2576 } 2577 2578 if (hasAttribute(Def, NewAttribute->getKind())) { 2579 ++I; 2580 continue; // regular attr merging will take care of validating this. 2581 } 2582 2583 if (isa<C11NoReturnAttr>(NewAttribute)) { 2584 // C's _Noreturn is allowed to be added to a function after it is defined. 2585 ++I; 2586 continue; 2587 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2588 if (AA->isAlignas()) { 2589 // C++11 [dcl.align]p6: 2590 // if any declaration of an entity has an alignment-specifier, 2591 // every defining declaration of that entity shall specify an 2592 // equivalent alignment. 2593 // C11 6.7.5/7: 2594 // If the definition of an object does not have an alignment 2595 // specifier, any other declaration of that object shall also 2596 // have no alignment specifier. 2597 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2598 << AA; 2599 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2600 << AA; 2601 NewAttributes.erase(NewAttributes.begin() + I); 2602 --E; 2603 continue; 2604 } 2605 } 2606 2607 S.Diag(NewAttribute->getLocation(), 2608 diag::warn_attribute_precede_definition); 2609 S.Diag(Def->getLocation(), diag::note_previous_definition); 2610 NewAttributes.erase(NewAttributes.begin() + I); 2611 --E; 2612 } 2613 } 2614 2615 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2616 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2617 AvailabilityMergeKind AMK) { 2618 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2619 UsedAttr *NewAttr = OldAttr->clone(Context); 2620 NewAttr->setInherited(true); 2621 New->addAttr(NewAttr); 2622 } 2623 2624 if (!Old->hasAttrs() && !New->hasAttrs()) 2625 return; 2626 2627 // Attributes declared post-definition are currently ignored. 2628 checkNewAttributesAfterDef(*this, New, Old); 2629 2630 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2631 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2632 if (OldA->getLabel() != NewA->getLabel()) { 2633 // This redeclaration changes __asm__ label. 2634 Diag(New->getLocation(), diag::err_different_asm_label); 2635 Diag(OldA->getLocation(), diag::note_previous_declaration); 2636 } 2637 } else if (Old->isUsed()) { 2638 // This redeclaration adds an __asm__ label to a declaration that has 2639 // already been ODR-used. 2640 Diag(New->getLocation(), diag::err_late_asm_label_name) 2641 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2642 } 2643 } 2644 2645 // Re-declaration cannot add abi_tag's. 2646 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2647 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2648 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2649 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2650 NewTag) == OldAbiTagAttr->tags_end()) { 2651 Diag(NewAbiTagAttr->getLocation(), 2652 diag::err_new_abi_tag_on_redeclaration) 2653 << NewTag; 2654 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2655 } 2656 } 2657 } else { 2658 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2659 Diag(Old->getLocation(), diag::note_previous_declaration); 2660 } 2661 } 2662 2663 // This redeclaration adds a section attribute. 2664 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2665 if (auto *VD = dyn_cast<VarDecl>(New)) { 2666 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2667 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2668 Diag(Old->getLocation(), diag::note_previous_declaration); 2669 } 2670 } 2671 } 2672 2673 if (!Old->hasAttrs()) 2674 return; 2675 2676 bool foundAny = New->hasAttrs(); 2677 2678 // Ensure that any moving of objects within the allocated map is done before 2679 // we process them. 2680 if (!foundAny) New->setAttrs(AttrVec()); 2681 2682 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2683 // Ignore deprecated/unavailable/availability attributes if requested. 2684 AvailabilityMergeKind LocalAMK = AMK_None; 2685 if (isa<DeprecatedAttr>(I) || 2686 isa<UnavailableAttr>(I) || 2687 isa<AvailabilityAttr>(I)) { 2688 switch (AMK) { 2689 case AMK_None: 2690 continue; 2691 2692 case AMK_Redeclaration: 2693 case AMK_Override: 2694 case AMK_ProtocolImplementation: 2695 LocalAMK = AMK; 2696 break; 2697 } 2698 } 2699 2700 // Already handled. 2701 if (isa<UsedAttr>(I)) 2702 continue; 2703 2704 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2705 foundAny = true; 2706 } 2707 2708 if (mergeAlignedAttrs(*this, New, Old)) 2709 foundAny = true; 2710 2711 if (!foundAny) New->dropAttrs(); 2712 } 2713 2714 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2715 /// to the new one. 2716 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2717 const ParmVarDecl *oldDecl, 2718 Sema &S) { 2719 // C++11 [dcl.attr.depend]p2: 2720 // The first declaration of a function shall specify the 2721 // carries_dependency attribute for its declarator-id if any declaration 2722 // of the function specifies the carries_dependency attribute. 2723 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2724 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2725 S.Diag(CDA->getLocation(), 2726 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2727 // Find the first declaration of the parameter. 2728 // FIXME: Should we build redeclaration chains for function parameters? 2729 const FunctionDecl *FirstFD = 2730 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2731 const ParmVarDecl *FirstVD = 2732 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2733 S.Diag(FirstVD->getLocation(), 2734 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2735 } 2736 2737 if (!oldDecl->hasAttrs()) 2738 return; 2739 2740 bool foundAny = newDecl->hasAttrs(); 2741 2742 // Ensure that any moving of objects within the allocated map is 2743 // done before we process them. 2744 if (!foundAny) newDecl->setAttrs(AttrVec()); 2745 2746 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2747 if (!DeclHasAttr(newDecl, I)) { 2748 InheritableAttr *newAttr = 2749 cast<InheritableParamAttr>(I->clone(S.Context)); 2750 newAttr->setInherited(true); 2751 newDecl->addAttr(newAttr); 2752 foundAny = true; 2753 } 2754 } 2755 2756 if (!foundAny) newDecl->dropAttrs(); 2757 } 2758 2759 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2760 const ParmVarDecl *OldParam, 2761 Sema &S) { 2762 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2763 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2764 if (*Oldnullability != *Newnullability) { 2765 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2766 << DiagNullabilityKind( 2767 *Newnullability, 2768 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2769 != 0)) 2770 << DiagNullabilityKind( 2771 *Oldnullability, 2772 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2773 != 0)); 2774 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2775 } 2776 } else { 2777 QualType NewT = NewParam->getType(); 2778 NewT = S.Context.getAttributedType( 2779 AttributedType::getNullabilityAttrKind(*Oldnullability), 2780 NewT, NewT); 2781 NewParam->setType(NewT); 2782 } 2783 } 2784 } 2785 2786 namespace { 2787 2788 /// Used in MergeFunctionDecl to keep track of function parameters in 2789 /// C. 2790 struct GNUCompatibleParamWarning { 2791 ParmVarDecl *OldParm; 2792 ParmVarDecl *NewParm; 2793 QualType PromotedType; 2794 }; 2795 2796 } // end anonymous namespace 2797 2798 /// getSpecialMember - get the special member enum for a method. 2799 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2800 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2801 if (Ctor->isDefaultConstructor()) 2802 return Sema::CXXDefaultConstructor; 2803 2804 if (Ctor->isCopyConstructor()) 2805 return Sema::CXXCopyConstructor; 2806 2807 if (Ctor->isMoveConstructor()) 2808 return Sema::CXXMoveConstructor; 2809 } else if (isa<CXXDestructorDecl>(MD)) { 2810 return Sema::CXXDestructor; 2811 } else if (MD->isCopyAssignmentOperator()) { 2812 return Sema::CXXCopyAssignment; 2813 } else if (MD->isMoveAssignmentOperator()) { 2814 return Sema::CXXMoveAssignment; 2815 } 2816 2817 return Sema::CXXInvalid; 2818 } 2819 2820 // Determine whether the previous declaration was a definition, implicit 2821 // declaration, or a declaration. 2822 template <typename T> 2823 static std::pair<diag::kind, SourceLocation> 2824 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2825 diag::kind PrevDiag; 2826 SourceLocation OldLocation = Old->getLocation(); 2827 if (Old->isThisDeclarationADefinition()) 2828 PrevDiag = diag::note_previous_definition; 2829 else if (Old->isImplicit()) { 2830 PrevDiag = diag::note_previous_implicit_declaration; 2831 if (OldLocation.isInvalid()) 2832 OldLocation = New->getLocation(); 2833 } else 2834 PrevDiag = diag::note_previous_declaration; 2835 return std::make_pair(PrevDiag, OldLocation); 2836 } 2837 2838 /// canRedefineFunction - checks if a function can be redefined. Currently, 2839 /// only extern inline functions can be redefined, and even then only in 2840 /// GNU89 mode. 2841 static bool canRedefineFunction(const FunctionDecl *FD, 2842 const LangOptions& LangOpts) { 2843 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2844 !LangOpts.CPlusPlus && 2845 FD->isInlineSpecified() && 2846 FD->getStorageClass() == SC_Extern); 2847 } 2848 2849 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2850 const AttributedType *AT = T->getAs<AttributedType>(); 2851 while (AT && !AT->isCallingConv()) 2852 AT = AT->getModifiedType()->getAs<AttributedType>(); 2853 return AT; 2854 } 2855 2856 template <typename T> 2857 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2858 const DeclContext *DC = Old->getDeclContext(); 2859 if (DC->isRecord()) 2860 return false; 2861 2862 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2863 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2864 return true; 2865 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2866 return true; 2867 return false; 2868 } 2869 2870 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2871 static bool isExternC(VarTemplateDecl *) { return false; } 2872 2873 /// Check whether a redeclaration of an entity introduced by a 2874 /// using-declaration is valid, given that we know it's not an overload 2875 /// (nor a hidden tag declaration). 2876 template<typename ExpectedDecl> 2877 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2878 ExpectedDecl *New) { 2879 // C++11 [basic.scope.declarative]p4: 2880 // Given a set of declarations in a single declarative region, each of 2881 // which specifies the same unqualified name, 2882 // -- they shall all refer to the same entity, or all refer to functions 2883 // and function templates; or 2884 // -- exactly one declaration shall declare a class name or enumeration 2885 // name that is not a typedef name and the other declarations shall all 2886 // refer to the same variable or enumerator, or all refer to functions 2887 // and function templates; in this case the class name or enumeration 2888 // name is hidden (3.3.10). 2889 2890 // C++11 [namespace.udecl]p14: 2891 // If a function declaration in namespace scope or block scope has the 2892 // same name and the same parameter-type-list as a function introduced 2893 // by a using-declaration, and the declarations do not declare the same 2894 // function, the program is ill-formed. 2895 2896 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2897 if (Old && 2898 !Old->getDeclContext()->getRedeclContext()->Equals( 2899 New->getDeclContext()->getRedeclContext()) && 2900 !(isExternC(Old) && isExternC(New))) 2901 Old = nullptr; 2902 2903 if (!Old) { 2904 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2905 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2906 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2907 return true; 2908 } 2909 return false; 2910 } 2911 2912 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2913 const FunctionDecl *B) { 2914 assert(A->getNumParams() == B->getNumParams()); 2915 2916 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2917 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2918 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2919 if (AttrA == AttrB) 2920 return true; 2921 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2922 }; 2923 2924 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2925 } 2926 2927 /// If necessary, adjust the semantic declaration context for a qualified 2928 /// declaration to name the correct inline namespace within the qualifier. 2929 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2930 DeclaratorDecl *OldD) { 2931 // The only case where we need to update the DeclContext is when 2932 // redeclaration lookup for a qualified name finds a declaration 2933 // in an inline namespace within the context named by the qualifier: 2934 // 2935 // inline namespace N { int f(); } 2936 // int ::f(); // Sema DC needs adjusting from :: to N::. 2937 // 2938 // For unqualified declarations, the semantic context *can* change 2939 // along the redeclaration chain (for local extern declarations, 2940 // extern "C" declarations, and friend declarations in particular). 2941 if (!NewD->getQualifier()) 2942 return; 2943 2944 // NewD is probably already in the right context. 2945 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2946 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2947 if (NamedDC->Equals(SemaDC)) 2948 return; 2949 2950 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2951 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2952 "unexpected context for redeclaration"); 2953 2954 auto *LexDC = NewD->getLexicalDeclContext(); 2955 auto FixSemaDC = [=](NamedDecl *D) { 2956 if (!D) 2957 return; 2958 D->setDeclContext(SemaDC); 2959 D->setLexicalDeclContext(LexDC); 2960 }; 2961 2962 FixSemaDC(NewD); 2963 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 2964 FixSemaDC(FD->getDescribedFunctionTemplate()); 2965 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 2966 FixSemaDC(VD->getDescribedVarTemplate()); 2967 } 2968 2969 /// MergeFunctionDecl - We just parsed a function 'New' from 2970 /// declarator D which has the same name and scope as a previous 2971 /// declaration 'Old'. Figure out how to resolve this situation, 2972 /// merging decls or emitting diagnostics as appropriate. 2973 /// 2974 /// In C++, New and Old must be declarations that are not 2975 /// overloaded. Use IsOverload to determine whether New and Old are 2976 /// overloaded, and to select the Old declaration that New should be 2977 /// merged with. 2978 /// 2979 /// Returns true if there was an error, false otherwise. 2980 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2981 Scope *S, bool MergeTypeWithOld) { 2982 // Verify the old decl was also a function. 2983 FunctionDecl *Old = OldD->getAsFunction(); 2984 if (!Old) { 2985 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2986 if (New->getFriendObjectKind()) { 2987 Diag(New->getLocation(), diag::err_using_decl_friend); 2988 Diag(Shadow->getTargetDecl()->getLocation(), 2989 diag::note_using_decl_target); 2990 Diag(Shadow->getUsingDecl()->getLocation(), 2991 diag::note_using_decl) << 0; 2992 return true; 2993 } 2994 2995 // Check whether the two declarations might declare the same function. 2996 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2997 return true; 2998 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2999 } else { 3000 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3001 << New->getDeclName(); 3002 notePreviousDefinition(OldD, New->getLocation()); 3003 return true; 3004 } 3005 } 3006 3007 // If the old declaration is invalid, just give up here. 3008 if (Old->isInvalidDecl()) 3009 return true; 3010 3011 // Disallow redeclaration of some builtins. 3012 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3013 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3014 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3015 << Old << Old->getType(); 3016 return true; 3017 } 3018 3019 diag::kind PrevDiag; 3020 SourceLocation OldLocation; 3021 std::tie(PrevDiag, OldLocation) = 3022 getNoteDiagForInvalidRedeclaration(Old, New); 3023 3024 // Don't complain about this if we're in GNU89 mode and the old function 3025 // is an extern inline function. 3026 // Don't complain about specializations. They are not supposed to have 3027 // storage classes. 3028 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3029 New->getStorageClass() == SC_Static && 3030 Old->hasExternalFormalLinkage() && 3031 !New->getTemplateSpecializationInfo() && 3032 !canRedefineFunction(Old, getLangOpts())) { 3033 if (getLangOpts().MicrosoftExt) { 3034 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3035 Diag(OldLocation, PrevDiag); 3036 } else { 3037 Diag(New->getLocation(), diag::err_static_non_static) << New; 3038 Diag(OldLocation, PrevDiag); 3039 return true; 3040 } 3041 } 3042 3043 if (New->hasAttr<InternalLinkageAttr>() && 3044 !Old->hasAttr<InternalLinkageAttr>()) { 3045 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3046 << New->getDeclName(); 3047 notePreviousDefinition(Old, New->getLocation()); 3048 New->dropAttr<InternalLinkageAttr>(); 3049 } 3050 3051 if (CheckRedeclarationModuleOwnership(New, Old)) 3052 return true; 3053 3054 if (!getLangOpts().CPlusPlus) { 3055 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3056 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3057 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3058 << New << OldOvl; 3059 3060 // Try our best to find a decl that actually has the overloadable 3061 // attribute for the note. In most cases (e.g. programs with only one 3062 // broken declaration/definition), this won't matter. 3063 // 3064 // FIXME: We could do this if we juggled some extra state in 3065 // OverloadableAttr, rather than just removing it. 3066 const Decl *DiagOld = Old; 3067 if (OldOvl) { 3068 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3069 const auto *A = D->getAttr<OverloadableAttr>(); 3070 return A && !A->isImplicit(); 3071 }); 3072 // If we've implicitly added *all* of the overloadable attrs to this 3073 // chain, emitting a "previous redecl" note is pointless. 3074 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3075 } 3076 3077 if (DiagOld) 3078 Diag(DiagOld->getLocation(), 3079 diag::note_attribute_overloadable_prev_overload) 3080 << OldOvl; 3081 3082 if (OldOvl) 3083 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3084 else 3085 New->dropAttr<OverloadableAttr>(); 3086 } 3087 } 3088 3089 // If a function is first declared with a calling convention, but is later 3090 // declared or defined without one, all following decls assume the calling 3091 // convention of the first. 3092 // 3093 // It's OK if a function is first declared without a calling convention, 3094 // but is later declared or defined with the default calling convention. 3095 // 3096 // To test if either decl has an explicit calling convention, we look for 3097 // AttributedType sugar nodes on the type as written. If they are missing or 3098 // were canonicalized away, we assume the calling convention was implicit. 3099 // 3100 // Note also that we DO NOT return at this point, because we still have 3101 // other tests to run. 3102 QualType OldQType = Context.getCanonicalType(Old->getType()); 3103 QualType NewQType = Context.getCanonicalType(New->getType()); 3104 const FunctionType *OldType = cast<FunctionType>(OldQType); 3105 const FunctionType *NewType = cast<FunctionType>(NewQType); 3106 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3107 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3108 bool RequiresAdjustment = false; 3109 3110 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3111 FunctionDecl *First = Old->getFirstDecl(); 3112 const FunctionType *FT = 3113 First->getType().getCanonicalType()->castAs<FunctionType>(); 3114 FunctionType::ExtInfo FI = FT->getExtInfo(); 3115 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3116 if (!NewCCExplicit) { 3117 // Inherit the CC from the previous declaration if it was specified 3118 // there but not here. 3119 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3120 RequiresAdjustment = true; 3121 } else { 3122 // Calling conventions aren't compatible, so complain. 3123 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3124 Diag(New->getLocation(), diag::err_cconv_change) 3125 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3126 << !FirstCCExplicit 3127 << (!FirstCCExplicit ? "" : 3128 FunctionType::getNameForCallConv(FI.getCC())); 3129 3130 // Put the note on the first decl, since it is the one that matters. 3131 Diag(First->getLocation(), diag::note_previous_declaration); 3132 return true; 3133 } 3134 } 3135 3136 // FIXME: diagnose the other way around? 3137 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3138 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3139 RequiresAdjustment = true; 3140 } 3141 3142 // Merge regparm attribute. 3143 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3144 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3145 if (NewTypeInfo.getHasRegParm()) { 3146 Diag(New->getLocation(), diag::err_regparm_mismatch) 3147 << NewType->getRegParmType() 3148 << OldType->getRegParmType(); 3149 Diag(OldLocation, diag::note_previous_declaration); 3150 return true; 3151 } 3152 3153 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3154 RequiresAdjustment = true; 3155 } 3156 3157 // Merge ns_returns_retained attribute. 3158 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3159 if (NewTypeInfo.getProducesResult()) { 3160 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3161 << "'ns_returns_retained'"; 3162 Diag(OldLocation, diag::note_previous_declaration); 3163 return true; 3164 } 3165 3166 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3167 RequiresAdjustment = true; 3168 } 3169 3170 if (OldTypeInfo.getNoCallerSavedRegs() != 3171 NewTypeInfo.getNoCallerSavedRegs()) { 3172 if (NewTypeInfo.getNoCallerSavedRegs()) { 3173 AnyX86NoCallerSavedRegistersAttr *Attr = 3174 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3175 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3176 Diag(OldLocation, diag::note_previous_declaration); 3177 return true; 3178 } 3179 3180 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3181 RequiresAdjustment = true; 3182 } 3183 3184 if (RequiresAdjustment) { 3185 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3186 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3187 New->setType(QualType(AdjustedType, 0)); 3188 NewQType = Context.getCanonicalType(New->getType()); 3189 NewType = cast<FunctionType>(NewQType); 3190 } 3191 3192 // If this redeclaration makes the function inline, we may need to add it to 3193 // UndefinedButUsed. 3194 if (!Old->isInlined() && New->isInlined() && 3195 !New->hasAttr<GNUInlineAttr>() && 3196 !getLangOpts().GNUInline && 3197 Old->isUsed(false) && 3198 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3199 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3200 SourceLocation())); 3201 3202 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3203 // about it. 3204 if (New->hasAttr<GNUInlineAttr>() && 3205 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3206 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3207 } 3208 3209 // If pass_object_size params don't match up perfectly, this isn't a valid 3210 // redeclaration. 3211 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3212 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3213 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3214 << New->getDeclName(); 3215 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3216 return true; 3217 } 3218 3219 if (getLangOpts().CPlusPlus) { 3220 // C++1z [over.load]p2 3221 // Certain function declarations cannot be overloaded: 3222 // -- Function declarations that differ only in the return type, 3223 // the exception specification, or both cannot be overloaded. 3224 3225 // Check the exception specifications match. This may recompute the type of 3226 // both Old and New if it resolved exception specifications, so grab the 3227 // types again after this. Because this updates the type, we do this before 3228 // any of the other checks below, which may update the "de facto" NewQType 3229 // but do not necessarily update the type of New. 3230 if (CheckEquivalentExceptionSpec(Old, New)) 3231 return true; 3232 OldQType = Context.getCanonicalType(Old->getType()); 3233 NewQType = Context.getCanonicalType(New->getType()); 3234 3235 // Go back to the type source info to compare the declared return types, 3236 // per C++1y [dcl.type.auto]p13: 3237 // Redeclarations or specializations of a function or function template 3238 // with a declared return type that uses a placeholder type shall also 3239 // use that placeholder, not a deduced type. 3240 QualType OldDeclaredReturnType = 3241 (Old->getTypeSourceInfo() 3242 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3243 : OldType)->getReturnType(); 3244 QualType NewDeclaredReturnType = 3245 (New->getTypeSourceInfo() 3246 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3247 : NewType)->getReturnType(); 3248 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3249 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3250 New->isLocalExternDecl())) { 3251 QualType ResQT; 3252 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3253 OldDeclaredReturnType->isObjCObjectPointerType()) 3254 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3255 if (ResQT.isNull()) { 3256 if (New->isCXXClassMember() && New->isOutOfLine()) 3257 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3258 << New << New->getReturnTypeSourceRange(); 3259 else 3260 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3261 << New->getReturnTypeSourceRange(); 3262 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3263 << Old->getReturnTypeSourceRange(); 3264 return true; 3265 } 3266 else 3267 NewQType = ResQT; 3268 } 3269 3270 QualType OldReturnType = OldType->getReturnType(); 3271 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3272 if (OldReturnType != NewReturnType) { 3273 // If this function has a deduced return type and has already been 3274 // defined, copy the deduced value from the old declaration. 3275 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3276 if (OldAT && OldAT->isDeduced()) { 3277 New->setType( 3278 SubstAutoType(New->getType(), 3279 OldAT->isDependentType() ? Context.DependentTy 3280 : OldAT->getDeducedType())); 3281 NewQType = Context.getCanonicalType( 3282 SubstAutoType(NewQType, 3283 OldAT->isDependentType() ? Context.DependentTy 3284 : OldAT->getDeducedType())); 3285 } 3286 } 3287 3288 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3289 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3290 if (OldMethod && NewMethod) { 3291 // Preserve triviality. 3292 NewMethod->setTrivial(OldMethod->isTrivial()); 3293 3294 // MSVC allows explicit template specialization at class scope: 3295 // 2 CXXMethodDecls referring to the same function will be injected. 3296 // We don't want a redeclaration error. 3297 bool IsClassScopeExplicitSpecialization = 3298 OldMethod->isFunctionTemplateSpecialization() && 3299 NewMethod->isFunctionTemplateSpecialization(); 3300 bool isFriend = NewMethod->getFriendObjectKind(); 3301 3302 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3303 !IsClassScopeExplicitSpecialization) { 3304 // -- Member function declarations with the same name and the 3305 // same parameter types cannot be overloaded if any of them 3306 // is a static member function declaration. 3307 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3308 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3309 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3310 return true; 3311 } 3312 3313 // C++ [class.mem]p1: 3314 // [...] A member shall not be declared twice in the 3315 // member-specification, except that a nested class or member 3316 // class template can be declared and then later defined. 3317 if (!inTemplateInstantiation()) { 3318 unsigned NewDiag; 3319 if (isa<CXXConstructorDecl>(OldMethod)) 3320 NewDiag = diag::err_constructor_redeclared; 3321 else if (isa<CXXDestructorDecl>(NewMethod)) 3322 NewDiag = diag::err_destructor_redeclared; 3323 else if (isa<CXXConversionDecl>(NewMethod)) 3324 NewDiag = diag::err_conv_function_redeclared; 3325 else 3326 NewDiag = diag::err_member_redeclared; 3327 3328 Diag(New->getLocation(), NewDiag); 3329 } else { 3330 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3331 << New << New->getType(); 3332 } 3333 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3334 return true; 3335 3336 // Complain if this is an explicit declaration of a special 3337 // member that was initially declared implicitly. 3338 // 3339 // As an exception, it's okay to befriend such methods in order 3340 // to permit the implicit constructor/destructor/operator calls. 3341 } else if (OldMethod->isImplicit()) { 3342 if (isFriend) { 3343 NewMethod->setImplicit(); 3344 } else { 3345 Diag(NewMethod->getLocation(), 3346 diag::err_definition_of_implicitly_declared_member) 3347 << New << getSpecialMember(OldMethod); 3348 return true; 3349 } 3350 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3351 Diag(NewMethod->getLocation(), 3352 diag::err_definition_of_explicitly_defaulted_member) 3353 << getSpecialMember(OldMethod); 3354 return true; 3355 } 3356 } 3357 3358 // C++11 [dcl.attr.noreturn]p1: 3359 // The first declaration of a function shall specify the noreturn 3360 // attribute if any declaration of that function specifies the noreturn 3361 // attribute. 3362 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3363 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3364 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3365 Diag(Old->getFirstDecl()->getLocation(), 3366 diag::note_noreturn_missing_first_decl); 3367 } 3368 3369 // C++11 [dcl.attr.depend]p2: 3370 // The first declaration of a function shall specify the 3371 // carries_dependency attribute for its declarator-id if any declaration 3372 // of the function specifies the carries_dependency attribute. 3373 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3374 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3375 Diag(CDA->getLocation(), 3376 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3377 Diag(Old->getFirstDecl()->getLocation(), 3378 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3379 } 3380 3381 // (C++98 8.3.5p3): 3382 // All declarations for a function shall agree exactly in both the 3383 // return type and the parameter-type-list. 3384 // We also want to respect all the extended bits except noreturn. 3385 3386 // noreturn should now match unless the old type info didn't have it. 3387 QualType OldQTypeForComparison = OldQType; 3388 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3389 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3390 const FunctionType *OldTypeForComparison 3391 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3392 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3393 assert(OldQTypeForComparison.isCanonical()); 3394 } 3395 3396 if (haveIncompatibleLanguageLinkages(Old, New)) { 3397 // As a special case, retain the language linkage from previous 3398 // declarations of a friend function as an extension. 3399 // 3400 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3401 // and is useful because there's otherwise no way to specify language 3402 // linkage within class scope. 3403 // 3404 // Check cautiously as the friend object kind isn't yet complete. 3405 if (New->getFriendObjectKind() != Decl::FOK_None) { 3406 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3407 Diag(OldLocation, PrevDiag); 3408 } else { 3409 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3410 Diag(OldLocation, PrevDiag); 3411 return true; 3412 } 3413 } 3414 3415 if (OldQTypeForComparison == NewQType) 3416 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3417 3418 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3419 New->isLocalExternDecl()) { 3420 // It's OK if we couldn't merge types for a local function declaraton 3421 // if either the old or new type is dependent. We'll merge the types 3422 // when we instantiate the function. 3423 return false; 3424 } 3425 3426 // Fall through for conflicting redeclarations and redefinitions. 3427 } 3428 3429 // C: Function types need to be compatible, not identical. This handles 3430 // duplicate function decls like "void f(int); void f(enum X);" properly. 3431 if (!getLangOpts().CPlusPlus && 3432 Context.typesAreCompatible(OldQType, NewQType)) { 3433 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3434 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3435 const FunctionProtoType *OldProto = nullptr; 3436 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3437 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3438 // The old declaration provided a function prototype, but the 3439 // new declaration does not. Merge in the prototype. 3440 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3441 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3442 NewQType = 3443 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3444 OldProto->getExtProtoInfo()); 3445 New->setType(NewQType); 3446 New->setHasInheritedPrototype(); 3447 3448 // Synthesize parameters with the same types. 3449 SmallVector<ParmVarDecl*, 16> Params; 3450 for (const auto &ParamType : OldProto->param_types()) { 3451 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3452 SourceLocation(), nullptr, 3453 ParamType, /*TInfo=*/nullptr, 3454 SC_None, nullptr); 3455 Param->setScopeInfo(0, Params.size()); 3456 Param->setImplicit(); 3457 Params.push_back(Param); 3458 } 3459 3460 New->setParams(Params); 3461 } 3462 3463 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3464 } 3465 3466 // GNU C permits a K&R definition to follow a prototype declaration 3467 // if the declared types of the parameters in the K&R definition 3468 // match the types in the prototype declaration, even when the 3469 // promoted types of the parameters from the K&R definition differ 3470 // from the types in the prototype. GCC then keeps the types from 3471 // the prototype. 3472 // 3473 // If a variadic prototype is followed by a non-variadic K&R definition, 3474 // the K&R definition becomes variadic. This is sort of an edge case, but 3475 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3476 // C99 6.9.1p8. 3477 if (!getLangOpts().CPlusPlus && 3478 Old->hasPrototype() && !New->hasPrototype() && 3479 New->getType()->getAs<FunctionProtoType>() && 3480 Old->getNumParams() == New->getNumParams()) { 3481 SmallVector<QualType, 16> ArgTypes; 3482 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3483 const FunctionProtoType *OldProto 3484 = Old->getType()->getAs<FunctionProtoType>(); 3485 const FunctionProtoType *NewProto 3486 = New->getType()->getAs<FunctionProtoType>(); 3487 3488 // Determine whether this is the GNU C extension. 3489 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3490 NewProto->getReturnType()); 3491 bool LooseCompatible = !MergedReturn.isNull(); 3492 for (unsigned Idx = 0, End = Old->getNumParams(); 3493 LooseCompatible && Idx != End; ++Idx) { 3494 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3495 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3496 if (Context.typesAreCompatible(OldParm->getType(), 3497 NewProto->getParamType(Idx))) { 3498 ArgTypes.push_back(NewParm->getType()); 3499 } else if (Context.typesAreCompatible(OldParm->getType(), 3500 NewParm->getType(), 3501 /*CompareUnqualified=*/true)) { 3502 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3503 NewProto->getParamType(Idx) }; 3504 Warnings.push_back(Warn); 3505 ArgTypes.push_back(NewParm->getType()); 3506 } else 3507 LooseCompatible = false; 3508 } 3509 3510 if (LooseCompatible) { 3511 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3512 Diag(Warnings[Warn].NewParm->getLocation(), 3513 diag::ext_param_promoted_not_compatible_with_prototype) 3514 << Warnings[Warn].PromotedType 3515 << Warnings[Warn].OldParm->getType(); 3516 if (Warnings[Warn].OldParm->getLocation().isValid()) 3517 Diag(Warnings[Warn].OldParm->getLocation(), 3518 diag::note_previous_declaration); 3519 } 3520 3521 if (MergeTypeWithOld) 3522 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3523 OldProto->getExtProtoInfo())); 3524 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3525 } 3526 3527 // Fall through to diagnose conflicting types. 3528 } 3529 3530 // A function that has already been declared has been redeclared or 3531 // defined with a different type; show an appropriate diagnostic. 3532 3533 // If the previous declaration was an implicitly-generated builtin 3534 // declaration, then at the very least we should use a specialized note. 3535 unsigned BuiltinID; 3536 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3537 // If it's actually a library-defined builtin function like 'malloc' 3538 // or 'printf', just warn about the incompatible redeclaration. 3539 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3540 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3541 Diag(OldLocation, diag::note_previous_builtin_declaration) 3542 << Old << Old->getType(); 3543 3544 // If this is a global redeclaration, just forget hereafter 3545 // about the "builtin-ness" of the function. 3546 // 3547 // Doing this for local extern declarations is problematic. If 3548 // the builtin declaration remains visible, a second invalid 3549 // local declaration will produce a hard error; if it doesn't 3550 // remain visible, a single bogus local redeclaration (which is 3551 // actually only a warning) could break all the downstream code. 3552 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3553 New->getIdentifier()->revertBuiltin(); 3554 3555 return false; 3556 } 3557 3558 PrevDiag = diag::note_previous_builtin_declaration; 3559 } 3560 3561 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3562 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3563 return true; 3564 } 3565 3566 /// Completes the merge of two function declarations that are 3567 /// known to be compatible. 3568 /// 3569 /// This routine handles the merging of attributes and other 3570 /// properties of function declarations from the old declaration to 3571 /// the new declaration, once we know that New is in fact a 3572 /// redeclaration of Old. 3573 /// 3574 /// \returns false 3575 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3576 Scope *S, bool MergeTypeWithOld) { 3577 // Merge the attributes 3578 mergeDeclAttributes(New, Old); 3579 3580 // Merge "pure" flag. 3581 if (Old->isPure()) 3582 New->setPure(); 3583 3584 // Merge "used" flag. 3585 if (Old->getMostRecentDecl()->isUsed(false)) 3586 New->setIsUsed(); 3587 3588 // Merge attributes from the parameters. These can mismatch with K&R 3589 // declarations. 3590 if (New->getNumParams() == Old->getNumParams()) 3591 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3592 ParmVarDecl *NewParam = New->getParamDecl(i); 3593 ParmVarDecl *OldParam = Old->getParamDecl(i); 3594 mergeParamDeclAttributes(NewParam, OldParam, *this); 3595 mergeParamDeclTypes(NewParam, OldParam, *this); 3596 } 3597 3598 if (getLangOpts().CPlusPlus) 3599 return MergeCXXFunctionDecl(New, Old, S); 3600 3601 // Merge the function types so the we get the composite types for the return 3602 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3603 // was visible. 3604 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3605 if (!Merged.isNull() && MergeTypeWithOld) 3606 New->setType(Merged); 3607 3608 return false; 3609 } 3610 3611 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3612 ObjCMethodDecl *oldMethod) { 3613 // Merge the attributes, including deprecated/unavailable 3614 AvailabilityMergeKind MergeKind = 3615 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3616 ? AMK_ProtocolImplementation 3617 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3618 : AMK_Override; 3619 3620 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3621 3622 // Merge attributes from the parameters. 3623 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3624 oe = oldMethod->param_end(); 3625 for (ObjCMethodDecl::param_iterator 3626 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3627 ni != ne && oi != oe; ++ni, ++oi) 3628 mergeParamDeclAttributes(*ni, *oi, *this); 3629 3630 CheckObjCMethodOverride(newMethod, oldMethod); 3631 } 3632 3633 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3634 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3635 3636 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3637 ? diag::err_redefinition_different_type 3638 : diag::err_redeclaration_different_type) 3639 << New->getDeclName() << New->getType() << Old->getType(); 3640 3641 diag::kind PrevDiag; 3642 SourceLocation OldLocation; 3643 std::tie(PrevDiag, OldLocation) 3644 = getNoteDiagForInvalidRedeclaration(Old, New); 3645 S.Diag(OldLocation, PrevDiag); 3646 New->setInvalidDecl(); 3647 } 3648 3649 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3650 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3651 /// emitting diagnostics as appropriate. 3652 /// 3653 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3654 /// to here in AddInitializerToDecl. We can't check them before the initializer 3655 /// is attached. 3656 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3657 bool MergeTypeWithOld) { 3658 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3659 return; 3660 3661 QualType MergedT; 3662 if (getLangOpts().CPlusPlus) { 3663 if (New->getType()->isUndeducedType()) { 3664 // We don't know what the new type is until the initializer is attached. 3665 return; 3666 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3667 // These could still be something that needs exception specs checked. 3668 return MergeVarDeclExceptionSpecs(New, Old); 3669 } 3670 // C++ [basic.link]p10: 3671 // [...] the types specified by all declarations referring to a given 3672 // object or function shall be identical, except that declarations for an 3673 // array object can specify array types that differ by the presence or 3674 // absence of a major array bound (8.3.4). 3675 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3676 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3677 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3678 3679 // We are merging a variable declaration New into Old. If it has an array 3680 // bound, and that bound differs from Old's bound, we should diagnose the 3681 // mismatch. 3682 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3683 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3684 PrevVD = PrevVD->getPreviousDecl()) { 3685 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3686 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3687 continue; 3688 3689 if (!Context.hasSameType(NewArray, PrevVDTy)) 3690 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3691 } 3692 } 3693 3694 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3695 if (Context.hasSameType(OldArray->getElementType(), 3696 NewArray->getElementType())) 3697 MergedT = New->getType(); 3698 } 3699 // FIXME: Check visibility. New is hidden but has a complete type. If New 3700 // has no array bound, it should not inherit one from Old, if Old is not 3701 // visible. 3702 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3703 if (Context.hasSameType(OldArray->getElementType(), 3704 NewArray->getElementType())) 3705 MergedT = Old->getType(); 3706 } 3707 } 3708 else if (New->getType()->isObjCObjectPointerType() && 3709 Old->getType()->isObjCObjectPointerType()) { 3710 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3711 Old->getType()); 3712 } 3713 } else { 3714 // C 6.2.7p2: 3715 // All declarations that refer to the same object or function shall have 3716 // compatible type. 3717 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3718 } 3719 if (MergedT.isNull()) { 3720 // It's OK if we couldn't merge types if either type is dependent, for a 3721 // block-scope variable. In other cases (static data members of class 3722 // templates, variable templates, ...), we require the types to be 3723 // equivalent. 3724 // FIXME: The C++ standard doesn't say anything about this. 3725 if ((New->getType()->isDependentType() || 3726 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3727 // If the old type was dependent, we can't merge with it, so the new type 3728 // becomes dependent for now. We'll reproduce the original type when we 3729 // instantiate the TypeSourceInfo for the variable. 3730 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3731 New->setType(Context.DependentTy); 3732 return; 3733 } 3734 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3735 } 3736 3737 // Don't actually update the type on the new declaration if the old 3738 // declaration was an extern declaration in a different scope. 3739 if (MergeTypeWithOld) 3740 New->setType(MergedT); 3741 } 3742 3743 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3744 LookupResult &Previous) { 3745 // C11 6.2.7p4: 3746 // For an identifier with internal or external linkage declared 3747 // in a scope in which a prior declaration of that identifier is 3748 // visible, if the prior declaration specifies internal or 3749 // external linkage, the type of the identifier at the later 3750 // declaration becomes the composite type. 3751 // 3752 // If the variable isn't visible, we do not merge with its type. 3753 if (Previous.isShadowed()) 3754 return false; 3755 3756 if (S.getLangOpts().CPlusPlus) { 3757 // C++11 [dcl.array]p3: 3758 // If there is a preceding declaration of the entity in the same 3759 // scope in which the bound was specified, an omitted array bound 3760 // is taken to be the same as in that earlier declaration. 3761 return NewVD->isPreviousDeclInSameBlockScope() || 3762 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3763 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3764 } else { 3765 // If the old declaration was function-local, don't merge with its 3766 // type unless we're in the same function. 3767 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3768 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3769 } 3770 } 3771 3772 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3773 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3774 /// situation, merging decls or emitting diagnostics as appropriate. 3775 /// 3776 /// Tentative definition rules (C99 6.9.2p2) are checked by 3777 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3778 /// definitions here, since the initializer hasn't been attached. 3779 /// 3780 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3781 // If the new decl is already invalid, don't do any other checking. 3782 if (New->isInvalidDecl()) 3783 return; 3784 3785 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3786 return; 3787 3788 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3789 3790 // Verify the old decl was also a variable or variable template. 3791 VarDecl *Old = nullptr; 3792 VarTemplateDecl *OldTemplate = nullptr; 3793 if (Previous.isSingleResult()) { 3794 if (NewTemplate) { 3795 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3796 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3797 3798 if (auto *Shadow = 3799 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3800 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3801 return New->setInvalidDecl(); 3802 } else { 3803 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3804 3805 if (auto *Shadow = 3806 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3807 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3808 return New->setInvalidDecl(); 3809 } 3810 } 3811 if (!Old) { 3812 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3813 << New->getDeclName(); 3814 notePreviousDefinition(Previous.getRepresentativeDecl(), 3815 New->getLocation()); 3816 return New->setInvalidDecl(); 3817 } 3818 3819 // Ensure the template parameters are compatible. 3820 if (NewTemplate && 3821 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3822 OldTemplate->getTemplateParameters(), 3823 /*Complain=*/true, TPL_TemplateMatch)) 3824 return New->setInvalidDecl(); 3825 3826 // C++ [class.mem]p1: 3827 // A member shall not be declared twice in the member-specification [...] 3828 // 3829 // Here, we need only consider static data members. 3830 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3831 Diag(New->getLocation(), diag::err_duplicate_member) 3832 << New->getIdentifier(); 3833 Diag(Old->getLocation(), diag::note_previous_declaration); 3834 New->setInvalidDecl(); 3835 } 3836 3837 mergeDeclAttributes(New, Old); 3838 // Warn if an already-declared variable is made a weak_import in a subsequent 3839 // declaration 3840 if (New->hasAttr<WeakImportAttr>() && 3841 Old->getStorageClass() == SC_None && 3842 !Old->hasAttr<WeakImportAttr>()) { 3843 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3844 notePreviousDefinition(Old, New->getLocation()); 3845 // Remove weak_import attribute on new declaration. 3846 New->dropAttr<WeakImportAttr>(); 3847 } 3848 3849 if (New->hasAttr<InternalLinkageAttr>() && 3850 !Old->hasAttr<InternalLinkageAttr>()) { 3851 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3852 << New->getDeclName(); 3853 notePreviousDefinition(Old, New->getLocation()); 3854 New->dropAttr<InternalLinkageAttr>(); 3855 } 3856 3857 // Merge the types. 3858 VarDecl *MostRecent = Old->getMostRecentDecl(); 3859 if (MostRecent != Old) { 3860 MergeVarDeclTypes(New, MostRecent, 3861 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3862 if (New->isInvalidDecl()) 3863 return; 3864 } 3865 3866 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3867 if (New->isInvalidDecl()) 3868 return; 3869 3870 diag::kind PrevDiag; 3871 SourceLocation OldLocation; 3872 std::tie(PrevDiag, OldLocation) = 3873 getNoteDiagForInvalidRedeclaration(Old, New); 3874 3875 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3876 if (New->getStorageClass() == SC_Static && 3877 !New->isStaticDataMember() && 3878 Old->hasExternalFormalLinkage()) { 3879 if (getLangOpts().MicrosoftExt) { 3880 Diag(New->getLocation(), diag::ext_static_non_static) 3881 << New->getDeclName(); 3882 Diag(OldLocation, PrevDiag); 3883 } else { 3884 Diag(New->getLocation(), diag::err_static_non_static) 3885 << New->getDeclName(); 3886 Diag(OldLocation, PrevDiag); 3887 return New->setInvalidDecl(); 3888 } 3889 } 3890 // C99 6.2.2p4: 3891 // For an identifier declared with the storage-class specifier 3892 // extern in a scope in which a prior declaration of that 3893 // identifier is visible,23) if the prior declaration specifies 3894 // internal or external linkage, the linkage of the identifier at 3895 // the later declaration is the same as the linkage specified at 3896 // the prior declaration. If no prior declaration is visible, or 3897 // if the prior declaration specifies no linkage, then the 3898 // identifier has external linkage. 3899 if (New->hasExternalStorage() && Old->hasLinkage()) 3900 /* Okay */; 3901 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3902 !New->isStaticDataMember() && 3903 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3904 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3905 Diag(OldLocation, PrevDiag); 3906 return New->setInvalidDecl(); 3907 } 3908 3909 // Check if extern is followed by non-extern and vice-versa. 3910 if (New->hasExternalStorage() && 3911 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3912 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3913 Diag(OldLocation, PrevDiag); 3914 return New->setInvalidDecl(); 3915 } 3916 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3917 !New->hasExternalStorage()) { 3918 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3919 Diag(OldLocation, PrevDiag); 3920 return New->setInvalidDecl(); 3921 } 3922 3923 if (CheckRedeclarationModuleOwnership(New, Old)) 3924 return; 3925 3926 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3927 3928 // FIXME: The test for external storage here seems wrong? We still 3929 // need to check for mismatches. 3930 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3931 // Don't complain about out-of-line definitions of static members. 3932 !(Old->getLexicalDeclContext()->isRecord() && 3933 !New->getLexicalDeclContext()->isRecord())) { 3934 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3935 Diag(OldLocation, PrevDiag); 3936 return New->setInvalidDecl(); 3937 } 3938 3939 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3940 if (VarDecl *Def = Old->getDefinition()) { 3941 // C++1z [dcl.fcn.spec]p4: 3942 // If the definition of a variable appears in a translation unit before 3943 // its first declaration as inline, the program is ill-formed. 3944 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3945 Diag(Def->getLocation(), diag::note_previous_definition); 3946 } 3947 } 3948 3949 // If this redeclaration makes the variable inline, we may need to add it to 3950 // UndefinedButUsed. 3951 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3952 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3953 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3954 SourceLocation())); 3955 3956 if (New->getTLSKind() != Old->getTLSKind()) { 3957 if (!Old->getTLSKind()) { 3958 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3959 Diag(OldLocation, PrevDiag); 3960 } else if (!New->getTLSKind()) { 3961 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3962 Diag(OldLocation, PrevDiag); 3963 } else { 3964 // Do not allow redeclaration to change the variable between requiring 3965 // static and dynamic initialization. 3966 // FIXME: GCC allows this, but uses the TLS keyword on the first 3967 // declaration to determine the kind. Do we need to be compatible here? 3968 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3969 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3970 Diag(OldLocation, PrevDiag); 3971 } 3972 } 3973 3974 // C++ doesn't have tentative definitions, so go right ahead and check here. 3975 if (getLangOpts().CPlusPlus && 3976 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3977 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3978 Old->getCanonicalDecl()->isConstexpr()) { 3979 // This definition won't be a definition any more once it's been merged. 3980 Diag(New->getLocation(), 3981 diag::warn_deprecated_redundant_constexpr_static_def); 3982 } else if (VarDecl *Def = Old->getDefinition()) { 3983 if (checkVarDeclRedefinition(Def, New)) 3984 return; 3985 } 3986 } 3987 3988 if (haveIncompatibleLanguageLinkages(Old, New)) { 3989 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3990 Diag(OldLocation, PrevDiag); 3991 New->setInvalidDecl(); 3992 return; 3993 } 3994 3995 // Merge "used" flag. 3996 if (Old->getMostRecentDecl()->isUsed(false)) 3997 New->setIsUsed(); 3998 3999 // Keep a chain of previous declarations. 4000 New->setPreviousDecl(Old); 4001 if (NewTemplate) 4002 NewTemplate->setPreviousDecl(OldTemplate); 4003 adjustDeclContextForDeclaratorDecl(New, Old); 4004 4005 // Inherit access appropriately. 4006 New->setAccess(Old->getAccess()); 4007 if (NewTemplate) 4008 NewTemplate->setAccess(New->getAccess()); 4009 4010 if (Old->isInline()) 4011 New->setImplicitlyInline(); 4012 } 4013 4014 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4015 SourceManager &SrcMgr = getSourceManager(); 4016 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4017 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4018 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4019 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4020 auto &HSI = PP.getHeaderSearchInfo(); 4021 StringRef HdrFilename = 4022 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4023 4024 auto noteFromModuleOrInclude = [&](Module *Mod, 4025 SourceLocation IncLoc) -> bool { 4026 // Redefinition errors with modules are common with non modular mapped 4027 // headers, example: a non-modular header H in module A that also gets 4028 // included directly in a TU. Pointing twice to the same header/definition 4029 // is confusing, try to get better diagnostics when modules is on. 4030 if (IncLoc.isValid()) { 4031 if (Mod) { 4032 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4033 << HdrFilename.str() << Mod->getFullModuleName(); 4034 if (!Mod->DefinitionLoc.isInvalid()) 4035 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4036 << Mod->getFullModuleName(); 4037 } else { 4038 Diag(IncLoc, diag::note_redefinition_include_same_file) 4039 << HdrFilename.str(); 4040 } 4041 return true; 4042 } 4043 4044 return false; 4045 }; 4046 4047 // Is it the same file and same offset? Provide more information on why 4048 // this leads to a redefinition error. 4049 bool EmittedDiag = false; 4050 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4051 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4052 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4053 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4054 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4055 4056 // If the header has no guards, emit a note suggesting one. 4057 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4058 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4059 4060 if (EmittedDiag) 4061 return; 4062 } 4063 4064 // Redefinition coming from different files or couldn't do better above. 4065 if (Old->getLocation().isValid()) 4066 Diag(Old->getLocation(), diag::note_previous_definition); 4067 } 4068 4069 /// We've just determined that \p Old and \p New both appear to be definitions 4070 /// of the same variable. Either diagnose or fix the problem. 4071 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4072 if (!hasVisibleDefinition(Old) && 4073 (New->getFormalLinkage() == InternalLinkage || 4074 New->isInline() || 4075 New->getDescribedVarTemplate() || 4076 New->getNumTemplateParameterLists() || 4077 New->getDeclContext()->isDependentContext())) { 4078 // The previous definition is hidden, and multiple definitions are 4079 // permitted (in separate TUs). Demote this to a declaration. 4080 New->demoteThisDefinitionToDeclaration(); 4081 4082 // Make the canonical definition visible. 4083 if (auto *OldTD = Old->getDescribedVarTemplate()) 4084 makeMergedDefinitionVisible(OldTD); 4085 makeMergedDefinitionVisible(Old); 4086 return false; 4087 } else { 4088 Diag(New->getLocation(), diag::err_redefinition) << New; 4089 notePreviousDefinition(Old, New->getLocation()); 4090 New->setInvalidDecl(); 4091 return true; 4092 } 4093 } 4094 4095 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4096 /// no declarator (e.g. "struct foo;") is parsed. 4097 Decl * 4098 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4099 RecordDecl *&AnonRecord) { 4100 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4101 AnonRecord); 4102 } 4103 4104 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4105 // disambiguate entities defined in different scopes. 4106 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4107 // compatibility. 4108 // We will pick our mangling number depending on which version of MSVC is being 4109 // targeted. 4110 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4111 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4112 ? S->getMSCurManglingNumber() 4113 : S->getMSLastManglingNumber(); 4114 } 4115 4116 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4117 if (!Context.getLangOpts().CPlusPlus) 4118 return; 4119 4120 if (isa<CXXRecordDecl>(Tag->getParent())) { 4121 // If this tag is the direct child of a class, number it if 4122 // it is anonymous. 4123 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4124 return; 4125 MangleNumberingContext &MCtx = 4126 Context.getManglingNumberContext(Tag->getParent()); 4127 Context.setManglingNumber( 4128 Tag, MCtx.getManglingNumber( 4129 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4130 return; 4131 } 4132 4133 // If this tag isn't a direct child of a class, number it if it is local. 4134 Decl *ManglingContextDecl; 4135 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4136 Tag->getDeclContext(), ManglingContextDecl)) { 4137 Context.setManglingNumber( 4138 Tag, MCtx->getManglingNumber( 4139 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4140 } 4141 } 4142 4143 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4144 TypedefNameDecl *NewTD) { 4145 if (TagFromDeclSpec->isInvalidDecl()) 4146 return; 4147 4148 // Do nothing if the tag already has a name for linkage purposes. 4149 if (TagFromDeclSpec->hasNameForLinkage()) 4150 return; 4151 4152 // A well-formed anonymous tag must always be a TUK_Definition. 4153 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4154 4155 // The type must match the tag exactly; no qualifiers allowed. 4156 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4157 Context.getTagDeclType(TagFromDeclSpec))) { 4158 if (getLangOpts().CPlusPlus) 4159 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4160 return; 4161 } 4162 4163 // If we've already computed linkage for the anonymous tag, then 4164 // adding a typedef name for the anonymous decl can change that 4165 // linkage, which might be a serious problem. Diagnose this as 4166 // unsupported and ignore the typedef name. TODO: we should 4167 // pursue this as a language defect and establish a formal rule 4168 // for how to handle it. 4169 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4170 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4171 4172 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4173 tagLoc = getLocForEndOfToken(tagLoc); 4174 4175 llvm::SmallString<40> textToInsert; 4176 textToInsert += ' '; 4177 textToInsert += NewTD->getIdentifier()->getName(); 4178 Diag(tagLoc, diag::note_typedef_changes_linkage) 4179 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4180 return; 4181 } 4182 4183 // Otherwise, set this is the anon-decl typedef for the tag. 4184 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4185 } 4186 4187 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4188 switch (T) { 4189 case DeclSpec::TST_class: 4190 return 0; 4191 case DeclSpec::TST_struct: 4192 return 1; 4193 case DeclSpec::TST_interface: 4194 return 2; 4195 case DeclSpec::TST_union: 4196 return 3; 4197 case DeclSpec::TST_enum: 4198 return 4; 4199 default: 4200 llvm_unreachable("unexpected type specifier"); 4201 } 4202 } 4203 4204 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4205 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4206 /// parameters to cope with template friend declarations. 4207 Decl * 4208 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4209 MultiTemplateParamsArg TemplateParams, 4210 bool IsExplicitInstantiation, 4211 RecordDecl *&AnonRecord) { 4212 Decl *TagD = nullptr; 4213 TagDecl *Tag = nullptr; 4214 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4215 DS.getTypeSpecType() == DeclSpec::TST_struct || 4216 DS.getTypeSpecType() == DeclSpec::TST_interface || 4217 DS.getTypeSpecType() == DeclSpec::TST_union || 4218 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4219 TagD = DS.getRepAsDecl(); 4220 4221 if (!TagD) // We probably had an error 4222 return nullptr; 4223 4224 // Note that the above type specs guarantee that the 4225 // type rep is a Decl, whereas in many of the others 4226 // it's a Type. 4227 if (isa<TagDecl>(TagD)) 4228 Tag = cast<TagDecl>(TagD); 4229 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4230 Tag = CTD->getTemplatedDecl(); 4231 } 4232 4233 if (Tag) { 4234 handleTagNumbering(Tag, S); 4235 Tag->setFreeStanding(); 4236 if (Tag->isInvalidDecl()) 4237 return Tag; 4238 } 4239 4240 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4241 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4242 // or incomplete types shall not be restrict-qualified." 4243 if (TypeQuals & DeclSpec::TQ_restrict) 4244 Diag(DS.getRestrictSpecLoc(), 4245 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4246 << DS.getSourceRange(); 4247 } 4248 4249 if (DS.isInlineSpecified()) 4250 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4251 << getLangOpts().CPlusPlus17; 4252 4253 if (DS.isConstexprSpecified()) { 4254 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4255 // and definitions of functions and variables. 4256 if (Tag) 4257 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4258 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4259 else 4260 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4261 // Don't emit warnings after this error. 4262 return TagD; 4263 } 4264 4265 DiagnoseFunctionSpecifiers(DS); 4266 4267 if (DS.isFriendSpecified()) { 4268 // If we're dealing with a decl but not a TagDecl, assume that 4269 // whatever routines created it handled the friendship aspect. 4270 if (TagD && !Tag) 4271 return nullptr; 4272 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4273 } 4274 4275 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4276 bool IsExplicitSpecialization = 4277 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4278 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4279 !IsExplicitInstantiation && !IsExplicitSpecialization && 4280 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4281 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4282 // nested-name-specifier unless it is an explicit instantiation 4283 // or an explicit specialization. 4284 // 4285 // FIXME: We allow class template partial specializations here too, per the 4286 // obvious intent of DR1819. 4287 // 4288 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4289 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4290 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4291 return nullptr; 4292 } 4293 4294 // Track whether this decl-specifier declares anything. 4295 bool DeclaresAnything = true; 4296 4297 // Handle anonymous struct definitions. 4298 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4299 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4300 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4301 if (getLangOpts().CPlusPlus || 4302 Record->getDeclContext()->isRecord()) { 4303 // If CurContext is a DeclContext that can contain statements, 4304 // RecursiveASTVisitor won't visit the decls that 4305 // BuildAnonymousStructOrUnion() will put into CurContext. 4306 // Also store them here so that they can be part of the 4307 // DeclStmt that gets created in this case. 4308 // FIXME: Also return the IndirectFieldDecls created by 4309 // BuildAnonymousStructOr union, for the same reason? 4310 if (CurContext->isFunctionOrMethod()) 4311 AnonRecord = Record; 4312 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4313 Context.getPrintingPolicy()); 4314 } 4315 4316 DeclaresAnything = false; 4317 } 4318 } 4319 4320 // C11 6.7.2.1p2: 4321 // A struct-declaration that does not declare an anonymous structure or 4322 // anonymous union shall contain a struct-declarator-list. 4323 // 4324 // This rule also existed in C89 and C99; the grammar for struct-declaration 4325 // did not permit a struct-declaration without a struct-declarator-list. 4326 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4327 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4328 // Check for Microsoft C extension: anonymous struct/union member. 4329 // Handle 2 kinds of anonymous struct/union: 4330 // struct STRUCT; 4331 // union UNION; 4332 // and 4333 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4334 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4335 if ((Tag && Tag->getDeclName()) || 4336 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4337 RecordDecl *Record = nullptr; 4338 if (Tag) 4339 Record = dyn_cast<RecordDecl>(Tag); 4340 else if (const RecordType *RT = 4341 DS.getRepAsType().get()->getAsStructureType()) 4342 Record = RT->getDecl(); 4343 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4344 Record = UT->getDecl(); 4345 4346 if (Record && getLangOpts().MicrosoftExt) { 4347 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4348 << Record->isUnion() << DS.getSourceRange(); 4349 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4350 } 4351 4352 DeclaresAnything = false; 4353 } 4354 } 4355 4356 // Skip all the checks below if we have a type error. 4357 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4358 (TagD && TagD->isInvalidDecl())) 4359 return TagD; 4360 4361 if (getLangOpts().CPlusPlus && 4362 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4363 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4364 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4365 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4366 DeclaresAnything = false; 4367 4368 if (!DS.isMissingDeclaratorOk()) { 4369 // Customize diagnostic for a typedef missing a name. 4370 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4371 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4372 << DS.getSourceRange(); 4373 else 4374 DeclaresAnything = false; 4375 } 4376 4377 if (DS.isModulePrivateSpecified() && 4378 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4379 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4380 << Tag->getTagKind() 4381 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4382 4383 ActOnDocumentableDecl(TagD); 4384 4385 // C 6.7/2: 4386 // A declaration [...] shall declare at least a declarator [...], a tag, 4387 // or the members of an enumeration. 4388 // C++ [dcl.dcl]p3: 4389 // [If there are no declarators], and except for the declaration of an 4390 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4391 // names into the program, or shall redeclare a name introduced by a 4392 // previous declaration. 4393 if (!DeclaresAnything) { 4394 // In C, we allow this as a (popular) extension / bug. Don't bother 4395 // producing further diagnostics for redundant qualifiers after this. 4396 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4397 return TagD; 4398 } 4399 4400 // C++ [dcl.stc]p1: 4401 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4402 // init-declarator-list of the declaration shall not be empty. 4403 // C++ [dcl.fct.spec]p1: 4404 // If a cv-qualifier appears in a decl-specifier-seq, the 4405 // init-declarator-list of the declaration shall not be empty. 4406 // 4407 // Spurious qualifiers here appear to be valid in C. 4408 unsigned DiagID = diag::warn_standalone_specifier; 4409 if (getLangOpts().CPlusPlus) 4410 DiagID = diag::ext_standalone_specifier; 4411 4412 // Note that a linkage-specification sets a storage class, but 4413 // 'extern "C" struct foo;' is actually valid and not theoretically 4414 // useless. 4415 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4416 if (SCS == DeclSpec::SCS_mutable) 4417 // Since mutable is not a viable storage class specifier in C, there is 4418 // no reason to treat it as an extension. Instead, diagnose as an error. 4419 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4420 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4421 Diag(DS.getStorageClassSpecLoc(), DiagID) 4422 << DeclSpec::getSpecifierName(SCS); 4423 } 4424 4425 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4426 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4427 << DeclSpec::getSpecifierName(TSCS); 4428 if (DS.getTypeQualifiers()) { 4429 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4430 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4431 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4432 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4433 // Restrict is covered above. 4434 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4435 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4436 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4437 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4438 } 4439 4440 // Warn about ignored type attributes, for example: 4441 // __attribute__((aligned)) struct A; 4442 // Attributes should be placed after tag to apply to type declaration. 4443 if (!DS.getAttributes().empty()) { 4444 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4445 if (TypeSpecType == DeclSpec::TST_class || 4446 TypeSpecType == DeclSpec::TST_struct || 4447 TypeSpecType == DeclSpec::TST_interface || 4448 TypeSpecType == DeclSpec::TST_union || 4449 TypeSpecType == DeclSpec::TST_enum) { 4450 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4451 attrs = attrs->getNext()) 4452 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4453 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4454 } 4455 } 4456 4457 return TagD; 4458 } 4459 4460 /// We are trying to inject an anonymous member into the given scope; 4461 /// check if there's an existing declaration that can't be overloaded. 4462 /// 4463 /// \return true if this is a forbidden redeclaration 4464 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4465 Scope *S, 4466 DeclContext *Owner, 4467 DeclarationName Name, 4468 SourceLocation NameLoc, 4469 bool IsUnion) { 4470 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4471 Sema::ForVisibleRedeclaration); 4472 if (!SemaRef.LookupName(R, S)) return false; 4473 4474 // Pick a representative declaration. 4475 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4476 assert(PrevDecl && "Expected a non-null Decl"); 4477 4478 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4479 return false; 4480 4481 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4482 << IsUnion << Name; 4483 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4484 4485 return true; 4486 } 4487 4488 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4489 /// anonymous struct or union AnonRecord into the owning context Owner 4490 /// and scope S. This routine will be invoked just after we realize 4491 /// that an unnamed union or struct is actually an anonymous union or 4492 /// struct, e.g., 4493 /// 4494 /// @code 4495 /// union { 4496 /// int i; 4497 /// float f; 4498 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4499 /// // f into the surrounding scope.x 4500 /// @endcode 4501 /// 4502 /// This routine is recursive, injecting the names of nested anonymous 4503 /// structs/unions into the owning context and scope as well. 4504 static bool 4505 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4506 RecordDecl *AnonRecord, AccessSpecifier AS, 4507 SmallVectorImpl<NamedDecl *> &Chaining) { 4508 bool Invalid = false; 4509 4510 // Look every FieldDecl and IndirectFieldDecl with a name. 4511 for (auto *D : AnonRecord->decls()) { 4512 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4513 cast<NamedDecl>(D)->getDeclName()) { 4514 ValueDecl *VD = cast<ValueDecl>(D); 4515 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4516 VD->getLocation(), 4517 AnonRecord->isUnion())) { 4518 // C++ [class.union]p2: 4519 // The names of the members of an anonymous union shall be 4520 // distinct from the names of any other entity in the 4521 // scope in which the anonymous union is declared. 4522 Invalid = true; 4523 } else { 4524 // C++ [class.union]p2: 4525 // For the purpose of name lookup, after the anonymous union 4526 // definition, the members of the anonymous union are 4527 // considered to have been defined in the scope in which the 4528 // anonymous union is declared. 4529 unsigned OldChainingSize = Chaining.size(); 4530 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4531 Chaining.append(IF->chain_begin(), IF->chain_end()); 4532 else 4533 Chaining.push_back(VD); 4534 4535 assert(Chaining.size() >= 2); 4536 NamedDecl **NamedChain = 4537 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4538 for (unsigned i = 0; i < Chaining.size(); i++) 4539 NamedChain[i] = Chaining[i]; 4540 4541 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4542 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4543 VD->getType(), {NamedChain, Chaining.size()}); 4544 4545 for (const auto *Attr : VD->attrs()) 4546 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4547 4548 IndirectField->setAccess(AS); 4549 IndirectField->setImplicit(); 4550 SemaRef.PushOnScopeChains(IndirectField, S); 4551 4552 // That includes picking up the appropriate access specifier. 4553 if (AS != AS_none) IndirectField->setAccess(AS); 4554 4555 Chaining.resize(OldChainingSize); 4556 } 4557 } 4558 } 4559 4560 return Invalid; 4561 } 4562 4563 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4564 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4565 /// illegal input values are mapped to SC_None. 4566 static StorageClass 4567 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4568 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4569 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4570 "Parser allowed 'typedef' as storage class VarDecl."); 4571 switch (StorageClassSpec) { 4572 case DeclSpec::SCS_unspecified: return SC_None; 4573 case DeclSpec::SCS_extern: 4574 if (DS.isExternInLinkageSpec()) 4575 return SC_None; 4576 return SC_Extern; 4577 case DeclSpec::SCS_static: return SC_Static; 4578 case DeclSpec::SCS_auto: return SC_Auto; 4579 case DeclSpec::SCS_register: return SC_Register; 4580 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4581 // Illegal SCSs map to None: error reporting is up to the caller. 4582 case DeclSpec::SCS_mutable: // Fall through. 4583 case DeclSpec::SCS_typedef: return SC_None; 4584 } 4585 llvm_unreachable("unknown storage class specifier"); 4586 } 4587 4588 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4589 assert(Record->hasInClassInitializer()); 4590 4591 for (const auto *I : Record->decls()) { 4592 const auto *FD = dyn_cast<FieldDecl>(I); 4593 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4594 FD = IFD->getAnonField(); 4595 if (FD && FD->hasInClassInitializer()) 4596 return FD->getLocation(); 4597 } 4598 4599 llvm_unreachable("couldn't find in-class initializer"); 4600 } 4601 4602 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4603 SourceLocation DefaultInitLoc) { 4604 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4605 return; 4606 4607 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4608 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4609 } 4610 4611 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4612 CXXRecordDecl *AnonUnion) { 4613 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4614 return; 4615 4616 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4617 } 4618 4619 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4620 /// anonymous structure or union. Anonymous unions are a C++ feature 4621 /// (C++ [class.union]) and a C11 feature; anonymous structures 4622 /// are a C11 feature and GNU C++ extension. 4623 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4624 AccessSpecifier AS, 4625 RecordDecl *Record, 4626 const PrintingPolicy &Policy) { 4627 DeclContext *Owner = Record->getDeclContext(); 4628 4629 // Diagnose whether this anonymous struct/union is an extension. 4630 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4631 Diag(Record->getLocation(), diag::ext_anonymous_union); 4632 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4633 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4634 else if (!Record->isUnion() && !getLangOpts().C11) 4635 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4636 4637 // C and C++ require different kinds of checks for anonymous 4638 // structs/unions. 4639 bool Invalid = false; 4640 if (getLangOpts().CPlusPlus) { 4641 const char *PrevSpec = nullptr; 4642 unsigned DiagID; 4643 if (Record->isUnion()) { 4644 // C++ [class.union]p6: 4645 // Anonymous unions declared in a named namespace or in the 4646 // global namespace shall be declared static. 4647 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4648 (isa<TranslationUnitDecl>(Owner) || 4649 (isa<NamespaceDecl>(Owner) && 4650 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4651 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4652 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4653 4654 // Recover by adding 'static'. 4655 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4656 PrevSpec, DiagID, Policy); 4657 } 4658 // C++ [class.union]p6: 4659 // A storage class is not allowed in a declaration of an 4660 // anonymous union in a class scope. 4661 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4662 isa<RecordDecl>(Owner)) { 4663 Diag(DS.getStorageClassSpecLoc(), 4664 diag::err_anonymous_union_with_storage_spec) 4665 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4666 4667 // Recover by removing the storage specifier. 4668 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4669 SourceLocation(), 4670 PrevSpec, DiagID, Context.getPrintingPolicy()); 4671 } 4672 } 4673 4674 // Ignore const/volatile/restrict qualifiers. 4675 if (DS.getTypeQualifiers()) { 4676 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4677 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4678 << Record->isUnion() << "const" 4679 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4680 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4681 Diag(DS.getVolatileSpecLoc(), 4682 diag::ext_anonymous_struct_union_qualified) 4683 << Record->isUnion() << "volatile" 4684 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4685 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4686 Diag(DS.getRestrictSpecLoc(), 4687 diag::ext_anonymous_struct_union_qualified) 4688 << Record->isUnion() << "restrict" 4689 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4690 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4691 Diag(DS.getAtomicSpecLoc(), 4692 diag::ext_anonymous_struct_union_qualified) 4693 << Record->isUnion() << "_Atomic" 4694 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4695 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4696 Diag(DS.getUnalignedSpecLoc(), 4697 diag::ext_anonymous_struct_union_qualified) 4698 << Record->isUnion() << "__unaligned" 4699 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4700 4701 DS.ClearTypeQualifiers(); 4702 } 4703 4704 // C++ [class.union]p2: 4705 // The member-specification of an anonymous union shall only 4706 // define non-static data members. [Note: nested types and 4707 // functions cannot be declared within an anonymous union. ] 4708 for (auto *Mem : Record->decls()) { 4709 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4710 // C++ [class.union]p3: 4711 // An anonymous union shall not have private or protected 4712 // members (clause 11). 4713 assert(FD->getAccess() != AS_none); 4714 if (FD->getAccess() != AS_public) { 4715 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4716 << Record->isUnion() << (FD->getAccess() == AS_protected); 4717 Invalid = true; 4718 } 4719 4720 // C++ [class.union]p1 4721 // An object of a class with a non-trivial constructor, a non-trivial 4722 // copy constructor, a non-trivial destructor, or a non-trivial copy 4723 // assignment operator cannot be a member of a union, nor can an 4724 // array of such objects. 4725 if (CheckNontrivialField(FD)) 4726 Invalid = true; 4727 } else if (Mem->isImplicit()) { 4728 // Any implicit members are fine. 4729 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4730 // This is a type that showed up in an 4731 // elaborated-type-specifier inside the anonymous struct or 4732 // union, but which actually declares a type outside of the 4733 // anonymous struct or union. It's okay. 4734 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4735 if (!MemRecord->isAnonymousStructOrUnion() && 4736 MemRecord->getDeclName()) { 4737 // Visual C++ allows type definition in anonymous struct or union. 4738 if (getLangOpts().MicrosoftExt) 4739 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4740 << Record->isUnion(); 4741 else { 4742 // This is a nested type declaration. 4743 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4744 << Record->isUnion(); 4745 Invalid = true; 4746 } 4747 } else { 4748 // This is an anonymous type definition within another anonymous type. 4749 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4750 // not part of standard C++. 4751 Diag(MemRecord->getLocation(), 4752 diag::ext_anonymous_record_with_anonymous_type) 4753 << Record->isUnion(); 4754 } 4755 } else if (isa<AccessSpecDecl>(Mem)) { 4756 // Any access specifier is fine. 4757 } else if (isa<StaticAssertDecl>(Mem)) { 4758 // In C++1z, static_assert declarations are also fine. 4759 } else { 4760 // We have something that isn't a non-static data 4761 // member. Complain about it. 4762 unsigned DK = diag::err_anonymous_record_bad_member; 4763 if (isa<TypeDecl>(Mem)) 4764 DK = diag::err_anonymous_record_with_type; 4765 else if (isa<FunctionDecl>(Mem)) 4766 DK = diag::err_anonymous_record_with_function; 4767 else if (isa<VarDecl>(Mem)) 4768 DK = diag::err_anonymous_record_with_static; 4769 4770 // Visual C++ allows type definition in anonymous struct or union. 4771 if (getLangOpts().MicrosoftExt && 4772 DK == diag::err_anonymous_record_with_type) 4773 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4774 << Record->isUnion(); 4775 else { 4776 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4777 Invalid = true; 4778 } 4779 } 4780 } 4781 4782 // C++11 [class.union]p8 (DR1460): 4783 // At most one variant member of a union may have a 4784 // brace-or-equal-initializer. 4785 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4786 Owner->isRecord()) 4787 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4788 cast<CXXRecordDecl>(Record)); 4789 } 4790 4791 if (!Record->isUnion() && !Owner->isRecord()) { 4792 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4793 << getLangOpts().CPlusPlus; 4794 Invalid = true; 4795 } 4796 4797 // Mock up a declarator. 4798 Declarator Dc(DS, DeclaratorContext::MemberContext); 4799 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4800 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4801 4802 // Create a declaration for this anonymous struct/union. 4803 NamedDecl *Anon = nullptr; 4804 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4805 Anon = FieldDecl::Create(Context, OwningClass, 4806 DS.getLocStart(), 4807 Record->getLocation(), 4808 /*IdentifierInfo=*/nullptr, 4809 Context.getTypeDeclType(Record), 4810 TInfo, 4811 /*BitWidth=*/nullptr, /*Mutable=*/false, 4812 /*InitStyle=*/ICIS_NoInit); 4813 Anon->setAccess(AS); 4814 if (getLangOpts().CPlusPlus) 4815 FieldCollector->Add(cast<FieldDecl>(Anon)); 4816 } else { 4817 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4818 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4819 if (SCSpec == DeclSpec::SCS_mutable) { 4820 // mutable can only appear on non-static class members, so it's always 4821 // an error here 4822 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4823 Invalid = true; 4824 SC = SC_None; 4825 } 4826 4827 Anon = VarDecl::Create(Context, Owner, 4828 DS.getLocStart(), 4829 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4830 Context.getTypeDeclType(Record), 4831 TInfo, SC); 4832 4833 // Default-initialize the implicit variable. This initialization will be 4834 // trivial in almost all cases, except if a union member has an in-class 4835 // initializer: 4836 // union { int n = 0; }; 4837 ActOnUninitializedDecl(Anon); 4838 } 4839 Anon->setImplicit(); 4840 4841 // Mark this as an anonymous struct/union type. 4842 Record->setAnonymousStructOrUnion(true); 4843 4844 // Add the anonymous struct/union object to the current 4845 // context. We'll be referencing this object when we refer to one of 4846 // its members. 4847 Owner->addDecl(Anon); 4848 4849 // Inject the members of the anonymous struct/union into the owning 4850 // context and into the identifier resolver chain for name lookup 4851 // purposes. 4852 SmallVector<NamedDecl*, 2> Chain; 4853 Chain.push_back(Anon); 4854 4855 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4856 Invalid = true; 4857 4858 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4859 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4860 Decl *ManglingContextDecl; 4861 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4862 NewVD->getDeclContext(), ManglingContextDecl)) { 4863 Context.setManglingNumber( 4864 NewVD, MCtx->getManglingNumber( 4865 NewVD, getMSManglingNumber(getLangOpts(), S))); 4866 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4867 } 4868 } 4869 } 4870 4871 if (Invalid) 4872 Anon->setInvalidDecl(); 4873 4874 return Anon; 4875 } 4876 4877 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4878 /// Microsoft C anonymous structure. 4879 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4880 /// Example: 4881 /// 4882 /// struct A { int a; }; 4883 /// struct B { struct A; int b; }; 4884 /// 4885 /// void foo() { 4886 /// B var; 4887 /// var.a = 3; 4888 /// } 4889 /// 4890 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4891 RecordDecl *Record) { 4892 assert(Record && "expected a record!"); 4893 4894 // Mock up a declarator. 4895 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4896 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4897 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4898 4899 auto *ParentDecl = cast<RecordDecl>(CurContext); 4900 QualType RecTy = Context.getTypeDeclType(Record); 4901 4902 // Create a declaration for this anonymous struct. 4903 NamedDecl *Anon = FieldDecl::Create(Context, 4904 ParentDecl, 4905 DS.getLocStart(), 4906 DS.getLocStart(), 4907 /*IdentifierInfo=*/nullptr, 4908 RecTy, 4909 TInfo, 4910 /*BitWidth=*/nullptr, /*Mutable=*/false, 4911 /*InitStyle=*/ICIS_NoInit); 4912 Anon->setImplicit(); 4913 4914 // Add the anonymous struct object to the current context. 4915 CurContext->addDecl(Anon); 4916 4917 // Inject the members of the anonymous struct into the current 4918 // context and into the identifier resolver chain for name lookup 4919 // purposes. 4920 SmallVector<NamedDecl*, 2> Chain; 4921 Chain.push_back(Anon); 4922 4923 RecordDecl *RecordDef = Record->getDefinition(); 4924 if (RequireCompleteType(Anon->getLocation(), RecTy, 4925 diag::err_field_incomplete) || 4926 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4927 AS_none, Chain)) { 4928 Anon->setInvalidDecl(); 4929 ParentDecl->setInvalidDecl(); 4930 } 4931 4932 return Anon; 4933 } 4934 4935 /// GetNameForDeclarator - Determine the full declaration name for the 4936 /// given Declarator. 4937 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4938 return GetNameFromUnqualifiedId(D.getName()); 4939 } 4940 4941 /// Retrieves the declaration name from a parsed unqualified-id. 4942 DeclarationNameInfo 4943 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4944 DeclarationNameInfo NameInfo; 4945 NameInfo.setLoc(Name.StartLocation); 4946 4947 switch (Name.getKind()) { 4948 4949 case UnqualifiedIdKind::IK_ImplicitSelfParam: 4950 case UnqualifiedIdKind::IK_Identifier: 4951 NameInfo.setName(Name.Identifier); 4952 NameInfo.setLoc(Name.StartLocation); 4953 return NameInfo; 4954 4955 case UnqualifiedIdKind::IK_DeductionGuideName: { 4956 // C++ [temp.deduct.guide]p3: 4957 // The simple-template-id shall name a class template specialization. 4958 // The template-name shall be the same identifier as the template-name 4959 // of the simple-template-id. 4960 // These together intend to imply that the template-name shall name a 4961 // class template. 4962 // FIXME: template<typename T> struct X {}; 4963 // template<typename T> using Y = X<T>; 4964 // Y(int) -> Y<int>; 4965 // satisfies these rules but does not name a class template. 4966 TemplateName TN = Name.TemplateName.get().get(); 4967 auto *Template = TN.getAsTemplateDecl(); 4968 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4969 Diag(Name.StartLocation, 4970 diag::err_deduction_guide_name_not_class_template) 4971 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4972 if (Template) 4973 Diag(Template->getLocation(), diag::note_template_decl_here); 4974 return DeclarationNameInfo(); 4975 } 4976 4977 NameInfo.setName( 4978 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4979 NameInfo.setLoc(Name.StartLocation); 4980 return NameInfo; 4981 } 4982 4983 case UnqualifiedIdKind::IK_OperatorFunctionId: 4984 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4985 Name.OperatorFunctionId.Operator)); 4986 NameInfo.setLoc(Name.StartLocation); 4987 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4988 = Name.OperatorFunctionId.SymbolLocations[0]; 4989 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4990 = Name.EndLocation.getRawEncoding(); 4991 return NameInfo; 4992 4993 case UnqualifiedIdKind::IK_LiteralOperatorId: 4994 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4995 Name.Identifier)); 4996 NameInfo.setLoc(Name.StartLocation); 4997 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4998 return NameInfo; 4999 5000 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5001 TypeSourceInfo *TInfo; 5002 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5003 if (Ty.isNull()) 5004 return DeclarationNameInfo(); 5005 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5006 Context.getCanonicalType(Ty))); 5007 NameInfo.setLoc(Name.StartLocation); 5008 NameInfo.setNamedTypeInfo(TInfo); 5009 return NameInfo; 5010 } 5011 5012 case UnqualifiedIdKind::IK_ConstructorName: { 5013 TypeSourceInfo *TInfo; 5014 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5015 if (Ty.isNull()) 5016 return DeclarationNameInfo(); 5017 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5018 Context.getCanonicalType(Ty))); 5019 NameInfo.setLoc(Name.StartLocation); 5020 NameInfo.setNamedTypeInfo(TInfo); 5021 return NameInfo; 5022 } 5023 5024 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5025 // In well-formed code, we can only have a constructor 5026 // template-id that refers to the current context, so go there 5027 // to find the actual type being constructed. 5028 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5029 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5030 return DeclarationNameInfo(); 5031 5032 // Determine the type of the class being constructed. 5033 QualType CurClassType = Context.getTypeDeclType(CurClass); 5034 5035 // FIXME: Check two things: that the template-id names the same type as 5036 // CurClassType, and that the template-id does not occur when the name 5037 // was qualified. 5038 5039 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5040 Context.getCanonicalType(CurClassType))); 5041 NameInfo.setLoc(Name.StartLocation); 5042 // FIXME: should we retrieve TypeSourceInfo? 5043 NameInfo.setNamedTypeInfo(nullptr); 5044 return NameInfo; 5045 } 5046 5047 case UnqualifiedIdKind::IK_DestructorName: { 5048 TypeSourceInfo *TInfo; 5049 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5050 if (Ty.isNull()) 5051 return DeclarationNameInfo(); 5052 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5053 Context.getCanonicalType(Ty))); 5054 NameInfo.setLoc(Name.StartLocation); 5055 NameInfo.setNamedTypeInfo(TInfo); 5056 return NameInfo; 5057 } 5058 5059 case UnqualifiedIdKind::IK_TemplateId: { 5060 TemplateName TName = Name.TemplateId->Template.get(); 5061 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5062 return Context.getNameForTemplate(TName, TNameLoc); 5063 } 5064 5065 } // switch (Name.getKind()) 5066 5067 llvm_unreachable("Unknown name kind"); 5068 } 5069 5070 static QualType getCoreType(QualType Ty) { 5071 do { 5072 if (Ty->isPointerType() || Ty->isReferenceType()) 5073 Ty = Ty->getPointeeType(); 5074 else if (Ty->isArrayType()) 5075 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5076 else 5077 return Ty.withoutLocalFastQualifiers(); 5078 } while (true); 5079 } 5080 5081 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5082 /// and Definition have "nearly" matching parameters. This heuristic is 5083 /// used to improve diagnostics in the case where an out-of-line function 5084 /// definition doesn't match any declaration within the class or namespace. 5085 /// Also sets Params to the list of indices to the parameters that differ 5086 /// between the declaration and the definition. If hasSimilarParameters 5087 /// returns true and Params is empty, then all of the parameters match. 5088 static bool hasSimilarParameters(ASTContext &Context, 5089 FunctionDecl *Declaration, 5090 FunctionDecl *Definition, 5091 SmallVectorImpl<unsigned> &Params) { 5092 Params.clear(); 5093 if (Declaration->param_size() != Definition->param_size()) 5094 return false; 5095 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5096 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5097 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5098 5099 // The parameter types are identical 5100 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5101 continue; 5102 5103 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5104 QualType DefParamBaseTy = getCoreType(DefParamTy); 5105 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5106 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5107 5108 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5109 (DeclTyName && DeclTyName == DefTyName)) 5110 Params.push_back(Idx); 5111 else // The two parameters aren't even close 5112 return false; 5113 } 5114 5115 return true; 5116 } 5117 5118 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5119 /// declarator needs to be rebuilt in the current instantiation. 5120 /// Any bits of declarator which appear before the name are valid for 5121 /// consideration here. That's specifically the type in the decl spec 5122 /// and the base type in any member-pointer chunks. 5123 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5124 DeclarationName Name) { 5125 // The types we specifically need to rebuild are: 5126 // - typenames, typeofs, and decltypes 5127 // - types which will become injected class names 5128 // Of course, we also need to rebuild any type referencing such a 5129 // type. It's safest to just say "dependent", but we call out a 5130 // few cases here. 5131 5132 DeclSpec &DS = D.getMutableDeclSpec(); 5133 switch (DS.getTypeSpecType()) { 5134 case DeclSpec::TST_typename: 5135 case DeclSpec::TST_typeofType: 5136 case DeclSpec::TST_underlyingType: 5137 case DeclSpec::TST_atomic: { 5138 // Grab the type from the parser. 5139 TypeSourceInfo *TSI = nullptr; 5140 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5141 if (T.isNull() || !T->isDependentType()) break; 5142 5143 // Make sure there's a type source info. This isn't really much 5144 // of a waste; most dependent types should have type source info 5145 // attached already. 5146 if (!TSI) 5147 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5148 5149 // Rebuild the type in the current instantiation. 5150 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5151 if (!TSI) return true; 5152 5153 // Store the new type back in the decl spec. 5154 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5155 DS.UpdateTypeRep(LocType); 5156 break; 5157 } 5158 5159 case DeclSpec::TST_decltype: 5160 case DeclSpec::TST_typeofExpr: { 5161 Expr *E = DS.getRepAsExpr(); 5162 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5163 if (Result.isInvalid()) return true; 5164 DS.UpdateExprRep(Result.get()); 5165 break; 5166 } 5167 5168 default: 5169 // Nothing to do for these decl specs. 5170 break; 5171 } 5172 5173 // It doesn't matter what order we do this in. 5174 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5175 DeclaratorChunk &Chunk = D.getTypeObject(I); 5176 5177 // The only type information in the declarator which can come 5178 // before the declaration name is the base type of a member 5179 // pointer. 5180 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5181 continue; 5182 5183 // Rebuild the scope specifier in-place. 5184 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5185 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5186 return true; 5187 } 5188 5189 return false; 5190 } 5191 5192 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5193 D.setFunctionDefinitionKind(FDK_Declaration); 5194 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5195 5196 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5197 Dcl && Dcl->getDeclContext()->isFileContext()) 5198 Dcl->setTopLevelDeclInObjCContainer(); 5199 5200 if (getLangOpts().OpenCL) 5201 setCurrentOpenCLExtensionForDecl(Dcl); 5202 5203 return Dcl; 5204 } 5205 5206 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5207 /// If T is the name of a class, then each of the following shall have a 5208 /// name different from T: 5209 /// - every static data member of class T; 5210 /// - every member function of class T 5211 /// - every member of class T that is itself a type; 5212 /// \returns true if the declaration name violates these rules. 5213 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5214 DeclarationNameInfo NameInfo) { 5215 DeclarationName Name = NameInfo.getName(); 5216 5217 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5218 while (Record && Record->isAnonymousStructOrUnion()) 5219 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5220 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5221 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5222 return true; 5223 } 5224 5225 return false; 5226 } 5227 5228 /// Diagnose a declaration whose declarator-id has the given 5229 /// nested-name-specifier. 5230 /// 5231 /// \param SS The nested-name-specifier of the declarator-id. 5232 /// 5233 /// \param DC The declaration context to which the nested-name-specifier 5234 /// resolves. 5235 /// 5236 /// \param Name The name of the entity being declared. 5237 /// 5238 /// \param Loc The location of the name of the entity being declared. 5239 /// 5240 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5241 /// we're declaring an explicit / partial specialization / instantiation. 5242 /// 5243 /// \returns true if we cannot safely recover from this error, false otherwise. 5244 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5245 DeclarationName Name, 5246 SourceLocation Loc, bool IsTemplateId) { 5247 DeclContext *Cur = CurContext; 5248 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5249 Cur = Cur->getParent(); 5250 5251 // If the user provided a superfluous scope specifier that refers back to the 5252 // class in which the entity is already declared, diagnose and ignore it. 5253 // 5254 // class X { 5255 // void X::f(); 5256 // }; 5257 // 5258 // Note, it was once ill-formed to give redundant qualification in all 5259 // contexts, but that rule was removed by DR482. 5260 if (Cur->Equals(DC)) { 5261 if (Cur->isRecord()) { 5262 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5263 : diag::err_member_extra_qualification) 5264 << Name << FixItHint::CreateRemoval(SS.getRange()); 5265 SS.clear(); 5266 } else { 5267 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5268 } 5269 return false; 5270 } 5271 5272 // Check whether the qualifying scope encloses the scope of the original 5273 // declaration. For a template-id, we perform the checks in 5274 // CheckTemplateSpecializationScope. 5275 if (!Cur->Encloses(DC) && !IsTemplateId) { 5276 if (Cur->isRecord()) 5277 Diag(Loc, diag::err_member_qualification) 5278 << Name << SS.getRange(); 5279 else if (isa<TranslationUnitDecl>(DC)) 5280 Diag(Loc, diag::err_invalid_declarator_global_scope) 5281 << Name << SS.getRange(); 5282 else if (isa<FunctionDecl>(Cur)) 5283 Diag(Loc, diag::err_invalid_declarator_in_function) 5284 << Name << SS.getRange(); 5285 else if (isa<BlockDecl>(Cur)) 5286 Diag(Loc, diag::err_invalid_declarator_in_block) 5287 << Name << SS.getRange(); 5288 else 5289 Diag(Loc, diag::err_invalid_declarator_scope) 5290 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5291 5292 return true; 5293 } 5294 5295 if (Cur->isRecord()) { 5296 // Cannot qualify members within a class. 5297 Diag(Loc, diag::err_member_qualification) 5298 << Name << SS.getRange(); 5299 SS.clear(); 5300 5301 // C++ constructors and destructors with incorrect scopes can break 5302 // our AST invariants by having the wrong underlying types. If 5303 // that's the case, then drop this declaration entirely. 5304 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5305 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5306 !Context.hasSameType(Name.getCXXNameType(), 5307 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5308 return true; 5309 5310 return false; 5311 } 5312 5313 // C++11 [dcl.meaning]p1: 5314 // [...] "The nested-name-specifier of the qualified declarator-id shall 5315 // not begin with a decltype-specifer" 5316 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5317 while (SpecLoc.getPrefix()) 5318 SpecLoc = SpecLoc.getPrefix(); 5319 if (dyn_cast_or_null<DecltypeType>( 5320 SpecLoc.getNestedNameSpecifier()->getAsType())) 5321 Diag(Loc, diag::err_decltype_in_declarator) 5322 << SpecLoc.getTypeLoc().getSourceRange(); 5323 5324 return false; 5325 } 5326 5327 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5328 MultiTemplateParamsArg TemplateParamLists) { 5329 // TODO: consider using NameInfo for diagnostic. 5330 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5331 DeclarationName Name = NameInfo.getName(); 5332 5333 // All of these full declarators require an identifier. If it doesn't have 5334 // one, the ParsedFreeStandingDeclSpec action should be used. 5335 if (D.isDecompositionDeclarator()) { 5336 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5337 } else if (!Name) { 5338 if (!D.isInvalidType()) // Reject this if we think it is valid. 5339 Diag(D.getDeclSpec().getLocStart(), 5340 diag::err_declarator_need_ident) 5341 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5342 return nullptr; 5343 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5344 return nullptr; 5345 5346 // The scope passed in may not be a decl scope. Zip up the scope tree until 5347 // we find one that is. 5348 while ((S->getFlags() & Scope::DeclScope) == 0 || 5349 (S->getFlags() & Scope::TemplateParamScope) != 0) 5350 S = S->getParent(); 5351 5352 DeclContext *DC = CurContext; 5353 if (D.getCXXScopeSpec().isInvalid()) 5354 D.setInvalidType(); 5355 else if (D.getCXXScopeSpec().isSet()) { 5356 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5357 UPPC_DeclarationQualifier)) 5358 return nullptr; 5359 5360 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5361 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5362 if (!DC || isa<EnumDecl>(DC)) { 5363 // If we could not compute the declaration context, it's because the 5364 // declaration context is dependent but does not refer to a class, 5365 // class template, or class template partial specialization. Complain 5366 // and return early, to avoid the coming semantic disaster. 5367 Diag(D.getIdentifierLoc(), 5368 diag::err_template_qualified_declarator_no_match) 5369 << D.getCXXScopeSpec().getScopeRep() 5370 << D.getCXXScopeSpec().getRange(); 5371 return nullptr; 5372 } 5373 bool IsDependentContext = DC->isDependentContext(); 5374 5375 if (!IsDependentContext && 5376 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5377 return nullptr; 5378 5379 // If a class is incomplete, do not parse entities inside it. 5380 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5381 Diag(D.getIdentifierLoc(), 5382 diag::err_member_def_undefined_record) 5383 << Name << DC << D.getCXXScopeSpec().getRange(); 5384 return nullptr; 5385 } 5386 if (!D.getDeclSpec().isFriendSpecified()) { 5387 if (diagnoseQualifiedDeclaration( 5388 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5389 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5390 if (DC->isRecord()) 5391 return nullptr; 5392 5393 D.setInvalidType(); 5394 } 5395 } 5396 5397 // Check whether we need to rebuild the type of the given 5398 // declaration in the current instantiation. 5399 if (EnteringContext && IsDependentContext && 5400 TemplateParamLists.size() != 0) { 5401 ContextRAII SavedContext(*this, DC); 5402 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5403 D.setInvalidType(); 5404 } 5405 } 5406 5407 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5408 QualType R = TInfo->getType(); 5409 5410 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5411 UPPC_DeclarationType)) 5412 D.setInvalidType(); 5413 5414 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5415 forRedeclarationInCurContext()); 5416 5417 // See if this is a redefinition of a variable in the same scope. 5418 if (!D.getCXXScopeSpec().isSet()) { 5419 bool IsLinkageLookup = false; 5420 bool CreateBuiltins = false; 5421 5422 // If the declaration we're planning to build will be a function 5423 // or object with linkage, then look for another declaration with 5424 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5425 // 5426 // If the declaration we're planning to build will be declared with 5427 // external linkage in the translation unit, create any builtin with 5428 // the same name. 5429 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5430 /* Do nothing*/; 5431 else if (CurContext->isFunctionOrMethod() && 5432 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5433 R->isFunctionType())) { 5434 IsLinkageLookup = true; 5435 CreateBuiltins = 5436 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5437 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5438 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5439 CreateBuiltins = true; 5440 5441 if (IsLinkageLookup) { 5442 Previous.clear(LookupRedeclarationWithLinkage); 5443 Previous.setRedeclarationKind(ForExternalRedeclaration); 5444 } 5445 5446 LookupName(Previous, S, CreateBuiltins); 5447 } else { // Something like "int foo::x;" 5448 LookupQualifiedName(Previous, DC); 5449 5450 // C++ [dcl.meaning]p1: 5451 // When the declarator-id is qualified, the declaration shall refer to a 5452 // previously declared member of the class or namespace to which the 5453 // qualifier refers (or, in the case of a namespace, of an element of the 5454 // inline namespace set of that namespace (7.3.1)) or to a specialization 5455 // thereof; [...] 5456 // 5457 // Note that we already checked the context above, and that we do not have 5458 // enough information to make sure that Previous contains the declaration 5459 // we want to match. For example, given: 5460 // 5461 // class X { 5462 // void f(); 5463 // void f(float); 5464 // }; 5465 // 5466 // void X::f(int) { } // ill-formed 5467 // 5468 // In this case, Previous will point to the overload set 5469 // containing the two f's declared in X, but neither of them 5470 // matches. 5471 5472 // C++ [dcl.meaning]p1: 5473 // [...] the member shall not merely have been introduced by a 5474 // using-declaration in the scope of the class or namespace nominated by 5475 // the nested-name-specifier of the declarator-id. 5476 RemoveUsingDecls(Previous); 5477 } 5478 5479 if (Previous.isSingleResult() && 5480 Previous.getFoundDecl()->isTemplateParameter()) { 5481 // Maybe we will complain about the shadowed template parameter. 5482 if (!D.isInvalidType()) 5483 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5484 Previous.getFoundDecl()); 5485 5486 // Just pretend that we didn't see the previous declaration. 5487 Previous.clear(); 5488 } 5489 5490 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5491 // Forget that the previous declaration is the injected-class-name. 5492 Previous.clear(); 5493 5494 // In C++, the previous declaration we find might be a tag type 5495 // (class or enum). In this case, the new declaration will hide the 5496 // tag type. Note that this applies to functions, function templates, and 5497 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5498 if (Previous.isSingleTagDecl() && 5499 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5500 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5501 Previous.clear(); 5502 5503 // Check that there are no default arguments other than in the parameters 5504 // of a function declaration (C++ only). 5505 if (getLangOpts().CPlusPlus) 5506 CheckExtraCXXDefaultArguments(D); 5507 5508 NamedDecl *New; 5509 5510 bool AddToScope = true; 5511 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5512 if (TemplateParamLists.size()) { 5513 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5514 return nullptr; 5515 } 5516 5517 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5518 } else if (R->isFunctionType()) { 5519 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5520 TemplateParamLists, 5521 AddToScope); 5522 } else { 5523 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5524 AddToScope); 5525 } 5526 5527 if (!New) 5528 return nullptr; 5529 5530 // If this has an identifier and is not a function template specialization, 5531 // add it to the scope stack. 5532 if (New->getDeclName() && AddToScope) { 5533 // Only make a locally-scoped extern declaration visible if it is the first 5534 // declaration of this entity. Qualified lookup for such an entity should 5535 // only find this declaration if there is no visible declaration of it. 5536 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5537 PushOnScopeChains(New, S, AddToContext); 5538 if (!AddToContext) 5539 CurContext->addHiddenDecl(New); 5540 } 5541 5542 if (isInOpenMPDeclareTargetContext()) 5543 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5544 5545 return New; 5546 } 5547 5548 /// Helper method to turn variable array types into constant array 5549 /// types in certain situations which would otherwise be errors (for 5550 /// GCC compatibility). 5551 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5552 ASTContext &Context, 5553 bool &SizeIsNegative, 5554 llvm::APSInt &Oversized) { 5555 // This method tries to turn a variable array into a constant 5556 // array even when the size isn't an ICE. This is necessary 5557 // for compatibility with code that depends on gcc's buggy 5558 // constant expression folding, like struct {char x[(int)(char*)2];} 5559 SizeIsNegative = false; 5560 Oversized = 0; 5561 5562 if (T->isDependentType()) 5563 return QualType(); 5564 5565 QualifierCollector Qs; 5566 const Type *Ty = Qs.strip(T); 5567 5568 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5569 QualType Pointee = PTy->getPointeeType(); 5570 QualType FixedType = 5571 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5572 Oversized); 5573 if (FixedType.isNull()) return FixedType; 5574 FixedType = Context.getPointerType(FixedType); 5575 return Qs.apply(Context, FixedType); 5576 } 5577 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5578 QualType Inner = PTy->getInnerType(); 5579 QualType FixedType = 5580 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5581 Oversized); 5582 if (FixedType.isNull()) return FixedType; 5583 FixedType = Context.getParenType(FixedType); 5584 return Qs.apply(Context, FixedType); 5585 } 5586 5587 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5588 if (!VLATy) 5589 return QualType(); 5590 // FIXME: We should probably handle this case 5591 if (VLATy->getElementType()->isVariablyModifiedType()) 5592 return QualType(); 5593 5594 llvm::APSInt Res; 5595 if (!VLATy->getSizeExpr() || 5596 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5597 return QualType(); 5598 5599 // Check whether the array size is negative. 5600 if (Res.isSigned() && Res.isNegative()) { 5601 SizeIsNegative = true; 5602 return QualType(); 5603 } 5604 5605 // Check whether the array is too large to be addressed. 5606 unsigned ActiveSizeBits 5607 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5608 Res); 5609 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5610 Oversized = Res; 5611 return QualType(); 5612 } 5613 5614 return Context.getConstantArrayType(VLATy->getElementType(), 5615 Res, ArrayType::Normal, 0); 5616 } 5617 5618 static void 5619 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5620 SrcTL = SrcTL.getUnqualifiedLoc(); 5621 DstTL = DstTL.getUnqualifiedLoc(); 5622 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5623 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5624 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5625 DstPTL.getPointeeLoc()); 5626 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5627 return; 5628 } 5629 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5630 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5631 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5632 DstPTL.getInnerLoc()); 5633 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5634 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5635 return; 5636 } 5637 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5638 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5639 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5640 TypeLoc DstElemTL = DstATL.getElementLoc(); 5641 DstElemTL.initializeFullCopy(SrcElemTL); 5642 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5643 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5644 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5645 } 5646 5647 /// Helper method to turn variable array types into constant array 5648 /// types in certain situations which would otherwise be errors (for 5649 /// GCC compatibility). 5650 static TypeSourceInfo* 5651 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5652 ASTContext &Context, 5653 bool &SizeIsNegative, 5654 llvm::APSInt &Oversized) { 5655 QualType FixedTy 5656 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5657 SizeIsNegative, Oversized); 5658 if (FixedTy.isNull()) 5659 return nullptr; 5660 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5661 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5662 FixedTInfo->getTypeLoc()); 5663 return FixedTInfo; 5664 } 5665 5666 /// Register the given locally-scoped extern "C" declaration so 5667 /// that it can be found later for redeclarations. We include any extern "C" 5668 /// declaration that is not visible in the translation unit here, not just 5669 /// function-scope declarations. 5670 void 5671 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5672 if (!getLangOpts().CPlusPlus && 5673 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5674 // Don't need to track declarations in the TU in C. 5675 return; 5676 5677 // Note that we have a locally-scoped external with this name. 5678 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5679 } 5680 5681 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5682 // FIXME: We can have multiple results via __attribute__((overloadable)). 5683 auto Result = Context.getExternCContextDecl()->lookup(Name); 5684 return Result.empty() ? nullptr : *Result.begin(); 5685 } 5686 5687 /// Diagnose function specifiers on a declaration of an identifier that 5688 /// does not identify a function. 5689 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5690 // FIXME: We should probably indicate the identifier in question to avoid 5691 // confusion for constructs like "virtual int a(), b;" 5692 if (DS.isVirtualSpecified()) 5693 Diag(DS.getVirtualSpecLoc(), 5694 diag::err_virtual_non_function); 5695 5696 if (DS.isExplicitSpecified()) 5697 Diag(DS.getExplicitSpecLoc(), 5698 diag::err_explicit_non_function); 5699 5700 if (DS.isNoreturnSpecified()) 5701 Diag(DS.getNoreturnSpecLoc(), 5702 diag::err_noreturn_non_function); 5703 } 5704 5705 NamedDecl* 5706 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5707 TypeSourceInfo *TInfo, LookupResult &Previous) { 5708 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5709 if (D.getCXXScopeSpec().isSet()) { 5710 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5711 << D.getCXXScopeSpec().getRange(); 5712 D.setInvalidType(); 5713 // Pretend we didn't see the scope specifier. 5714 DC = CurContext; 5715 Previous.clear(); 5716 } 5717 5718 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5719 5720 if (D.getDeclSpec().isInlineSpecified()) 5721 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5722 << getLangOpts().CPlusPlus17; 5723 if (D.getDeclSpec().isConstexprSpecified()) 5724 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5725 << 1; 5726 5727 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5728 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5729 Diag(D.getName().StartLocation, 5730 diag::err_deduction_guide_invalid_specifier) 5731 << "typedef"; 5732 else 5733 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5734 << D.getName().getSourceRange(); 5735 return nullptr; 5736 } 5737 5738 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5739 if (!NewTD) return nullptr; 5740 5741 // Handle attributes prior to checking for duplicates in MergeVarDecl 5742 ProcessDeclAttributes(S, NewTD, D); 5743 5744 CheckTypedefForVariablyModifiedType(S, NewTD); 5745 5746 bool Redeclaration = D.isRedeclaration(); 5747 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5748 D.setRedeclaration(Redeclaration); 5749 return ND; 5750 } 5751 5752 void 5753 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5754 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5755 // then it shall have block scope. 5756 // Note that variably modified types must be fixed before merging the decl so 5757 // that redeclarations will match. 5758 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5759 QualType T = TInfo->getType(); 5760 if (T->isVariablyModifiedType()) { 5761 setFunctionHasBranchProtectedScope(); 5762 5763 if (S->getFnParent() == nullptr) { 5764 bool SizeIsNegative; 5765 llvm::APSInt Oversized; 5766 TypeSourceInfo *FixedTInfo = 5767 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5768 SizeIsNegative, 5769 Oversized); 5770 if (FixedTInfo) { 5771 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5772 NewTD->setTypeSourceInfo(FixedTInfo); 5773 } else { 5774 if (SizeIsNegative) 5775 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5776 else if (T->isVariableArrayType()) 5777 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5778 else if (Oversized.getBoolValue()) 5779 Diag(NewTD->getLocation(), diag::err_array_too_large) 5780 << Oversized.toString(10); 5781 else 5782 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5783 NewTD->setInvalidDecl(); 5784 } 5785 } 5786 } 5787 } 5788 5789 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5790 /// declares a typedef-name, either using the 'typedef' type specifier or via 5791 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5792 NamedDecl* 5793 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5794 LookupResult &Previous, bool &Redeclaration) { 5795 5796 // Find the shadowed declaration before filtering for scope. 5797 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5798 5799 // Merge the decl with the existing one if appropriate. If the decl is 5800 // in an outer scope, it isn't the same thing. 5801 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5802 /*AllowInlineNamespace*/false); 5803 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5804 if (!Previous.empty()) { 5805 Redeclaration = true; 5806 MergeTypedefNameDecl(S, NewTD, Previous); 5807 } 5808 5809 if (ShadowedDecl && !Redeclaration) 5810 CheckShadow(NewTD, ShadowedDecl, Previous); 5811 5812 // If this is the C FILE type, notify the AST context. 5813 if (IdentifierInfo *II = NewTD->getIdentifier()) 5814 if (!NewTD->isInvalidDecl() && 5815 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5816 if (II->isStr("FILE")) 5817 Context.setFILEDecl(NewTD); 5818 else if (II->isStr("jmp_buf")) 5819 Context.setjmp_bufDecl(NewTD); 5820 else if (II->isStr("sigjmp_buf")) 5821 Context.setsigjmp_bufDecl(NewTD); 5822 else if (II->isStr("ucontext_t")) 5823 Context.setucontext_tDecl(NewTD); 5824 } 5825 5826 return NewTD; 5827 } 5828 5829 /// Determines whether the given declaration is an out-of-scope 5830 /// previous declaration. 5831 /// 5832 /// This routine should be invoked when name lookup has found a 5833 /// previous declaration (PrevDecl) that is not in the scope where a 5834 /// new declaration by the same name is being introduced. If the new 5835 /// declaration occurs in a local scope, previous declarations with 5836 /// linkage may still be considered previous declarations (C99 5837 /// 6.2.2p4-5, C++ [basic.link]p6). 5838 /// 5839 /// \param PrevDecl the previous declaration found by name 5840 /// lookup 5841 /// 5842 /// \param DC the context in which the new declaration is being 5843 /// declared. 5844 /// 5845 /// \returns true if PrevDecl is an out-of-scope previous declaration 5846 /// for a new delcaration with the same name. 5847 static bool 5848 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5849 ASTContext &Context) { 5850 if (!PrevDecl) 5851 return false; 5852 5853 if (!PrevDecl->hasLinkage()) 5854 return false; 5855 5856 if (Context.getLangOpts().CPlusPlus) { 5857 // C++ [basic.link]p6: 5858 // If there is a visible declaration of an entity with linkage 5859 // having the same name and type, ignoring entities declared 5860 // outside the innermost enclosing namespace scope, the block 5861 // scope declaration declares that same entity and receives the 5862 // linkage of the previous declaration. 5863 DeclContext *OuterContext = DC->getRedeclContext(); 5864 if (!OuterContext->isFunctionOrMethod()) 5865 // This rule only applies to block-scope declarations. 5866 return false; 5867 5868 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5869 if (PrevOuterContext->isRecord()) 5870 // We found a member function: ignore it. 5871 return false; 5872 5873 // Find the innermost enclosing namespace for the new and 5874 // previous declarations. 5875 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5876 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5877 5878 // The previous declaration is in a different namespace, so it 5879 // isn't the same function. 5880 if (!OuterContext->Equals(PrevOuterContext)) 5881 return false; 5882 } 5883 5884 return true; 5885 } 5886 5887 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5888 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5889 if (!SS.isSet()) return; 5890 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5891 } 5892 5893 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5894 QualType type = decl->getType(); 5895 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5896 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5897 // Various kinds of declaration aren't allowed to be __autoreleasing. 5898 unsigned kind = -1U; 5899 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5900 if (var->hasAttr<BlocksAttr>()) 5901 kind = 0; // __block 5902 else if (!var->hasLocalStorage()) 5903 kind = 1; // global 5904 } else if (isa<ObjCIvarDecl>(decl)) { 5905 kind = 3; // ivar 5906 } else if (isa<FieldDecl>(decl)) { 5907 kind = 2; // field 5908 } 5909 5910 if (kind != -1U) { 5911 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5912 << kind; 5913 } 5914 } else if (lifetime == Qualifiers::OCL_None) { 5915 // Try to infer lifetime. 5916 if (!type->isObjCLifetimeType()) 5917 return false; 5918 5919 lifetime = type->getObjCARCImplicitLifetime(); 5920 type = Context.getLifetimeQualifiedType(type, lifetime); 5921 decl->setType(type); 5922 } 5923 5924 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5925 // Thread-local variables cannot have lifetime. 5926 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5927 var->getTLSKind()) { 5928 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5929 << var->getType(); 5930 return true; 5931 } 5932 } 5933 5934 return false; 5935 } 5936 5937 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5938 // Ensure that an auto decl is deduced otherwise the checks below might cache 5939 // the wrong linkage. 5940 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5941 5942 // 'weak' only applies to declarations with external linkage. 5943 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5944 if (!ND.isExternallyVisible()) { 5945 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5946 ND.dropAttr<WeakAttr>(); 5947 } 5948 } 5949 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5950 if (ND.isExternallyVisible()) { 5951 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5952 ND.dropAttr<WeakRefAttr>(); 5953 ND.dropAttr<AliasAttr>(); 5954 } 5955 } 5956 5957 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5958 if (VD->hasInit()) { 5959 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5960 assert(VD->isThisDeclarationADefinition() && 5961 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5962 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5963 VD->dropAttr<AliasAttr>(); 5964 } 5965 } 5966 } 5967 5968 // 'selectany' only applies to externally visible variable declarations. 5969 // It does not apply to functions. 5970 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5971 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5972 S.Diag(Attr->getLocation(), 5973 diag::err_attribute_selectany_non_extern_data); 5974 ND.dropAttr<SelectAnyAttr>(); 5975 } 5976 } 5977 5978 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5979 // dll attributes require external linkage. Static locals may have external 5980 // linkage but still cannot be explicitly imported or exported. 5981 auto *VD = dyn_cast<VarDecl>(&ND); 5982 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5983 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5984 << &ND << Attr; 5985 ND.setInvalidDecl(); 5986 } 5987 } 5988 5989 // Virtual functions cannot be marked as 'notail'. 5990 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5991 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5992 if (MD->isVirtual()) { 5993 S.Diag(ND.getLocation(), 5994 diag::err_invalid_attribute_on_virtual_function) 5995 << Attr; 5996 ND.dropAttr<NotTailCalledAttr>(); 5997 } 5998 } 5999 6000 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6001 NamedDecl *NewDecl, 6002 bool IsSpecialization, 6003 bool IsDefinition) { 6004 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6005 return; 6006 6007 bool IsTemplate = false; 6008 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6009 OldDecl = OldTD->getTemplatedDecl(); 6010 IsTemplate = true; 6011 if (!IsSpecialization) 6012 IsDefinition = false; 6013 } 6014 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6015 NewDecl = NewTD->getTemplatedDecl(); 6016 IsTemplate = true; 6017 } 6018 6019 if (!OldDecl || !NewDecl) 6020 return; 6021 6022 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6023 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6024 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6025 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6026 6027 // dllimport and dllexport are inheritable attributes so we have to exclude 6028 // inherited attribute instances. 6029 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6030 (NewExportAttr && !NewExportAttr->isInherited()); 6031 6032 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6033 // the only exception being explicit specializations. 6034 // Implicitly generated declarations are also excluded for now because there 6035 // is no other way to switch these to use dllimport or dllexport. 6036 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6037 6038 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6039 // Allow with a warning for free functions and global variables. 6040 bool JustWarn = false; 6041 if (!OldDecl->isCXXClassMember()) { 6042 auto *VD = dyn_cast<VarDecl>(OldDecl); 6043 if (VD && !VD->getDescribedVarTemplate()) 6044 JustWarn = true; 6045 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6046 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6047 JustWarn = true; 6048 } 6049 6050 // We cannot change a declaration that's been used because IR has already 6051 // been emitted. Dllimported functions will still work though (modulo 6052 // address equality) as they can use the thunk. 6053 if (OldDecl->isUsed()) 6054 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6055 JustWarn = false; 6056 6057 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6058 : diag::err_attribute_dll_redeclaration; 6059 S.Diag(NewDecl->getLocation(), DiagID) 6060 << NewDecl 6061 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6062 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6063 if (!JustWarn) { 6064 NewDecl->setInvalidDecl(); 6065 return; 6066 } 6067 } 6068 6069 // A redeclaration is not allowed to drop a dllimport attribute, the only 6070 // exceptions being inline function definitions (except for function 6071 // templates), local extern declarations, qualified friend declarations or 6072 // special MSVC extension: in the last case, the declaration is treated as if 6073 // it were marked dllexport. 6074 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6075 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6076 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6077 // Ignore static data because out-of-line definitions are diagnosed 6078 // separately. 6079 IsStaticDataMember = VD->isStaticDataMember(); 6080 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6081 VarDecl::DeclarationOnly; 6082 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6083 IsInline = FD->isInlined(); 6084 IsQualifiedFriend = FD->getQualifier() && 6085 FD->getFriendObjectKind() == Decl::FOK_Declared; 6086 } 6087 6088 if (OldImportAttr && !HasNewAttr && 6089 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6090 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6091 if (IsMicrosoft && IsDefinition) { 6092 S.Diag(NewDecl->getLocation(), 6093 diag::warn_redeclaration_without_import_attribute) 6094 << NewDecl; 6095 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6096 NewDecl->dropAttr<DLLImportAttr>(); 6097 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6098 NewImportAttr->getRange(), S.Context, 6099 NewImportAttr->getSpellingListIndex())); 6100 } else { 6101 S.Diag(NewDecl->getLocation(), 6102 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6103 << NewDecl << OldImportAttr; 6104 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6105 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6106 OldDecl->dropAttr<DLLImportAttr>(); 6107 NewDecl->dropAttr<DLLImportAttr>(); 6108 } 6109 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6110 // In MinGW, seeing a function declared inline drops the dllimport 6111 // attribute. 6112 OldDecl->dropAttr<DLLImportAttr>(); 6113 NewDecl->dropAttr<DLLImportAttr>(); 6114 S.Diag(NewDecl->getLocation(), 6115 diag::warn_dllimport_dropped_from_inline_function) 6116 << NewDecl << OldImportAttr; 6117 } 6118 6119 // A specialization of a class template member function is processed here 6120 // since it's a redeclaration. If the parent class is dllexport, the 6121 // specialization inherits that attribute. This doesn't happen automatically 6122 // since the parent class isn't instantiated until later. 6123 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6124 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6125 !NewImportAttr && !NewExportAttr) { 6126 if (const DLLExportAttr *ParentExportAttr = 6127 MD->getParent()->getAttr<DLLExportAttr>()) { 6128 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6129 NewAttr->setInherited(true); 6130 NewDecl->addAttr(NewAttr); 6131 } 6132 } 6133 } 6134 } 6135 6136 /// Given that we are within the definition of the given function, 6137 /// will that definition behave like C99's 'inline', where the 6138 /// definition is discarded except for optimization purposes? 6139 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6140 // Try to avoid calling GetGVALinkageForFunction. 6141 6142 // All cases of this require the 'inline' keyword. 6143 if (!FD->isInlined()) return false; 6144 6145 // This is only possible in C++ with the gnu_inline attribute. 6146 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6147 return false; 6148 6149 // Okay, go ahead and call the relatively-more-expensive function. 6150 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6151 } 6152 6153 /// Determine whether a variable is extern "C" prior to attaching 6154 /// an initializer. We can't just call isExternC() here, because that 6155 /// will also compute and cache whether the declaration is externally 6156 /// visible, which might change when we attach the initializer. 6157 /// 6158 /// This can only be used if the declaration is known to not be a 6159 /// redeclaration of an internal linkage declaration. 6160 /// 6161 /// For instance: 6162 /// 6163 /// auto x = []{}; 6164 /// 6165 /// Attaching the initializer here makes this declaration not externally 6166 /// visible, because its type has internal linkage. 6167 /// 6168 /// FIXME: This is a hack. 6169 template<typename T> 6170 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6171 if (S.getLangOpts().CPlusPlus) { 6172 // In C++, the overloadable attribute negates the effects of extern "C". 6173 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6174 return false; 6175 6176 // So do CUDA's host/device attributes. 6177 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6178 D->template hasAttr<CUDAHostAttr>())) 6179 return false; 6180 } 6181 return D->isExternC(); 6182 } 6183 6184 static bool shouldConsiderLinkage(const VarDecl *VD) { 6185 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6186 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6187 return VD->hasExternalStorage(); 6188 if (DC->isFileContext()) 6189 return true; 6190 if (DC->isRecord()) 6191 return false; 6192 llvm_unreachable("Unexpected context"); 6193 } 6194 6195 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6196 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6197 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6198 isa<OMPDeclareReductionDecl>(DC)) 6199 return true; 6200 if (DC->isRecord()) 6201 return false; 6202 llvm_unreachable("Unexpected context"); 6203 } 6204 6205 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6206 AttributeList::Kind Kind) { 6207 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6208 if (L->getKind() == Kind) 6209 return true; 6210 return false; 6211 } 6212 6213 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6214 AttributeList::Kind Kind) { 6215 // Check decl attributes on the DeclSpec. 6216 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6217 return true; 6218 6219 // Walk the declarator structure, checking decl attributes that were in a type 6220 // position to the decl itself. 6221 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6222 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6223 return true; 6224 } 6225 6226 // Finally, check attributes on the decl itself. 6227 return hasParsedAttr(S, PD.getAttributes(), Kind); 6228 } 6229 6230 /// Adjust the \c DeclContext for a function or variable that might be a 6231 /// function-local external declaration. 6232 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6233 if (!DC->isFunctionOrMethod()) 6234 return false; 6235 6236 // If this is a local extern function or variable declared within a function 6237 // template, don't add it into the enclosing namespace scope until it is 6238 // instantiated; it might have a dependent type right now. 6239 if (DC->isDependentContext()) 6240 return true; 6241 6242 // C++11 [basic.link]p7: 6243 // When a block scope declaration of an entity with linkage is not found to 6244 // refer to some other declaration, then that entity is a member of the 6245 // innermost enclosing namespace. 6246 // 6247 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6248 // semantically-enclosing namespace, not a lexically-enclosing one. 6249 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6250 DC = DC->getParent(); 6251 return true; 6252 } 6253 6254 /// Returns true if given declaration has external C language linkage. 6255 static bool isDeclExternC(const Decl *D) { 6256 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6257 return FD->isExternC(); 6258 if (const auto *VD = dyn_cast<VarDecl>(D)) 6259 return VD->isExternC(); 6260 6261 llvm_unreachable("Unknown type of decl!"); 6262 } 6263 6264 NamedDecl *Sema::ActOnVariableDeclarator( 6265 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6266 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6267 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6268 QualType R = TInfo->getType(); 6269 DeclarationName Name = GetNameForDeclarator(D).getName(); 6270 6271 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6272 6273 if (D.isDecompositionDeclarator()) { 6274 // Take the name of the first declarator as our name for diagnostic 6275 // purposes. 6276 auto &Decomp = D.getDecompositionDeclarator(); 6277 if (!Decomp.bindings().empty()) { 6278 II = Decomp.bindings()[0].Name; 6279 Name = II; 6280 } 6281 } else if (!II) { 6282 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6283 return nullptr; 6284 } 6285 6286 if (getLangOpts().OpenCL) { 6287 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6288 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6289 // argument. 6290 if (R->isImageType() || R->isPipeType()) { 6291 Diag(D.getIdentifierLoc(), 6292 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6293 << R; 6294 D.setInvalidType(); 6295 return nullptr; 6296 } 6297 6298 // OpenCL v1.2 s6.9.r: 6299 // The event type cannot be used to declare a program scope variable. 6300 // OpenCL v2.0 s6.9.q: 6301 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6302 if (NULL == S->getParent()) { 6303 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6304 Diag(D.getIdentifierLoc(), 6305 diag::err_invalid_type_for_program_scope_var) << R; 6306 D.setInvalidType(); 6307 return nullptr; 6308 } 6309 } 6310 6311 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6312 QualType NR = R; 6313 while (NR->isPointerType()) { 6314 if (NR->isFunctionPointerType()) { 6315 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6316 D.setInvalidType(); 6317 break; 6318 } 6319 NR = NR->getPointeeType(); 6320 } 6321 6322 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6323 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6324 // half array type (unless the cl_khr_fp16 extension is enabled). 6325 if (Context.getBaseElementType(R)->isHalfType()) { 6326 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6327 D.setInvalidType(); 6328 } 6329 } 6330 6331 if (R->isSamplerT()) { 6332 // OpenCL v1.2 s6.9.b p4: 6333 // The sampler type cannot be used with the __local and __global address 6334 // space qualifiers. 6335 if (R.getAddressSpace() == LangAS::opencl_local || 6336 R.getAddressSpace() == LangAS::opencl_global) { 6337 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6338 } 6339 6340 // OpenCL v1.2 s6.12.14.1: 6341 // A global sampler must be declared with either the constant address 6342 // space qualifier or with the const qualifier. 6343 if (DC->isTranslationUnit() && 6344 !(R.getAddressSpace() == LangAS::opencl_constant || 6345 R.isConstQualified())) { 6346 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6347 D.setInvalidType(); 6348 } 6349 } 6350 6351 // OpenCL v1.2 s6.9.r: 6352 // The event type cannot be used with the __local, __constant and __global 6353 // address space qualifiers. 6354 if (R->isEventT()) { 6355 if (R.getAddressSpace() != LangAS::opencl_private) { 6356 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6357 D.setInvalidType(); 6358 } 6359 } 6360 6361 // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not 6362 // supported. OpenCL C does not support thread_local either, and 6363 // also reject all other thread storage class specifiers. 6364 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6365 if (TSC != TSCS_unspecified) { 6366 bool IsCXX = getLangOpts().OpenCLCPlusPlus; 6367 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6368 diag::err_opencl_unknown_type_specifier) 6369 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString() 6370 << DeclSpec::getSpecifierName(TSC) << 1; 6371 D.setInvalidType(); 6372 return nullptr; 6373 } 6374 } 6375 6376 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6377 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6378 6379 // dllimport globals without explicit storage class are treated as extern. We 6380 // have to change the storage class this early to get the right DeclContext. 6381 if (SC == SC_None && !DC->isRecord() && 6382 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6383 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6384 SC = SC_Extern; 6385 6386 DeclContext *OriginalDC = DC; 6387 bool IsLocalExternDecl = SC == SC_Extern && 6388 adjustContextForLocalExternDecl(DC); 6389 6390 if (SCSpec == DeclSpec::SCS_mutable) { 6391 // mutable can only appear on non-static class members, so it's always 6392 // an error here 6393 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6394 D.setInvalidType(); 6395 SC = SC_None; 6396 } 6397 6398 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6399 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6400 D.getDeclSpec().getStorageClassSpecLoc())) { 6401 // In C++11, the 'register' storage class specifier is deprecated. 6402 // Suppress the warning in system macros, it's used in macros in some 6403 // popular C system headers, such as in glibc's htonl() macro. 6404 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6405 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6406 : diag::warn_deprecated_register) 6407 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6408 } 6409 6410 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6411 6412 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6413 // C99 6.9p2: The storage-class specifiers auto and register shall not 6414 // appear in the declaration specifiers in an external declaration. 6415 // Global Register+Asm is a GNU extension we support. 6416 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6417 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6418 D.setInvalidType(); 6419 } 6420 } 6421 6422 bool IsMemberSpecialization = false; 6423 bool IsVariableTemplateSpecialization = false; 6424 bool IsPartialSpecialization = false; 6425 bool IsVariableTemplate = false; 6426 VarDecl *NewVD = nullptr; 6427 VarTemplateDecl *NewTemplate = nullptr; 6428 TemplateParameterList *TemplateParams = nullptr; 6429 if (!getLangOpts().CPlusPlus) { 6430 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6431 D.getIdentifierLoc(), II, 6432 R, TInfo, SC); 6433 6434 if (R->getContainedDeducedType()) 6435 ParsingInitForAutoVars.insert(NewVD); 6436 6437 if (D.isInvalidType()) 6438 NewVD->setInvalidDecl(); 6439 } else { 6440 bool Invalid = false; 6441 6442 if (DC->isRecord() && !CurContext->isRecord()) { 6443 // This is an out-of-line definition of a static data member. 6444 switch (SC) { 6445 case SC_None: 6446 break; 6447 case SC_Static: 6448 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6449 diag::err_static_out_of_line) 6450 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6451 break; 6452 case SC_Auto: 6453 case SC_Register: 6454 case SC_Extern: 6455 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6456 // to names of variables declared in a block or to function parameters. 6457 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6458 // of class members 6459 6460 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6461 diag::err_storage_class_for_static_member) 6462 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6463 break; 6464 case SC_PrivateExtern: 6465 llvm_unreachable("C storage class in c++!"); 6466 } 6467 } 6468 6469 if (SC == SC_Static && CurContext->isRecord()) { 6470 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6471 if (RD->isLocalClass()) 6472 Diag(D.getIdentifierLoc(), 6473 diag::err_static_data_member_not_allowed_in_local_class) 6474 << Name << RD->getDeclName(); 6475 6476 // C++98 [class.union]p1: If a union contains a static data member, 6477 // the program is ill-formed. C++11 drops this restriction. 6478 if (RD->isUnion()) 6479 Diag(D.getIdentifierLoc(), 6480 getLangOpts().CPlusPlus11 6481 ? diag::warn_cxx98_compat_static_data_member_in_union 6482 : diag::ext_static_data_member_in_union) << Name; 6483 // We conservatively disallow static data members in anonymous structs. 6484 else if (!RD->getDeclName()) 6485 Diag(D.getIdentifierLoc(), 6486 diag::err_static_data_member_not_allowed_in_anon_struct) 6487 << Name << RD->isUnion(); 6488 } 6489 } 6490 6491 // Match up the template parameter lists with the scope specifier, then 6492 // determine whether we have a template or a template specialization. 6493 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6494 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6495 D.getCXXScopeSpec(), 6496 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6497 ? D.getName().TemplateId 6498 : nullptr, 6499 TemplateParamLists, 6500 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6501 6502 if (TemplateParams) { 6503 if (!TemplateParams->size() && 6504 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6505 // There is an extraneous 'template<>' for this variable. Complain 6506 // about it, but allow the declaration of the variable. 6507 Diag(TemplateParams->getTemplateLoc(), 6508 diag::err_template_variable_noparams) 6509 << II 6510 << SourceRange(TemplateParams->getTemplateLoc(), 6511 TemplateParams->getRAngleLoc()); 6512 TemplateParams = nullptr; 6513 } else { 6514 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6515 // This is an explicit specialization or a partial specialization. 6516 // FIXME: Check that we can declare a specialization here. 6517 IsVariableTemplateSpecialization = true; 6518 IsPartialSpecialization = TemplateParams->size() > 0; 6519 } else { // if (TemplateParams->size() > 0) 6520 // This is a template declaration. 6521 IsVariableTemplate = true; 6522 6523 // Check that we can declare a template here. 6524 if (CheckTemplateDeclScope(S, TemplateParams)) 6525 return nullptr; 6526 6527 // Only C++1y supports variable templates (N3651). 6528 Diag(D.getIdentifierLoc(), 6529 getLangOpts().CPlusPlus14 6530 ? diag::warn_cxx11_compat_variable_template 6531 : diag::ext_variable_template); 6532 } 6533 } 6534 } else { 6535 assert((Invalid || 6536 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6537 "should have a 'template<>' for this decl"); 6538 } 6539 6540 if (IsVariableTemplateSpecialization) { 6541 SourceLocation TemplateKWLoc = 6542 TemplateParamLists.size() > 0 6543 ? TemplateParamLists[0]->getTemplateLoc() 6544 : SourceLocation(); 6545 DeclResult Res = ActOnVarTemplateSpecialization( 6546 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6547 IsPartialSpecialization); 6548 if (Res.isInvalid()) 6549 return nullptr; 6550 NewVD = cast<VarDecl>(Res.get()); 6551 AddToScope = false; 6552 } else if (D.isDecompositionDeclarator()) { 6553 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6554 D.getIdentifierLoc(), R, TInfo, SC, 6555 Bindings); 6556 } else 6557 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6558 D.getIdentifierLoc(), II, R, TInfo, SC); 6559 6560 // If this is supposed to be a variable template, create it as such. 6561 if (IsVariableTemplate) { 6562 NewTemplate = 6563 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6564 TemplateParams, NewVD); 6565 NewVD->setDescribedVarTemplate(NewTemplate); 6566 } 6567 6568 // If this decl has an auto type in need of deduction, make a note of the 6569 // Decl so we can diagnose uses of it in its own initializer. 6570 if (R->getContainedDeducedType()) 6571 ParsingInitForAutoVars.insert(NewVD); 6572 6573 if (D.isInvalidType() || Invalid) { 6574 NewVD->setInvalidDecl(); 6575 if (NewTemplate) 6576 NewTemplate->setInvalidDecl(); 6577 } 6578 6579 SetNestedNameSpecifier(NewVD, D); 6580 6581 // If we have any template parameter lists that don't directly belong to 6582 // the variable (matching the scope specifier), store them. 6583 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6584 if (TemplateParamLists.size() > VDTemplateParamLists) 6585 NewVD->setTemplateParameterListsInfo( 6586 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6587 6588 if (D.getDeclSpec().isConstexprSpecified()) { 6589 NewVD->setConstexpr(true); 6590 // C++1z [dcl.spec.constexpr]p1: 6591 // A static data member declared with the constexpr specifier is 6592 // implicitly an inline variable. 6593 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6594 NewVD->setImplicitlyInline(); 6595 } 6596 } 6597 6598 if (D.getDeclSpec().isInlineSpecified()) { 6599 if (!getLangOpts().CPlusPlus) { 6600 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6601 << 0; 6602 } else if (CurContext->isFunctionOrMethod()) { 6603 // 'inline' is not allowed on block scope variable declaration. 6604 Diag(D.getDeclSpec().getInlineSpecLoc(), 6605 diag::err_inline_declaration_block_scope) << Name 6606 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6607 } else { 6608 Diag(D.getDeclSpec().getInlineSpecLoc(), 6609 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6610 : diag::ext_inline_variable); 6611 NewVD->setInlineSpecified(); 6612 } 6613 } 6614 6615 // Set the lexical context. If the declarator has a C++ scope specifier, the 6616 // lexical context will be different from the semantic context. 6617 NewVD->setLexicalDeclContext(CurContext); 6618 if (NewTemplate) 6619 NewTemplate->setLexicalDeclContext(CurContext); 6620 6621 if (IsLocalExternDecl) { 6622 if (D.isDecompositionDeclarator()) 6623 for (auto *B : Bindings) 6624 B->setLocalExternDecl(); 6625 else 6626 NewVD->setLocalExternDecl(); 6627 } 6628 6629 bool EmitTLSUnsupportedError = false; 6630 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6631 // C++11 [dcl.stc]p4: 6632 // When thread_local is applied to a variable of block scope the 6633 // storage-class-specifier static is implied if it does not appear 6634 // explicitly. 6635 // Core issue: 'static' is not implied if the variable is declared 6636 // 'extern'. 6637 if (NewVD->hasLocalStorage() && 6638 (SCSpec != DeclSpec::SCS_unspecified || 6639 TSCS != DeclSpec::TSCS_thread_local || 6640 !DC->isFunctionOrMethod())) 6641 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6642 diag::err_thread_non_global) 6643 << DeclSpec::getSpecifierName(TSCS); 6644 else if (!Context.getTargetInfo().isTLSSupported()) { 6645 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6646 // Postpone error emission until we've collected attributes required to 6647 // figure out whether it's a host or device variable and whether the 6648 // error should be ignored. 6649 EmitTLSUnsupportedError = true; 6650 // We still need to mark the variable as TLS so it shows up in AST with 6651 // proper storage class for other tools to use even if we're not going 6652 // to emit any code for it. 6653 NewVD->setTSCSpec(TSCS); 6654 } else 6655 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6656 diag::err_thread_unsupported); 6657 } else 6658 NewVD->setTSCSpec(TSCS); 6659 } 6660 6661 // C99 6.7.4p3 6662 // An inline definition of a function with external linkage shall 6663 // not contain a definition of a modifiable object with static or 6664 // thread storage duration... 6665 // We only apply this when the function is required to be defined 6666 // elsewhere, i.e. when the function is not 'extern inline'. Note 6667 // that a local variable with thread storage duration still has to 6668 // be marked 'static'. Also note that it's possible to get these 6669 // semantics in C++ using __attribute__((gnu_inline)). 6670 if (SC == SC_Static && S->getFnParent() != nullptr && 6671 !NewVD->getType().isConstQualified()) { 6672 FunctionDecl *CurFD = getCurFunctionDecl(); 6673 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6674 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6675 diag::warn_static_local_in_extern_inline); 6676 MaybeSuggestAddingStaticToDecl(CurFD); 6677 } 6678 } 6679 6680 if (D.getDeclSpec().isModulePrivateSpecified()) { 6681 if (IsVariableTemplateSpecialization) 6682 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6683 << (IsPartialSpecialization ? 1 : 0) 6684 << FixItHint::CreateRemoval( 6685 D.getDeclSpec().getModulePrivateSpecLoc()); 6686 else if (IsMemberSpecialization) 6687 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6688 << 2 6689 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6690 else if (NewVD->hasLocalStorage()) 6691 Diag(NewVD->getLocation(), diag::err_module_private_local) 6692 << 0 << NewVD->getDeclName() 6693 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6694 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6695 else { 6696 NewVD->setModulePrivate(); 6697 if (NewTemplate) 6698 NewTemplate->setModulePrivate(); 6699 for (auto *B : Bindings) 6700 B->setModulePrivate(); 6701 } 6702 } 6703 6704 // Handle attributes prior to checking for duplicates in MergeVarDecl 6705 ProcessDeclAttributes(S, NewVD, D); 6706 6707 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6708 if (EmitTLSUnsupportedError && 6709 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6710 (getLangOpts().OpenMPIsDevice && 6711 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6712 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6713 diag::err_thread_unsupported); 6714 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6715 // storage [duration]." 6716 if (SC == SC_None && S->getFnParent() != nullptr && 6717 (NewVD->hasAttr<CUDASharedAttr>() || 6718 NewVD->hasAttr<CUDAConstantAttr>())) { 6719 NewVD->setStorageClass(SC_Static); 6720 } 6721 } 6722 6723 // Ensure that dllimport globals without explicit storage class are treated as 6724 // extern. The storage class is set above using parsed attributes. Now we can 6725 // check the VarDecl itself. 6726 assert(!NewVD->hasAttr<DLLImportAttr>() || 6727 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6728 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6729 6730 // In auto-retain/release, infer strong retension for variables of 6731 // retainable type. 6732 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6733 NewVD->setInvalidDecl(); 6734 6735 // Handle GNU asm-label extension (encoded as an attribute). 6736 if (Expr *E = (Expr*)D.getAsmLabel()) { 6737 // The parser guarantees this is a string. 6738 StringLiteral *SE = cast<StringLiteral>(E); 6739 StringRef Label = SE->getString(); 6740 if (S->getFnParent() != nullptr) { 6741 switch (SC) { 6742 case SC_None: 6743 case SC_Auto: 6744 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6745 break; 6746 case SC_Register: 6747 // Local Named register 6748 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6749 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6750 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6751 break; 6752 case SC_Static: 6753 case SC_Extern: 6754 case SC_PrivateExtern: 6755 break; 6756 } 6757 } else if (SC == SC_Register) { 6758 // Global Named register 6759 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6760 const auto &TI = Context.getTargetInfo(); 6761 bool HasSizeMismatch; 6762 6763 if (!TI.isValidGCCRegisterName(Label)) 6764 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6765 else if (!TI.validateGlobalRegisterVariable(Label, 6766 Context.getTypeSize(R), 6767 HasSizeMismatch)) 6768 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6769 else if (HasSizeMismatch) 6770 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6771 } 6772 6773 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6774 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6775 NewVD->setInvalidDecl(true); 6776 } 6777 } 6778 6779 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6780 Context, Label, 0)); 6781 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6782 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6783 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6784 if (I != ExtnameUndeclaredIdentifiers.end()) { 6785 if (isDeclExternC(NewVD)) { 6786 NewVD->addAttr(I->second); 6787 ExtnameUndeclaredIdentifiers.erase(I); 6788 } else 6789 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6790 << /*Variable*/1 << NewVD; 6791 } 6792 } 6793 6794 // Find the shadowed declaration before filtering for scope. 6795 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6796 ? getShadowedDeclaration(NewVD, Previous) 6797 : nullptr; 6798 6799 // Don't consider existing declarations that are in a different 6800 // scope and are out-of-semantic-context declarations (if the new 6801 // declaration has linkage). 6802 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6803 D.getCXXScopeSpec().isNotEmpty() || 6804 IsMemberSpecialization || 6805 IsVariableTemplateSpecialization); 6806 6807 // Check whether the previous declaration is in the same block scope. This 6808 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6809 if (getLangOpts().CPlusPlus && 6810 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6811 NewVD->setPreviousDeclInSameBlockScope( 6812 Previous.isSingleResult() && !Previous.isShadowed() && 6813 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6814 6815 if (!getLangOpts().CPlusPlus) { 6816 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6817 } else { 6818 // If this is an explicit specialization of a static data member, check it. 6819 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6820 CheckMemberSpecialization(NewVD, Previous)) 6821 NewVD->setInvalidDecl(); 6822 6823 // Merge the decl with the existing one if appropriate. 6824 if (!Previous.empty()) { 6825 if (Previous.isSingleResult() && 6826 isa<FieldDecl>(Previous.getFoundDecl()) && 6827 D.getCXXScopeSpec().isSet()) { 6828 // The user tried to define a non-static data member 6829 // out-of-line (C++ [dcl.meaning]p1). 6830 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6831 << D.getCXXScopeSpec().getRange(); 6832 Previous.clear(); 6833 NewVD->setInvalidDecl(); 6834 } 6835 } else if (D.getCXXScopeSpec().isSet()) { 6836 // No previous declaration in the qualifying scope. 6837 Diag(D.getIdentifierLoc(), diag::err_no_member) 6838 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6839 << D.getCXXScopeSpec().getRange(); 6840 NewVD->setInvalidDecl(); 6841 } 6842 6843 if (!IsVariableTemplateSpecialization) 6844 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6845 6846 if (NewTemplate) { 6847 VarTemplateDecl *PrevVarTemplate = 6848 NewVD->getPreviousDecl() 6849 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6850 : nullptr; 6851 6852 // Check the template parameter list of this declaration, possibly 6853 // merging in the template parameter list from the previous variable 6854 // template declaration. 6855 if (CheckTemplateParameterList( 6856 TemplateParams, 6857 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6858 : nullptr, 6859 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6860 DC->isDependentContext()) 6861 ? TPC_ClassTemplateMember 6862 : TPC_VarTemplate)) 6863 NewVD->setInvalidDecl(); 6864 6865 // If we are providing an explicit specialization of a static variable 6866 // template, make a note of that. 6867 if (PrevVarTemplate && 6868 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6869 PrevVarTemplate->setMemberSpecialization(); 6870 } 6871 } 6872 6873 // Diagnose shadowed variables iff this isn't a redeclaration. 6874 if (ShadowedDecl && !D.isRedeclaration()) 6875 CheckShadow(NewVD, ShadowedDecl, Previous); 6876 6877 ProcessPragmaWeak(S, NewVD); 6878 6879 // If this is the first declaration of an extern C variable, update 6880 // the map of such variables. 6881 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6882 isIncompleteDeclExternC(*this, NewVD)) 6883 RegisterLocallyScopedExternCDecl(NewVD, S); 6884 6885 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6886 Decl *ManglingContextDecl; 6887 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6888 NewVD->getDeclContext(), ManglingContextDecl)) { 6889 Context.setManglingNumber( 6890 NewVD, MCtx->getManglingNumber( 6891 NewVD, getMSManglingNumber(getLangOpts(), S))); 6892 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6893 } 6894 } 6895 6896 // Special handling of variable named 'main'. 6897 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6898 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6899 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6900 6901 // C++ [basic.start.main]p3 6902 // A program that declares a variable main at global scope is ill-formed. 6903 if (getLangOpts().CPlusPlus) 6904 Diag(D.getLocStart(), diag::err_main_global_variable); 6905 6906 // In C, and external-linkage variable named main results in undefined 6907 // behavior. 6908 else if (NewVD->hasExternalFormalLinkage()) 6909 Diag(D.getLocStart(), diag::warn_main_redefined); 6910 } 6911 6912 if (D.isRedeclaration() && !Previous.empty()) { 6913 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6914 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6915 D.isFunctionDefinition()); 6916 } 6917 6918 if (NewTemplate) { 6919 if (NewVD->isInvalidDecl()) 6920 NewTemplate->setInvalidDecl(); 6921 ActOnDocumentableDecl(NewTemplate); 6922 return NewTemplate; 6923 } 6924 6925 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6926 CompleteMemberSpecialization(NewVD, Previous); 6927 6928 return NewVD; 6929 } 6930 6931 /// Enum describing the %select options in diag::warn_decl_shadow. 6932 enum ShadowedDeclKind { 6933 SDK_Local, 6934 SDK_Global, 6935 SDK_StaticMember, 6936 SDK_Field, 6937 SDK_Typedef, 6938 SDK_Using 6939 }; 6940 6941 /// Determine what kind of declaration we're shadowing. 6942 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6943 const DeclContext *OldDC) { 6944 if (isa<TypeAliasDecl>(ShadowedDecl)) 6945 return SDK_Using; 6946 else if (isa<TypedefDecl>(ShadowedDecl)) 6947 return SDK_Typedef; 6948 else if (isa<RecordDecl>(OldDC)) 6949 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6950 6951 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6952 } 6953 6954 /// Return the location of the capture if the given lambda captures the given 6955 /// variable \p VD, or an invalid source location otherwise. 6956 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6957 const VarDecl *VD) { 6958 for (const Capture &Capture : LSI->Captures) { 6959 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6960 return Capture.getLocation(); 6961 } 6962 return SourceLocation(); 6963 } 6964 6965 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6966 const LookupResult &R) { 6967 // Only diagnose if we're shadowing an unambiguous field or variable. 6968 if (R.getResultKind() != LookupResult::Found) 6969 return false; 6970 6971 // Return false if warning is ignored. 6972 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6973 } 6974 6975 /// Return the declaration shadowed by the given variable \p D, or null 6976 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6977 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6978 const LookupResult &R) { 6979 if (!shouldWarnIfShadowedDecl(Diags, R)) 6980 return nullptr; 6981 6982 // Don't diagnose declarations at file scope. 6983 if (D->hasGlobalStorage()) 6984 return nullptr; 6985 6986 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6987 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6988 ? ShadowedDecl 6989 : nullptr; 6990 } 6991 6992 /// Return the declaration shadowed by the given typedef \p D, or null 6993 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6994 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6995 const LookupResult &R) { 6996 // Don't warn if typedef declaration is part of a class 6997 if (D->getDeclContext()->isRecord()) 6998 return nullptr; 6999 7000 if (!shouldWarnIfShadowedDecl(Diags, R)) 7001 return nullptr; 7002 7003 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7004 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7005 } 7006 7007 /// Diagnose variable or built-in function shadowing. Implements 7008 /// -Wshadow. 7009 /// 7010 /// This method is called whenever a VarDecl is added to a "useful" 7011 /// scope. 7012 /// 7013 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7014 /// \param R the lookup of the name 7015 /// 7016 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7017 const LookupResult &R) { 7018 DeclContext *NewDC = D->getDeclContext(); 7019 7020 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7021 // Fields are not shadowed by variables in C++ static methods. 7022 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7023 if (MD->isStatic()) 7024 return; 7025 7026 // Fields shadowed by constructor parameters are a special case. Usually 7027 // the constructor initializes the field with the parameter. 7028 if (isa<CXXConstructorDecl>(NewDC)) 7029 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7030 // Remember that this was shadowed so we can either warn about its 7031 // modification or its existence depending on warning settings. 7032 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7033 return; 7034 } 7035 } 7036 7037 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7038 if (shadowedVar->isExternC()) { 7039 // For shadowing external vars, make sure that we point to the global 7040 // declaration, not a locally scoped extern declaration. 7041 for (auto I : shadowedVar->redecls()) 7042 if (I->isFileVarDecl()) { 7043 ShadowedDecl = I; 7044 break; 7045 } 7046 } 7047 7048 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7049 7050 unsigned WarningDiag = diag::warn_decl_shadow; 7051 SourceLocation CaptureLoc; 7052 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7053 isa<CXXMethodDecl>(NewDC)) { 7054 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7055 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7056 if (RD->getLambdaCaptureDefault() == LCD_None) { 7057 // Try to avoid warnings for lambdas with an explicit capture list. 7058 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7059 // Warn only when the lambda captures the shadowed decl explicitly. 7060 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7061 if (CaptureLoc.isInvalid()) 7062 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7063 } else { 7064 // Remember that this was shadowed so we can avoid the warning if the 7065 // shadowed decl isn't captured and the warning settings allow it. 7066 cast<LambdaScopeInfo>(getCurFunction()) 7067 ->ShadowingDecls.push_back( 7068 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7069 return; 7070 } 7071 } 7072 7073 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7074 // A variable can't shadow a local variable in an enclosing scope, if 7075 // they are separated by a non-capturing declaration context. 7076 for (DeclContext *ParentDC = NewDC; 7077 ParentDC && !ParentDC->Equals(OldDC); 7078 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7079 // Only block literals, captured statements, and lambda expressions 7080 // can capture; other scopes don't. 7081 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7082 !isLambdaCallOperator(ParentDC)) { 7083 return; 7084 } 7085 } 7086 } 7087 } 7088 } 7089 7090 // Only warn about certain kinds of shadowing for class members. 7091 if (NewDC && NewDC->isRecord()) { 7092 // In particular, don't warn about shadowing non-class members. 7093 if (!OldDC->isRecord()) 7094 return; 7095 7096 // TODO: should we warn about static data members shadowing 7097 // static data members from base classes? 7098 7099 // TODO: don't diagnose for inaccessible shadowed members. 7100 // This is hard to do perfectly because we might friend the 7101 // shadowing context, but that's just a false negative. 7102 } 7103 7104 7105 DeclarationName Name = R.getLookupName(); 7106 7107 // Emit warning and note. 7108 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7109 return; 7110 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7111 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7112 if (!CaptureLoc.isInvalid()) 7113 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7114 << Name << /*explicitly*/ 1; 7115 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7116 } 7117 7118 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7119 /// when these variables are captured by the lambda. 7120 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7121 for (const auto &Shadow : LSI->ShadowingDecls) { 7122 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7123 // Try to avoid the warning when the shadowed decl isn't captured. 7124 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7125 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7126 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7127 ? diag::warn_decl_shadow_uncaptured_local 7128 : diag::warn_decl_shadow) 7129 << Shadow.VD->getDeclName() 7130 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7131 if (!CaptureLoc.isInvalid()) 7132 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7133 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7134 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7135 } 7136 } 7137 7138 /// Check -Wshadow without the advantage of a previous lookup. 7139 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7140 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7141 return; 7142 7143 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7144 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7145 LookupName(R, S); 7146 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7147 CheckShadow(D, ShadowedDecl, R); 7148 } 7149 7150 /// Check if 'E', which is an expression that is about to be modified, refers 7151 /// to a constructor parameter that shadows a field. 7152 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7153 // Quickly ignore expressions that can't be shadowing ctor parameters. 7154 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7155 return; 7156 E = E->IgnoreParenImpCasts(); 7157 auto *DRE = dyn_cast<DeclRefExpr>(E); 7158 if (!DRE) 7159 return; 7160 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7161 auto I = ShadowingDecls.find(D); 7162 if (I == ShadowingDecls.end()) 7163 return; 7164 const NamedDecl *ShadowedDecl = I->second; 7165 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7166 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7167 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7168 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7169 7170 // Avoid issuing multiple warnings about the same decl. 7171 ShadowingDecls.erase(I); 7172 } 7173 7174 /// Check for conflict between this global or extern "C" declaration and 7175 /// previous global or extern "C" declarations. This is only used in C++. 7176 template<typename T> 7177 static bool checkGlobalOrExternCConflict( 7178 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7179 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7180 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7181 7182 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7183 // The common case: this global doesn't conflict with any extern "C" 7184 // declaration. 7185 return false; 7186 } 7187 7188 if (Prev) { 7189 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7190 // Both the old and new declarations have C language linkage. This is a 7191 // redeclaration. 7192 Previous.clear(); 7193 Previous.addDecl(Prev); 7194 return true; 7195 } 7196 7197 // This is a global, non-extern "C" declaration, and there is a previous 7198 // non-global extern "C" declaration. Diagnose if this is a variable 7199 // declaration. 7200 if (!isa<VarDecl>(ND)) 7201 return false; 7202 } else { 7203 // The declaration is extern "C". Check for any declaration in the 7204 // translation unit which might conflict. 7205 if (IsGlobal) { 7206 // We have already performed the lookup into the translation unit. 7207 IsGlobal = false; 7208 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7209 I != E; ++I) { 7210 if (isa<VarDecl>(*I)) { 7211 Prev = *I; 7212 break; 7213 } 7214 } 7215 } else { 7216 DeclContext::lookup_result R = 7217 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7218 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7219 I != E; ++I) { 7220 if (isa<VarDecl>(*I)) { 7221 Prev = *I; 7222 break; 7223 } 7224 // FIXME: If we have any other entity with this name in global scope, 7225 // the declaration is ill-formed, but that is a defect: it breaks the 7226 // 'stat' hack, for instance. Only variables can have mangled name 7227 // clashes with extern "C" declarations, so only they deserve a 7228 // diagnostic. 7229 } 7230 } 7231 7232 if (!Prev) 7233 return false; 7234 } 7235 7236 // Use the first declaration's location to ensure we point at something which 7237 // is lexically inside an extern "C" linkage-spec. 7238 assert(Prev && "should have found a previous declaration to diagnose"); 7239 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7240 Prev = FD->getFirstDecl(); 7241 else 7242 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7243 7244 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7245 << IsGlobal << ND; 7246 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7247 << IsGlobal; 7248 return false; 7249 } 7250 7251 /// Apply special rules for handling extern "C" declarations. Returns \c true 7252 /// if we have found that this is a redeclaration of some prior entity. 7253 /// 7254 /// Per C++ [dcl.link]p6: 7255 /// Two declarations [for a function or variable] with C language linkage 7256 /// with the same name that appear in different scopes refer to the same 7257 /// [entity]. An entity with C language linkage shall not be declared with 7258 /// the same name as an entity in global scope. 7259 template<typename T> 7260 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7261 LookupResult &Previous) { 7262 if (!S.getLangOpts().CPlusPlus) { 7263 // In C, when declaring a global variable, look for a corresponding 'extern' 7264 // variable declared in function scope. We don't need this in C++, because 7265 // we find local extern decls in the surrounding file-scope DeclContext. 7266 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7267 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7268 Previous.clear(); 7269 Previous.addDecl(Prev); 7270 return true; 7271 } 7272 } 7273 return false; 7274 } 7275 7276 // A declaration in the translation unit can conflict with an extern "C" 7277 // declaration. 7278 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7279 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7280 7281 // An extern "C" declaration can conflict with a declaration in the 7282 // translation unit or can be a redeclaration of an extern "C" declaration 7283 // in another scope. 7284 if (isIncompleteDeclExternC(S,ND)) 7285 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7286 7287 // Neither global nor extern "C": nothing to do. 7288 return false; 7289 } 7290 7291 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7292 // If the decl is already known invalid, don't check it. 7293 if (NewVD->isInvalidDecl()) 7294 return; 7295 7296 QualType T = NewVD->getType(); 7297 7298 // Defer checking an 'auto' type until its initializer is attached. 7299 if (T->isUndeducedType()) 7300 return; 7301 7302 if (NewVD->hasAttrs()) 7303 CheckAlignasUnderalignment(NewVD); 7304 7305 if (T->isObjCObjectType()) { 7306 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7307 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7308 T = Context.getObjCObjectPointerType(T); 7309 NewVD->setType(T); 7310 } 7311 7312 // Emit an error if an address space was applied to decl with local storage. 7313 // This includes arrays of objects with address space qualifiers, but not 7314 // automatic variables that point to other address spaces. 7315 // ISO/IEC TR 18037 S5.1.2 7316 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7317 T.getAddressSpace() != LangAS::Default) { 7318 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7319 NewVD->setInvalidDecl(); 7320 return; 7321 } 7322 7323 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7324 // scope. 7325 if (getLangOpts().OpenCLVersion == 120 && 7326 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7327 NewVD->isStaticLocal()) { 7328 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7329 NewVD->setInvalidDecl(); 7330 return; 7331 } 7332 7333 if (getLangOpts().OpenCL) { 7334 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7335 if (NewVD->hasAttr<BlocksAttr>()) { 7336 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7337 return; 7338 } 7339 7340 if (T->isBlockPointerType()) { 7341 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7342 // can't use 'extern' storage class. 7343 if (!T.isConstQualified()) { 7344 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7345 << 0 /*const*/; 7346 NewVD->setInvalidDecl(); 7347 return; 7348 } 7349 if (NewVD->hasExternalStorage()) { 7350 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7351 NewVD->setInvalidDecl(); 7352 return; 7353 } 7354 } 7355 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7356 // __constant address space. 7357 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7358 // variables inside a function can also be declared in the global 7359 // address space. 7360 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7361 NewVD->hasExternalStorage()) { 7362 if (!T->isSamplerT() && 7363 !(T.getAddressSpace() == LangAS::opencl_constant || 7364 (T.getAddressSpace() == LangAS::opencl_global && 7365 getLangOpts().OpenCLVersion == 200))) { 7366 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7367 if (getLangOpts().OpenCLVersion == 200) 7368 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7369 << Scope << "global or constant"; 7370 else 7371 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7372 << Scope << "constant"; 7373 NewVD->setInvalidDecl(); 7374 return; 7375 } 7376 } else { 7377 if (T.getAddressSpace() == LangAS::opencl_global) { 7378 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7379 << 1 /*is any function*/ << "global"; 7380 NewVD->setInvalidDecl(); 7381 return; 7382 } 7383 if (T.getAddressSpace() == LangAS::opencl_constant || 7384 T.getAddressSpace() == LangAS::opencl_local) { 7385 FunctionDecl *FD = getCurFunctionDecl(); 7386 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7387 // in functions. 7388 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7389 if (T.getAddressSpace() == LangAS::opencl_constant) 7390 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7391 << 0 /*non-kernel only*/ << "constant"; 7392 else 7393 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7394 << 0 /*non-kernel only*/ << "local"; 7395 NewVD->setInvalidDecl(); 7396 return; 7397 } 7398 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7399 // in the outermost scope of a kernel function. 7400 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7401 if (!getCurScope()->isFunctionScope()) { 7402 if (T.getAddressSpace() == LangAS::opencl_constant) 7403 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7404 << "constant"; 7405 else 7406 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7407 << "local"; 7408 NewVD->setInvalidDecl(); 7409 return; 7410 } 7411 } 7412 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7413 // Do not allow other address spaces on automatic variable. 7414 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7415 NewVD->setInvalidDecl(); 7416 return; 7417 } 7418 } 7419 } 7420 7421 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7422 && !NewVD->hasAttr<BlocksAttr>()) { 7423 if (getLangOpts().getGC() != LangOptions::NonGC) 7424 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7425 else { 7426 assert(!getLangOpts().ObjCAutoRefCount); 7427 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7428 } 7429 } 7430 7431 bool isVM = T->isVariablyModifiedType(); 7432 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7433 NewVD->hasAttr<BlocksAttr>()) 7434 setFunctionHasBranchProtectedScope(); 7435 7436 if ((isVM && NewVD->hasLinkage()) || 7437 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7438 bool SizeIsNegative; 7439 llvm::APSInt Oversized; 7440 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7441 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7442 QualType FixedT; 7443 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7444 FixedT = FixedTInfo->getType(); 7445 else if (FixedTInfo) { 7446 // Type and type-as-written are canonically different. We need to fix up 7447 // both types separately. 7448 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7449 Oversized); 7450 } 7451 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7452 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7453 // FIXME: This won't give the correct result for 7454 // int a[10][n]; 7455 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7456 7457 if (NewVD->isFileVarDecl()) 7458 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7459 << SizeRange; 7460 else if (NewVD->isStaticLocal()) 7461 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7462 << SizeRange; 7463 else 7464 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7465 << SizeRange; 7466 NewVD->setInvalidDecl(); 7467 return; 7468 } 7469 7470 if (!FixedTInfo) { 7471 if (NewVD->isFileVarDecl()) 7472 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7473 else 7474 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7475 NewVD->setInvalidDecl(); 7476 return; 7477 } 7478 7479 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7480 NewVD->setType(FixedT); 7481 NewVD->setTypeSourceInfo(FixedTInfo); 7482 } 7483 7484 if (T->isVoidType()) { 7485 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7486 // of objects and functions. 7487 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7488 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7489 << T; 7490 NewVD->setInvalidDecl(); 7491 return; 7492 } 7493 } 7494 7495 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7496 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7497 NewVD->setInvalidDecl(); 7498 return; 7499 } 7500 7501 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7502 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7503 NewVD->setInvalidDecl(); 7504 return; 7505 } 7506 7507 if (NewVD->isConstexpr() && !T->isDependentType() && 7508 RequireLiteralType(NewVD->getLocation(), T, 7509 diag::err_constexpr_var_non_literal)) { 7510 NewVD->setInvalidDecl(); 7511 return; 7512 } 7513 } 7514 7515 /// Perform semantic checking on a newly-created variable 7516 /// declaration. 7517 /// 7518 /// This routine performs all of the type-checking required for a 7519 /// variable declaration once it has been built. It is used both to 7520 /// check variables after they have been parsed and their declarators 7521 /// have been translated into a declaration, and to check variables 7522 /// that have been instantiated from a template. 7523 /// 7524 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7525 /// 7526 /// Returns true if the variable declaration is a redeclaration. 7527 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7528 CheckVariableDeclarationType(NewVD); 7529 7530 // If the decl is already known invalid, don't check it. 7531 if (NewVD->isInvalidDecl()) 7532 return false; 7533 7534 // If we did not find anything by this name, look for a non-visible 7535 // extern "C" declaration with the same name. 7536 if (Previous.empty() && 7537 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7538 Previous.setShadowed(); 7539 7540 if (!Previous.empty()) { 7541 MergeVarDecl(NewVD, Previous); 7542 return true; 7543 } 7544 return false; 7545 } 7546 7547 namespace { 7548 struct FindOverriddenMethod { 7549 Sema *S; 7550 CXXMethodDecl *Method; 7551 7552 /// Member lookup function that determines whether a given C++ 7553 /// method overrides a method in a base class, to be used with 7554 /// CXXRecordDecl::lookupInBases(). 7555 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7556 RecordDecl *BaseRecord = 7557 Specifier->getType()->getAs<RecordType>()->getDecl(); 7558 7559 DeclarationName Name = Method->getDeclName(); 7560 7561 // FIXME: Do we care about other names here too? 7562 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7563 // We really want to find the base class destructor here. 7564 QualType T = S->Context.getTypeDeclType(BaseRecord); 7565 CanQualType CT = S->Context.getCanonicalType(T); 7566 7567 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7568 } 7569 7570 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7571 Path.Decls = Path.Decls.slice(1)) { 7572 NamedDecl *D = Path.Decls.front(); 7573 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7574 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7575 return true; 7576 } 7577 } 7578 7579 return false; 7580 } 7581 }; 7582 7583 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7584 } // end anonymous namespace 7585 7586 /// Report an error regarding overriding, along with any relevant 7587 /// overridden methods. 7588 /// 7589 /// \param DiagID the primary error to report. 7590 /// \param MD the overriding method. 7591 /// \param OEK which overrides to include as notes. 7592 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7593 OverrideErrorKind OEK = OEK_All) { 7594 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7595 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7596 // This check (& the OEK parameter) could be replaced by a predicate, but 7597 // without lambdas that would be overkill. This is still nicer than writing 7598 // out the diag loop 3 times. 7599 if ((OEK == OEK_All) || 7600 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7601 (OEK == OEK_Deleted && O->isDeleted())) 7602 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7603 } 7604 } 7605 7606 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7607 /// and if so, check that it's a valid override and remember it. 7608 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7609 // Look for methods in base classes that this method might override. 7610 CXXBasePaths Paths; 7611 FindOverriddenMethod FOM; 7612 FOM.Method = MD; 7613 FOM.S = this; 7614 bool hasDeletedOverridenMethods = false; 7615 bool hasNonDeletedOverridenMethods = false; 7616 bool AddedAny = false; 7617 if (DC->lookupInBases(FOM, Paths)) { 7618 for (auto *I : Paths.found_decls()) { 7619 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7620 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7621 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7622 !CheckOverridingFunctionAttributes(MD, OldMD) && 7623 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7624 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7625 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7626 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7627 AddedAny = true; 7628 } 7629 } 7630 } 7631 } 7632 7633 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7634 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7635 } 7636 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7637 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7638 } 7639 7640 return AddedAny; 7641 } 7642 7643 namespace { 7644 // Struct for holding all of the extra arguments needed by 7645 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7646 struct ActOnFDArgs { 7647 Scope *S; 7648 Declarator &D; 7649 MultiTemplateParamsArg TemplateParamLists; 7650 bool AddToScope; 7651 }; 7652 } // end anonymous namespace 7653 7654 namespace { 7655 7656 // Callback to only accept typo corrections that have a non-zero edit distance. 7657 // Also only accept corrections that have the same parent decl. 7658 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7659 public: 7660 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7661 CXXRecordDecl *Parent) 7662 : Context(Context), OriginalFD(TypoFD), 7663 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7664 7665 bool ValidateCandidate(const TypoCorrection &candidate) override { 7666 if (candidate.getEditDistance() == 0) 7667 return false; 7668 7669 SmallVector<unsigned, 1> MismatchedParams; 7670 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7671 CDeclEnd = candidate.end(); 7672 CDecl != CDeclEnd; ++CDecl) { 7673 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7674 7675 if (FD && !FD->hasBody() && 7676 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7677 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7678 CXXRecordDecl *Parent = MD->getParent(); 7679 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7680 return true; 7681 } else if (!ExpectedParent) { 7682 return true; 7683 } 7684 } 7685 } 7686 7687 return false; 7688 } 7689 7690 private: 7691 ASTContext &Context; 7692 FunctionDecl *OriginalFD; 7693 CXXRecordDecl *ExpectedParent; 7694 }; 7695 7696 } // end anonymous namespace 7697 7698 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7699 TypoCorrectedFunctionDefinitions.insert(F); 7700 } 7701 7702 /// Generate diagnostics for an invalid function redeclaration. 7703 /// 7704 /// This routine handles generating the diagnostic messages for an invalid 7705 /// function redeclaration, including finding possible similar declarations 7706 /// or performing typo correction if there are no previous declarations with 7707 /// the same name. 7708 /// 7709 /// Returns a NamedDecl iff typo correction was performed and substituting in 7710 /// the new declaration name does not cause new errors. 7711 static NamedDecl *DiagnoseInvalidRedeclaration( 7712 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7713 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7714 DeclarationName Name = NewFD->getDeclName(); 7715 DeclContext *NewDC = NewFD->getDeclContext(); 7716 SmallVector<unsigned, 1> MismatchedParams; 7717 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7718 TypoCorrection Correction; 7719 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7720 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7721 : diag::err_member_decl_does_not_match; 7722 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7723 IsLocalFriend ? Sema::LookupLocalFriendName 7724 : Sema::LookupOrdinaryName, 7725 Sema::ForVisibleRedeclaration); 7726 7727 NewFD->setInvalidDecl(); 7728 if (IsLocalFriend) 7729 SemaRef.LookupName(Prev, S); 7730 else 7731 SemaRef.LookupQualifiedName(Prev, NewDC); 7732 assert(!Prev.isAmbiguous() && 7733 "Cannot have an ambiguity in previous-declaration lookup"); 7734 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7735 if (!Prev.empty()) { 7736 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7737 Func != FuncEnd; ++Func) { 7738 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7739 if (FD && 7740 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7741 // Add 1 to the index so that 0 can mean the mismatch didn't 7742 // involve a parameter 7743 unsigned ParamNum = 7744 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7745 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7746 } 7747 } 7748 // If the qualified name lookup yielded nothing, try typo correction 7749 } else if ((Correction = SemaRef.CorrectTypo( 7750 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7751 &ExtraArgs.D.getCXXScopeSpec(), 7752 llvm::make_unique<DifferentNameValidatorCCC>( 7753 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7754 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7755 // Set up everything for the call to ActOnFunctionDeclarator 7756 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7757 ExtraArgs.D.getIdentifierLoc()); 7758 Previous.clear(); 7759 Previous.setLookupName(Correction.getCorrection()); 7760 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7761 CDeclEnd = Correction.end(); 7762 CDecl != CDeclEnd; ++CDecl) { 7763 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7764 if (FD && !FD->hasBody() && 7765 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7766 Previous.addDecl(FD); 7767 } 7768 } 7769 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7770 7771 NamedDecl *Result; 7772 // Retry building the function declaration with the new previous 7773 // declarations, and with errors suppressed. 7774 { 7775 // Trap errors. 7776 Sema::SFINAETrap Trap(SemaRef); 7777 7778 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7779 // pieces need to verify the typo-corrected C++ declaration and hopefully 7780 // eliminate the need for the parameter pack ExtraArgs. 7781 Result = SemaRef.ActOnFunctionDeclarator( 7782 ExtraArgs.S, ExtraArgs.D, 7783 Correction.getCorrectionDecl()->getDeclContext(), 7784 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7785 ExtraArgs.AddToScope); 7786 7787 if (Trap.hasErrorOccurred()) 7788 Result = nullptr; 7789 } 7790 7791 if (Result) { 7792 // Determine which correction we picked. 7793 Decl *Canonical = Result->getCanonicalDecl(); 7794 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7795 I != E; ++I) 7796 if ((*I)->getCanonicalDecl() == Canonical) 7797 Correction.setCorrectionDecl(*I); 7798 7799 // Let Sema know about the correction. 7800 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7801 SemaRef.diagnoseTypo( 7802 Correction, 7803 SemaRef.PDiag(IsLocalFriend 7804 ? diag::err_no_matching_local_friend_suggest 7805 : diag::err_member_decl_does_not_match_suggest) 7806 << Name << NewDC << IsDefinition); 7807 return Result; 7808 } 7809 7810 // Pretend the typo correction never occurred 7811 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7812 ExtraArgs.D.getIdentifierLoc()); 7813 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7814 Previous.clear(); 7815 Previous.setLookupName(Name); 7816 } 7817 7818 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7819 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7820 7821 bool NewFDisConst = false; 7822 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7823 NewFDisConst = NewMD->isConst(); 7824 7825 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7826 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7827 NearMatch != NearMatchEnd; ++NearMatch) { 7828 FunctionDecl *FD = NearMatch->first; 7829 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7830 bool FDisConst = MD && MD->isConst(); 7831 bool IsMember = MD || !IsLocalFriend; 7832 7833 // FIXME: These notes are poorly worded for the local friend case. 7834 if (unsigned Idx = NearMatch->second) { 7835 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7836 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7837 if (Loc.isInvalid()) Loc = FD->getLocation(); 7838 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7839 : diag::note_local_decl_close_param_match) 7840 << Idx << FDParam->getType() 7841 << NewFD->getParamDecl(Idx - 1)->getType(); 7842 } else if (FDisConst != NewFDisConst) { 7843 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7844 << NewFDisConst << FD->getSourceRange().getEnd(); 7845 } else 7846 SemaRef.Diag(FD->getLocation(), 7847 IsMember ? diag::note_member_def_close_match 7848 : diag::note_local_decl_close_match); 7849 } 7850 return nullptr; 7851 } 7852 7853 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7854 switch (D.getDeclSpec().getStorageClassSpec()) { 7855 default: llvm_unreachable("Unknown storage class!"); 7856 case DeclSpec::SCS_auto: 7857 case DeclSpec::SCS_register: 7858 case DeclSpec::SCS_mutable: 7859 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7860 diag::err_typecheck_sclass_func); 7861 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7862 D.setInvalidType(); 7863 break; 7864 case DeclSpec::SCS_unspecified: break; 7865 case DeclSpec::SCS_extern: 7866 if (D.getDeclSpec().isExternInLinkageSpec()) 7867 return SC_None; 7868 return SC_Extern; 7869 case DeclSpec::SCS_static: { 7870 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7871 // C99 6.7.1p5: 7872 // The declaration of an identifier for a function that has 7873 // block scope shall have no explicit storage-class specifier 7874 // other than extern 7875 // See also (C++ [dcl.stc]p4). 7876 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7877 diag::err_static_block_func); 7878 break; 7879 } else 7880 return SC_Static; 7881 } 7882 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7883 } 7884 7885 // No explicit storage class has already been returned 7886 return SC_None; 7887 } 7888 7889 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7890 DeclContext *DC, QualType &R, 7891 TypeSourceInfo *TInfo, 7892 StorageClass SC, 7893 bool &IsVirtualOkay) { 7894 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7895 DeclarationName Name = NameInfo.getName(); 7896 7897 FunctionDecl *NewFD = nullptr; 7898 bool isInline = D.getDeclSpec().isInlineSpecified(); 7899 7900 if (!SemaRef.getLangOpts().CPlusPlus) { 7901 // Determine whether the function was written with a 7902 // prototype. This true when: 7903 // - there is a prototype in the declarator, or 7904 // - the type R of the function is some kind of typedef or other non- 7905 // attributed reference to a type name (which eventually refers to a 7906 // function type). 7907 bool HasPrototype = 7908 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7909 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7910 7911 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7912 D.getLocStart(), NameInfo, R, 7913 TInfo, SC, isInline, 7914 HasPrototype, false); 7915 if (D.isInvalidType()) 7916 NewFD->setInvalidDecl(); 7917 7918 return NewFD; 7919 } 7920 7921 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7922 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7923 7924 // Check that the return type is not an abstract class type. 7925 // For record types, this is done by the AbstractClassUsageDiagnoser once 7926 // the class has been completely parsed. 7927 if (!DC->isRecord() && 7928 SemaRef.RequireNonAbstractType( 7929 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7930 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7931 D.setInvalidType(); 7932 7933 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7934 // This is a C++ constructor declaration. 7935 assert(DC->isRecord() && 7936 "Constructors can only be declared in a member context"); 7937 7938 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7939 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7940 D.getLocStart(), NameInfo, 7941 R, TInfo, isExplicit, isInline, 7942 /*isImplicitlyDeclared=*/false, 7943 isConstexpr); 7944 7945 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7946 // This is a C++ destructor declaration. 7947 if (DC->isRecord()) { 7948 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7949 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7950 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7951 SemaRef.Context, Record, 7952 D.getLocStart(), 7953 NameInfo, R, TInfo, isInline, 7954 /*isImplicitlyDeclared=*/false); 7955 7956 // If the class is complete, then we now create the implicit exception 7957 // specification. If the class is incomplete or dependent, we can't do 7958 // it yet. 7959 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7960 Record->getDefinition() && !Record->isBeingDefined() && 7961 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7962 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7963 } 7964 7965 IsVirtualOkay = true; 7966 return NewDD; 7967 7968 } else { 7969 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7970 D.setInvalidType(); 7971 7972 // Create a FunctionDecl to satisfy the function definition parsing 7973 // code path. 7974 return FunctionDecl::Create(SemaRef.Context, DC, 7975 D.getLocStart(), 7976 D.getIdentifierLoc(), Name, R, TInfo, 7977 SC, isInline, 7978 /*hasPrototype=*/true, isConstexpr); 7979 } 7980 7981 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7982 if (!DC->isRecord()) { 7983 SemaRef.Diag(D.getIdentifierLoc(), 7984 diag::err_conv_function_not_member); 7985 return nullptr; 7986 } 7987 7988 SemaRef.CheckConversionDeclarator(D, R, SC); 7989 IsVirtualOkay = true; 7990 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7991 D.getLocStart(), NameInfo, 7992 R, TInfo, isInline, isExplicit, 7993 isConstexpr, SourceLocation()); 7994 7995 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7996 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7997 7998 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7999 isExplicit, NameInfo, R, TInfo, 8000 D.getLocEnd()); 8001 } else if (DC->isRecord()) { 8002 // If the name of the function is the same as the name of the record, 8003 // then this must be an invalid constructor that has a return type. 8004 // (The parser checks for a return type and makes the declarator a 8005 // constructor if it has no return type). 8006 if (Name.getAsIdentifierInfo() && 8007 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8008 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8009 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8010 << SourceRange(D.getIdentifierLoc()); 8011 return nullptr; 8012 } 8013 8014 // This is a C++ method declaration. 8015 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 8016 cast<CXXRecordDecl>(DC), 8017 D.getLocStart(), NameInfo, R, 8018 TInfo, SC, isInline, 8019 isConstexpr, SourceLocation()); 8020 IsVirtualOkay = !Ret->isStatic(); 8021 return Ret; 8022 } else { 8023 bool isFriend = 8024 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8025 if (!isFriend && SemaRef.CurContext->isRecord()) 8026 return nullptr; 8027 8028 // Determine whether the function was written with a 8029 // prototype. This true when: 8030 // - we're in C++ (where every function has a prototype), 8031 return FunctionDecl::Create(SemaRef.Context, DC, 8032 D.getLocStart(), 8033 NameInfo, R, TInfo, SC, isInline, 8034 true/*HasPrototype*/, isConstexpr); 8035 } 8036 } 8037 8038 enum OpenCLParamType { 8039 ValidKernelParam, 8040 PtrPtrKernelParam, 8041 PtrKernelParam, 8042 InvalidAddrSpacePtrKernelParam, 8043 InvalidKernelParam, 8044 RecordKernelParam 8045 }; 8046 8047 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8048 if (PT->isPointerType()) { 8049 QualType PointeeType = PT->getPointeeType(); 8050 if (PointeeType->isPointerType()) 8051 return PtrPtrKernelParam; 8052 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8053 PointeeType.getAddressSpace() == LangAS::opencl_private || 8054 PointeeType.getAddressSpace() == LangAS::Default) 8055 return InvalidAddrSpacePtrKernelParam; 8056 return PtrKernelParam; 8057 } 8058 8059 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 8060 // be used as builtin types. 8061 8062 if (PT->isImageType()) 8063 return PtrKernelParam; 8064 8065 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8066 return InvalidKernelParam; 8067 8068 // OpenCL extension spec v1.2 s9.5: 8069 // This extension adds support for half scalar and vector types as built-in 8070 // types that can be used for arithmetic operations, conversions etc. 8071 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8072 return InvalidKernelParam; 8073 8074 if (PT->isRecordType()) 8075 return RecordKernelParam; 8076 8077 return ValidKernelParam; 8078 } 8079 8080 static void checkIsValidOpenCLKernelParameter( 8081 Sema &S, 8082 Declarator &D, 8083 ParmVarDecl *Param, 8084 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8085 QualType PT = Param->getType(); 8086 8087 // Cache the valid types we encounter to avoid rechecking structs that are 8088 // used again 8089 if (ValidTypes.count(PT.getTypePtr())) 8090 return; 8091 8092 switch (getOpenCLKernelParameterType(S, PT)) { 8093 case PtrPtrKernelParam: 8094 // OpenCL v1.2 s6.9.a: 8095 // A kernel function argument cannot be declared as a 8096 // pointer to a pointer type. 8097 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8098 D.setInvalidType(); 8099 return; 8100 8101 case InvalidAddrSpacePtrKernelParam: 8102 // OpenCL v1.0 s6.5: 8103 // __kernel function arguments declared to be a pointer of a type can point 8104 // to one of the following address spaces only : __global, __local or 8105 // __constant. 8106 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8107 D.setInvalidType(); 8108 return; 8109 8110 // OpenCL v1.2 s6.9.k: 8111 // Arguments to kernel functions in a program cannot be declared with the 8112 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8113 // uintptr_t or a struct and/or union that contain fields declared to be 8114 // one of these built-in scalar types. 8115 8116 case InvalidKernelParam: 8117 // OpenCL v1.2 s6.8 n: 8118 // A kernel function argument cannot be declared 8119 // of event_t type. 8120 // Do not diagnose half type since it is diagnosed as invalid argument 8121 // type for any function elsewhere. 8122 if (!PT->isHalfType()) 8123 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8124 D.setInvalidType(); 8125 return; 8126 8127 case PtrKernelParam: 8128 case ValidKernelParam: 8129 ValidTypes.insert(PT.getTypePtr()); 8130 return; 8131 8132 case RecordKernelParam: 8133 break; 8134 } 8135 8136 // Track nested structs we will inspect 8137 SmallVector<const Decl *, 4> VisitStack; 8138 8139 // Track where we are in the nested structs. Items will migrate from 8140 // VisitStack to HistoryStack as we do the DFS for bad field. 8141 SmallVector<const FieldDecl *, 4> HistoryStack; 8142 HistoryStack.push_back(nullptr); 8143 8144 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8145 VisitStack.push_back(PD); 8146 8147 assert(VisitStack.back() && "First decl null?"); 8148 8149 do { 8150 const Decl *Next = VisitStack.pop_back_val(); 8151 if (!Next) { 8152 assert(!HistoryStack.empty()); 8153 // Found a marker, we have gone up a level 8154 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8155 ValidTypes.insert(Hist->getType().getTypePtr()); 8156 8157 continue; 8158 } 8159 8160 // Adds everything except the original parameter declaration (which is not a 8161 // field itself) to the history stack. 8162 const RecordDecl *RD; 8163 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8164 HistoryStack.push_back(Field); 8165 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8166 } else { 8167 RD = cast<RecordDecl>(Next); 8168 } 8169 8170 // Add a null marker so we know when we've gone back up a level 8171 VisitStack.push_back(nullptr); 8172 8173 for (const auto *FD : RD->fields()) { 8174 QualType QT = FD->getType(); 8175 8176 if (ValidTypes.count(QT.getTypePtr())) 8177 continue; 8178 8179 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8180 if (ParamType == ValidKernelParam) 8181 continue; 8182 8183 if (ParamType == RecordKernelParam) { 8184 VisitStack.push_back(FD); 8185 continue; 8186 } 8187 8188 // OpenCL v1.2 s6.9.p: 8189 // Arguments to kernel functions that are declared to be a struct or union 8190 // do not allow OpenCL objects to be passed as elements of the struct or 8191 // union. 8192 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8193 ParamType == InvalidAddrSpacePtrKernelParam) { 8194 S.Diag(Param->getLocation(), 8195 diag::err_record_with_pointers_kernel_param) 8196 << PT->isUnionType() 8197 << PT; 8198 } else { 8199 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8200 } 8201 8202 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8203 << PD->getDeclName(); 8204 8205 // We have an error, now let's go back up through history and show where 8206 // the offending field came from 8207 for (ArrayRef<const FieldDecl *>::const_iterator 8208 I = HistoryStack.begin() + 1, 8209 E = HistoryStack.end(); 8210 I != E; ++I) { 8211 const FieldDecl *OuterField = *I; 8212 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8213 << OuterField->getType(); 8214 } 8215 8216 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8217 << QT->isPointerType() 8218 << QT; 8219 D.setInvalidType(); 8220 return; 8221 } 8222 } while (!VisitStack.empty()); 8223 } 8224 8225 /// Find the DeclContext in which a tag is implicitly declared if we see an 8226 /// elaborated type specifier in the specified context, and lookup finds 8227 /// nothing. 8228 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8229 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8230 DC = DC->getParent(); 8231 return DC; 8232 } 8233 8234 /// Find the Scope in which a tag is implicitly declared if we see an 8235 /// elaborated type specifier in the specified context, and lookup finds 8236 /// nothing. 8237 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8238 while (S->isClassScope() || 8239 (LangOpts.CPlusPlus && 8240 S->isFunctionPrototypeScope()) || 8241 ((S->getFlags() & Scope::DeclScope) == 0) || 8242 (S->getEntity() && S->getEntity()->isTransparentContext())) 8243 S = S->getParent(); 8244 return S; 8245 } 8246 8247 NamedDecl* 8248 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8249 TypeSourceInfo *TInfo, LookupResult &Previous, 8250 MultiTemplateParamsArg TemplateParamLists, 8251 bool &AddToScope) { 8252 QualType R = TInfo->getType(); 8253 8254 assert(R.getTypePtr()->isFunctionType()); 8255 8256 // TODO: consider using NameInfo for diagnostic. 8257 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8258 DeclarationName Name = NameInfo.getName(); 8259 StorageClass SC = getFunctionStorageClass(*this, D); 8260 8261 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8262 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8263 diag::err_invalid_thread) 8264 << DeclSpec::getSpecifierName(TSCS); 8265 8266 if (D.isFirstDeclarationOfMember()) 8267 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8268 D.getIdentifierLoc()); 8269 8270 bool isFriend = false; 8271 FunctionTemplateDecl *FunctionTemplate = nullptr; 8272 bool isMemberSpecialization = false; 8273 bool isFunctionTemplateSpecialization = false; 8274 8275 bool isDependentClassScopeExplicitSpecialization = false; 8276 bool HasExplicitTemplateArgs = false; 8277 TemplateArgumentListInfo TemplateArgs; 8278 8279 bool isVirtualOkay = false; 8280 8281 DeclContext *OriginalDC = DC; 8282 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8283 8284 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8285 isVirtualOkay); 8286 if (!NewFD) return nullptr; 8287 8288 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8289 NewFD->setTopLevelDeclInObjCContainer(); 8290 8291 // Set the lexical context. If this is a function-scope declaration, or has a 8292 // C++ scope specifier, or is the object of a friend declaration, the lexical 8293 // context will be different from the semantic context. 8294 NewFD->setLexicalDeclContext(CurContext); 8295 8296 if (IsLocalExternDecl) 8297 NewFD->setLocalExternDecl(); 8298 8299 if (getLangOpts().CPlusPlus) { 8300 bool isInline = D.getDeclSpec().isInlineSpecified(); 8301 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8302 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8303 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8304 isFriend = D.getDeclSpec().isFriendSpecified(); 8305 if (isFriend && !isInline && D.isFunctionDefinition()) { 8306 // C++ [class.friend]p5 8307 // A function can be defined in a friend declaration of a 8308 // class . . . . Such a function is implicitly inline. 8309 NewFD->setImplicitlyInline(); 8310 } 8311 8312 // If this is a method defined in an __interface, and is not a constructor 8313 // or an overloaded operator, then set the pure flag (isVirtual will already 8314 // return true). 8315 if (const CXXRecordDecl *Parent = 8316 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8317 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8318 NewFD->setPure(true); 8319 8320 // C++ [class.union]p2 8321 // A union can have member functions, but not virtual functions. 8322 if (isVirtual && Parent->isUnion()) 8323 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8324 } 8325 8326 SetNestedNameSpecifier(NewFD, D); 8327 isMemberSpecialization = false; 8328 isFunctionTemplateSpecialization = false; 8329 if (D.isInvalidType()) 8330 NewFD->setInvalidDecl(); 8331 8332 // Match up the template parameter lists with the scope specifier, then 8333 // determine whether we have a template or a template specialization. 8334 bool Invalid = false; 8335 if (TemplateParameterList *TemplateParams = 8336 MatchTemplateParametersToScopeSpecifier( 8337 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8338 D.getCXXScopeSpec(), 8339 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8340 ? D.getName().TemplateId 8341 : nullptr, 8342 TemplateParamLists, isFriend, isMemberSpecialization, 8343 Invalid)) { 8344 if (TemplateParams->size() > 0) { 8345 // This is a function template 8346 8347 // Check that we can declare a template here. 8348 if (CheckTemplateDeclScope(S, TemplateParams)) 8349 NewFD->setInvalidDecl(); 8350 8351 // A destructor cannot be a template. 8352 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8353 Diag(NewFD->getLocation(), diag::err_destructor_template); 8354 NewFD->setInvalidDecl(); 8355 } 8356 8357 // If we're adding a template to a dependent context, we may need to 8358 // rebuilding some of the types used within the template parameter list, 8359 // now that we know what the current instantiation is. 8360 if (DC->isDependentContext()) { 8361 ContextRAII SavedContext(*this, DC); 8362 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8363 Invalid = true; 8364 } 8365 8366 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8367 NewFD->getLocation(), 8368 Name, TemplateParams, 8369 NewFD); 8370 FunctionTemplate->setLexicalDeclContext(CurContext); 8371 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8372 8373 // For source fidelity, store the other template param lists. 8374 if (TemplateParamLists.size() > 1) { 8375 NewFD->setTemplateParameterListsInfo(Context, 8376 TemplateParamLists.drop_back(1)); 8377 } 8378 } else { 8379 // This is a function template specialization. 8380 isFunctionTemplateSpecialization = true; 8381 // For source fidelity, store all the template param lists. 8382 if (TemplateParamLists.size() > 0) 8383 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8384 8385 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8386 if (isFriend) { 8387 // We want to remove the "template<>", found here. 8388 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8389 8390 // If we remove the template<> and the name is not a 8391 // template-id, we're actually silently creating a problem: 8392 // the friend declaration will refer to an untemplated decl, 8393 // and clearly the user wants a template specialization. So 8394 // we need to insert '<>' after the name. 8395 SourceLocation InsertLoc; 8396 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8397 InsertLoc = D.getName().getSourceRange().getEnd(); 8398 InsertLoc = getLocForEndOfToken(InsertLoc); 8399 } 8400 8401 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8402 << Name << RemoveRange 8403 << FixItHint::CreateRemoval(RemoveRange) 8404 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8405 } 8406 } 8407 } 8408 else { 8409 // All template param lists were matched against the scope specifier: 8410 // this is NOT (an explicit specialization of) a template. 8411 if (TemplateParamLists.size() > 0) 8412 // For source fidelity, store all the template param lists. 8413 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8414 } 8415 8416 if (Invalid) { 8417 NewFD->setInvalidDecl(); 8418 if (FunctionTemplate) 8419 FunctionTemplate->setInvalidDecl(); 8420 } 8421 8422 // C++ [dcl.fct.spec]p5: 8423 // The virtual specifier shall only be used in declarations of 8424 // nonstatic class member functions that appear within a 8425 // member-specification of a class declaration; see 10.3. 8426 // 8427 if (isVirtual && !NewFD->isInvalidDecl()) { 8428 if (!isVirtualOkay) { 8429 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8430 diag::err_virtual_non_function); 8431 } else if (!CurContext->isRecord()) { 8432 // 'virtual' was specified outside of the class. 8433 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8434 diag::err_virtual_out_of_class) 8435 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8436 } else if (NewFD->getDescribedFunctionTemplate()) { 8437 // C++ [temp.mem]p3: 8438 // A member function template shall not be virtual. 8439 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8440 diag::err_virtual_member_function_template) 8441 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8442 } else { 8443 // Okay: Add virtual to the method. 8444 NewFD->setVirtualAsWritten(true); 8445 } 8446 8447 if (getLangOpts().CPlusPlus14 && 8448 NewFD->getReturnType()->isUndeducedType()) 8449 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8450 } 8451 8452 if (getLangOpts().CPlusPlus14 && 8453 (NewFD->isDependentContext() || 8454 (isFriend && CurContext->isDependentContext())) && 8455 NewFD->getReturnType()->isUndeducedType()) { 8456 // If the function template is referenced directly (for instance, as a 8457 // member of the current instantiation), pretend it has a dependent type. 8458 // This is not really justified by the standard, but is the only sane 8459 // thing to do. 8460 // FIXME: For a friend function, we have not marked the function as being 8461 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8462 const FunctionProtoType *FPT = 8463 NewFD->getType()->castAs<FunctionProtoType>(); 8464 QualType Result = 8465 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8466 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8467 FPT->getExtProtoInfo())); 8468 } 8469 8470 // C++ [dcl.fct.spec]p3: 8471 // The inline specifier shall not appear on a block scope function 8472 // declaration. 8473 if (isInline && !NewFD->isInvalidDecl()) { 8474 if (CurContext->isFunctionOrMethod()) { 8475 // 'inline' is not allowed on block scope function declaration. 8476 Diag(D.getDeclSpec().getInlineSpecLoc(), 8477 diag::err_inline_declaration_block_scope) << Name 8478 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8479 } 8480 } 8481 8482 // C++ [dcl.fct.spec]p6: 8483 // The explicit specifier shall be used only in the declaration of a 8484 // constructor or conversion function within its class definition; 8485 // see 12.3.1 and 12.3.2. 8486 if (isExplicit && !NewFD->isInvalidDecl() && 8487 !isa<CXXDeductionGuideDecl>(NewFD)) { 8488 if (!CurContext->isRecord()) { 8489 // 'explicit' was specified outside of the class. 8490 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8491 diag::err_explicit_out_of_class) 8492 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8493 } else if (!isa<CXXConstructorDecl>(NewFD) && 8494 !isa<CXXConversionDecl>(NewFD)) { 8495 // 'explicit' was specified on a function that wasn't a constructor 8496 // or conversion function. 8497 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8498 diag::err_explicit_non_ctor_or_conv_function) 8499 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8500 } 8501 } 8502 8503 if (isConstexpr) { 8504 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8505 // are implicitly inline. 8506 NewFD->setImplicitlyInline(); 8507 8508 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8509 // be either constructors or to return a literal type. Therefore, 8510 // destructors cannot be declared constexpr. 8511 if (isa<CXXDestructorDecl>(NewFD)) 8512 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8513 } 8514 8515 // If __module_private__ was specified, mark the function accordingly. 8516 if (D.getDeclSpec().isModulePrivateSpecified()) { 8517 if (isFunctionTemplateSpecialization) { 8518 SourceLocation ModulePrivateLoc 8519 = D.getDeclSpec().getModulePrivateSpecLoc(); 8520 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8521 << 0 8522 << FixItHint::CreateRemoval(ModulePrivateLoc); 8523 } else { 8524 NewFD->setModulePrivate(); 8525 if (FunctionTemplate) 8526 FunctionTemplate->setModulePrivate(); 8527 } 8528 } 8529 8530 if (isFriend) { 8531 if (FunctionTemplate) { 8532 FunctionTemplate->setObjectOfFriendDecl(); 8533 FunctionTemplate->setAccess(AS_public); 8534 } 8535 NewFD->setObjectOfFriendDecl(); 8536 NewFD->setAccess(AS_public); 8537 } 8538 8539 // If a function is defined as defaulted or deleted, mark it as such now. 8540 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8541 // definition kind to FDK_Definition. 8542 switch (D.getFunctionDefinitionKind()) { 8543 case FDK_Declaration: 8544 case FDK_Definition: 8545 break; 8546 8547 case FDK_Defaulted: 8548 NewFD->setDefaulted(); 8549 break; 8550 8551 case FDK_Deleted: 8552 NewFD->setDeletedAsWritten(); 8553 break; 8554 } 8555 8556 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8557 D.isFunctionDefinition()) { 8558 // C++ [class.mfct]p2: 8559 // A member function may be defined (8.4) in its class definition, in 8560 // which case it is an inline member function (7.1.2) 8561 NewFD->setImplicitlyInline(); 8562 } 8563 8564 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8565 !CurContext->isRecord()) { 8566 // C++ [class.static]p1: 8567 // A data or function member of a class may be declared static 8568 // in a class definition, in which case it is a static member of 8569 // the class. 8570 8571 // Complain about the 'static' specifier if it's on an out-of-line 8572 // member function definition. 8573 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8574 diag::err_static_out_of_line) 8575 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8576 } 8577 8578 // C++11 [except.spec]p15: 8579 // A deallocation function with no exception-specification is treated 8580 // as if it were specified with noexcept(true). 8581 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8582 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8583 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8584 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8585 NewFD->setType(Context.getFunctionType( 8586 FPT->getReturnType(), FPT->getParamTypes(), 8587 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8588 } 8589 8590 // Filter out previous declarations that don't match the scope. 8591 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8592 D.getCXXScopeSpec().isNotEmpty() || 8593 isMemberSpecialization || 8594 isFunctionTemplateSpecialization); 8595 8596 // Handle GNU asm-label extension (encoded as an attribute). 8597 if (Expr *E = (Expr*) D.getAsmLabel()) { 8598 // The parser guarantees this is a string. 8599 StringLiteral *SE = cast<StringLiteral>(E); 8600 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8601 SE->getString(), 0)); 8602 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8603 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8604 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8605 if (I != ExtnameUndeclaredIdentifiers.end()) { 8606 if (isDeclExternC(NewFD)) { 8607 NewFD->addAttr(I->second); 8608 ExtnameUndeclaredIdentifiers.erase(I); 8609 } else 8610 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8611 << /*Variable*/0 << NewFD; 8612 } 8613 } 8614 8615 // Copy the parameter declarations from the declarator D to the function 8616 // declaration NewFD, if they are available. First scavenge them into Params. 8617 SmallVector<ParmVarDecl*, 16> Params; 8618 unsigned FTIIdx; 8619 if (D.isFunctionDeclarator(FTIIdx)) { 8620 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8621 8622 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8623 // function that takes no arguments, not a function that takes a 8624 // single void argument. 8625 // We let through "const void" here because Sema::GetTypeForDeclarator 8626 // already checks for that case. 8627 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8628 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8629 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8630 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8631 Param->setDeclContext(NewFD); 8632 Params.push_back(Param); 8633 8634 if (Param->isInvalidDecl()) 8635 NewFD->setInvalidDecl(); 8636 } 8637 } 8638 8639 if (!getLangOpts().CPlusPlus) { 8640 // In C, find all the tag declarations from the prototype and move them 8641 // into the function DeclContext. Remove them from the surrounding tag 8642 // injection context of the function, which is typically but not always 8643 // the TU. 8644 DeclContext *PrototypeTagContext = 8645 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8646 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8647 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8648 8649 // We don't want to reparent enumerators. Look at their parent enum 8650 // instead. 8651 if (!TD) { 8652 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8653 TD = cast<EnumDecl>(ECD->getDeclContext()); 8654 } 8655 if (!TD) 8656 continue; 8657 DeclContext *TagDC = TD->getLexicalDeclContext(); 8658 if (!TagDC->containsDecl(TD)) 8659 continue; 8660 TagDC->removeDecl(TD); 8661 TD->setDeclContext(NewFD); 8662 NewFD->addDecl(TD); 8663 8664 // Preserve the lexical DeclContext if it is not the surrounding tag 8665 // injection context of the FD. In this example, the semantic context of 8666 // E will be f and the lexical context will be S, while both the 8667 // semantic and lexical contexts of S will be f: 8668 // void f(struct S { enum E { a } f; } s); 8669 if (TagDC != PrototypeTagContext) 8670 TD->setLexicalDeclContext(TagDC); 8671 } 8672 } 8673 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8674 // When we're declaring a function with a typedef, typeof, etc as in the 8675 // following example, we'll need to synthesize (unnamed) 8676 // parameters for use in the declaration. 8677 // 8678 // @code 8679 // typedef void fn(int); 8680 // fn f; 8681 // @endcode 8682 8683 // Synthesize a parameter for each argument type. 8684 for (const auto &AI : FT->param_types()) { 8685 ParmVarDecl *Param = 8686 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8687 Param->setScopeInfo(0, Params.size()); 8688 Params.push_back(Param); 8689 } 8690 } else { 8691 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8692 "Should not need args for typedef of non-prototype fn"); 8693 } 8694 8695 // Finally, we know we have the right number of parameters, install them. 8696 NewFD->setParams(Params); 8697 8698 if (D.getDeclSpec().isNoreturnSpecified()) 8699 NewFD->addAttr( 8700 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8701 Context, 0)); 8702 8703 // Functions returning a variably modified type violate C99 6.7.5.2p2 8704 // because all functions have linkage. 8705 if (!NewFD->isInvalidDecl() && 8706 NewFD->getReturnType()->isVariablyModifiedType()) { 8707 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8708 NewFD->setInvalidDecl(); 8709 } 8710 8711 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8712 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8713 !NewFD->hasAttr<SectionAttr>()) { 8714 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8715 PragmaClangTextSection.SectionName, 8716 PragmaClangTextSection.PragmaLocation)); 8717 } 8718 8719 // Apply an implicit SectionAttr if #pragma code_seg is active. 8720 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8721 !NewFD->hasAttr<SectionAttr>()) { 8722 NewFD->addAttr( 8723 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8724 CodeSegStack.CurrentValue->getString(), 8725 CodeSegStack.CurrentPragmaLocation)); 8726 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8727 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8728 ASTContext::PSF_Read, 8729 NewFD)) 8730 NewFD->dropAttr<SectionAttr>(); 8731 } 8732 8733 // Handle attributes. 8734 ProcessDeclAttributes(S, NewFD, D); 8735 8736 if (getLangOpts().OpenCL) { 8737 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8738 // type declaration will generate a compilation error. 8739 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8740 if (AddressSpace != LangAS::Default) { 8741 Diag(NewFD->getLocation(), 8742 diag::err_opencl_return_value_with_address_space); 8743 NewFD->setInvalidDecl(); 8744 } 8745 } 8746 8747 if (!getLangOpts().CPlusPlus) { 8748 // Perform semantic checking on the function declaration. 8749 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8750 CheckMain(NewFD, D.getDeclSpec()); 8751 8752 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8753 CheckMSVCRTEntryPoint(NewFD); 8754 8755 if (!NewFD->isInvalidDecl()) 8756 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8757 isMemberSpecialization)); 8758 else if (!Previous.empty()) 8759 // Recover gracefully from an invalid redeclaration. 8760 D.setRedeclaration(true); 8761 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8762 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8763 "previous declaration set still overloaded"); 8764 8765 // Diagnose no-prototype function declarations with calling conventions that 8766 // don't support variadic calls. Only do this in C and do it after merging 8767 // possibly prototyped redeclarations. 8768 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8769 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8770 CallingConv CC = FT->getExtInfo().getCC(); 8771 if (!supportsVariadicCall(CC)) { 8772 // Windows system headers sometimes accidentally use stdcall without 8773 // (void) parameters, so we relax this to a warning. 8774 int DiagID = 8775 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8776 Diag(NewFD->getLocation(), DiagID) 8777 << FunctionType::getNameForCallConv(CC); 8778 } 8779 } 8780 } else { 8781 // C++11 [replacement.functions]p3: 8782 // The program's definitions shall not be specified as inline. 8783 // 8784 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8785 // 8786 // Suppress the diagnostic if the function is __attribute__((used)), since 8787 // that forces an external definition to be emitted. 8788 if (D.getDeclSpec().isInlineSpecified() && 8789 NewFD->isReplaceableGlobalAllocationFunction() && 8790 !NewFD->hasAttr<UsedAttr>()) 8791 Diag(D.getDeclSpec().getInlineSpecLoc(), 8792 diag::ext_operator_new_delete_declared_inline) 8793 << NewFD->getDeclName(); 8794 8795 // If the declarator is a template-id, translate the parser's template 8796 // argument list into our AST format. 8797 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8798 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8799 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8800 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8801 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8802 TemplateId->NumArgs); 8803 translateTemplateArguments(TemplateArgsPtr, 8804 TemplateArgs); 8805 8806 HasExplicitTemplateArgs = true; 8807 8808 if (NewFD->isInvalidDecl()) { 8809 HasExplicitTemplateArgs = false; 8810 } else if (FunctionTemplate) { 8811 // Function template with explicit template arguments. 8812 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8813 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8814 8815 HasExplicitTemplateArgs = false; 8816 } else { 8817 assert((isFunctionTemplateSpecialization || 8818 D.getDeclSpec().isFriendSpecified()) && 8819 "should have a 'template<>' for this decl"); 8820 // "friend void foo<>(int);" is an implicit specialization decl. 8821 isFunctionTemplateSpecialization = true; 8822 } 8823 } else if (isFriend && isFunctionTemplateSpecialization) { 8824 // This combination is only possible in a recovery case; the user 8825 // wrote something like: 8826 // template <> friend void foo(int); 8827 // which we're recovering from as if the user had written: 8828 // friend void foo<>(int); 8829 // Go ahead and fake up a template id. 8830 HasExplicitTemplateArgs = true; 8831 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8832 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8833 } 8834 8835 // We do not add HD attributes to specializations here because 8836 // they may have different constexpr-ness compared to their 8837 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8838 // may end up with different effective targets. Instead, a 8839 // specialization inherits its target attributes from its template 8840 // in the CheckFunctionTemplateSpecialization() call below. 8841 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8842 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8843 8844 // If it's a friend (and only if it's a friend), it's possible 8845 // that either the specialized function type or the specialized 8846 // template is dependent, and therefore matching will fail. In 8847 // this case, don't check the specialization yet. 8848 bool InstantiationDependent = false; 8849 if (isFunctionTemplateSpecialization && isFriend && 8850 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8851 TemplateSpecializationType::anyDependentTemplateArguments( 8852 TemplateArgs, 8853 InstantiationDependent))) { 8854 assert(HasExplicitTemplateArgs && 8855 "friend function specialization without template args"); 8856 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8857 Previous)) 8858 NewFD->setInvalidDecl(); 8859 } else if (isFunctionTemplateSpecialization) { 8860 if (CurContext->isDependentContext() && CurContext->isRecord() 8861 && !isFriend) { 8862 isDependentClassScopeExplicitSpecialization = true; 8863 } else if (!NewFD->isInvalidDecl() && 8864 CheckFunctionTemplateSpecialization( 8865 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8866 Previous)) 8867 NewFD->setInvalidDecl(); 8868 8869 // C++ [dcl.stc]p1: 8870 // A storage-class-specifier shall not be specified in an explicit 8871 // specialization (14.7.3) 8872 FunctionTemplateSpecializationInfo *Info = 8873 NewFD->getTemplateSpecializationInfo(); 8874 if (Info && SC != SC_None) { 8875 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8876 Diag(NewFD->getLocation(), 8877 diag::err_explicit_specialization_inconsistent_storage_class) 8878 << SC 8879 << FixItHint::CreateRemoval( 8880 D.getDeclSpec().getStorageClassSpecLoc()); 8881 8882 else 8883 Diag(NewFD->getLocation(), 8884 diag::ext_explicit_specialization_storage_class) 8885 << FixItHint::CreateRemoval( 8886 D.getDeclSpec().getStorageClassSpecLoc()); 8887 } 8888 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8889 if (CheckMemberSpecialization(NewFD, Previous)) 8890 NewFD->setInvalidDecl(); 8891 } 8892 8893 // Perform semantic checking on the function declaration. 8894 if (!isDependentClassScopeExplicitSpecialization) { 8895 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8896 CheckMain(NewFD, D.getDeclSpec()); 8897 8898 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8899 CheckMSVCRTEntryPoint(NewFD); 8900 8901 if (!NewFD->isInvalidDecl()) 8902 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8903 isMemberSpecialization)); 8904 else if (!Previous.empty()) 8905 // Recover gracefully from an invalid redeclaration. 8906 D.setRedeclaration(true); 8907 } 8908 8909 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8910 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8911 "previous declaration set still overloaded"); 8912 8913 NamedDecl *PrincipalDecl = (FunctionTemplate 8914 ? cast<NamedDecl>(FunctionTemplate) 8915 : NewFD); 8916 8917 if (isFriend && NewFD->getPreviousDecl()) { 8918 AccessSpecifier Access = AS_public; 8919 if (!NewFD->isInvalidDecl()) 8920 Access = NewFD->getPreviousDecl()->getAccess(); 8921 8922 NewFD->setAccess(Access); 8923 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8924 } 8925 8926 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8927 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8928 PrincipalDecl->setNonMemberOperator(); 8929 8930 // If we have a function template, check the template parameter 8931 // list. This will check and merge default template arguments. 8932 if (FunctionTemplate) { 8933 FunctionTemplateDecl *PrevTemplate = 8934 FunctionTemplate->getPreviousDecl(); 8935 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8936 PrevTemplate ? PrevTemplate->getTemplateParameters() 8937 : nullptr, 8938 D.getDeclSpec().isFriendSpecified() 8939 ? (D.isFunctionDefinition() 8940 ? TPC_FriendFunctionTemplateDefinition 8941 : TPC_FriendFunctionTemplate) 8942 : (D.getCXXScopeSpec().isSet() && 8943 DC && DC->isRecord() && 8944 DC->isDependentContext()) 8945 ? TPC_ClassTemplateMember 8946 : TPC_FunctionTemplate); 8947 } 8948 8949 if (NewFD->isInvalidDecl()) { 8950 // Ignore all the rest of this. 8951 } else if (!D.isRedeclaration()) { 8952 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8953 AddToScope }; 8954 // Fake up an access specifier if it's supposed to be a class member. 8955 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8956 NewFD->setAccess(AS_public); 8957 8958 // Qualified decls generally require a previous declaration. 8959 if (D.getCXXScopeSpec().isSet()) { 8960 // ...with the major exception of templated-scope or 8961 // dependent-scope friend declarations. 8962 8963 // TODO: we currently also suppress this check in dependent 8964 // contexts because (1) the parameter depth will be off when 8965 // matching friend templates and (2) we might actually be 8966 // selecting a friend based on a dependent factor. But there 8967 // are situations where these conditions don't apply and we 8968 // can actually do this check immediately. 8969 if (isFriend && 8970 (TemplateParamLists.size() || 8971 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8972 CurContext->isDependentContext())) { 8973 // ignore these 8974 } else { 8975 // The user tried to provide an out-of-line definition for a 8976 // function that is a member of a class or namespace, but there 8977 // was no such member function declared (C++ [class.mfct]p2, 8978 // C++ [namespace.memdef]p2). For example: 8979 // 8980 // class X { 8981 // void f() const; 8982 // }; 8983 // 8984 // void X::f() { } // ill-formed 8985 // 8986 // Complain about this problem, and attempt to suggest close 8987 // matches (e.g., those that differ only in cv-qualifiers and 8988 // whether the parameter types are references). 8989 8990 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8991 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8992 AddToScope = ExtraArgs.AddToScope; 8993 return Result; 8994 } 8995 } 8996 8997 // Unqualified local friend declarations are required to resolve 8998 // to something. 8999 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9000 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9001 *this, Previous, NewFD, ExtraArgs, true, S)) { 9002 AddToScope = ExtraArgs.AddToScope; 9003 return Result; 9004 } 9005 } 9006 } else if (!D.isFunctionDefinition() && 9007 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9008 !isFriend && !isFunctionTemplateSpecialization && 9009 !isMemberSpecialization) { 9010 // An out-of-line member function declaration must also be a 9011 // definition (C++ [class.mfct]p2). 9012 // Note that this is not the case for explicit specializations of 9013 // function templates or member functions of class templates, per 9014 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9015 // extension for compatibility with old SWIG code which likes to 9016 // generate them. 9017 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9018 << D.getCXXScopeSpec().getRange(); 9019 } 9020 } 9021 9022 ProcessPragmaWeak(S, NewFD); 9023 checkAttributesAfterMerging(*this, *NewFD); 9024 9025 AddKnownFunctionAttributes(NewFD); 9026 9027 if (NewFD->hasAttr<OverloadableAttr>() && 9028 !NewFD->getType()->getAs<FunctionProtoType>()) { 9029 Diag(NewFD->getLocation(), 9030 diag::err_attribute_overloadable_no_prototype) 9031 << NewFD; 9032 9033 // Turn this into a variadic function with no parameters. 9034 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9035 FunctionProtoType::ExtProtoInfo EPI( 9036 Context.getDefaultCallingConvention(true, false)); 9037 EPI.Variadic = true; 9038 EPI.ExtInfo = FT->getExtInfo(); 9039 9040 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9041 NewFD->setType(R); 9042 } 9043 9044 // If there's a #pragma GCC visibility in scope, and this isn't a class 9045 // member, set the visibility of this function. 9046 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9047 AddPushedVisibilityAttribute(NewFD); 9048 9049 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9050 // marking the function. 9051 AddCFAuditedAttribute(NewFD); 9052 9053 // If this is a function definition, check if we have to apply optnone due to 9054 // a pragma. 9055 if(D.isFunctionDefinition()) 9056 AddRangeBasedOptnone(NewFD); 9057 9058 // If this is the first declaration of an extern C variable, update 9059 // the map of such variables. 9060 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9061 isIncompleteDeclExternC(*this, NewFD)) 9062 RegisterLocallyScopedExternCDecl(NewFD, S); 9063 9064 // Set this FunctionDecl's range up to the right paren. 9065 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9066 9067 if (D.isRedeclaration() && !Previous.empty()) { 9068 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9069 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9070 isMemberSpecialization || 9071 isFunctionTemplateSpecialization, 9072 D.isFunctionDefinition()); 9073 } 9074 9075 if (getLangOpts().CUDA) { 9076 IdentifierInfo *II = NewFD->getIdentifier(); 9077 if (II && 9078 II->isStr(getLangOpts().HIP ? "hipConfigureCall" 9079 : "cudaConfigureCall") && 9080 !NewFD->isInvalidDecl() && 9081 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9082 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9083 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9084 Context.setcudaConfigureCallDecl(NewFD); 9085 } 9086 9087 // Variadic functions, other than a *declaration* of printf, are not allowed 9088 // in device-side CUDA code, unless someone passed 9089 // -fcuda-allow-variadic-functions. 9090 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9091 (NewFD->hasAttr<CUDADeviceAttr>() || 9092 NewFD->hasAttr<CUDAGlobalAttr>()) && 9093 !(II && II->isStr("printf") && NewFD->isExternC() && 9094 !D.isFunctionDefinition())) { 9095 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9096 } 9097 } 9098 9099 MarkUnusedFileScopedDecl(NewFD); 9100 9101 if (getLangOpts().CPlusPlus) { 9102 if (FunctionTemplate) { 9103 if (NewFD->isInvalidDecl()) 9104 FunctionTemplate->setInvalidDecl(); 9105 return FunctionTemplate; 9106 } 9107 9108 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9109 CompleteMemberSpecialization(NewFD, Previous); 9110 } 9111 9112 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9113 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9114 if ((getLangOpts().OpenCLVersion >= 120) 9115 && (SC == SC_Static)) { 9116 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9117 D.setInvalidType(); 9118 } 9119 9120 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9121 if (!NewFD->getReturnType()->isVoidType()) { 9122 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9123 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9124 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9125 : FixItHint()); 9126 D.setInvalidType(); 9127 } 9128 9129 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9130 for (auto Param : NewFD->parameters()) 9131 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9132 } 9133 for (const ParmVarDecl *Param : NewFD->parameters()) { 9134 QualType PT = Param->getType(); 9135 9136 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9137 // types. 9138 if (getLangOpts().OpenCLVersion >= 200) { 9139 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9140 QualType ElemTy = PipeTy->getElementType(); 9141 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9142 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9143 D.setInvalidType(); 9144 } 9145 } 9146 } 9147 } 9148 9149 // Here we have an function template explicit specialization at class scope. 9150 // The actual specialization will be postponed to template instatiation 9151 // time via the ClassScopeFunctionSpecializationDecl node. 9152 if (isDependentClassScopeExplicitSpecialization) { 9153 ClassScopeFunctionSpecializationDecl *NewSpec = 9154 ClassScopeFunctionSpecializationDecl::Create( 9155 Context, CurContext, NewFD->getLocation(), 9156 cast<CXXMethodDecl>(NewFD), 9157 HasExplicitTemplateArgs, TemplateArgs); 9158 CurContext->addDecl(NewSpec); 9159 AddToScope = false; 9160 } 9161 9162 // Diagnose availability attributes. Availability cannot be used on functions 9163 // that are run during load/unload. 9164 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9165 if (NewFD->hasAttr<ConstructorAttr>()) { 9166 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9167 << 1; 9168 NewFD->dropAttr<AvailabilityAttr>(); 9169 } 9170 if (NewFD->hasAttr<DestructorAttr>()) { 9171 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9172 << 2; 9173 NewFD->dropAttr<AvailabilityAttr>(); 9174 } 9175 } 9176 9177 return NewFD; 9178 } 9179 9180 /// Checks if the new declaration declared in dependent context must be 9181 /// put in the same redeclaration chain as the specified declaration. 9182 /// 9183 /// \param D Declaration that is checked. 9184 /// \param PrevDecl Previous declaration found with proper lookup method for the 9185 /// same declaration name. 9186 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9187 /// belongs to. 9188 /// 9189 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9190 // Any declarations should be put into redeclaration chains except for 9191 // friend declaration in a dependent context that names a function in 9192 // namespace scope. 9193 // 9194 // This allows to compile code like: 9195 // 9196 // void func(); 9197 // template<typename T> class C1 { friend void func() { } }; 9198 // template<typename T> class C2 { friend void func() { } }; 9199 // 9200 // This code snippet is a valid code unless both templates are instantiated. 9201 return !(D->getLexicalDeclContext()->isDependentContext() && 9202 D->getDeclContext()->isFileContext() && 9203 D->getFriendObjectKind() != Decl::FOK_None); 9204 } 9205 9206 /// Check the target attribute of the function for MultiVersion 9207 /// validity. 9208 /// 9209 /// Returns true if there was an error, false otherwise. 9210 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9211 const auto *TA = FD->getAttr<TargetAttr>(); 9212 assert(TA && "MultiVersion Candidate requires a target attribute"); 9213 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9214 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9215 enum ErrType { Feature = 0, Architecture = 1 }; 9216 9217 if (!ParseInfo.Architecture.empty() && 9218 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9219 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9220 << Architecture << ParseInfo.Architecture; 9221 return true; 9222 } 9223 9224 for (const auto &Feat : ParseInfo.Features) { 9225 auto BareFeat = StringRef{Feat}.substr(1); 9226 if (Feat[0] == '-') { 9227 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9228 << Feature << ("no-" + BareFeat).str(); 9229 return true; 9230 } 9231 9232 if (!TargetInfo.validateCpuSupports(BareFeat) || 9233 !TargetInfo.isValidFeatureName(BareFeat)) { 9234 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9235 << Feature << BareFeat; 9236 return true; 9237 } 9238 } 9239 return false; 9240 } 9241 9242 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9243 const FunctionDecl *NewFD, 9244 bool CausesMV) { 9245 enum DoesntSupport { 9246 FuncTemplates = 0, 9247 VirtFuncs = 1, 9248 DeducedReturn = 2, 9249 Constructors = 3, 9250 Destructors = 4, 9251 DeletedFuncs = 5, 9252 DefaultedFuncs = 6 9253 }; 9254 enum Different { 9255 CallingConv = 0, 9256 ReturnType = 1, 9257 ConstexprSpec = 2, 9258 InlineSpec = 3, 9259 StorageClass = 4, 9260 Linkage = 5 9261 }; 9262 9263 // For now, disallow all other attributes. These should be opt-in, but 9264 // an analysis of all of them is a future FIXME. 9265 if (CausesMV && OldFD && 9266 std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) { 9267 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs); 9268 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9269 return true; 9270 } 9271 9272 if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1) 9273 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs); 9274 9275 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9276 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9277 << FuncTemplates; 9278 9279 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9280 if (NewCXXFD->isVirtual()) 9281 return S.Diag(NewCXXFD->getLocation(), 9282 diag::err_multiversion_doesnt_support) 9283 << VirtFuncs; 9284 9285 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9286 return S.Diag(NewCXXCtor->getLocation(), 9287 diag::err_multiversion_doesnt_support) 9288 << Constructors; 9289 9290 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9291 return S.Diag(NewCXXDtor->getLocation(), 9292 diag::err_multiversion_doesnt_support) 9293 << Destructors; 9294 } 9295 9296 if (NewFD->isDeleted()) 9297 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9298 << DeletedFuncs; 9299 9300 if (NewFD->isDefaulted()) 9301 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9302 << DefaultedFuncs; 9303 9304 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9305 const auto *NewType = cast<FunctionType>(NewQType); 9306 QualType NewReturnType = NewType->getReturnType(); 9307 9308 if (NewReturnType->isUndeducedType()) 9309 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9310 << DeducedReturn; 9311 9312 // Only allow transition to MultiVersion if it hasn't been used. 9313 if (OldFD && CausesMV && OldFD->isUsed(false)) 9314 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9315 9316 // Ensure the return type is identical. 9317 if (OldFD) { 9318 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9319 const auto *OldType = cast<FunctionType>(OldQType); 9320 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9321 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9322 9323 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9324 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9325 << CallingConv; 9326 9327 QualType OldReturnType = OldType->getReturnType(); 9328 9329 if (OldReturnType != NewReturnType) 9330 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9331 << ReturnType; 9332 9333 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9334 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9335 << ConstexprSpec; 9336 9337 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9338 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9339 << InlineSpec; 9340 9341 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9342 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9343 << StorageClass; 9344 9345 if (OldFD->isExternC() != NewFD->isExternC()) 9346 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9347 << Linkage; 9348 9349 if (S.CheckEquivalentExceptionSpec( 9350 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9351 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9352 return true; 9353 } 9354 return false; 9355 } 9356 9357 /// Check the validity of a mulitversion function declaration. 9358 /// Also sets the multiversion'ness' of the function itself. 9359 /// 9360 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9361 /// 9362 /// Returns true if there was an error, false otherwise. 9363 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9364 bool &Redeclaration, NamedDecl *&OldDecl, 9365 bool &MergeTypeWithPrevious, 9366 LookupResult &Previous) { 9367 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9368 if (NewFD->isMain()) { 9369 if (NewTA && NewTA->isDefaultVersion()) { 9370 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9371 NewFD->setInvalidDecl(); 9372 return true; 9373 } 9374 return false; 9375 } 9376 9377 // If there is no matching previous decl, only 'default' can 9378 // cause MultiVersioning. 9379 if (!OldDecl) { 9380 if (NewTA && NewTA->isDefaultVersion()) { 9381 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 9382 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9383 NewFD->setInvalidDecl(); 9384 return true; 9385 } 9386 if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) { 9387 NewFD->setInvalidDecl(); 9388 return true; 9389 } 9390 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9391 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9392 NewFD->setInvalidDecl(); 9393 return true; 9394 } 9395 9396 NewFD->setIsMultiVersion(); 9397 } 9398 return false; 9399 } 9400 9401 if (OldDecl->getDeclContext()->getRedeclContext() != 9402 NewFD->getDeclContext()->getRedeclContext()) 9403 return false; 9404 9405 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9406 // Unresolved 'using' statements (the other way OldDecl can be not a function) 9407 // likely cannot cause a problem here. 9408 if (!OldFD) 9409 return false; 9410 9411 if (!OldFD->isMultiVersion() && !NewTA) 9412 return false; 9413 9414 if (OldFD->isMultiVersion() && !NewTA) { 9415 S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl); 9416 NewFD->setInvalidDecl(); 9417 return true; 9418 } 9419 9420 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9421 // Sort order doesn't matter, it just needs to be consistent. 9422 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end()); 9423 9424 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9425 if (!OldFD->isMultiVersion()) { 9426 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9427 // to change, this is a simple redeclaration. 9428 if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()) 9429 return false; 9430 9431 // Otherwise, this decl causes MultiVersioning. 9432 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9433 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9434 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9435 NewFD->setInvalidDecl(); 9436 return true; 9437 } 9438 9439 if (!OldFD->getType()->getAs<FunctionProtoType>()) { 9440 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9441 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9442 NewFD->setInvalidDecl(); 9443 return true; 9444 } 9445 9446 if (CheckMultiVersionValue(S, NewFD)) { 9447 NewFD->setInvalidDecl(); 9448 return true; 9449 } 9450 9451 if (CheckMultiVersionValue(S, OldFD)) { 9452 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9453 NewFD->setInvalidDecl(); 9454 return true; 9455 } 9456 9457 TargetAttr::ParsedTargetAttr OldParsed = 9458 OldTA->parse(std::less<std::string>()); 9459 9460 if (OldParsed == NewParsed) { 9461 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9462 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9463 NewFD->setInvalidDecl(); 9464 return true; 9465 } 9466 9467 for (const auto *FD : OldFD->redecls()) { 9468 const auto *CurTA = FD->getAttr<TargetAttr>(); 9469 if (!CurTA || CurTA->isInherited()) { 9470 S.Diag(FD->getLocation(), diag::err_target_required_in_redecl); 9471 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9472 NewFD->setInvalidDecl(); 9473 return true; 9474 } 9475 } 9476 9477 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) { 9478 NewFD->setInvalidDecl(); 9479 return true; 9480 } 9481 9482 OldFD->setIsMultiVersion(); 9483 NewFD->setIsMultiVersion(); 9484 Redeclaration = false; 9485 MergeTypeWithPrevious = false; 9486 OldDecl = nullptr; 9487 Previous.clear(); 9488 return false; 9489 } 9490 9491 bool UseMemberUsingDeclRules = 9492 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9493 9494 // Next, check ALL non-overloads to see if this is a redeclaration of a 9495 // previous member of the MultiVersion set. 9496 for (NamedDecl *ND : Previous) { 9497 FunctionDecl *CurFD = ND->getAsFunction(); 9498 if (!CurFD) 9499 continue; 9500 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9501 continue; 9502 9503 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9504 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9505 NewFD->setIsMultiVersion(); 9506 Redeclaration = true; 9507 OldDecl = ND; 9508 return false; 9509 } 9510 9511 TargetAttr::ParsedTargetAttr CurParsed = 9512 CurTA->parse(std::less<std::string>()); 9513 9514 if (CurParsed == NewParsed) { 9515 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9516 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9517 NewFD->setInvalidDecl(); 9518 return true; 9519 } 9520 } 9521 9522 // Else, this is simply a non-redecl case. 9523 if (CheckMultiVersionValue(S, NewFD)) { 9524 NewFD->setInvalidDecl(); 9525 return true; 9526 } 9527 9528 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) { 9529 NewFD->setInvalidDecl(); 9530 return true; 9531 } 9532 9533 NewFD->setIsMultiVersion(); 9534 Redeclaration = false; 9535 MergeTypeWithPrevious = false; 9536 OldDecl = nullptr; 9537 Previous.clear(); 9538 return false; 9539 } 9540 9541 /// Perform semantic checking of a new function declaration. 9542 /// 9543 /// Performs semantic analysis of the new function declaration 9544 /// NewFD. This routine performs all semantic checking that does not 9545 /// require the actual declarator involved in the declaration, and is 9546 /// used both for the declaration of functions as they are parsed 9547 /// (called via ActOnDeclarator) and for the declaration of functions 9548 /// that have been instantiated via C++ template instantiation (called 9549 /// via InstantiateDecl). 9550 /// 9551 /// \param IsMemberSpecialization whether this new function declaration is 9552 /// a member specialization (that replaces any definition provided by the 9553 /// previous declaration). 9554 /// 9555 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9556 /// 9557 /// \returns true if the function declaration is a redeclaration. 9558 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9559 LookupResult &Previous, 9560 bool IsMemberSpecialization) { 9561 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9562 "Variably modified return types are not handled here"); 9563 9564 // Determine whether the type of this function should be merged with 9565 // a previous visible declaration. This never happens for functions in C++, 9566 // and always happens in C if the previous declaration was visible. 9567 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9568 !Previous.isShadowed(); 9569 9570 bool Redeclaration = false; 9571 NamedDecl *OldDecl = nullptr; 9572 bool MayNeedOverloadableChecks = false; 9573 9574 // Merge or overload the declaration with an existing declaration of 9575 // the same name, if appropriate. 9576 if (!Previous.empty()) { 9577 // Determine whether NewFD is an overload of PrevDecl or 9578 // a declaration that requires merging. If it's an overload, 9579 // there's no more work to do here; we'll just add the new 9580 // function to the scope. 9581 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9582 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9583 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9584 Redeclaration = true; 9585 OldDecl = Candidate; 9586 } 9587 } else { 9588 MayNeedOverloadableChecks = true; 9589 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9590 /*NewIsUsingDecl*/ false)) { 9591 case Ovl_Match: 9592 Redeclaration = true; 9593 break; 9594 9595 case Ovl_NonFunction: 9596 Redeclaration = true; 9597 break; 9598 9599 case Ovl_Overload: 9600 Redeclaration = false; 9601 break; 9602 } 9603 } 9604 } 9605 9606 // Check for a previous extern "C" declaration with this name. 9607 if (!Redeclaration && 9608 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9609 if (!Previous.empty()) { 9610 // This is an extern "C" declaration with the same name as a previous 9611 // declaration, and thus redeclares that entity... 9612 Redeclaration = true; 9613 OldDecl = Previous.getFoundDecl(); 9614 MergeTypeWithPrevious = false; 9615 9616 // ... except in the presence of __attribute__((overloadable)). 9617 if (OldDecl->hasAttr<OverloadableAttr>() || 9618 NewFD->hasAttr<OverloadableAttr>()) { 9619 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9620 MayNeedOverloadableChecks = true; 9621 Redeclaration = false; 9622 OldDecl = nullptr; 9623 } 9624 } 9625 } 9626 } 9627 9628 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 9629 MergeTypeWithPrevious, Previous)) 9630 return Redeclaration; 9631 9632 // C++11 [dcl.constexpr]p8: 9633 // A constexpr specifier for a non-static member function that is not 9634 // a constructor declares that member function to be const. 9635 // 9636 // This needs to be delayed until we know whether this is an out-of-line 9637 // definition of a static member function. 9638 // 9639 // This rule is not present in C++1y, so we produce a backwards 9640 // compatibility warning whenever it happens in C++11. 9641 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9642 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9643 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9644 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9645 CXXMethodDecl *OldMD = nullptr; 9646 if (OldDecl) 9647 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9648 if (!OldMD || !OldMD->isStatic()) { 9649 const FunctionProtoType *FPT = 9650 MD->getType()->castAs<FunctionProtoType>(); 9651 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9652 EPI.TypeQuals |= Qualifiers::Const; 9653 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9654 FPT->getParamTypes(), EPI)); 9655 9656 // Warn that we did this, if we're not performing template instantiation. 9657 // In that case, we'll have warned already when the template was defined. 9658 if (!inTemplateInstantiation()) { 9659 SourceLocation AddConstLoc; 9660 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9661 .IgnoreParens().getAs<FunctionTypeLoc>()) 9662 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9663 9664 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9665 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9666 } 9667 } 9668 } 9669 9670 if (Redeclaration) { 9671 // NewFD and OldDecl represent declarations that need to be 9672 // merged. 9673 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9674 NewFD->setInvalidDecl(); 9675 return Redeclaration; 9676 } 9677 9678 Previous.clear(); 9679 Previous.addDecl(OldDecl); 9680 9681 if (FunctionTemplateDecl *OldTemplateDecl = 9682 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9683 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 9684 NewFD->setPreviousDeclaration(OldFD); 9685 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9686 FunctionTemplateDecl *NewTemplateDecl 9687 = NewFD->getDescribedFunctionTemplate(); 9688 assert(NewTemplateDecl && "Template/non-template mismatch"); 9689 if (NewFD->isCXXClassMember()) { 9690 NewFD->setAccess(OldTemplateDecl->getAccess()); 9691 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9692 } 9693 9694 // If this is an explicit specialization of a member that is a function 9695 // template, mark it as a member specialization. 9696 if (IsMemberSpecialization && 9697 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9698 NewTemplateDecl->setMemberSpecialization(); 9699 assert(OldTemplateDecl->isMemberSpecialization()); 9700 // Explicit specializations of a member template do not inherit deleted 9701 // status from the parent member template that they are specializing. 9702 if (OldFD->isDeleted()) { 9703 // FIXME: This assert will not hold in the presence of modules. 9704 assert(OldFD->getCanonicalDecl() == OldFD); 9705 // FIXME: We need an update record for this AST mutation. 9706 OldFD->setDeletedAsWritten(false); 9707 } 9708 } 9709 9710 } else { 9711 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9712 auto *OldFD = cast<FunctionDecl>(OldDecl); 9713 // This needs to happen first so that 'inline' propagates. 9714 NewFD->setPreviousDeclaration(OldFD); 9715 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9716 if (NewFD->isCXXClassMember()) 9717 NewFD->setAccess(OldFD->getAccess()); 9718 } 9719 } 9720 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9721 !NewFD->getAttr<OverloadableAttr>()) { 9722 assert((Previous.empty() || 9723 llvm::any_of(Previous, 9724 [](const NamedDecl *ND) { 9725 return ND->hasAttr<OverloadableAttr>(); 9726 })) && 9727 "Non-redecls shouldn't happen without overloadable present"); 9728 9729 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9730 const auto *FD = dyn_cast<FunctionDecl>(ND); 9731 return FD && !FD->hasAttr<OverloadableAttr>(); 9732 }); 9733 9734 if (OtherUnmarkedIter != Previous.end()) { 9735 Diag(NewFD->getLocation(), 9736 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9737 Diag((*OtherUnmarkedIter)->getLocation(), 9738 diag::note_attribute_overloadable_prev_overload) 9739 << false; 9740 9741 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9742 } 9743 } 9744 9745 // Semantic checking for this function declaration (in isolation). 9746 9747 if (getLangOpts().CPlusPlus) { 9748 // C++-specific checks. 9749 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9750 CheckConstructor(Constructor); 9751 } else if (CXXDestructorDecl *Destructor = 9752 dyn_cast<CXXDestructorDecl>(NewFD)) { 9753 CXXRecordDecl *Record = Destructor->getParent(); 9754 QualType ClassType = Context.getTypeDeclType(Record); 9755 9756 // FIXME: Shouldn't we be able to perform this check even when the class 9757 // type is dependent? Both gcc and edg can handle that. 9758 if (!ClassType->isDependentType()) { 9759 DeclarationName Name 9760 = Context.DeclarationNames.getCXXDestructorName( 9761 Context.getCanonicalType(ClassType)); 9762 if (NewFD->getDeclName() != Name) { 9763 Diag(NewFD->getLocation(), diag::err_destructor_name); 9764 NewFD->setInvalidDecl(); 9765 return Redeclaration; 9766 } 9767 } 9768 } else if (CXXConversionDecl *Conversion 9769 = dyn_cast<CXXConversionDecl>(NewFD)) { 9770 ActOnConversionDeclarator(Conversion); 9771 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9772 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9773 CheckDeductionGuideTemplate(TD); 9774 9775 // A deduction guide is not on the list of entities that can be 9776 // explicitly specialized. 9777 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9778 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9779 << /*explicit specialization*/ 1; 9780 } 9781 9782 // Find any virtual functions that this function overrides. 9783 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9784 if (!Method->isFunctionTemplateSpecialization() && 9785 !Method->getDescribedFunctionTemplate() && 9786 Method->isCanonicalDecl()) { 9787 if (AddOverriddenMethods(Method->getParent(), Method)) { 9788 // If the function was marked as "static", we have a problem. 9789 if (NewFD->getStorageClass() == SC_Static) { 9790 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9791 } 9792 } 9793 } 9794 9795 if (Method->isStatic()) 9796 checkThisInStaticMemberFunctionType(Method); 9797 } 9798 9799 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9800 if (NewFD->isOverloadedOperator() && 9801 CheckOverloadedOperatorDeclaration(NewFD)) { 9802 NewFD->setInvalidDecl(); 9803 return Redeclaration; 9804 } 9805 9806 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9807 if (NewFD->getLiteralIdentifier() && 9808 CheckLiteralOperatorDeclaration(NewFD)) { 9809 NewFD->setInvalidDecl(); 9810 return Redeclaration; 9811 } 9812 9813 // In C++, check default arguments now that we have merged decls. Unless 9814 // the lexical context is the class, because in this case this is done 9815 // during delayed parsing anyway. 9816 if (!CurContext->isRecord()) 9817 CheckCXXDefaultArguments(NewFD); 9818 9819 // If this function declares a builtin function, check the type of this 9820 // declaration against the expected type for the builtin. 9821 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9822 ASTContext::GetBuiltinTypeError Error; 9823 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9824 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9825 // If the type of the builtin differs only in its exception 9826 // specification, that's OK. 9827 // FIXME: If the types do differ in this way, it would be better to 9828 // retain the 'noexcept' form of the type. 9829 if (!T.isNull() && 9830 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9831 NewFD->getType())) 9832 // The type of this function differs from the type of the builtin, 9833 // so forget about the builtin entirely. 9834 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9835 } 9836 9837 // If this function is declared as being extern "C", then check to see if 9838 // the function returns a UDT (class, struct, or union type) that is not C 9839 // compatible, and if it does, warn the user. 9840 // But, issue any diagnostic on the first declaration only. 9841 if (Previous.empty() && NewFD->isExternC()) { 9842 QualType R = NewFD->getReturnType(); 9843 if (R->isIncompleteType() && !R->isVoidType()) 9844 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9845 << NewFD << R; 9846 else if (!R.isPODType(Context) && !R->isVoidType() && 9847 !R->isObjCObjectPointerType()) 9848 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9849 } 9850 9851 // C++1z [dcl.fct]p6: 9852 // [...] whether the function has a non-throwing exception-specification 9853 // [is] part of the function type 9854 // 9855 // This results in an ABI break between C++14 and C++17 for functions whose 9856 // declared type includes an exception-specification in a parameter or 9857 // return type. (Exception specifications on the function itself are OK in 9858 // most cases, and exception specifications are not permitted in most other 9859 // contexts where they could make it into a mangling.) 9860 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 9861 auto HasNoexcept = [&](QualType T) -> bool { 9862 // Strip off declarator chunks that could be between us and a function 9863 // type. We don't need to look far, exception specifications are very 9864 // restricted prior to C++17. 9865 if (auto *RT = T->getAs<ReferenceType>()) 9866 T = RT->getPointeeType(); 9867 else if (T->isAnyPointerType()) 9868 T = T->getPointeeType(); 9869 else if (auto *MPT = T->getAs<MemberPointerType>()) 9870 T = MPT->getPointeeType(); 9871 if (auto *FPT = T->getAs<FunctionProtoType>()) 9872 if (FPT->isNothrow()) 9873 return true; 9874 return false; 9875 }; 9876 9877 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9878 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9879 for (QualType T : FPT->param_types()) 9880 AnyNoexcept |= HasNoexcept(T); 9881 if (AnyNoexcept) 9882 Diag(NewFD->getLocation(), 9883 diag::warn_cxx17_compat_exception_spec_in_signature) 9884 << NewFD; 9885 } 9886 9887 if (!Redeclaration && LangOpts.CUDA) 9888 checkCUDATargetOverload(NewFD, Previous); 9889 } 9890 return Redeclaration; 9891 } 9892 9893 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9894 // C++11 [basic.start.main]p3: 9895 // A program that [...] declares main to be inline, static or 9896 // constexpr is ill-formed. 9897 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9898 // appear in a declaration of main. 9899 // static main is not an error under C99, but we should warn about it. 9900 // We accept _Noreturn main as an extension. 9901 if (FD->getStorageClass() == SC_Static) 9902 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9903 ? diag::err_static_main : diag::warn_static_main) 9904 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9905 if (FD->isInlineSpecified()) 9906 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9907 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9908 if (DS.isNoreturnSpecified()) { 9909 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9910 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9911 Diag(NoreturnLoc, diag::ext_noreturn_main); 9912 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9913 << FixItHint::CreateRemoval(NoreturnRange); 9914 } 9915 if (FD->isConstexpr()) { 9916 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9917 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9918 FD->setConstexpr(false); 9919 } 9920 9921 if (getLangOpts().OpenCL) { 9922 Diag(FD->getLocation(), diag::err_opencl_no_main) 9923 << FD->hasAttr<OpenCLKernelAttr>(); 9924 FD->setInvalidDecl(); 9925 return; 9926 } 9927 9928 QualType T = FD->getType(); 9929 assert(T->isFunctionType() && "function decl is not of function type"); 9930 const FunctionType* FT = T->castAs<FunctionType>(); 9931 9932 // Set default calling convention for main() 9933 if (FT->getCallConv() != CC_C) { 9934 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 9935 FD->setType(QualType(FT, 0)); 9936 T = Context.getCanonicalType(FD->getType()); 9937 } 9938 9939 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9940 // In C with GNU extensions we allow main() to have non-integer return 9941 // type, but we should warn about the extension, and we disable the 9942 // implicit-return-zero rule. 9943 9944 // GCC in C mode accepts qualified 'int'. 9945 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9946 FD->setHasImplicitReturnZero(true); 9947 else { 9948 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9949 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9950 if (RTRange.isValid()) 9951 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9952 << FixItHint::CreateReplacement(RTRange, "int"); 9953 } 9954 } else { 9955 // In C and C++, main magically returns 0 if you fall off the end; 9956 // set the flag which tells us that. 9957 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9958 9959 // All the standards say that main() should return 'int'. 9960 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9961 FD->setHasImplicitReturnZero(true); 9962 else { 9963 // Otherwise, this is just a flat-out error. 9964 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9965 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9966 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9967 : FixItHint()); 9968 FD->setInvalidDecl(true); 9969 } 9970 } 9971 9972 // Treat protoless main() as nullary. 9973 if (isa<FunctionNoProtoType>(FT)) return; 9974 9975 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9976 unsigned nparams = FTP->getNumParams(); 9977 assert(FD->getNumParams() == nparams); 9978 9979 bool HasExtraParameters = (nparams > 3); 9980 9981 if (FTP->isVariadic()) { 9982 Diag(FD->getLocation(), diag::ext_variadic_main); 9983 // FIXME: if we had information about the location of the ellipsis, we 9984 // could add a FixIt hint to remove it as a parameter. 9985 } 9986 9987 // Darwin passes an undocumented fourth argument of type char**. If 9988 // other platforms start sprouting these, the logic below will start 9989 // getting shifty. 9990 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9991 HasExtraParameters = false; 9992 9993 if (HasExtraParameters) { 9994 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9995 FD->setInvalidDecl(true); 9996 nparams = 3; 9997 } 9998 9999 // FIXME: a lot of the following diagnostics would be improved 10000 // if we had some location information about types. 10001 10002 QualType CharPP = 10003 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10004 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10005 10006 for (unsigned i = 0; i < nparams; ++i) { 10007 QualType AT = FTP->getParamType(i); 10008 10009 bool mismatch = true; 10010 10011 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10012 mismatch = false; 10013 else if (Expected[i] == CharPP) { 10014 // As an extension, the following forms are okay: 10015 // char const ** 10016 // char const * const * 10017 // char * const * 10018 10019 QualifierCollector qs; 10020 const PointerType* PT; 10021 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10022 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10023 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10024 Context.CharTy)) { 10025 qs.removeConst(); 10026 mismatch = !qs.empty(); 10027 } 10028 } 10029 10030 if (mismatch) { 10031 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10032 // TODO: suggest replacing given type with expected type 10033 FD->setInvalidDecl(true); 10034 } 10035 } 10036 10037 if (nparams == 1 && !FD->isInvalidDecl()) { 10038 Diag(FD->getLocation(), diag::warn_main_one_arg); 10039 } 10040 10041 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10042 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10043 FD->setInvalidDecl(); 10044 } 10045 } 10046 10047 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10048 QualType T = FD->getType(); 10049 assert(T->isFunctionType() && "function decl is not of function type"); 10050 const FunctionType *FT = T->castAs<FunctionType>(); 10051 10052 // Set an implicit return of 'zero' if the function can return some integral, 10053 // enumeration, pointer or nullptr type. 10054 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10055 FT->getReturnType()->isAnyPointerType() || 10056 FT->getReturnType()->isNullPtrType()) 10057 // DllMain is exempt because a return value of zero means it failed. 10058 if (FD->getName() != "DllMain") 10059 FD->setHasImplicitReturnZero(true); 10060 10061 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10062 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10063 FD->setInvalidDecl(); 10064 } 10065 } 10066 10067 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10068 // FIXME: Need strict checking. In C89, we need to check for 10069 // any assignment, increment, decrement, function-calls, or 10070 // commas outside of a sizeof. In C99, it's the same list, 10071 // except that the aforementioned are allowed in unevaluated 10072 // expressions. Everything else falls under the 10073 // "may accept other forms of constant expressions" exception. 10074 // (We never end up here for C++, so the constant expression 10075 // rules there don't matter.) 10076 const Expr *Culprit; 10077 if (Init->isConstantInitializer(Context, false, &Culprit)) 10078 return false; 10079 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10080 << Culprit->getSourceRange(); 10081 return true; 10082 } 10083 10084 namespace { 10085 // Visits an initialization expression to see if OrigDecl is evaluated in 10086 // its own initialization and throws a warning if it does. 10087 class SelfReferenceChecker 10088 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10089 Sema &S; 10090 Decl *OrigDecl; 10091 bool isRecordType; 10092 bool isPODType; 10093 bool isReferenceType; 10094 10095 bool isInitList; 10096 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10097 10098 public: 10099 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10100 10101 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10102 S(S), OrigDecl(OrigDecl) { 10103 isPODType = false; 10104 isRecordType = false; 10105 isReferenceType = false; 10106 isInitList = false; 10107 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10108 isPODType = VD->getType().isPODType(S.Context); 10109 isRecordType = VD->getType()->isRecordType(); 10110 isReferenceType = VD->getType()->isReferenceType(); 10111 } 10112 } 10113 10114 // For most expressions, just call the visitor. For initializer lists, 10115 // track the index of the field being initialized since fields are 10116 // initialized in order allowing use of previously initialized fields. 10117 void CheckExpr(Expr *E) { 10118 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10119 if (!InitList) { 10120 Visit(E); 10121 return; 10122 } 10123 10124 // Track and increment the index here. 10125 isInitList = true; 10126 InitFieldIndex.push_back(0); 10127 for (auto Child : InitList->children()) { 10128 CheckExpr(cast<Expr>(Child)); 10129 ++InitFieldIndex.back(); 10130 } 10131 InitFieldIndex.pop_back(); 10132 } 10133 10134 // Returns true if MemberExpr is checked and no further checking is needed. 10135 // Returns false if additional checking is required. 10136 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10137 llvm::SmallVector<FieldDecl*, 4> Fields; 10138 Expr *Base = E; 10139 bool ReferenceField = false; 10140 10141 // Get the field memebers used. 10142 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10143 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10144 if (!FD) 10145 return false; 10146 Fields.push_back(FD); 10147 if (FD->getType()->isReferenceType()) 10148 ReferenceField = true; 10149 Base = ME->getBase()->IgnoreParenImpCasts(); 10150 } 10151 10152 // Keep checking only if the base Decl is the same. 10153 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10154 if (!DRE || DRE->getDecl() != OrigDecl) 10155 return false; 10156 10157 // A reference field can be bound to an unininitialized field. 10158 if (CheckReference && !ReferenceField) 10159 return true; 10160 10161 // Convert FieldDecls to their index number. 10162 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10163 for (const FieldDecl *I : llvm::reverse(Fields)) 10164 UsedFieldIndex.push_back(I->getFieldIndex()); 10165 10166 // See if a warning is needed by checking the first difference in index 10167 // numbers. If field being used has index less than the field being 10168 // initialized, then the use is safe. 10169 for (auto UsedIter = UsedFieldIndex.begin(), 10170 UsedEnd = UsedFieldIndex.end(), 10171 OrigIter = InitFieldIndex.begin(), 10172 OrigEnd = InitFieldIndex.end(); 10173 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10174 if (*UsedIter < *OrigIter) 10175 return true; 10176 if (*UsedIter > *OrigIter) 10177 break; 10178 } 10179 10180 // TODO: Add a different warning which will print the field names. 10181 HandleDeclRefExpr(DRE); 10182 return true; 10183 } 10184 10185 // For most expressions, the cast is directly above the DeclRefExpr. 10186 // For conditional operators, the cast can be outside the conditional 10187 // operator if both expressions are DeclRefExpr's. 10188 void HandleValue(Expr *E) { 10189 E = E->IgnoreParens(); 10190 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10191 HandleDeclRefExpr(DRE); 10192 return; 10193 } 10194 10195 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10196 Visit(CO->getCond()); 10197 HandleValue(CO->getTrueExpr()); 10198 HandleValue(CO->getFalseExpr()); 10199 return; 10200 } 10201 10202 if (BinaryConditionalOperator *BCO = 10203 dyn_cast<BinaryConditionalOperator>(E)) { 10204 Visit(BCO->getCond()); 10205 HandleValue(BCO->getFalseExpr()); 10206 return; 10207 } 10208 10209 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10210 HandleValue(OVE->getSourceExpr()); 10211 return; 10212 } 10213 10214 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10215 if (BO->getOpcode() == BO_Comma) { 10216 Visit(BO->getLHS()); 10217 HandleValue(BO->getRHS()); 10218 return; 10219 } 10220 } 10221 10222 if (isa<MemberExpr>(E)) { 10223 if (isInitList) { 10224 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10225 false /*CheckReference*/)) 10226 return; 10227 } 10228 10229 Expr *Base = E->IgnoreParenImpCasts(); 10230 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10231 // Check for static member variables and don't warn on them. 10232 if (!isa<FieldDecl>(ME->getMemberDecl())) 10233 return; 10234 Base = ME->getBase()->IgnoreParenImpCasts(); 10235 } 10236 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10237 HandleDeclRefExpr(DRE); 10238 return; 10239 } 10240 10241 Visit(E); 10242 } 10243 10244 // Reference types not handled in HandleValue are handled here since all 10245 // uses of references are bad, not just r-value uses. 10246 void VisitDeclRefExpr(DeclRefExpr *E) { 10247 if (isReferenceType) 10248 HandleDeclRefExpr(E); 10249 } 10250 10251 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10252 if (E->getCastKind() == CK_LValueToRValue) { 10253 HandleValue(E->getSubExpr()); 10254 return; 10255 } 10256 10257 Inherited::VisitImplicitCastExpr(E); 10258 } 10259 10260 void VisitMemberExpr(MemberExpr *E) { 10261 if (isInitList) { 10262 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10263 return; 10264 } 10265 10266 // Don't warn on arrays since they can be treated as pointers. 10267 if (E->getType()->canDecayToPointerType()) return; 10268 10269 // Warn when a non-static method call is followed by non-static member 10270 // field accesses, which is followed by a DeclRefExpr. 10271 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10272 bool Warn = (MD && !MD->isStatic()); 10273 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10274 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10275 if (!isa<FieldDecl>(ME->getMemberDecl())) 10276 Warn = false; 10277 Base = ME->getBase()->IgnoreParenImpCasts(); 10278 } 10279 10280 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10281 if (Warn) 10282 HandleDeclRefExpr(DRE); 10283 return; 10284 } 10285 10286 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10287 // Visit that expression. 10288 Visit(Base); 10289 } 10290 10291 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10292 Expr *Callee = E->getCallee(); 10293 10294 if (isa<UnresolvedLookupExpr>(Callee)) 10295 return Inherited::VisitCXXOperatorCallExpr(E); 10296 10297 Visit(Callee); 10298 for (auto Arg: E->arguments()) 10299 HandleValue(Arg->IgnoreParenImpCasts()); 10300 } 10301 10302 void VisitUnaryOperator(UnaryOperator *E) { 10303 // For POD record types, addresses of its own members are well-defined. 10304 if (E->getOpcode() == UO_AddrOf && isRecordType && 10305 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10306 if (!isPODType) 10307 HandleValue(E->getSubExpr()); 10308 return; 10309 } 10310 10311 if (E->isIncrementDecrementOp()) { 10312 HandleValue(E->getSubExpr()); 10313 return; 10314 } 10315 10316 Inherited::VisitUnaryOperator(E); 10317 } 10318 10319 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10320 10321 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10322 if (E->getConstructor()->isCopyConstructor()) { 10323 Expr *ArgExpr = E->getArg(0); 10324 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10325 if (ILE->getNumInits() == 1) 10326 ArgExpr = ILE->getInit(0); 10327 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10328 if (ICE->getCastKind() == CK_NoOp) 10329 ArgExpr = ICE->getSubExpr(); 10330 HandleValue(ArgExpr); 10331 return; 10332 } 10333 Inherited::VisitCXXConstructExpr(E); 10334 } 10335 10336 void VisitCallExpr(CallExpr *E) { 10337 // Treat std::move as a use. 10338 if (E->isCallToStdMove()) { 10339 HandleValue(E->getArg(0)); 10340 return; 10341 } 10342 10343 Inherited::VisitCallExpr(E); 10344 } 10345 10346 void VisitBinaryOperator(BinaryOperator *E) { 10347 if (E->isCompoundAssignmentOp()) { 10348 HandleValue(E->getLHS()); 10349 Visit(E->getRHS()); 10350 return; 10351 } 10352 10353 Inherited::VisitBinaryOperator(E); 10354 } 10355 10356 // A custom visitor for BinaryConditionalOperator is needed because the 10357 // regular visitor would check the condition and true expression separately 10358 // but both point to the same place giving duplicate diagnostics. 10359 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10360 Visit(E->getCond()); 10361 Visit(E->getFalseExpr()); 10362 } 10363 10364 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10365 Decl* ReferenceDecl = DRE->getDecl(); 10366 if (OrigDecl != ReferenceDecl) return; 10367 unsigned diag; 10368 if (isReferenceType) { 10369 diag = diag::warn_uninit_self_reference_in_reference_init; 10370 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10371 diag = diag::warn_static_self_reference_in_init; 10372 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10373 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10374 DRE->getDecl()->getType()->isRecordType()) { 10375 diag = diag::warn_uninit_self_reference_in_init; 10376 } else { 10377 // Local variables will be handled by the CFG analysis. 10378 return; 10379 } 10380 10381 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10382 S.PDiag(diag) 10383 << DRE->getDecl() 10384 << OrigDecl->getLocation() 10385 << DRE->getSourceRange()); 10386 } 10387 }; 10388 10389 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10390 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10391 bool DirectInit) { 10392 // Parameters arguments are occassionially constructed with itself, 10393 // for instance, in recursive functions. Skip them. 10394 if (isa<ParmVarDecl>(OrigDecl)) 10395 return; 10396 10397 E = E->IgnoreParens(); 10398 10399 // Skip checking T a = a where T is not a record or reference type. 10400 // Doing so is a way to silence uninitialized warnings. 10401 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10402 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10403 if (ICE->getCastKind() == CK_LValueToRValue) 10404 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10405 if (DRE->getDecl() == OrigDecl) 10406 return; 10407 10408 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10409 } 10410 } // end anonymous namespace 10411 10412 namespace { 10413 // Simple wrapper to add the name of a variable or (if no variable is 10414 // available) a DeclarationName into a diagnostic. 10415 struct VarDeclOrName { 10416 VarDecl *VDecl; 10417 DeclarationName Name; 10418 10419 friend const Sema::SemaDiagnosticBuilder & 10420 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10421 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10422 } 10423 }; 10424 } // end anonymous namespace 10425 10426 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10427 DeclarationName Name, QualType Type, 10428 TypeSourceInfo *TSI, 10429 SourceRange Range, bool DirectInit, 10430 Expr *Init) { 10431 bool IsInitCapture = !VDecl; 10432 assert((!VDecl || !VDecl->isInitCapture()) && 10433 "init captures are expected to be deduced prior to initialization"); 10434 10435 VarDeclOrName VN{VDecl, Name}; 10436 10437 DeducedType *Deduced = Type->getContainedDeducedType(); 10438 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10439 10440 // C++11 [dcl.spec.auto]p3 10441 if (!Init) { 10442 assert(VDecl && "no init for init capture deduction?"); 10443 10444 // Except for class argument deduction, and then for an initializing 10445 // declaration only, i.e. no static at class scope or extern. 10446 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10447 VDecl->hasExternalStorage() || 10448 VDecl->isStaticDataMember()) { 10449 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10450 << VDecl->getDeclName() << Type; 10451 return QualType(); 10452 } 10453 } 10454 10455 ArrayRef<Expr*> DeduceInits; 10456 if (Init) 10457 DeduceInits = Init; 10458 10459 if (DirectInit) { 10460 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10461 DeduceInits = PL->exprs(); 10462 } 10463 10464 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10465 assert(VDecl && "non-auto type for init capture deduction?"); 10466 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10467 InitializationKind Kind = InitializationKind::CreateForInit( 10468 VDecl->getLocation(), DirectInit, Init); 10469 // FIXME: Initialization should not be taking a mutable list of inits. 10470 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10471 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10472 InitsCopy); 10473 } 10474 10475 if (DirectInit) { 10476 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10477 DeduceInits = IL->inits(); 10478 } 10479 10480 // Deduction only works if we have exactly one source expression. 10481 if (DeduceInits.empty()) { 10482 // It isn't possible to write this directly, but it is possible to 10483 // end up in this situation with "auto x(some_pack...);" 10484 Diag(Init->getLocStart(), IsInitCapture 10485 ? diag::err_init_capture_no_expression 10486 : diag::err_auto_var_init_no_expression) 10487 << VN << Type << Range; 10488 return QualType(); 10489 } 10490 10491 if (DeduceInits.size() > 1) { 10492 Diag(DeduceInits[1]->getLocStart(), 10493 IsInitCapture ? diag::err_init_capture_multiple_expressions 10494 : diag::err_auto_var_init_multiple_expressions) 10495 << VN << Type << Range; 10496 return QualType(); 10497 } 10498 10499 Expr *DeduceInit = DeduceInits[0]; 10500 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10501 Diag(Init->getLocStart(), IsInitCapture 10502 ? diag::err_init_capture_paren_braces 10503 : diag::err_auto_var_init_paren_braces) 10504 << isa<InitListExpr>(Init) << VN << Type << Range; 10505 return QualType(); 10506 } 10507 10508 // Expressions default to 'id' when we're in a debugger. 10509 bool DefaultedAnyToId = false; 10510 if (getLangOpts().DebuggerCastResultToId && 10511 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10512 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10513 if (Result.isInvalid()) { 10514 return QualType(); 10515 } 10516 Init = Result.get(); 10517 DefaultedAnyToId = true; 10518 } 10519 10520 // C++ [dcl.decomp]p1: 10521 // If the assignment-expression [...] has array type A and no ref-qualifier 10522 // is present, e has type cv A 10523 if (VDecl && isa<DecompositionDecl>(VDecl) && 10524 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10525 DeduceInit->getType()->isConstantArrayType()) 10526 return Context.getQualifiedType(DeduceInit->getType(), 10527 Type.getQualifiers()); 10528 10529 QualType DeducedType; 10530 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10531 if (!IsInitCapture) 10532 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10533 else if (isa<InitListExpr>(Init)) 10534 Diag(Range.getBegin(), 10535 diag::err_init_capture_deduction_failure_from_init_list) 10536 << VN 10537 << (DeduceInit->getType().isNull() ? TSI->getType() 10538 : DeduceInit->getType()) 10539 << DeduceInit->getSourceRange(); 10540 else 10541 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10542 << VN << TSI->getType() 10543 << (DeduceInit->getType().isNull() ? TSI->getType() 10544 : DeduceInit->getType()) 10545 << DeduceInit->getSourceRange(); 10546 } 10547 10548 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10549 // 'id' instead of a specific object type prevents most of our usual 10550 // checks. 10551 // We only want to warn outside of template instantiations, though: 10552 // inside a template, the 'id' could have come from a parameter. 10553 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10554 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10555 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10556 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10557 } 10558 10559 return DeducedType; 10560 } 10561 10562 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10563 Expr *Init) { 10564 QualType DeducedType = deduceVarTypeFromInitializer( 10565 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10566 VDecl->getSourceRange(), DirectInit, Init); 10567 if (DeducedType.isNull()) { 10568 VDecl->setInvalidDecl(); 10569 return true; 10570 } 10571 10572 VDecl->setType(DeducedType); 10573 assert(VDecl->isLinkageValid()); 10574 10575 // In ARC, infer lifetime. 10576 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10577 VDecl->setInvalidDecl(); 10578 10579 // If this is a redeclaration, check that the type we just deduced matches 10580 // the previously declared type. 10581 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10582 // We never need to merge the type, because we cannot form an incomplete 10583 // array of auto, nor deduce such a type. 10584 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10585 } 10586 10587 // Check the deduced type is valid for a variable declaration. 10588 CheckVariableDeclarationType(VDecl); 10589 return VDecl->isInvalidDecl(); 10590 } 10591 10592 /// AddInitializerToDecl - Adds the initializer Init to the 10593 /// declaration dcl. If DirectInit is true, this is C++ direct 10594 /// initialization rather than copy initialization. 10595 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10596 // If there is no declaration, there was an error parsing it. Just ignore 10597 // the initializer. 10598 if (!RealDecl || RealDecl->isInvalidDecl()) { 10599 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10600 return; 10601 } 10602 10603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10604 // Pure-specifiers are handled in ActOnPureSpecifier. 10605 Diag(Method->getLocation(), diag::err_member_function_initialization) 10606 << Method->getDeclName() << Init->getSourceRange(); 10607 Method->setInvalidDecl(); 10608 return; 10609 } 10610 10611 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10612 if (!VDecl) { 10613 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10614 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10615 RealDecl->setInvalidDecl(); 10616 return; 10617 } 10618 10619 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10620 if (VDecl->getType()->isUndeducedType()) { 10621 // Attempt typo correction early so that the type of the init expression can 10622 // be deduced based on the chosen correction if the original init contains a 10623 // TypoExpr. 10624 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10625 if (!Res.isUsable()) { 10626 RealDecl->setInvalidDecl(); 10627 return; 10628 } 10629 Init = Res.get(); 10630 10631 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10632 return; 10633 } 10634 10635 // dllimport cannot be used on variable definitions. 10636 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10637 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10638 VDecl->setInvalidDecl(); 10639 return; 10640 } 10641 10642 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10643 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10644 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10645 VDecl->setInvalidDecl(); 10646 return; 10647 } 10648 10649 if (!VDecl->getType()->isDependentType()) { 10650 // A definition must end up with a complete type, which means it must be 10651 // complete with the restriction that an array type might be completed by 10652 // the initializer; note that later code assumes this restriction. 10653 QualType BaseDeclType = VDecl->getType(); 10654 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10655 BaseDeclType = Array->getElementType(); 10656 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10657 diag::err_typecheck_decl_incomplete_type)) { 10658 RealDecl->setInvalidDecl(); 10659 return; 10660 } 10661 10662 // The variable can not have an abstract class type. 10663 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10664 diag::err_abstract_type_in_decl, 10665 AbstractVariableType)) 10666 VDecl->setInvalidDecl(); 10667 } 10668 10669 // If adding the initializer will turn this declaration into a definition, 10670 // and we already have a definition for this variable, diagnose or otherwise 10671 // handle the situation. 10672 VarDecl *Def; 10673 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10674 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10675 !VDecl->isThisDeclarationADemotedDefinition() && 10676 checkVarDeclRedefinition(Def, VDecl)) 10677 return; 10678 10679 if (getLangOpts().CPlusPlus) { 10680 // C++ [class.static.data]p4 10681 // If a static data member is of const integral or const 10682 // enumeration type, its declaration in the class definition can 10683 // specify a constant-initializer which shall be an integral 10684 // constant expression (5.19). In that case, the member can appear 10685 // in integral constant expressions. The member shall still be 10686 // defined in a namespace scope if it is used in the program and the 10687 // namespace scope definition shall not contain an initializer. 10688 // 10689 // We already performed a redefinition check above, but for static 10690 // data members we also need to check whether there was an in-class 10691 // declaration with an initializer. 10692 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10693 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10694 << VDecl->getDeclName(); 10695 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10696 diag::note_previous_initializer) 10697 << 0; 10698 return; 10699 } 10700 10701 if (VDecl->hasLocalStorage()) 10702 setFunctionHasBranchProtectedScope(); 10703 10704 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10705 VDecl->setInvalidDecl(); 10706 return; 10707 } 10708 } 10709 10710 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10711 // a kernel function cannot be initialized." 10712 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10713 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10714 VDecl->setInvalidDecl(); 10715 return; 10716 } 10717 10718 // Get the decls type and save a reference for later, since 10719 // CheckInitializerTypes may change it. 10720 QualType DclT = VDecl->getType(), SavT = DclT; 10721 10722 // Expressions default to 'id' when we're in a debugger 10723 // and we are assigning it to a variable of Objective-C pointer type. 10724 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10725 Init->getType() == Context.UnknownAnyTy) { 10726 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10727 if (Result.isInvalid()) { 10728 VDecl->setInvalidDecl(); 10729 return; 10730 } 10731 Init = Result.get(); 10732 } 10733 10734 // Perform the initialization. 10735 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10736 if (!VDecl->isInvalidDecl()) { 10737 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10738 InitializationKind Kind = InitializationKind::CreateForInit( 10739 VDecl->getLocation(), DirectInit, Init); 10740 10741 MultiExprArg Args = Init; 10742 if (CXXDirectInit) 10743 Args = MultiExprArg(CXXDirectInit->getExprs(), 10744 CXXDirectInit->getNumExprs()); 10745 10746 // Try to correct any TypoExprs in the initialization arguments. 10747 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10748 ExprResult Res = CorrectDelayedTyposInExpr( 10749 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10750 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10751 return Init.Failed() ? ExprError() : E; 10752 }); 10753 if (Res.isInvalid()) { 10754 VDecl->setInvalidDecl(); 10755 } else if (Res.get() != Args[Idx]) { 10756 Args[Idx] = Res.get(); 10757 } 10758 } 10759 if (VDecl->isInvalidDecl()) 10760 return; 10761 10762 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10763 /*TopLevelOfInitList=*/false, 10764 /*TreatUnavailableAsInvalid=*/false); 10765 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10766 if (Result.isInvalid()) { 10767 VDecl->setInvalidDecl(); 10768 return; 10769 } 10770 10771 Init = Result.getAs<Expr>(); 10772 } 10773 10774 // Check for self-references within variable initializers. 10775 // Variables declared within a function/method body (except for references) 10776 // are handled by a dataflow analysis. 10777 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10778 VDecl->getType()->isReferenceType()) { 10779 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10780 } 10781 10782 // If the type changed, it means we had an incomplete type that was 10783 // completed by the initializer. For example: 10784 // int ary[] = { 1, 3, 5 }; 10785 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10786 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10787 VDecl->setType(DclT); 10788 10789 if (!VDecl->isInvalidDecl()) { 10790 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10791 10792 if (VDecl->hasAttr<BlocksAttr>()) 10793 checkRetainCycles(VDecl, Init); 10794 10795 // It is safe to assign a weak reference into a strong variable. 10796 // Although this code can still have problems: 10797 // id x = self.weakProp; 10798 // id y = self.weakProp; 10799 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10800 // paths through the function. This should be revisited if 10801 // -Wrepeated-use-of-weak is made flow-sensitive. 10802 if (FunctionScopeInfo *FSI = getCurFunction()) 10803 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10804 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10805 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10806 Init->getLocStart())) 10807 FSI->markSafeWeakUse(Init); 10808 } 10809 10810 // The initialization is usually a full-expression. 10811 // 10812 // FIXME: If this is a braced initialization of an aggregate, it is not 10813 // an expression, and each individual field initializer is a separate 10814 // full-expression. For instance, in: 10815 // 10816 // struct Temp { ~Temp(); }; 10817 // struct S { S(Temp); }; 10818 // struct T { S a, b; } t = { Temp(), Temp() } 10819 // 10820 // we should destroy the first Temp before constructing the second. 10821 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10822 false, 10823 VDecl->isConstexpr()); 10824 if (Result.isInvalid()) { 10825 VDecl->setInvalidDecl(); 10826 return; 10827 } 10828 Init = Result.get(); 10829 10830 // Attach the initializer to the decl. 10831 VDecl->setInit(Init); 10832 10833 if (VDecl->isLocalVarDecl()) { 10834 // Don't check the initializer if the declaration is malformed. 10835 if (VDecl->isInvalidDecl()) { 10836 // do nothing 10837 10838 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10839 // This is true even in OpenCL C++. 10840 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10841 CheckForConstantInitializer(Init, DclT); 10842 10843 // Otherwise, C++ does not restrict the initializer. 10844 } else if (getLangOpts().CPlusPlus) { 10845 // do nothing 10846 10847 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10848 // static storage duration shall be constant expressions or string literals. 10849 } else if (VDecl->getStorageClass() == SC_Static) { 10850 CheckForConstantInitializer(Init, DclT); 10851 10852 // C89 is stricter than C99 for aggregate initializers. 10853 // C89 6.5.7p3: All the expressions [...] in an initializer list 10854 // for an object that has aggregate or union type shall be 10855 // constant expressions. 10856 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10857 isa<InitListExpr>(Init)) { 10858 const Expr *Culprit; 10859 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10860 Diag(Culprit->getExprLoc(), 10861 diag::ext_aggregate_init_not_constant) 10862 << Culprit->getSourceRange(); 10863 } 10864 } 10865 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10866 VDecl->getLexicalDeclContext()->isRecord()) { 10867 // This is an in-class initialization for a static data member, e.g., 10868 // 10869 // struct S { 10870 // static const int value = 17; 10871 // }; 10872 10873 // C++ [class.mem]p4: 10874 // A member-declarator can contain a constant-initializer only 10875 // if it declares a static member (9.4) of const integral or 10876 // const enumeration type, see 9.4.2. 10877 // 10878 // C++11 [class.static.data]p3: 10879 // If a non-volatile non-inline const static data member is of integral 10880 // or enumeration type, its declaration in the class definition can 10881 // specify a brace-or-equal-initializer in which every initializer-clause 10882 // that is an assignment-expression is a constant expression. A static 10883 // data member of literal type can be declared in the class definition 10884 // with the constexpr specifier; if so, its declaration shall specify a 10885 // brace-or-equal-initializer in which every initializer-clause that is 10886 // an assignment-expression is a constant expression. 10887 10888 // Do nothing on dependent types. 10889 if (DclT->isDependentType()) { 10890 10891 // Allow any 'static constexpr' members, whether or not they are of literal 10892 // type. We separately check that every constexpr variable is of literal 10893 // type. 10894 } else if (VDecl->isConstexpr()) { 10895 10896 // Require constness. 10897 } else if (!DclT.isConstQualified()) { 10898 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10899 << Init->getSourceRange(); 10900 VDecl->setInvalidDecl(); 10901 10902 // We allow integer constant expressions in all cases. 10903 } else if (DclT->isIntegralOrEnumerationType()) { 10904 // Check whether the expression is a constant expression. 10905 SourceLocation Loc; 10906 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10907 // In C++11, a non-constexpr const static data member with an 10908 // in-class initializer cannot be volatile. 10909 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10910 else if (Init->isValueDependent()) 10911 ; // Nothing to check. 10912 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10913 ; // Ok, it's an ICE! 10914 else if (Init->isEvaluatable(Context)) { 10915 // If we can constant fold the initializer through heroics, accept it, 10916 // but report this as a use of an extension for -pedantic. 10917 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10918 << Init->getSourceRange(); 10919 } else { 10920 // Otherwise, this is some crazy unknown case. Report the issue at the 10921 // location provided by the isIntegerConstantExpr failed check. 10922 Diag(Loc, diag::err_in_class_initializer_non_constant) 10923 << Init->getSourceRange(); 10924 VDecl->setInvalidDecl(); 10925 } 10926 10927 // We allow foldable floating-point constants as an extension. 10928 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10929 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10930 // it anyway and provide a fixit to add the 'constexpr'. 10931 if (getLangOpts().CPlusPlus11) { 10932 Diag(VDecl->getLocation(), 10933 diag::ext_in_class_initializer_float_type_cxx11) 10934 << DclT << Init->getSourceRange(); 10935 Diag(VDecl->getLocStart(), 10936 diag::note_in_class_initializer_float_type_cxx11) 10937 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10938 } else { 10939 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10940 << DclT << Init->getSourceRange(); 10941 10942 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10943 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10944 << Init->getSourceRange(); 10945 VDecl->setInvalidDecl(); 10946 } 10947 } 10948 10949 // Suggest adding 'constexpr' in C++11 for literal types. 10950 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10951 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10952 << DclT << Init->getSourceRange() 10953 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10954 VDecl->setConstexpr(true); 10955 10956 } else { 10957 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10958 << DclT << Init->getSourceRange(); 10959 VDecl->setInvalidDecl(); 10960 } 10961 } else if (VDecl->isFileVarDecl()) { 10962 // In C, extern is typically used to avoid tentative definitions when 10963 // declaring variables in headers, but adding an intializer makes it a 10964 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 10965 // In C++, extern is often used to give implictly static const variables 10966 // external linkage, so don't warn in that case. If selectany is present, 10967 // this might be header code intended for C and C++ inclusion, so apply the 10968 // C++ rules. 10969 if (VDecl->getStorageClass() == SC_Extern && 10970 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10971 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10972 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10973 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10974 Diag(VDecl->getLocation(), diag::warn_extern_init); 10975 10976 // C99 6.7.8p4. All file scoped initializers need to be constant. 10977 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10978 CheckForConstantInitializer(Init, DclT); 10979 } 10980 10981 // We will represent direct-initialization similarly to copy-initialization: 10982 // int x(1); -as-> int x = 1; 10983 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10984 // 10985 // Clients that want to distinguish between the two forms, can check for 10986 // direct initializer using VarDecl::getInitStyle(). 10987 // A major benefit is that clients that don't particularly care about which 10988 // exactly form was it (like the CodeGen) can handle both cases without 10989 // special case code. 10990 10991 // C++ 8.5p11: 10992 // The form of initialization (using parentheses or '=') is generally 10993 // insignificant, but does matter when the entity being initialized has a 10994 // class type. 10995 if (CXXDirectInit) { 10996 assert(DirectInit && "Call-style initializer must be direct init."); 10997 VDecl->setInitStyle(VarDecl::CallInit); 10998 } else if (DirectInit) { 10999 // This must be list-initialization. No other way is direct-initialization. 11000 VDecl->setInitStyle(VarDecl::ListInit); 11001 } 11002 11003 CheckCompleteVariableDeclaration(VDecl); 11004 } 11005 11006 /// ActOnInitializerError - Given that there was an error parsing an 11007 /// initializer for the given declaration, try to return to some form 11008 /// of sanity. 11009 void Sema::ActOnInitializerError(Decl *D) { 11010 // Our main concern here is re-establishing invariants like "a 11011 // variable's type is either dependent or complete". 11012 if (!D || D->isInvalidDecl()) return; 11013 11014 VarDecl *VD = dyn_cast<VarDecl>(D); 11015 if (!VD) return; 11016 11017 // Bindings are not usable if we can't make sense of the initializer. 11018 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11019 for (auto *BD : DD->bindings()) 11020 BD->setInvalidDecl(); 11021 11022 // Auto types are meaningless if we can't make sense of the initializer. 11023 if (ParsingInitForAutoVars.count(D)) { 11024 D->setInvalidDecl(); 11025 return; 11026 } 11027 11028 QualType Ty = VD->getType(); 11029 if (Ty->isDependentType()) return; 11030 11031 // Require a complete type. 11032 if (RequireCompleteType(VD->getLocation(), 11033 Context.getBaseElementType(Ty), 11034 diag::err_typecheck_decl_incomplete_type)) { 11035 VD->setInvalidDecl(); 11036 return; 11037 } 11038 11039 // Require a non-abstract type. 11040 if (RequireNonAbstractType(VD->getLocation(), Ty, 11041 diag::err_abstract_type_in_decl, 11042 AbstractVariableType)) { 11043 VD->setInvalidDecl(); 11044 return; 11045 } 11046 11047 // Don't bother complaining about constructors or destructors, 11048 // though. 11049 } 11050 11051 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11052 // If there is no declaration, there was an error parsing it. Just ignore it. 11053 if (!RealDecl) 11054 return; 11055 11056 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11057 QualType Type = Var->getType(); 11058 11059 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11060 if (isa<DecompositionDecl>(RealDecl)) { 11061 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11062 Var->setInvalidDecl(); 11063 return; 11064 } 11065 11066 if (Type->isUndeducedType() && 11067 DeduceVariableDeclarationType(Var, false, nullptr)) 11068 return; 11069 11070 // C++11 [class.static.data]p3: A static data member can be declared with 11071 // the constexpr specifier; if so, its declaration shall specify 11072 // a brace-or-equal-initializer. 11073 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11074 // the definition of a variable [...] or the declaration of a static data 11075 // member. 11076 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11077 !Var->isThisDeclarationADemotedDefinition()) { 11078 if (Var->isStaticDataMember()) { 11079 // C++1z removes the relevant rule; the in-class declaration is always 11080 // a definition there. 11081 if (!getLangOpts().CPlusPlus17) { 11082 Diag(Var->getLocation(), 11083 diag::err_constexpr_static_mem_var_requires_init) 11084 << Var->getDeclName(); 11085 Var->setInvalidDecl(); 11086 return; 11087 } 11088 } else { 11089 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11090 Var->setInvalidDecl(); 11091 return; 11092 } 11093 } 11094 11095 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11096 // be initialized. 11097 if (!Var->isInvalidDecl() && 11098 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11099 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11100 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11101 Var->setInvalidDecl(); 11102 return; 11103 } 11104 11105 switch (Var->isThisDeclarationADefinition()) { 11106 case VarDecl::Definition: 11107 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11108 break; 11109 11110 // We have an out-of-line definition of a static data member 11111 // that has an in-class initializer, so we type-check this like 11112 // a declaration. 11113 // 11114 LLVM_FALLTHROUGH; 11115 11116 case VarDecl::DeclarationOnly: 11117 // It's only a declaration. 11118 11119 // Block scope. C99 6.7p7: If an identifier for an object is 11120 // declared with no linkage (C99 6.2.2p6), the type for the 11121 // object shall be complete. 11122 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11123 !Var->hasLinkage() && !Var->isInvalidDecl() && 11124 RequireCompleteType(Var->getLocation(), Type, 11125 diag::err_typecheck_decl_incomplete_type)) 11126 Var->setInvalidDecl(); 11127 11128 // Make sure that the type is not abstract. 11129 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11130 RequireNonAbstractType(Var->getLocation(), Type, 11131 diag::err_abstract_type_in_decl, 11132 AbstractVariableType)) 11133 Var->setInvalidDecl(); 11134 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11135 Var->getStorageClass() == SC_PrivateExtern) { 11136 Diag(Var->getLocation(), diag::warn_private_extern); 11137 Diag(Var->getLocation(), diag::note_private_extern); 11138 } 11139 11140 return; 11141 11142 case VarDecl::TentativeDefinition: 11143 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11144 // object that has file scope without an initializer, and without a 11145 // storage-class specifier or with the storage-class specifier "static", 11146 // constitutes a tentative definition. Note: A tentative definition with 11147 // external linkage is valid (C99 6.2.2p5). 11148 if (!Var->isInvalidDecl()) { 11149 if (const IncompleteArrayType *ArrayT 11150 = Context.getAsIncompleteArrayType(Type)) { 11151 if (RequireCompleteType(Var->getLocation(), 11152 ArrayT->getElementType(), 11153 diag::err_illegal_decl_array_incomplete_type)) 11154 Var->setInvalidDecl(); 11155 } else if (Var->getStorageClass() == SC_Static) { 11156 // C99 6.9.2p3: If the declaration of an identifier for an object is 11157 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11158 // declared type shall not be an incomplete type. 11159 // NOTE: code such as the following 11160 // static struct s; 11161 // struct s { int a; }; 11162 // is accepted by gcc. Hence here we issue a warning instead of 11163 // an error and we do not invalidate the static declaration. 11164 // NOTE: to avoid multiple warnings, only check the first declaration. 11165 if (Var->isFirstDecl()) 11166 RequireCompleteType(Var->getLocation(), Type, 11167 diag::ext_typecheck_decl_incomplete_type); 11168 } 11169 } 11170 11171 // Record the tentative definition; we're done. 11172 if (!Var->isInvalidDecl()) 11173 TentativeDefinitions.push_back(Var); 11174 return; 11175 } 11176 11177 // Provide a specific diagnostic for uninitialized variable 11178 // definitions with incomplete array type. 11179 if (Type->isIncompleteArrayType()) { 11180 Diag(Var->getLocation(), 11181 diag::err_typecheck_incomplete_array_needs_initializer); 11182 Var->setInvalidDecl(); 11183 return; 11184 } 11185 11186 // Provide a specific diagnostic for uninitialized variable 11187 // definitions with reference type. 11188 if (Type->isReferenceType()) { 11189 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11190 << Var->getDeclName() 11191 << SourceRange(Var->getLocation(), Var->getLocation()); 11192 Var->setInvalidDecl(); 11193 return; 11194 } 11195 11196 // Do not attempt to type-check the default initializer for a 11197 // variable with dependent type. 11198 if (Type->isDependentType()) 11199 return; 11200 11201 if (Var->isInvalidDecl()) 11202 return; 11203 11204 if (!Var->hasAttr<AliasAttr>()) { 11205 if (RequireCompleteType(Var->getLocation(), 11206 Context.getBaseElementType(Type), 11207 diag::err_typecheck_decl_incomplete_type)) { 11208 Var->setInvalidDecl(); 11209 return; 11210 } 11211 } else { 11212 return; 11213 } 11214 11215 // The variable can not have an abstract class type. 11216 if (RequireNonAbstractType(Var->getLocation(), Type, 11217 diag::err_abstract_type_in_decl, 11218 AbstractVariableType)) { 11219 Var->setInvalidDecl(); 11220 return; 11221 } 11222 11223 // Check for jumps past the implicit initializer. C++0x 11224 // clarifies that this applies to a "variable with automatic 11225 // storage duration", not a "local variable". 11226 // C++11 [stmt.dcl]p3 11227 // A program that jumps from a point where a variable with automatic 11228 // storage duration is not in scope to a point where it is in scope is 11229 // ill-formed unless the variable has scalar type, class type with a 11230 // trivial default constructor and a trivial destructor, a cv-qualified 11231 // version of one of these types, or an array of one of the preceding 11232 // types and is declared without an initializer. 11233 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11234 if (const RecordType *Record 11235 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11236 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11237 // Mark the function (if we're in one) for further checking even if the 11238 // looser rules of C++11 do not require such checks, so that we can 11239 // diagnose incompatibilities with C++98. 11240 if (!CXXRecord->isPOD()) 11241 setFunctionHasBranchProtectedScope(); 11242 } 11243 } 11244 11245 // C++03 [dcl.init]p9: 11246 // If no initializer is specified for an object, and the 11247 // object is of (possibly cv-qualified) non-POD class type (or 11248 // array thereof), the object shall be default-initialized; if 11249 // the object is of const-qualified type, the underlying class 11250 // type shall have a user-declared default 11251 // constructor. Otherwise, if no initializer is specified for 11252 // a non- static object, the object and its subobjects, if 11253 // any, have an indeterminate initial value); if the object 11254 // or any of its subobjects are of const-qualified type, the 11255 // program is ill-formed. 11256 // C++0x [dcl.init]p11: 11257 // If no initializer is specified for an object, the object is 11258 // default-initialized; [...]. 11259 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11260 InitializationKind Kind 11261 = InitializationKind::CreateDefault(Var->getLocation()); 11262 11263 InitializationSequence InitSeq(*this, Entity, Kind, None); 11264 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11265 if (Init.isInvalid()) 11266 Var->setInvalidDecl(); 11267 else if (Init.get()) { 11268 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11269 // This is important for template substitution. 11270 Var->setInitStyle(VarDecl::CallInit); 11271 } 11272 11273 CheckCompleteVariableDeclaration(Var); 11274 } 11275 } 11276 11277 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11278 // If there is no declaration, there was an error parsing it. Ignore it. 11279 if (!D) 11280 return; 11281 11282 VarDecl *VD = dyn_cast<VarDecl>(D); 11283 if (!VD) { 11284 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11285 D->setInvalidDecl(); 11286 return; 11287 } 11288 11289 VD->setCXXForRangeDecl(true); 11290 11291 // for-range-declaration cannot be given a storage class specifier. 11292 int Error = -1; 11293 switch (VD->getStorageClass()) { 11294 case SC_None: 11295 break; 11296 case SC_Extern: 11297 Error = 0; 11298 break; 11299 case SC_Static: 11300 Error = 1; 11301 break; 11302 case SC_PrivateExtern: 11303 Error = 2; 11304 break; 11305 case SC_Auto: 11306 Error = 3; 11307 break; 11308 case SC_Register: 11309 Error = 4; 11310 break; 11311 } 11312 if (Error != -1) { 11313 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11314 << VD->getDeclName() << Error; 11315 D->setInvalidDecl(); 11316 } 11317 } 11318 11319 StmtResult 11320 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11321 IdentifierInfo *Ident, 11322 ParsedAttributes &Attrs, 11323 SourceLocation AttrEnd) { 11324 // C++1y [stmt.iter]p1: 11325 // A range-based for statement of the form 11326 // for ( for-range-identifier : for-range-initializer ) statement 11327 // is equivalent to 11328 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11329 DeclSpec DS(Attrs.getPool().getFactory()); 11330 11331 const char *PrevSpec; 11332 unsigned DiagID; 11333 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11334 getPrintingPolicy()); 11335 11336 Declarator D(DS, DeclaratorContext::ForContext); 11337 D.SetIdentifier(Ident, IdentLoc); 11338 D.takeAttributes(Attrs, AttrEnd); 11339 11340 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11341 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 11342 EmptyAttrs, IdentLoc); 11343 Decl *Var = ActOnDeclarator(S, D); 11344 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11345 FinalizeDeclaration(Var); 11346 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11347 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11348 } 11349 11350 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11351 if (var->isInvalidDecl()) return; 11352 11353 if (getLangOpts().OpenCL) { 11354 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11355 // initialiser 11356 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11357 !var->hasInit()) { 11358 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11359 << 1 /*Init*/; 11360 var->setInvalidDecl(); 11361 return; 11362 } 11363 } 11364 11365 // In Objective-C, don't allow jumps past the implicit initialization of a 11366 // local retaining variable. 11367 if (getLangOpts().ObjC1 && 11368 var->hasLocalStorage()) { 11369 switch (var->getType().getObjCLifetime()) { 11370 case Qualifiers::OCL_None: 11371 case Qualifiers::OCL_ExplicitNone: 11372 case Qualifiers::OCL_Autoreleasing: 11373 break; 11374 11375 case Qualifiers::OCL_Weak: 11376 case Qualifiers::OCL_Strong: 11377 setFunctionHasBranchProtectedScope(); 11378 break; 11379 } 11380 } 11381 11382 if (var->hasLocalStorage() && 11383 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11384 setFunctionHasBranchProtectedScope(); 11385 11386 // Warn about externally-visible variables being defined without a 11387 // prior declaration. We only want to do this for global 11388 // declarations, but we also specifically need to avoid doing it for 11389 // class members because the linkage of an anonymous class can 11390 // change if it's later given a typedef name. 11391 if (var->isThisDeclarationADefinition() && 11392 var->getDeclContext()->getRedeclContext()->isFileContext() && 11393 var->isExternallyVisible() && var->hasLinkage() && 11394 !var->isInline() && !var->getDescribedVarTemplate() && 11395 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11396 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11397 var->getLocation())) { 11398 // Find a previous declaration that's not a definition. 11399 VarDecl *prev = var->getPreviousDecl(); 11400 while (prev && prev->isThisDeclarationADefinition()) 11401 prev = prev->getPreviousDecl(); 11402 11403 if (!prev) 11404 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11405 } 11406 11407 // Cache the result of checking for constant initialization. 11408 Optional<bool> CacheHasConstInit; 11409 const Expr *CacheCulprit; 11410 auto checkConstInit = [&]() mutable { 11411 if (!CacheHasConstInit) 11412 CacheHasConstInit = var->getInit()->isConstantInitializer( 11413 Context, var->getType()->isReferenceType(), &CacheCulprit); 11414 return *CacheHasConstInit; 11415 }; 11416 11417 if (var->getTLSKind() == VarDecl::TLS_Static) { 11418 if (var->getType().isDestructedType()) { 11419 // GNU C++98 edits for __thread, [basic.start.term]p3: 11420 // The type of an object with thread storage duration shall not 11421 // have a non-trivial destructor. 11422 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11423 if (getLangOpts().CPlusPlus11) 11424 Diag(var->getLocation(), diag::note_use_thread_local); 11425 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11426 if (!checkConstInit()) { 11427 // GNU C++98 edits for __thread, [basic.start.init]p4: 11428 // An object of thread storage duration shall not require dynamic 11429 // initialization. 11430 // FIXME: Need strict checking here. 11431 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11432 << CacheCulprit->getSourceRange(); 11433 if (getLangOpts().CPlusPlus11) 11434 Diag(var->getLocation(), diag::note_use_thread_local); 11435 } 11436 } 11437 } 11438 11439 // Apply section attributes and pragmas to global variables. 11440 bool GlobalStorage = var->hasGlobalStorage(); 11441 if (GlobalStorage && var->isThisDeclarationADefinition() && 11442 !inTemplateInstantiation()) { 11443 PragmaStack<StringLiteral *> *Stack = nullptr; 11444 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11445 if (var->getType().isConstQualified()) 11446 Stack = &ConstSegStack; 11447 else if (!var->getInit()) { 11448 Stack = &BSSSegStack; 11449 SectionFlags |= ASTContext::PSF_Write; 11450 } else { 11451 Stack = &DataSegStack; 11452 SectionFlags |= ASTContext::PSF_Write; 11453 } 11454 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11455 var->addAttr(SectionAttr::CreateImplicit( 11456 Context, SectionAttr::Declspec_allocate, 11457 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11458 } 11459 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11460 if (UnifySection(SA->getName(), SectionFlags, var)) 11461 var->dropAttr<SectionAttr>(); 11462 11463 // Apply the init_seg attribute if this has an initializer. If the 11464 // initializer turns out to not be dynamic, we'll end up ignoring this 11465 // attribute. 11466 if (CurInitSeg && var->getInit()) 11467 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11468 CurInitSegLoc)); 11469 } 11470 11471 // All the following checks are C++ only. 11472 if (!getLangOpts().CPlusPlus) { 11473 // If this variable must be emitted, add it as an initializer for the 11474 // current module. 11475 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11476 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11477 return; 11478 } 11479 11480 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11481 CheckCompleteDecompositionDeclaration(DD); 11482 11483 QualType type = var->getType(); 11484 if (type->isDependentType()) return; 11485 11486 // __block variables might require us to capture a copy-initializer. 11487 if (var->hasAttr<BlocksAttr>()) { 11488 // It's currently invalid to ever have a __block variable with an 11489 // array type; should we diagnose that here? 11490 11491 // Regardless, we don't want to ignore array nesting when 11492 // constructing this copy. 11493 if (type->isStructureOrClassType()) { 11494 EnterExpressionEvaluationContext scope( 11495 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11496 SourceLocation poi = var->getLocation(); 11497 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11498 ExprResult result 11499 = PerformMoveOrCopyInitialization( 11500 InitializedEntity::InitializeBlock(poi, type, false), 11501 var, var->getType(), varRef, /*AllowNRVO=*/true); 11502 if (!result.isInvalid()) { 11503 result = MaybeCreateExprWithCleanups(result); 11504 Expr *init = result.getAs<Expr>(); 11505 Context.setBlockVarCopyInits(var, init); 11506 } 11507 } 11508 } 11509 11510 Expr *Init = var->getInit(); 11511 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11512 QualType baseType = Context.getBaseElementType(type); 11513 11514 if (Init && !Init->isValueDependent()) { 11515 if (var->isConstexpr()) { 11516 SmallVector<PartialDiagnosticAt, 8> Notes; 11517 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11518 SourceLocation DiagLoc = var->getLocation(); 11519 // If the note doesn't add any useful information other than a source 11520 // location, fold it into the primary diagnostic. 11521 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11522 diag::note_invalid_subexpr_in_const_expr) { 11523 DiagLoc = Notes[0].first; 11524 Notes.clear(); 11525 } 11526 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11527 << var << Init->getSourceRange(); 11528 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11529 Diag(Notes[I].first, Notes[I].second); 11530 } 11531 } else if (var->isUsableInConstantExpressions(Context)) { 11532 // Check whether the initializer of a const variable of integral or 11533 // enumeration type is an ICE now, since we can't tell whether it was 11534 // initialized by a constant expression if we check later. 11535 var->checkInitIsICE(); 11536 } 11537 11538 // Don't emit further diagnostics about constexpr globals since they 11539 // were just diagnosed. 11540 if (!var->isConstexpr() && GlobalStorage && 11541 var->hasAttr<RequireConstantInitAttr>()) { 11542 // FIXME: Need strict checking in C++03 here. 11543 bool DiagErr = getLangOpts().CPlusPlus11 11544 ? !var->checkInitIsICE() : !checkConstInit(); 11545 if (DiagErr) { 11546 auto attr = var->getAttr<RequireConstantInitAttr>(); 11547 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11548 << Init->getSourceRange(); 11549 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11550 << attr->getRange(); 11551 if (getLangOpts().CPlusPlus11) { 11552 APValue Value; 11553 SmallVector<PartialDiagnosticAt, 8> Notes; 11554 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11555 for (auto &it : Notes) 11556 Diag(it.first, it.second); 11557 } else { 11558 Diag(CacheCulprit->getExprLoc(), 11559 diag::note_invalid_subexpr_in_const_expr) 11560 << CacheCulprit->getSourceRange(); 11561 } 11562 } 11563 } 11564 else if (!var->isConstexpr() && IsGlobal && 11565 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11566 var->getLocation())) { 11567 // Warn about globals which don't have a constant initializer. Don't 11568 // warn about globals with a non-trivial destructor because we already 11569 // warned about them. 11570 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11571 if (!(RD && !RD->hasTrivialDestructor())) { 11572 if (!checkConstInit()) 11573 Diag(var->getLocation(), diag::warn_global_constructor) 11574 << Init->getSourceRange(); 11575 } 11576 } 11577 } 11578 11579 // Require the destructor. 11580 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11581 FinalizeVarWithDestructor(var, recordType); 11582 11583 // If this variable must be emitted, add it as an initializer for the current 11584 // module. 11585 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11586 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11587 } 11588 11589 /// Determines if a variable's alignment is dependent. 11590 static bool hasDependentAlignment(VarDecl *VD) { 11591 if (VD->getType()->isDependentType()) 11592 return true; 11593 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11594 if (I->isAlignmentDependent()) 11595 return true; 11596 return false; 11597 } 11598 11599 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11600 /// any semantic actions necessary after any initializer has been attached. 11601 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11602 // Note that we are no longer parsing the initializer for this declaration. 11603 ParsingInitForAutoVars.erase(ThisDecl); 11604 11605 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11606 if (!VD) 11607 return; 11608 11609 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11610 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11611 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11612 if (PragmaClangBSSSection.Valid) 11613 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11614 PragmaClangBSSSection.SectionName, 11615 PragmaClangBSSSection.PragmaLocation)); 11616 if (PragmaClangDataSection.Valid) 11617 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11618 PragmaClangDataSection.SectionName, 11619 PragmaClangDataSection.PragmaLocation)); 11620 if (PragmaClangRodataSection.Valid) 11621 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11622 PragmaClangRodataSection.SectionName, 11623 PragmaClangRodataSection.PragmaLocation)); 11624 } 11625 11626 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11627 for (auto *BD : DD->bindings()) { 11628 FinalizeDeclaration(BD); 11629 } 11630 } 11631 11632 checkAttributesAfterMerging(*this, *VD); 11633 11634 // Perform TLS alignment check here after attributes attached to the variable 11635 // which may affect the alignment have been processed. Only perform the check 11636 // if the target has a maximum TLS alignment (zero means no constraints). 11637 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11638 // Protect the check so that it's not performed on dependent types and 11639 // dependent alignments (we can't determine the alignment in that case). 11640 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11641 !VD->isInvalidDecl()) { 11642 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11643 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11644 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11645 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11646 << (unsigned)MaxAlignChars.getQuantity(); 11647 } 11648 } 11649 } 11650 11651 if (VD->isStaticLocal()) { 11652 if (FunctionDecl *FD = 11653 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11654 // Static locals inherit dll attributes from their function. 11655 if (Attr *A = getDLLAttr(FD)) { 11656 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11657 NewAttr->setInherited(true); 11658 VD->addAttr(NewAttr); 11659 } 11660 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11661 // function, only __shared__ variables may be declared with 11662 // static storage class. 11663 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11664 CUDADiagIfDeviceCode(VD->getLocation(), 11665 diag::err_device_static_local_var) 11666 << CurrentCUDATarget()) 11667 VD->setInvalidDecl(); 11668 } 11669 } 11670 11671 // Perform check for initializers of device-side global variables. 11672 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11673 // 7.5). We must also apply the same checks to all __shared__ 11674 // variables whether they are local or not. CUDA also allows 11675 // constant initializers for __constant__ and __device__ variables. 11676 if (getLangOpts().CUDA) { 11677 const Expr *Init = VD->getInit(); 11678 if (Init && VD->hasGlobalStorage()) { 11679 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11680 VD->hasAttr<CUDASharedAttr>()) { 11681 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11682 bool AllowedInit = false; 11683 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11684 AllowedInit = 11685 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11686 // We'll allow constant initializers even if it's a non-empty 11687 // constructor according to CUDA rules. This deviates from NVCC, 11688 // but allows us to handle things like constexpr constructors. 11689 if (!AllowedInit && 11690 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11691 AllowedInit = VD->getInit()->isConstantInitializer( 11692 Context, VD->getType()->isReferenceType()); 11693 11694 // Also make sure that destructor, if there is one, is empty. 11695 if (AllowedInit) 11696 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11697 AllowedInit = 11698 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11699 11700 if (!AllowedInit) { 11701 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11702 ? diag::err_shared_var_init 11703 : diag::err_dynamic_var_init) 11704 << Init->getSourceRange(); 11705 VD->setInvalidDecl(); 11706 } 11707 } else { 11708 // This is a host-side global variable. Check that the initializer is 11709 // callable from the host side. 11710 const FunctionDecl *InitFn = nullptr; 11711 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11712 InitFn = CE->getConstructor(); 11713 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11714 InitFn = CE->getDirectCallee(); 11715 } 11716 if (InitFn) { 11717 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11718 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11719 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11720 << InitFnTarget << InitFn; 11721 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11722 VD->setInvalidDecl(); 11723 } 11724 } 11725 } 11726 } 11727 } 11728 11729 // Grab the dllimport or dllexport attribute off of the VarDecl. 11730 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11731 11732 // Imported static data members cannot be defined out-of-line. 11733 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11734 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11735 VD->isThisDeclarationADefinition()) { 11736 // We allow definitions of dllimport class template static data members 11737 // with a warning. 11738 CXXRecordDecl *Context = 11739 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11740 bool IsClassTemplateMember = 11741 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11742 Context->getDescribedClassTemplate(); 11743 11744 Diag(VD->getLocation(), 11745 IsClassTemplateMember 11746 ? diag::warn_attribute_dllimport_static_field_definition 11747 : diag::err_attribute_dllimport_static_field_definition); 11748 Diag(IA->getLocation(), diag::note_attribute); 11749 if (!IsClassTemplateMember) 11750 VD->setInvalidDecl(); 11751 } 11752 } 11753 11754 // dllimport/dllexport variables cannot be thread local, their TLS index 11755 // isn't exported with the variable. 11756 if (DLLAttr && VD->getTLSKind()) { 11757 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11758 if (F && getDLLAttr(F)) { 11759 assert(VD->isStaticLocal()); 11760 // But if this is a static local in a dlimport/dllexport function, the 11761 // function will never be inlined, which means the var would never be 11762 // imported, so having it marked import/export is safe. 11763 } else { 11764 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11765 << DLLAttr; 11766 VD->setInvalidDecl(); 11767 } 11768 } 11769 11770 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11771 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11772 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11773 VD->dropAttr<UsedAttr>(); 11774 } 11775 } 11776 11777 const DeclContext *DC = VD->getDeclContext(); 11778 // If there's a #pragma GCC visibility in scope, and this isn't a class 11779 // member, set the visibility of this variable. 11780 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11781 AddPushedVisibilityAttribute(VD); 11782 11783 // FIXME: Warn on unused var template partial specializations. 11784 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11785 MarkUnusedFileScopedDecl(VD); 11786 11787 // Now we have parsed the initializer and can update the table of magic 11788 // tag values. 11789 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11790 !VD->getType()->isIntegralOrEnumerationType()) 11791 return; 11792 11793 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11794 const Expr *MagicValueExpr = VD->getInit(); 11795 if (!MagicValueExpr) { 11796 continue; 11797 } 11798 llvm::APSInt MagicValueInt; 11799 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11800 Diag(I->getRange().getBegin(), 11801 diag::err_type_tag_for_datatype_not_ice) 11802 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11803 continue; 11804 } 11805 if (MagicValueInt.getActiveBits() > 64) { 11806 Diag(I->getRange().getBegin(), 11807 diag::err_type_tag_for_datatype_too_large) 11808 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11809 continue; 11810 } 11811 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11812 RegisterTypeTagForDatatype(I->getArgumentKind(), 11813 MagicValue, 11814 I->getMatchingCType(), 11815 I->getLayoutCompatible(), 11816 I->getMustBeNull()); 11817 } 11818 } 11819 11820 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11821 auto *VD = dyn_cast<VarDecl>(DD); 11822 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11823 } 11824 11825 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11826 ArrayRef<Decl *> Group) { 11827 SmallVector<Decl*, 8> Decls; 11828 11829 if (DS.isTypeSpecOwned()) 11830 Decls.push_back(DS.getRepAsDecl()); 11831 11832 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11833 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11834 bool DiagnosedMultipleDecomps = false; 11835 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11836 bool DiagnosedNonDeducedAuto = false; 11837 11838 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11839 if (Decl *D = Group[i]) { 11840 // For declarators, there are some additional syntactic-ish checks we need 11841 // to perform. 11842 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11843 if (!FirstDeclaratorInGroup) 11844 FirstDeclaratorInGroup = DD; 11845 if (!FirstDecompDeclaratorInGroup) 11846 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11847 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11848 !hasDeducedAuto(DD)) 11849 FirstNonDeducedAutoInGroup = DD; 11850 11851 if (FirstDeclaratorInGroup != DD) { 11852 // A decomposition declaration cannot be combined with any other 11853 // declaration in the same group. 11854 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11855 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11856 diag::err_decomp_decl_not_alone) 11857 << FirstDeclaratorInGroup->getSourceRange() 11858 << DD->getSourceRange(); 11859 DiagnosedMultipleDecomps = true; 11860 } 11861 11862 // A declarator that uses 'auto' in any way other than to declare a 11863 // variable with a deduced type cannot be combined with any other 11864 // declarator in the same group. 11865 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11866 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11867 diag::err_auto_non_deduced_not_alone) 11868 << FirstNonDeducedAutoInGroup->getType() 11869 ->hasAutoForTrailingReturnType() 11870 << FirstDeclaratorInGroup->getSourceRange() 11871 << DD->getSourceRange(); 11872 DiagnosedNonDeducedAuto = true; 11873 } 11874 } 11875 } 11876 11877 Decls.push_back(D); 11878 } 11879 } 11880 11881 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11882 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11883 handleTagNumbering(Tag, S); 11884 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11885 getLangOpts().CPlusPlus) 11886 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11887 } 11888 } 11889 11890 return BuildDeclaratorGroup(Decls); 11891 } 11892 11893 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11894 /// group, performing any necessary semantic checking. 11895 Sema::DeclGroupPtrTy 11896 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11897 // C++14 [dcl.spec.auto]p7: (DR1347) 11898 // If the type that replaces the placeholder type is not the same in each 11899 // deduction, the program is ill-formed. 11900 if (Group.size() > 1) { 11901 QualType Deduced; 11902 VarDecl *DeducedDecl = nullptr; 11903 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11904 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11905 if (!D || D->isInvalidDecl()) 11906 break; 11907 DeducedType *DT = D->getType()->getContainedDeducedType(); 11908 if (!DT || DT->getDeducedType().isNull()) 11909 continue; 11910 if (Deduced.isNull()) { 11911 Deduced = DT->getDeducedType(); 11912 DeducedDecl = D; 11913 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11914 auto *AT = dyn_cast<AutoType>(DT); 11915 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11916 diag::err_auto_different_deductions) 11917 << (AT ? (unsigned)AT->getKeyword() : 3) 11918 << Deduced << DeducedDecl->getDeclName() 11919 << DT->getDeducedType() << D->getDeclName() 11920 << DeducedDecl->getInit()->getSourceRange() 11921 << D->getInit()->getSourceRange(); 11922 D->setInvalidDecl(); 11923 break; 11924 } 11925 } 11926 } 11927 11928 ActOnDocumentableDecls(Group); 11929 11930 return DeclGroupPtrTy::make( 11931 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11932 } 11933 11934 void Sema::ActOnDocumentableDecl(Decl *D) { 11935 ActOnDocumentableDecls(D); 11936 } 11937 11938 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11939 // Don't parse the comment if Doxygen diagnostics are ignored. 11940 if (Group.empty() || !Group[0]) 11941 return; 11942 11943 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11944 Group[0]->getLocation()) && 11945 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11946 Group[0]->getLocation())) 11947 return; 11948 11949 if (Group.size() >= 2) { 11950 // This is a decl group. Normally it will contain only declarations 11951 // produced from declarator list. But in case we have any definitions or 11952 // additional declaration references: 11953 // 'typedef struct S {} S;' 11954 // 'typedef struct S *S;' 11955 // 'struct S *pS;' 11956 // FinalizeDeclaratorGroup adds these as separate declarations. 11957 Decl *MaybeTagDecl = Group[0]; 11958 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11959 Group = Group.slice(1); 11960 } 11961 } 11962 11963 // See if there are any new comments that are not attached to a decl. 11964 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11965 if (!Comments.empty() && 11966 !Comments.back()->isAttached()) { 11967 // There is at least one comment that not attached to a decl. 11968 // Maybe it should be attached to one of these decls? 11969 // 11970 // Note that this way we pick up not only comments that precede the 11971 // declaration, but also comments that *follow* the declaration -- thanks to 11972 // the lookahead in the lexer: we've consumed the semicolon and looked 11973 // ahead through comments. 11974 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11975 Context.getCommentForDecl(Group[i], &PP); 11976 } 11977 } 11978 11979 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11980 /// to introduce parameters into function prototype scope. 11981 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11982 const DeclSpec &DS = D.getDeclSpec(); 11983 11984 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11985 11986 // C++03 [dcl.stc]p2 also permits 'auto'. 11987 StorageClass SC = SC_None; 11988 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11989 SC = SC_Register; 11990 // In C++11, the 'register' storage class specifier is deprecated. 11991 // In C++17, it is not allowed, but we tolerate it as an extension. 11992 if (getLangOpts().CPlusPlus11) { 11993 Diag(DS.getStorageClassSpecLoc(), 11994 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 11995 : diag::warn_deprecated_register) 11996 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11997 } 11998 } else if (getLangOpts().CPlusPlus && 11999 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 12000 SC = SC_Auto; 12001 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 12002 Diag(DS.getStorageClassSpecLoc(), 12003 diag::err_invalid_storage_class_in_func_decl); 12004 D.getMutableDeclSpec().ClearStorageClassSpecs(); 12005 } 12006 12007 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12008 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12009 << DeclSpec::getSpecifierName(TSCS); 12010 if (DS.isInlineSpecified()) 12011 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12012 << getLangOpts().CPlusPlus17; 12013 if (DS.isConstexprSpecified()) 12014 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12015 << 0; 12016 12017 DiagnoseFunctionSpecifiers(DS); 12018 12019 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12020 QualType parmDeclType = TInfo->getType(); 12021 12022 if (getLangOpts().CPlusPlus) { 12023 // Check that there are no default arguments inside the type of this 12024 // parameter. 12025 CheckExtraCXXDefaultArguments(D); 12026 12027 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12028 if (D.getCXXScopeSpec().isSet()) { 12029 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12030 << D.getCXXScopeSpec().getRange(); 12031 D.getCXXScopeSpec().clear(); 12032 } 12033 } 12034 12035 // Ensure we have a valid name 12036 IdentifierInfo *II = nullptr; 12037 if (D.hasName()) { 12038 II = D.getIdentifier(); 12039 if (!II) { 12040 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12041 << GetNameForDeclarator(D).getName(); 12042 D.setInvalidType(true); 12043 } 12044 } 12045 12046 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12047 if (II) { 12048 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12049 ForVisibleRedeclaration); 12050 LookupName(R, S); 12051 if (R.isSingleResult()) { 12052 NamedDecl *PrevDecl = R.getFoundDecl(); 12053 if (PrevDecl->isTemplateParameter()) { 12054 // Maybe we will complain about the shadowed template parameter. 12055 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12056 // Just pretend that we didn't see the previous declaration. 12057 PrevDecl = nullptr; 12058 } else if (S->isDeclScope(PrevDecl)) { 12059 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12060 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12061 12062 // Recover by removing the name 12063 II = nullptr; 12064 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12065 D.setInvalidType(true); 12066 } 12067 } 12068 } 12069 12070 // Temporarily put parameter variables in the translation unit, not 12071 // the enclosing context. This prevents them from accidentally 12072 // looking like class members in C++. 12073 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 12074 D.getLocStart(), 12075 D.getIdentifierLoc(), II, 12076 parmDeclType, TInfo, 12077 SC); 12078 12079 if (D.isInvalidType()) 12080 New->setInvalidDecl(); 12081 12082 assert(S->isFunctionPrototypeScope()); 12083 assert(S->getFunctionPrototypeDepth() >= 1); 12084 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12085 S->getNextFunctionPrototypeIndex()); 12086 12087 // Add the parameter declaration into this scope. 12088 S->AddDecl(New); 12089 if (II) 12090 IdResolver.AddDecl(New); 12091 12092 ProcessDeclAttributes(S, New, D); 12093 12094 if (D.getDeclSpec().isModulePrivateSpecified()) 12095 Diag(New->getLocation(), diag::err_module_private_local) 12096 << 1 << New->getDeclName() 12097 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12098 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12099 12100 if (New->hasAttr<BlocksAttr>()) { 12101 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12102 } 12103 return New; 12104 } 12105 12106 /// Synthesizes a variable for a parameter arising from a 12107 /// typedef. 12108 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12109 SourceLocation Loc, 12110 QualType T) { 12111 /* FIXME: setting StartLoc == Loc. 12112 Would it be worth to modify callers so as to provide proper source 12113 location for the unnamed parameters, embedding the parameter's type? */ 12114 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12115 T, Context.getTrivialTypeSourceInfo(T, Loc), 12116 SC_None, nullptr); 12117 Param->setImplicit(); 12118 return Param; 12119 } 12120 12121 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12122 // Don't diagnose unused-parameter errors in template instantiations; we 12123 // will already have done so in the template itself. 12124 if (inTemplateInstantiation()) 12125 return; 12126 12127 for (const ParmVarDecl *Parameter : Parameters) { 12128 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12129 !Parameter->hasAttr<UnusedAttr>()) { 12130 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12131 << Parameter->getDeclName(); 12132 } 12133 } 12134 } 12135 12136 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12137 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12138 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12139 return; 12140 12141 // Warn if the return value is pass-by-value and larger than the specified 12142 // threshold. 12143 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12144 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12145 if (Size > LangOpts.NumLargeByValueCopy) 12146 Diag(D->getLocation(), diag::warn_return_value_size) 12147 << D->getDeclName() << Size; 12148 } 12149 12150 // Warn if any parameter is pass-by-value and larger than the specified 12151 // threshold. 12152 for (const ParmVarDecl *Parameter : Parameters) { 12153 QualType T = Parameter->getType(); 12154 if (T->isDependentType() || !T.isPODType(Context)) 12155 continue; 12156 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12157 if (Size > LangOpts.NumLargeByValueCopy) 12158 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12159 << Parameter->getDeclName() << Size; 12160 } 12161 } 12162 12163 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12164 SourceLocation NameLoc, IdentifierInfo *Name, 12165 QualType T, TypeSourceInfo *TSInfo, 12166 StorageClass SC) { 12167 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12168 if (getLangOpts().ObjCAutoRefCount && 12169 T.getObjCLifetime() == Qualifiers::OCL_None && 12170 T->isObjCLifetimeType()) { 12171 12172 Qualifiers::ObjCLifetime lifetime; 12173 12174 // Special cases for arrays: 12175 // - if it's const, use __unsafe_unretained 12176 // - otherwise, it's an error 12177 if (T->isArrayType()) { 12178 if (!T.isConstQualified()) { 12179 DelayedDiagnostics.add( 12180 sema::DelayedDiagnostic::makeForbiddenType( 12181 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12182 } 12183 lifetime = Qualifiers::OCL_ExplicitNone; 12184 } else { 12185 lifetime = T->getObjCARCImplicitLifetime(); 12186 } 12187 T = Context.getLifetimeQualifiedType(T, lifetime); 12188 } 12189 12190 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12191 Context.getAdjustedParameterType(T), 12192 TSInfo, SC, nullptr); 12193 12194 // Parameters can not be abstract class types. 12195 // For record types, this is done by the AbstractClassUsageDiagnoser once 12196 // the class has been completely parsed. 12197 if (!CurContext->isRecord() && 12198 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12199 AbstractParamType)) 12200 New->setInvalidDecl(); 12201 12202 // Parameter declarators cannot be interface types. All ObjC objects are 12203 // passed by reference. 12204 if (T->isObjCObjectType()) { 12205 SourceLocation TypeEndLoc = 12206 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 12207 Diag(NameLoc, 12208 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12209 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12210 T = Context.getObjCObjectPointerType(T); 12211 New->setType(T); 12212 } 12213 12214 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12215 // duration shall not be qualified by an address-space qualifier." 12216 // Since all parameters have automatic store duration, they can not have 12217 // an address space. 12218 if (T.getAddressSpace() != LangAS::Default && 12219 // OpenCL allows function arguments declared to be an array of a type 12220 // to be qualified with an address space. 12221 !(getLangOpts().OpenCL && 12222 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12223 Diag(NameLoc, diag::err_arg_with_address_space); 12224 New->setInvalidDecl(); 12225 } 12226 12227 return New; 12228 } 12229 12230 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12231 SourceLocation LocAfterDecls) { 12232 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12233 12234 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12235 // for a K&R function. 12236 if (!FTI.hasPrototype) { 12237 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12238 --i; 12239 if (FTI.Params[i].Param == nullptr) { 12240 SmallString<256> Code; 12241 llvm::raw_svector_ostream(Code) 12242 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12243 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12244 << FTI.Params[i].Ident 12245 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12246 12247 // Implicitly declare the argument as type 'int' for lack of a better 12248 // type. 12249 AttributeFactory attrs; 12250 DeclSpec DS(attrs); 12251 const char* PrevSpec; // unused 12252 unsigned DiagID; // unused 12253 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12254 DiagID, Context.getPrintingPolicy()); 12255 // Use the identifier location for the type source range. 12256 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12257 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12258 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12259 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12260 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12261 } 12262 } 12263 } 12264 } 12265 12266 Decl * 12267 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12268 MultiTemplateParamsArg TemplateParameterLists, 12269 SkipBodyInfo *SkipBody) { 12270 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12271 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12272 Scope *ParentScope = FnBodyScope->getParent(); 12273 12274 D.setFunctionDefinitionKind(FDK_Definition); 12275 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12276 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12277 } 12278 12279 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12280 Consumer.HandleInlineFunctionDefinition(D); 12281 } 12282 12283 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12284 const FunctionDecl*& PossibleZeroParamPrototype) { 12285 // Don't warn about invalid declarations. 12286 if (FD->isInvalidDecl()) 12287 return false; 12288 12289 // Or declarations that aren't global. 12290 if (!FD->isGlobal()) 12291 return false; 12292 12293 // Don't warn about C++ member functions. 12294 if (isa<CXXMethodDecl>(FD)) 12295 return false; 12296 12297 // Don't warn about 'main'. 12298 if (FD->isMain()) 12299 return false; 12300 12301 // Don't warn about inline functions. 12302 if (FD->isInlined()) 12303 return false; 12304 12305 // Don't warn about function templates. 12306 if (FD->getDescribedFunctionTemplate()) 12307 return false; 12308 12309 // Don't warn about function template specializations. 12310 if (FD->isFunctionTemplateSpecialization()) 12311 return false; 12312 12313 // Don't warn for OpenCL kernels. 12314 if (FD->hasAttr<OpenCLKernelAttr>()) 12315 return false; 12316 12317 // Don't warn on explicitly deleted functions. 12318 if (FD->isDeleted()) 12319 return false; 12320 12321 bool MissingPrototype = true; 12322 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12323 Prev; Prev = Prev->getPreviousDecl()) { 12324 // Ignore any declarations that occur in function or method 12325 // scope, because they aren't visible from the header. 12326 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12327 continue; 12328 12329 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12330 if (FD->getNumParams() == 0) 12331 PossibleZeroParamPrototype = Prev; 12332 break; 12333 } 12334 12335 return MissingPrototype; 12336 } 12337 12338 void 12339 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12340 const FunctionDecl *EffectiveDefinition, 12341 SkipBodyInfo *SkipBody) { 12342 const FunctionDecl *Definition = EffectiveDefinition; 12343 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12344 // If this is a friend function defined in a class template, it does not 12345 // have a body until it is used, nevertheless it is a definition, see 12346 // [temp.inst]p2: 12347 // 12348 // ... for the purpose of determining whether an instantiated redeclaration 12349 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12350 // corresponds to a definition in the template is considered to be a 12351 // definition. 12352 // 12353 // The following code must produce redefinition error: 12354 // 12355 // template<typename T> struct C20 { friend void func_20() {} }; 12356 // C20<int> c20i; 12357 // void func_20() {} 12358 // 12359 for (auto I : FD->redecls()) { 12360 if (I != FD && !I->isInvalidDecl() && 12361 I->getFriendObjectKind() != Decl::FOK_None) { 12362 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12363 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12364 // A merged copy of the same function, instantiated as a member of 12365 // the same class, is OK. 12366 if (declaresSameEntity(OrigFD, Original) && 12367 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12368 cast<Decl>(FD->getLexicalDeclContext()))) 12369 continue; 12370 } 12371 12372 if (Original->isThisDeclarationADefinition()) { 12373 Definition = I; 12374 break; 12375 } 12376 } 12377 } 12378 } 12379 } 12380 if (!Definition) 12381 return; 12382 12383 if (canRedefineFunction(Definition, getLangOpts())) 12384 return; 12385 12386 // Don't emit an error when this is redefinition of a typo-corrected 12387 // definition. 12388 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12389 return; 12390 12391 // If we don't have a visible definition of the function, and it's inline or 12392 // a template, skip the new definition. 12393 if (SkipBody && !hasVisibleDefinition(Definition) && 12394 (Definition->getFormalLinkage() == InternalLinkage || 12395 Definition->isInlined() || 12396 Definition->getDescribedFunctionTemplate() || 12397 Definition->getNumTemplateParameterLists())) { 12398 SkipBody->ShouldSkip = true; 12399 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12400 makeMergedDefinitionVisible(TD); 12401 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12402 return; 12403 } 12404 12405 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12406 Definition->getStorageClass() == SC_Extern) 12407 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12408 << FD->getDeclName() << getLangOpts().CPlusPlus; 12409 else 12410 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12411 12412 Diag(Definition->getLocation(), diag::note_previous_definition); 12413 FD->setInvalidDecl(); 12414 } 12415 12416 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12417 Sema &S) { 12418 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12419 12420 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12421 LSI->CallOperator = CallOperator; 12422 LSI->Lambda = LambdaClass; 12423 LSI->ReturnType = CallOperator->getReturnType(); 12424 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12425 12426 if (LCD == LCD_None) 12427 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12428 else if (LCD == LCD_ByCopy) 12429 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12430 else if (LCD == LCD_ByRef) 12431 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12432 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12433 12434 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12435 LSI->Mutable = !CallOperator->isConst(); 12436 12437 // Add the captures to the LSI so they can be noted as already 12438 // captured within tryCaptureVar. 12439 auto I = LambdaClass->field_begin(); 12440 for (const auto &C : LambdaClass->captures()) { 12441 if (C.capturesVariable()) { 12442 VarDecl *VD = C.getCapturedVar(); 12443 if (VD->isInitCapture()) 12444 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12445 QualType CaptureType = VD->getType(); 12446 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12447 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12448 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12449 /*EllipsisLoc*/C.isPackExpansion() 12450 ? C.getEllipsisLoc() : SourceLocation(), 12451 CaptureType, /*Expr*/ nullptr); 12452 12453 } else if (C.capturesThis()) { 12454 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12455 /*Expr*/ nullptr, 12456 C.getCaptureKind() == LCK_StarThis); 12457 } else { 12458 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12459 } 12460 ++I; 12461 } 12462 } 12463 12464 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12465 SkipBodyInfo *SkipBody) { 12466 if (!D) { 12467 // Parsing the function declaration failed in some way. Push on a fake scope 12468 // anyway so we can try to parse the function body. 12469 PushFunctionScope(); 12470 return D; 12471 } 12472 12473 FunctionDecl *FD = nullptr; 12474 12475 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12476 FD = FunTmpl->getTemplatedDecl(); 12477 else 12478 FD = cast<FunctionDecl>(D); 12479 12480 // Check for defining attributes before the check for redefinition. 12481 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12482 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12483 FD->dropAttr<AliasAttr>(); 12484 FD->setInvalidDecl(); 12485 } 12486 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12487 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12488 FD->dropAttr<IFuncAttr>(); 12489 FD->setInvalidDecl(); 12490 } 12491 12492 // See if this is a redefinition. If 'will have body' is already set, then 12493 // these checks were already performed when it was set. 12494 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12495 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12496 12497 // If we're skipping the body, we're done. Don't enter the scope. 12498 if (SkipBody && SkipBody->ShouldSkip) 12499 return D; 12500 } 12501 12502 // Mark this function as "will have a body eventually". This lets users to 12503 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12504 // this function. 12505 FD->setWillHaveBody(); 12506 12507 // If we are instantiating a generic lambda call operator, push 12508 // a LambdaScopeInfo onto the function stack. But use the information 12509 // that's already been calculated (ActOnLambdaExpr) to prime the current 12510 // LambdaScopeInfo. 12511 // When the template operator is being specialized, the LambdaScopeInfo, 12512 // has to be properly restored so that tryCaptureVariable doesn't try 12513 // and capture any new variables. In addition when calculating potential 12514 // captures during transformation of nested lambdas, it is necessary to 12515 // have the LSI properly restored. 12516 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12517 assert(inTemplateInstantiation() && 12518 "There should be an active template instantiation on the stack " 12519 "when instantiating a generic lambda!"); 12520 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12521 } else { 12522 // Enter a new function scope 12523 PushFunctionScope(); 12524 } 12525 12526 // Builtin functions cannot be defined. 12527 if (unsigned BuiltinID = FD->getBuiltinID()) { 12528 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12529 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12530 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12531 FD->setInvalidDecl(); 12532 } 12533 } 12534 12535 // The return type of a function definition must be complete 12536 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12537 QualType ResultType = FD->getReturnType(); 12538 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12539 !FD->isInvalidDecl() && 12540 RequireCompleteType(FD->getLocation(), ResultType, 12541 diag::err_func_def_incomplete_result)) 12542 FD->setInvalidDecl(); 12543 12544 if (FnBodyScope) 12545 PushDeclContext(FnBodyScope, FD); 12546 12547 // Check the validity of our function parameters 12548 CheckParmsForFunctionDef(FD->parameters(), 12549 /*CheckParameterNames=*/true); 12550 12551 // Add non-parameter declarations already in the function to the current 12552 // scope. 12553 if (FnBodyScope) { 12554 for (Decl *NPD : FD->decls()) { 12555 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12556 if (!NonParmDecl) 12557 continue; 12558 assert(!isa<ParmVarDecl>(NonParmDecl) && 12559 "parameters should not be in newly created FD yet"); 12560 12561 // If the decl has a name, make it accessible in the current scope. 12562 if (NonParmDecl->getDeclName()) 12563 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12564 12565 // Similarly, dive into enums and fish their constants out, making them 12566 // accessible in this scope. 12567 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12568 for (auto *EI : ED->enumerators()) 12569 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12570 } 12571 } 12572 } 12573 12574 // Introduce our parameters into the function scope 12575 for (auto Param : FD->parameters()) { 12576 Param->setOwningFunction(FD); 12577 12578 // If this has an identifier, add it to the scope stack. 12579 if (Param->getIdentifier() && FnBodyScope) { 12580 CheckShadow(FnBodyScope, Param); 12581 12582 PushOnScopeChains(Param, FnBodyScope); 12583 } 12584 } 12585 12586 // Ensure that the function's exception specification is instantiated. 12587 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12588 ResolveExceptionSpec(D->getLocation(), FPT); 12589 12590 // dllimport cannot be applied to non-inline function definitions. 12591 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12592 !FD->isTemplateInstantiation()) { 12593 assert(!FD->hasAttr<DLLExportAttr>()); 12594 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12595 FD->setInvalidDecl(); 12596 return D; 12597 } 12598 // We want to attach documentation to original Decl (which might be 12599 // a function template). 12600 ActOnDocumentableDecl(D); 12601 if (getCurLexicalContext()->isObjCContainer() && 12602 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12603 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12604 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12605 12606 return D; 12607 } 12608 12609 /// Given the set of return statements within a function body, 12610 /// compute the variables that are subject to the named return value 12611 /// optimization. 12612 /// 12613 /// Each of the variables that is subject to the named return value 12614 /// optimization will be marked as NRVO variables in the AST, and any 12615 /// return statement that has a marked NRVO variable as its NRVO candidate can 12616 /// use the named return value optimization. 12617 /// 12618 /// This function applies a very simplistic algorithm for NRVO: if every return 12619 /// statement in the scope of a variable has the same NRVO candidate, that 12620 /// candidate is an NRVO variable. 12621 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12622 ReturnStmt **Returns = Scope->Returns.data(); 12623 12624 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12625 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12626 if (!NRVOCandidate->isNRVOVariable()) 12627 Returns[I]->setNRVOCandidate(nullptr); 12628 } 12629 } 12630 } 12631 12632 bool Sema::canDelayFunctionBody(const Declarator &D) { 12633 // We can't delay parsing the body of a constexpr function template (yet). 12634 if (D.getDeclSpec().isConstexprSpecified()) 12635 return false; 12636 12637 // We can't delay parsing the body of a function template with a deduced 12638 // return type (yet). 12639 if (D.getDeclSpec().hasAutoTypeSpec()) { 12640 // If the placeholder introduces a non-deduced trailing return type, 12641 // we can still delay parsing it. 12642 if (D.getNumTypeObjects()) { 12643 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12644 if (Outer.Kind == DeclaratorChunk::Function && 12645 Outer.Fun.hasTrailingReturnType()) { 12646 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12647 return Ty.isNull() || !Ty->isUndeducedType(); 12648 } 12649 } 12650 return false; 12651 } 12652 12653 return true; 12654 } 12655 12656 bool Sema::canSkipFunctionBody(Decl *D) { 12657 // We cannot skip the body of a function (or function template) which is 12658 // constexpr, since we may need to evaluate its body in order to parse the 12659 // rest of the file. 12660 // We cannot skip the body of a function with an undeduced return type, 12661 // because any callers of that function need to know the type. 12662 if (const FunctionDecl *FD = D->getAsFunction()) 12663 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12664 return false; 12665 return Consumer.shouldSkipFunctionBody(D); 12666 } 12667 12668 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12669 if (!Decl) 12670 return nullptr; 12671 if (FunctionDecl *FD = Decl->getAsFunction()) 12672 FD->setHasSkippedBody(); 12673 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 12674 MD->setHasSkippedBody(); 12675 return Decl; 12676 } 12677 12678 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12679 return ActOnFinishFunctionBody(D, BodyArg, false); 12680 } 12681 12682 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12683 bool IsInstantiation) { 12684 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12685 12686 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12687 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12688 12689 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12690 CheckCompletedCoroutineBody(FD, Body); 12691 12692 if (FD) { 12693 FD->setBody(Body); 12694 FD->setWillHaveBody(false); 12695 12696 if (getLangOpts().CPlusPlus14) { 12697 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12698 FD->getReturnType()->isUndeducedType()) { 12699 // If the function has a deduced result type but contains no 'return' 12700 // statements, the result type as written must be exactly 'auto', and 12701 // the deduced result type is 'void'. 12702 if (!FD->getReturnType()->getAs<AutoType>()) { 12703 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12704 << FD->getReturnType(); 12705 FD->setInvalidDecl(); 12706 } else { 12707 // Substitute 'void' for the 'auto' in the type. 12708 TypeLoc ResultType = getReturnTypeLoc(FD); 12709 Context.adjustDeducedFunctionResultType( 12710 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12711 } 12712 } 12713 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12714 // In C++11, we don't use 'auto' deduction rules for lambda call 12715 // operators because we don't support return type deduction. 12716 auto *LSI = getCurLambda(); 12717 if (LSI->HasImplicitReturnType) { 12718 deduceClosureReturnType(*LSI); 12719 12720 // C++11 [expr.prim.lambda]p4: 12721 // [...] if there are no return statements in the compound-statement 12722 // [the deduced type is] the type void 12723 QualType RetType = 12724 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12725 12726 // Update the return type to the deduced type. 12727 const FunctionProtoType *Proto = 12728 FD->getType()->getAs<FunctionProtoType>(); 12729 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12730 Proto->getExtProtoInfo())); 12731 } 12732 } 12733 12734 // If the function implicitly returns zero (like 'main') or is naked, 12735 // don't complain about missing return statements. 12736 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12737 WP.disableCheckFallThrough(); 12738 12739 // MSVC permits the use of pure specifier (=0) on function definition, 12740 // defined at class scope, warn about this non-standard construct. 12741 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12742 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12743 12744 if (!FD->isInvalidDecl()) { 12745 // Don't diagnose unused parameters of defaulted or deleted functions. 12746 if (!FD->isDeleted() && !FD->isDefaulted()) 12747 DiagnoseUnusedParameters(FD->parameters()); 12748 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12749 FD->getReturnType(), FD); 12750 12751 // If this is a structor, we need a vtable. 12752 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12753 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12754 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12755 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12756 12757 // Try to apply the named return value optimization. We have to check 12758 // if we can do this here because lambdas keep return statements around 12759 // to deduce an implicit return type. 12760 if (FD->getReturnType()->isRecordType() && 12761 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 12762 computeNRVO(Body, getCurFunction()); 12763 } 12764 12765 // GNU warning -Wmissing-prototypes: 12766 // Warn if a global function is defined without a previous 12767 // prototype declaration. This warning is issued even if the 12768 // definition itself provides a prototype. The aim is to detect 12769 // global functions that fail to be declared in header files. 12770 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12771 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12772 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12773 12774 if (PossibleZeroParamPrototype) { 12775 // We found a declaration that is not a prototype, 12776 // but that could be a zero-parameter prototype 12777 if (TypeSourceInfo *TI = 12778 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12779 TypeLoc TL = TI->getTypeLoc(); 12780 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12781 Diag(PossibleZeroParamPrototype->getLocation(), 12782 diag::note_declaration_not_a_prototype) 12783 << PossibleZeroParamPrototype 12784 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12785 } 12786 } 12787 12788 // GNU warning -Wstrict-prototypes 12789 // Warn if K&R function is defined without a previous declaration. 12790 // This warning is issued only if the definition itself does not provide 12791 // a prototype. Only K&R definitions do not provide a prototype. 12792 // An empty list in a function declarator that is part of a definition 12793 // of that function specifies that the function has no parameters 12794 // (C99 6.7.5.3p14) 12795 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12796 !LangOpts.CPlusPlus) { 12797 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12798 TypeLoc TL = TI->getTypeLoc(); 12799 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12800 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12801 } 12802 } 12803 12804 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12805 const CXXMethodDecl *KeyFunction; 12806 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12807 MD->isVirtual() && 12808 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12809 MD == KeyFunction->getCanonicalDecl()) { 12810 // Update the key-function state if necessary for this ABI. 12811 if (FD->isInlined() && 12812 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12813 Context.setNonKeyFunction(MD); 12814 12815 // If the newly-chosen key function is already defined, then we 12816 // need to mark the vtable as used retroactively. 12817 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12818 const FunctionDecl *Definition; 12819 if (KeyFunction && KeyFunction->isDefined(Definition)) 12820 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12821 } else { 12822 // We just defined they key function; mark the vtable as used. 12823 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12824 } 12825 } 12826 } 12827 12828 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12829 "Function parsing confused"); 12830 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12831 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12832 MD->setBody(Body); 12833 if (!MD->isInvalidDecl()) { 12834 DiagnoseUnusedParameters(MD->parameters()); 12835 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12836 MD->getReturnType(), MD); 12837 12838 if (Body) 12839 computeNRVO(Body, getCurFunction()); 12840 } 12841 if (getCurFunction()->ObjCShouldCallSuper) { 12842 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12843 << MD->getSelector().getAsString(); 12844 getCurFunction()->ObjCShouldCallSuper = false; 12845 } 12846 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12847 const ObjCMethodDecl *InitMethod = nullptr; 12848 bool isDesignated = 12849 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12850 assert(isDesignated && InitMethod); 12851 (void)isDesignated; 12852 12853 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12854 auto IFace = MD->getClassInterface(); 12855 if (!IFace) 12856 return false; 12857 auto SuperD = IFace->getSuperClass(); 12858 if (!SuperD) 12859 return false; 12860 return SuperD->getIdentifier() == 12861 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12862 }; 12863 // Don't issue this warning for unavailable inits or direct subclasses 12864 // of NSObject. 12865 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12866 Diag(MD->getLocation(), 12867 diag::warn_objc_designated_init_missing_super_call); 12868 Diag(InitMethod->getLocation(), 12869 diag::note_objc_designated_init_marked_here); 12870 } 12871 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12872 } 12873 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12874 // Don't issue this warning for unavaialable inits. 12875 if (!MD->isUnavailable()) 12876 Diag(MD->getLocation(), 12877 diag::warn_objc_secondary_init_missing_init_call); 12878 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12879 } 12880 } else { 12881 // Parsing the function declaration failed in some way. Pop the fake scope 12882 // we pushed on. 12883 PopFunctionScopeInfo(ActivePolicy, dcl); 12884 return nullptr; 12885 } 12886 12887 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12888 DiagnoseUnguardedAvailabilityViolations(dcl); 12889 12890 assert(!getCurFunction()->ObjCShouldCallSuper && 12891 "This should only be set for ObjC methods, which should have been " 12892 "handled in the block above."); 12893 12894 // Verify and clean out per-function state. 12895 if (Body && (!FD || !FD->isDefaulted())) { 12896 // C++ constructors that have function-try-blocks can't have return 12897 // statements in the handlers of that block. (C++ [except.handle]p14) 12898 // Verify this. 12899 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12900 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12901 12902 // Verify that gotos and switch cases don't jump into scopes illegally. 12903 if (getCurFunction()->NeedsScopeChecking() && 12904 !PP.isCodeCompletionEnabled()) 12905 DiagnoseInvalidJumps(Body); 12906 12907 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12908 if (!Destructor->getParent()->isDependentType()) 12909 CheckDestructor(Destructor); 12910 12911 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12912 Destructor->getParent()); 12913 } 12914 12915 // If any errors have occurred, clear out any temporaries that may have 12916 // been leftover. This ensures that these temporaries won't be picked up for 12917 // deletion in some later function. 12918 if (getDiagnostics().hasErrorOccurred() || 12919 getDiagnostics().getSuppressAllDiagnostics()) { 12920 DiscardCleanupsInEvaluationContext(); 12921 } 12922 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12923 !isa<FunctionTemplateDecl>(dcl)) { 12924 // Since the body is valid, issue any analysis-based warnings that are 12925 // enabled. 12926 ActivePolicy = &WP; 12927 } 12928 12929 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12930 (!CheckConstexprFunctionDecl(FD) || 12931 !CheckConstexprFunctionBody(FD, Body))) 12932 FD->setInvalidDecl(); 12933 12934 if (FD && FD->hasAttr<NakedAttr>()) { 12935 for (const Stmt *S : Body->children()) { 12936 // Allow local register variables without initializer as they don't 12937 // require prologue. 12938 bool RegisterVariables = false; 12939 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12940 for (const auto *Decl : DS->decls()) { 12941 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12942 RegisterVariables = 12943 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12944 if (!RegisterVariables) 12945 break; 12946 } 12947 } 12948 } 12949 if (RegisterVariables) 12950 continue; 12951 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12952 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12953 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12954 FD->setInvalidDecl(); 12955 break; 12956 } 12957 } 12958 } 12959 12960 assert(ExprCleanupObjects.size() == 12961 ExprEvalContexts.back().NumCleanupObjects && 12962 "Leftover temporaries in function"); 12963 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12964 assert(MaybeODRUseExprs.empty() && 12965 "Leftover expressions for odr-use checking"); 12966 } 12967 12968 if (!IsInstantiation) 12969 PopDeclContext(); 12970 12971 PopFunctionScopeInfo(ActivePolicy, dcl); 12972 // If any errors have occurred, clear out any temporaries that may have 12973 // been leftover. This ensures that these temporaries won't be picked up for 12974 // deletion in some later function. 12975 if (getDiagnostics().hasErrorOccurred()) { 12976 DiscardCleanupsInEvaluationContext(); 12977 } 12978 12979 return dcl; 12980 } 12981 12982 /// When we finish delayed parsing of an attribute, we must attach it to the 12983 /// relevant Decl. 12984 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12985 ParsedAttributes &Attrs) { 12986 // Always attach attributes to the underlying decl. 12987 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12988 D = TD->getTemplatedDecl(); 12989 ProcessDeclAttributeList(S, D, Attrs.getList()); 12990 12991 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12992 if (Method->isStatic()) 12993 checkThisInStaticMemberFunctionAttributes(Method); 12994 } 12995 12996 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12997 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12998 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12999 IdentifierInfo &II, Scope *S) { 13000 // Find the scope in which the identifier is injected and the corresponding 13001 // DeclContext. 13002 // FIXME: C89 does not say what happens if there is no enclosing block scope. 13003 // In that case, we inject the declaration into the translation unit scope 13004 // instead. 13005 Scope *BlockScope = S; 13006 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 13007 BlockScope = BlockScope->getParent(); 13008 13009 Scope *ContextScope = BlockScope; 13010 while (!ContextScope->getEntity()) 13011 ContextScope = ContextScope->getParent(); 13012 ContextRAII SavedContext(*this, ContextScope->getEntity()); 13013 13014 // Before we produce a declaration for an implicitly defined 13015 // function, see whether there was a locally-scoped declaration of 13016 // this name as a function or variable. If so, use that 13017 // (non-visible) declaration, and complain about it. 13018 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 13019 if (ExternCPrev) { 13020 // We still need to inject the function into the enclosing block scope so 13021 // that later (non-call) uses can see it. 13022 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13023 13024 // C89 footnote 38: 13025 // If in fact it is not defined as having type "function returning int", 13026 // the behavior is undefined. 13027 if (!isa<FunctionDecl>(ExternCPrev) || 13028 !Context.typesAreCompatible( 13029 cast<FunctionDecl>(ExternCPrev)->getType(), 13030 Context.getFunctionNoProtoType(Context.IntTy))) { 13031 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13032 << ExternCPrev << !getLangOpts().C99; 13033 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13034 return ExternCPrev; 13035 } 13036 } 13037 13038 // Extension in C99. Legal in C90, but warn about it. 13039 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13040 unsigned diag_id; 13041 if (II.getName().startswith("__builtin_")) 13042 diag_id = diag::warn_builtin_unknown; 13043 else if (getLangOpts().C99 || getLangOpts().OpenCL) 13044 diag_id = diag::ext_implicit_function_decl; 13045 else 13046 diag_id = diag::warn_implicit_function_decl; 13047 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL; 13048 13049 // If we found a prior declaration of this function, don't bother building 13050 // another one. We've already pushed that one into scope, so there's nothing 13051 // more to do. 13052 if (ExternCPrev) 13053 return ExternCPrev; 13054 13055 // Because typo correction is expensive, only do it if the implicit 13056 // function declaration is going to be treated as an error. 13057 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13058 TypoCorrection Corrected; 13059 if (S && 13060 (Corrected = CorrectTypo( 13061 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 13062 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 13063 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13064 /*ErrorRecovery*/false); 13065 } 13066 13067 // Set a Declarator for the implicit definition: int foo(); 13068 const char *Dummy; 13069 AttributeFactory attrFactory; 13070 DeclSpec DS(attrFactory); 13071 unsigned DiagID; 13072 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13073 Context.getPrintingPolicy()); 13074 (void)Error; // Silence warning. 13075 assert(!Error && "Error setting up implicit decl!"); 13076 SourceLocation NoLoc; 13077 Declarator D(DS, DeclaratorContext::BlockContext); 13078 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13079 /*IsAmbiguous=*/false, 13080 /*LParenLoc=*/NoLoc, 13081 /*Params=*/nullptr, 13082 /*NumParams=*/0, 13083 /*EllipsisLoc=*/NoLoc, 13084 /*RParenLoc=*/NoLoc, 13085 /*TypeQuals=*/0, 13086 /*RefQualifierIsLvalueRef=*/true, 13087 /*RefQualifierLoc=*/NoLoc, 13088 /*ConstQualifierLoc=*/NoLoc, 13089 /*VolatileQualifierLoc=*/NoLoc, 13090 /*RestrictQualifierLoc=*/NoLoc, 13091 /*MutableLoc=*/NoLoc, 13092 EST_None, 13093 /*ESpecRange=*/SourceRange(), 13094 /*Exceptions=*/nullptr, 13095 /*ExceptionRanges=*/nullptr, 13096 /*NumExceptions=*/0, 13097 /*NoexceptExpr=*/nullptr, 13098 /*ExceptionSpecTokens=*/nullptr, 13099 /*DeclsInPrototype=*/None, 13100 Loc, Loc, D), 13101 DS.getAttributes(), 13102 SourceLocation()); 13103 D.SetIdentifier(&II, Loc); 13104 13105 // Insert this function into the enclosing block scope. 13106 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13107 FD->setImplicit(); 13108 13109 AddKnownFunctionAttributes(FD); 13110 13111 return FD; 13112 } 13113 13114 /// Adds any function attributes that we know a priori based on 13115 /// the declaration of this function. 13116 /// 13117 /// These attributes can apply both to implicitly-declared builtins 13118 /// (like __builtin___printf_chk) or to library-declared functions 13119 /// like NSLog or printf. 13120 /// 13121 /// We need to check for duplicate attributes both here and where user-written 13122 /// attributes are applied to declarations. 13123 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13124 if (FD->isInvalidDecl()) 13125 return; 13126 13127 // If this is a built-in function, map its builtin attributes to 13128 // actual attributes. 13129 if (unsigned BuiltinID = FD->getBuiltinID()) { 13130 // Handle printf-formatting attributes. 13131 unsigned FormatIdx; 13132 bool HasVAListArg; 13133 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13134 if (!FD->hasAttr<FormatAttr>()) { 13135 const char *fmt = "printf"; 13136 unsigned int NumParams = FD->getNumParams(); 13137 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13138 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13139 fmt = "NSString"; 13140 FD->addAttr(FormatAttr::CreateImplicit(Context, 13141 &Context.Idents.get(fmt), 13142 FormatIdx+1, 13143 HasVAListArg ? 0 : FormatIdx+2, 13144 FD->getLocation())); 13145 } 13146 } 13147 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13148 HasVAListArg)) { 13149 if (!FD->hasAttr<FormatAttr>()) 13150 FD->addAttr(FormatAttr::CreateImplicit(Context, 13151 &Context.Idents.get("scanf"), 13152 FormatIdx+1, 13153 HasVAListArg ? 0 : FormatIdx+2, 13154 FD->getLocation())); 13155 } 13156 13157 // Mark const if we don't care about errno and that is the only thing 13158 // preventing the function from being const. This allows IRgen to use LLVM 13159 // intrinsics for such functions. 13160 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13161 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13162 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13163 13164 // We make "fma" on some platforms const because we know it does not set 13165 // errno in those environments even though it could set errno based on the 13166 // C standard. 13167 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13168 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13169 !FD->hasAttr<ConstAttr>()) { 13170 switch (BuiltinID) { 13171 case Builtin::BI__builtin_fma: 13172 case Builtin::BI__builtin_fmaf: 13173 case Builtin::BI__builtin_fmal: 13174 case Builtin::BIfma: 13175 case Builtin::BIfmaf: 13176 case Builtin::BIfmal: 13177 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13178 break; 13179 default: 13180 break; 13181 } 13182 } 13183 13184 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13185 !FD->hasAttr<ReturnsTwiceAttr>()) 13186 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13187 FD->getLocation())); 13188 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13189 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13190 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13191 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13192 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13193 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13194 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13195 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13196 // Add the appropriate attribute, depending on the CUDA compilation mode 13197 // and which target the builtin belongs to. For example, during host 13198 // compilation, aux builtins are __device__, while the rest are __host__. 13199 if (getLangOpts().CUDAIsDevice != 13200 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13201 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13202 else 13203 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13204 } 13205 } 13206 13207 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13208 // throw, add an implicit nothrow attribute to any extern "C" function we come 13209 // across. 13210 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13211 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13212 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13213 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13214 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13215 } 13216 13217 IdentifierInfo *Name = FD->getIdentifier(); 13218 if (!Name) 13219 return; 13220 if ((!getLangOpts().CPlusPlus && 13221 FD->getDeclContext()->isTranslationUnit()) || 13222 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13223 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13224 LinkageSpecDecl::lang_c)) { 13225 // Okay: this could be a libc/libm/Objective-C function we know 13226 // about. 13227 } else 13228 return; 13229 13230 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13231 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13232 // target-specific builtins, perhaps? 13233 if (!FD->hasAttr<FormatAttr>()) 13234 FD->addAttr(FormatAttr::CreateImplicit(Context, 13235 &Context.Idents.get("printf"), 2, 13236 Name->isStr("vasprintf") ? 0 : 3, 13237 FD->getLocation())); 13238 } 13239 13240 if (Name->isStr("__CFStringMakeConstantString")) { 13241 // We already have a __builtin___CFStringMakeConstantString, 13242 // but builds that use -fno-constant-cfstrings don't go through that. 13243 if (!FD->hasAttr<FormatArgAttr>()) 13244 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13245 FD->getLocation())); 13246 } 13247 } 13248 13249 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13250 TypeSourceInfo *TInfo) { 13251 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13252 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13253 13254 if (!TInfo) { 13255 assert(D.isInvalidType() && "no declarator info for valid type"); 13256 TInfo = Context.getTrivialTypeSourceInfo(T); 13257 } 13258 13259 // Scope manipulation handled by caller. 13260 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 13261 D.getLocStart(), 13262 D.getIdentifierLoc(), 13263 D.getIdentifier(), 13264 TInfo); 13265 13266 // Bail out immediately if we have an invalid declaration. 13267 if (D.isInvalidType()) { 13268 NewTD->setInvalidDecl(); 13269 return NewTD; 13270 } 13271 13272 if (D.getDeclSpec().isModulePrivateSpecified()) { 13273 if (CurContext->isFunctionOrMethod()) 13274 Diag(NewTD->getLocation(), diag::err_module_private_local) 13275 << 2 << NewTD->getDeclName() 13276 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13277 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13278 else 13279 NewTD->setModulePrivate(); 13280 } 13281 13282 // C++ [dcl.typedef]p8: 13283 // If the typedef declaration defines an unnamed class (or 13284 // enum), the first typedef-name declared by the declaration 13285 // to be that class type (or enum type) is used to denote the 13286 // class type (or enum type) for linkage purposes only. 13287 // We need to check whether the type was declared in the declaration. 13288 switch (D.getDeclSpec().getTypeSpecType()) { 13289 case TST_enum: 13290 case TST_struct: 13291 case TST_interface: 13292 case TST_union: 13293 case TST_class: { 13294 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13295 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13296 break; 13297 } 13298 13299 default: 13300 break; 13301 } 13302 13303 return NewTD; 13304 } 13305 13306 /// Check that this is a valid underlying type for an enum declaration. 13307 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13308 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13309 QualType T = TI->getType(); 13310 13311 if (T->isDependentType()) 13312 return false; 13313 13314 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13315 if (BT->isInteger()) 13316 return false; 13317 13318 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13319 return true; 13320 } 13321 13322 /// Check whether this is a valid redeclaration of a previous enumeration. 13323 /// \return true if the redeclaration was invalid. 13324 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13325 QualType EnumUnderlyingTy, bool IsFixed, 13326 const EnumDecl *Prev) { 13327 if (IsScoped != Prev->isScoped()) { 13328 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13329 << Prev->isScoped(); 13330 Diag(Prev->getLocation(), diag::note_previous_declaration); 13331 return true; 13332 } 13333 13334 if (IsFixed && Prev->isFixed()) { 13335 if (!EnumUnderlyingTy->isDependentType() && 13336 !Prev->getIntegerType()->isDependentType() && 13337 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13338 Prev->getIntegerType())) { 13339 // TODO: Highlight the underlying type of the redeclaration. 13340 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13341 << EnumUnderlyingTy << Prev->getIntegerType(); 13342 Diag(Prev->getLocation(), diag::note_previous_declaration) 13343 << Prev->getIntegerTypeRange(); 13344 return true; 13345 } 13346 } else if (IsFixed != Prev->isFixed()) { 13347 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13348 << Prev->isFixed(); 13349 Diag(Prev->getLocation(), diag::note_previous_declaration); 13350 return true; 13351 } 13352 13353 return false; 13354 } 13355 13356 /// Get diagnostic %select index for tag kind for 13357 /// redeclaration diagnostic message. 13358 /// WARNING: Indexes apply to particular diagnostics only! 13359 /// 13360 /// \returns diagnostic %select index. 13361 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13362 switch (Tag) { 13363 case TTK_Struct: return 0; 13364 case TTK_Interface: return 1; 13365 case TTK_Class: return 2; 13366 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13367 } 13368 } 13369 13370 /// Determine if tag kind is a class-key compatible with 13371 /// class for redeclaration (class, struct, or __interface). 13372 /// 13373 /// \returns true iff the tag kind is compatible. 13374 static bool isClassCompatTagKind(TagTypeKind Tag) 13375 { 13376 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13377 } 13378 13379 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13380 TagTypeKind TTK) { 13381 if (isa<TypedefDecl>(PrevDecl)) 13382 return NTK_Typedef; 13383 else if (isa<TypeAliasDecl>(PrevDecl)) 13384 return NTK_TypeAlias; 13385 else if (isa<ClassTemplateDecl>(PrevDecl)) 13386 return NTK_Template; 13387 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13388 return NTK_TypeAliasTemplate; 13389 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13390 return NTK_TemplateTemplateArgument; 13391 switch (TTK) { 13392 case TTK_Struct: 13393 case TTK_Interface: 13394 case TTK_Class: 13395 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13396 case TTK_Union: 13397 return NTK_NonUnion; 13398 case TTK_Enum: 13399 return NTK_NonEnum; 13400 } 13401 llvm_unreachable("invalid TTK"); 13402 } 13403 13404 /// Determine whether a tag with a given kind is acceptable 13405 /// as a redeclaration of the given tag declaration. 13406 /// 13407 /// \returns true if the new tag kind is acceptable, false otherwise. 13408 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13409 TagTypeKind NewTag, bool isDefinition, 13410 SourceLocation NewTagLoc, 13411 const IdentifierInfo *Name) { 13412 // C++ [dcl.type.elab]p3: 13413 // The class-key or enum keyword present in the 13414 // elaborated-type-specifier shall agree in kind with the 13415 // declaration to which the name in the elaborated-type-specifier 13416 // refers. This rule also applies to the form of 13417 // elaborated-type-specifier that declares a class-name or 13418 // friend class since it can be construed as referring to the 13419 // definition of the class. Thus, in any 13420 // elaborated-type-specifier, the enum keyword shall be used to 13421 // refer to an enumeration (7.2), the union class-key shall be 13422 // used to refer to a union (clause 9), and either the class or 13423 // struct class-key shall be used to refer to a class (clause 9) 13424 // declared using the class or struct class-key. 13425 TagTypeKind OldTag = Previous->getTagKind(); 13426 if (!isDefinition || !isClassCompatTagKind(NewTag)) 13427 if (OldTag == NewTag) 13428 return true; 13429 13430 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13431 // Warn about the struct/class tag mismatch. 13432 bool isTemplate = false; 13433 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13434 isTemplate = Record->getDescribedClassTemplate(); 13435 13436 if (inTemplateInstantiation()) { 13437 // In a template instantiation, do not offer fix-its for tag mismatches 13438 // since they usually mess up the template instead of fixing the problem. 13439 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13440 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13441 << getRedeclDiagFromTagKind(OldTag); 13442 return true; 13443 } 13444 13445 if (isDefinition) { 13446 // On definitions, check previous tags and issue a fix-it for each 13447 // one that doesn't match the current tag. 13448 if (Previous->getDefinition()) { 13449 // Don't suggest fix-its for redefinitions. 13450 return true; 13451 } 13452 13453 bool previousMismatch = false; 13454 for (auto I : Previous->redecls()) { 13455 if (I->getTagKind() != NewTag) { 13456 if (!previousMismatch) { 13457 previousMismatch = true; 13458 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13459 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13460 << getRedeclDiagFromTagKind(I->getTagKind()); 13461 } 13462 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13463 << getRedeclDiagFromTagKind(NewTag) 13464 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13465 TypeWithKeyword::getTagTypeKindName(NewTag)); 13466 } 13467 } 13468 return true; 13469 } 13470 13471 // Check for a previous definition. If current tag and definition 13472 // are same type, do nothing. If no definition, but disagree with 13473 // with previous tag type, give a warning, but no fix-it. 13474 const TagDecl *Redecl = Previous->getDefinition() ? 13475 Previous->getDefinition() : Previous; 13476 if (Redecl->getTagKind() == NewTag) { 13477 return true; 13478 } 13479 13480 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13481 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13482 << getRedeclDiagFromTagKind(OldTag); 13483 Diag(Redecl->getLocation(), diag::note_previous_use); 13484 13485 // If there is a previous definition, suggest a fix-it. 13486 if (Previous->getDefinition()) { 13487 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13488 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13489 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13490 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13491 } 13492 13493 return true; 13494 } 13495 return false; 13496 } 13497 13498 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13499 /// from an outer enclosing namespace or file scope inside a friend declaration. 13500 /// This should provide the commented out code in the following snippet: 13501 /// namespace N { 13502 /// struct X; 13503 /// namespace M { 13504 /// struct Y { friend struct /*N::*/ X; }; 13505 /// } 13506 /// } 13507 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13508 SourceLocation NameLoc) { 13509 // While the decl is in a namespace, do repeated lookup of that name and see 13510 // if we get the same namespace back. If we do not, continue until 13511 // translation unit scope, at which point we have a fully qualified NNS. 13512 SmallVector<IdentifierInfo *, 4> Namespaces; 13513 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13514 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13515 // This tag should be declared in a namespace, which can only be enclosed by 13516 // other namespaces. Bail if there's an anonymous namespace in the chain. 13517 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13518 if (!Namespace || Namespace->isAnonymousNamespace()) 13519 return FixItHint(); 13520 IdentifierInfo *II = Namespace->getIdentifier(); 13521 Namespaces.push_back(II); 13522 NamedDecl *Lookup = SemaRef.LookupSingleName( 13523 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13524 if (Lookup == Namespace) 13525 break; 13526 } 13527 13528 // Once we have all the namespaces, reverse them to go outermost first, and 13529 // build an NNS. 13530 SmallString<64> Insertion; 13531 llvm::raw_svector_ostream OS(Insertion); 13532 if (DC->isTranslationUnit()) 13533 OS << "::"; 13534 std::reverse(Namespaces.begin(), Namespaces.end()); 13535 for (auto *II : Namespaces) 13536 OS << II->getName() << "::"; 13537 return FixItHint::CreateInsertion(NameLoc, Insertion); 13538 } 13539 13540 /// Determine whether a tag originally declared in context \p OldDC can 13541 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 13542 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13543 /// using-declaration). 13544 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13545 DeclContext *NewDC) { 13546 OldDC = OldDC->getRedeclContext(); 13547 NewDC = NewDC->getRedeclContext(); 13548 13549 if (OldDC->Equals(NewDC)) 13550 return true; 13551 13552 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13553 // encloses the other). 13554 if (S.getLangOpts().MSVCCompat && 13555 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13556 return true; 13557 13558 return false; 13559 } 13560 13561 /// This is invoked when we see 'struct foo' or 'struct {'. In the 13562 /// former case, Name will be non-null. In the later case, Name will be null. 13563 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13564 /// reference/declaration/definition of a tag. 13565 /// 13566 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13567 /// trailing-type-specifier) other than one in an alias-declaration. 13568 /// 13569 /// \param SkipBody If non-null, will be set to indicate if the caller should 13570 /// skip the definition of this tag and treat it as if it were a declaration. 13571 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13572 SourceLocation KWLoc, CXXScopeSpec &SS, 13573 IdentifierInfo *Name, SourceLocation NameLoc, 13574 AttributeList *Attr, AccessSpecifier AS, 13575 SourceLocation ModulePrivateLoc, 13576 MultiTemplateParamsArg TemplateParameterLists, 13577 bool &OwnedDecl, bool &IsDependent, 13578 SourceLocation ScopedEnumKWLoc, 13579 bool ScopedEnumUsesClassTag, 13580 TypeResult UnderlyingType, 13581 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13582 SkipBodyInfo *SkipBody) { 13583 // If this is not a definition, it must have a name. 13584 IdentifierInfo *OrigName = Name; 13585 assert((Name != nullptr || TUK == TUK_Definition) && 13586 "Nameless record must be a definition!"); 13587 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13588 13589 OwnedDecl = false; 13590 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13591 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13592 13593 // FIXME: Check member specializations more carefully. 13594 bool isMemberSpecialization = false; 13595 bool Invalid = false; 13596 13597 // We only need to do this matching if we have template parameters 13598 // or a scope specifier, which also conveniently avoids this work 13599 // for non-C++ cases. 13600 if (TemplateParameterLists.size() > 0 || 13601 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13602 if (TemplateParameterList *TemplateParams = 13603 MatchTemplateParametersToScopeSpecifier( 13604 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13605 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13606 if (Kind == TTK_Enum) { 13607 Diag(KWLoc, diag::err_enum_template); 13608 return nullptr; 13609 } 13610 13611 if (TemplateParams->size() > 0) { 13612 // This is a declaration or definition of a class template (which may 13613 // be a member of another template). 13614 13615 if (Invalid) 13616 return nullptr; 13617 13618 OwnedDecl = false; 13619 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13620 SS, Name, NameLoc, Attr, 13621 TemplateParams, AS, 13622 ModulePrivateLoc, 13623 /*FriendLoc*/SourceLocation(), 13624 TemplateParameterLists.size()-1, 13625 TemplateParameterLists.data(), 13626 SkipBody); 13627 return Result.get(); 13628 } else { 13629 // The "template<>" header is extraneous. 13630 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13631 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13632 isMemberSpecialization = true; 13633 } 13634 } 13635 } 13636 13637 // Figure out the underlying type if this a enum declaration. We need to do 13638 // this early, because it's needed to detect if this is an incompatible 13639 // redeclaration. 13640 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13641 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 13642 13643 if (Kind == TTK_Enum) { 13644 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 13645 // No underlying type explicitly specified, or we failed to parse the 13646 // type, default to int. 13647 EnumUnderlying = Context.IntTy.getTypePtr(); 13648 } else if (UnderlyingType.get()) { 13649 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13650 // integral type; any cv-qualification is ignored. 13651 TypeSourceInfo *TI = nullptr; 13652 GetTypeFromParser(UnderlyingType.get(), &TI); 13653 EnumUnderlying = TI; 13654 13655 if (CheckEnumUnderlyingType(TI)) 13656 // Recover by falling back to int. 13657 EnumUnderlying = Context.IntTy.getTypePtr(); 13658 13659 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13660 UPPC_FixedUnderlyingType)) 13661 EnumUnderlying = Context.IntTy.getTypePtr(); 13662 13663 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13664 // For MSVC ABI compatibility, unfixed enums must use an underlying type 13665 // of 'int'. However, if this is an unfixed forward declaration, don't set 13666 // the underlying type unless the user enables -fms-compatibility. This 13667 // makes unfixed forward declared enums incomplete and is more conforming. 13668 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 13669 EnumUnderlying = Context.IntTy.getTypePtr(); 13670 } 13671 } 13672 13673 DeclContext *SearchDC = CurContext; 13674 DeclContext *DC = CurContext; 13675 bool isStdBadAlloc = false; 13676 bool isStdAlignValT = false; 13677 13678 RedeclarationKind Redecl = forRedeclarationInCurContext(); 13679 if (TUK == TUK_Friend || TUK == TUK_Reference) 13680 Redecl = NotForRedeclaration; 13681 13682 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13683 /// implemented asks for structural equivalence checking, the returned decl 13684 /// here is passed back to the parser, allowing the tag body to be parsed. 13685 auto createTagFromNewDecl = [&]() -> TagDecl * { 13686 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13687 // If there is an identifier, use the location of the identifier as the 13688 // location of the decl, otherwise use the location of the struct/union 13689 // keyword. 13690 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13691 TagDecl *New = nullptr; 13692 13693 if (Kind == TTK_Enum) { 13694 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13695 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 13696 // If this is an undefined enum, bail. 13697 if (TUK != TUK_Definition && !Invalid) 13698 return nullptr; 13699 if (EnumUnderlying) { 13700 EnumDecl *ED = cast<EnumDecl>(New); 13701 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13702 ED->setIntegerTypeSourceInfo(TI); 13703 else 13704 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13705 ED->setPromotionType(ED->getIntegerType()); 13706 } 13707 } else { // struct/union 13708 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13709 nullptr); 13710 } 13711 13712 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13713 // Add alignment attributes if necessary; these attributes are checked 13714 // when the ASTContext lays out the structure. 13715 // 13716 // It is important for implementing the correct semantics that this 13717 // happen here (in ActOnTag). The #pragma pack stack is 13718 // maintained as a result of parser callbacks which can occur at 13719 // many points during the parsing of a struct declaration (because 13720 // the #pragma tokens are effectively skipped over during the 13721 // parsing of the struct). 13722 if (TUK == TUK_Definition) { 13723 AddAlignmentAttributesForRecord(RD); 13724 AddMsStructLayoutForRecord(RD); 13725 } 13726 } 13727 New->setLexicalDeclContext(CurContext); 13728 return New; 13729 }; 13730 13731 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13732 if (Name && SS.isNotEmpty()) { 13733 // We have a nested-name tag ('struct foo::bar'). 13734 13735 // Check for invalid 'foo::'. 13736 if (SS.isInvalid()) { 13737 Name = nullptr; 13738 goto CreateNewDecl; 13739 } 13740 13741 // If this is a friend or a reference to a class in a dependent 13742 // context, don't try to make a decl for it. 13743 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13744 DC = computeDeclContext(SS, false); 13745 if (!DC) { 13746 IsDependent = true; 13747 return nullptr; 13748 } 13749 } else { 13750 DC = computeDeclContext(SS, true); 13751 if (!DC) { 13752 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13753 << SS.getRange(); 13754 return nullptr; 13755 } 13756 } 13757 13758 if (RequireCompleteDeclContext(SS, DC)) 13759 return nullptr; 13760 13761 SearchDC = DC; 13762 // Look-up name inside 'foo::'. 13763 LookupQualifiedName(Previous, DC); 13764 13765 if (Previous.isAmbiguous()) 13766 return nullptr; 13767 13768 if (Previous.empty()) { 13769 // Name lookup did not find anything. However, if the 13770 // nested-name-specifier refers to the current instantiation, 13771 // and that current instantiation has any dependent base 13772 // classes, we might find something at instantiation time: treat 13773 // this as a dependent elaborated-type-specifier. 13774 // But this only makes any sense for reference-like lookups. 13775 if (Previous.wasNotFoundInCurrentInstantiation() && 13776 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13777 IsDependent = true; 13778 return nullptr; 13779 } 13780 13781 // A tag 'foo::bar' must already exist. 13782 Diag(NameLoc, diag::err_not_tag_in_scope) 13783 << Kind << Name << DC << SS.getRange(); 13784 Name = nullptr; 13785 Invalid = true; 13786 goto CreateNewDecl; 13787 } 13788 } else if (Name) { 13789 // C++14 [class.mem]p14: 13790 // If T is the name of a class, then each of the following shall have a 13791 // name different from T: 13792 // -- every member of class T that is itself a type 13793 if (TUK != TUK_Reference && TUK != TUK_Friend && 13794 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13795 return nullptr; 13796 13797 // If this is a named struct, check to see if there was a previous forward 13798 // declaration or definition. 13799 // FIXME: We're looking into outer scopes here, even when we 13800 // shouldn't be. Doing so can result in ambiguities that we 13801 // shouldn't be diagnosing. 13802 LookupName(Previous, S); 13803 13804 // When declaring or defining a tag, ignore ambiguities introduced 13805 // by types using'ed into this scope. 13806 if (Previous.isAmbiguous() && 13807 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13808 LookupResult::Filter F = Previous.makeFilter(); 13809 while (F.hasNext()) { 13810 NamedDecl *ND = F.next(); 13811 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13812 SearchDC->getRedeclContext())) 13813 F.erase(); 13814 } 13815 F.done(); 13816 } 13817 13818 // C++11 [namespace.memdef]p3: 13819 // If the name in a friend declaration is neither qualified nor 13820 // a template-id and the declaration is a function or an 13821 // elaborated-type-specifier, the lookup to determine whether 13822 // the entity has been previously declared shall not consider 13823 // any scopes outside the innermost enclosing namespace. 13824 // 13825 // MSVC doesn't implement the above rule for types, so a friend tag 13826 // declaration may be a redeclaration of a type declared in an enclosing 13827 // scope. They do implement this rule for friend functions. 13828 // 13829 // Does it matter that this should be by scope instead of by 13830 // semantic context? 13831 if (!Previous.empty() && TUK == TUK_Friend) { 13832 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13833 LookupResult::Filter F = Previous.makeFilter(); 13834 bool FriendSawTagOutsideEnclosingNamespace = false; 13835 while (F.hasNext()) { 13836 NamedDecl *ND = F.next(); 13837 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13838 if (DC->isFileContext() && 13839 !EnclosingNS->Encloses(ND->getDeclContext())) { 13840 if (getLangOpts().MSVCCompat) 13841 FriendSawTagOutsideEnclosingNamespace = true; 13842 else 13843 F.erase(); 13844 } 13845 } 13846 F.done(); 13847 13848 // Diagnose this MSVC extension in the easy case where lookup would have 13849 // unambiguously found something outside the enclosing namespace. 13850 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13851 NamedDecl *ND = Previous.getFoundDecl(); 13852 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13853 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13854 } 13855 } 13856 13857 // Note: there used to be some attempt at recovery here. 13858 if (Previous.isAmbiguous()) 13859 return nullptr; 13860 13861 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13862 // FIXME: This makes sure that we ignore the contexts associated 13863 // with C structs, unions, and enums when looking for a matching 13864 // tag declaration or definition. See the similar lookup tweak 13865 // in Sema::LookupName; is there a better way to deal with this? 13866 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13867 SearchDC = SearchDC->getParent(); 13868 } 13869 } 13870 13871 if (Previous.isSingleResult() && 13872 Previous.getFoundDecl()->isTemplateParameter()) { 13873 // Maybe we will complain about the shadowed template parameter. 13874 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13875 // Just pretend that we didn't see the previous declaration. 13876 Previous.clear(); 13877 } 13878 13879 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13880 DC->Equals(getStdNamespace())) { 13881 if (Name->isStr("bad_alloc")) { 13882 // This is a declaration of or a reference to "std::bad_alloc". 13883 isStdBadAlloc = true; 13884 13885 // If std::bad_alloc has been implicitly declared (but made invisible to 13886 // name lookup), fill in this implicit declaration as the previous 13887 // declaration, so that the declarations get chained appropriately. 13888 if (Previous.empty() && StdBadAlloc) 13889 Previous.addDecl(getStdBadAlloc()); 13890 } else if (Name->isStr("align_val_t")) { 13891 isStdAlignValT = true; 13892 if (Previous.empty() && StdAlignValT) 13893 Previous.addDecl(getStdAlignValT()); 13894 } 13895 } 13896 13897 // If we didn't find a previous declaration, and this is a reference 13898 // (or friend reference), move to the correct scope. In C++, we 13899 // also need to do a redeclaration lookup there, just in case 13900 // there's a shadow friend decl. 13901 if (Name && Previous.empty() && 13902 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13903 if (Invalid) goto CreateNewDecl; 13904 assert(SS.isEmpty()); 13905 13906 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13907 // C++ [basic.scope.pdecl]p5: 13908 // -- for an elaborated-type-specifier of the form 13909 // 13910 // class-key identifier 13911 // 13912 // if the elaborated-type-specifier is used in the 13913 // decl-specifier-seq or parameter-declaration-clause of a 13914 // function defined in namespace scope, the identifier is 13915 // declared as a class-name in the namespace that contains 13916 // the declaration; otherwise, except as a friend 13917 // declaration, the identifier is declared in the smallest 13918 // non-class, non-function-prototype scope that contains the 13919 // declaration. 13920 // 13921 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13922 // C structs and unions. 13923 // 13924 // It is an error in C++ to declare (rather than define) an enum 13925 // type, including via an elaborated type specifier. We'll 13926 // diagnose that later; for now, declare the enum in the same 13927 // scope as we would have picked for any other tag type. 13928 // 13929 // GNU C also supports this behavior as part of its incomplete 13930 // enum types extension, while GNU C++ does not. 13931 // 13932 // Find the context where we'll be declaring the tag. 13933 // FIXME: We would like to maintain the current DeclContext as the 13934 // lexical context, 13935 SearchDC = getTagInjectionContext(SearchDC); 13936 13937 // Find the scope where we'll be declaring the tag. 13938 S = getTagInjectionScope(S, getLangOpts()); 13939 } else { 13940 assert(TUK == TUK_Friend); 13941 // C++ [namespace.memdef]p3: 13942 // If a friend declaration in a non-local class first declares a 13943 // class or function, the friend class or function is a member of 13944 // the innermost enclosing namespace. 13945 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13946 } 13947 13948 // In C++, we need to do a redeclaration lookup to properly 13949 // diagnose some problems. 13950 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13951 // hidden declaration so that we don't get ambiguity errors when using a 13952 // type declared by an elaborated-type-specifier. In C that is not correct 13953 // and we should instead merge compatible types found by lookup. 13954 if (getLangOpts().CPlusPlus) { 13955 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13956 LookupQualifiedName(Previous, SearchDC); 13957 } else { 13958 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13959 LookupName(Previous, S); 13960 } 13961 } 13962 13963 // If we have a known previous declaration to use, then use it. 13964 if (Previous.empty() && SkipBody && SkipBody->Previous) 13965 Previous.addDecl(SkipBody->Previous); 13966 13967 if (!Previous.empty()) { 13968 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13969 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13970 13971 // It's okay to have a tag decl in the same scope as a typedef 13972 // which hides a tag decl in the same scope. Finding this 13973 // insanity with a redeclaration lookup can only actually happen 13974 // in C++. 13975 // 13976 // This is also okay for elaborated-type-specifiers, which is 13977 // technically forbidden by the current standard but which is 13978 // okay according to the likely resolution of an open issue; 13979 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13980 if (getLangOpts().CPlusPlus) { 13981 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13982 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13983 TagDecl *Tag = TT->getDecl(); 13984 if (Tag->getDeclName() == Name && 13985 Tag->getDeclContext()->getRedeclContext() 13986 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13987 PrevDecl = Tag; 13988 Previous.clear(); 13989 Previous.addDecl(Tag); 13990 Previous.resolveKind(); 13991 } 13992 } 13993 } 13994 } 13995 13996 // If this is a redeclaration of a using shadow declaration, it must 13997 // declare a tag in the same context. In MSVC mode, we allow a 13998 // redefinition if either context is within the other. 13999 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 14000 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 14001 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 14002 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 14003 !(OldTag && isAcceptableTagRedeclContext( 14004 *this, OldTag->getDeclContext(), SearchDC))) { 14005 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 14006 Diag(Shadow->getTargetDecl()->getLocation(), 14007 diag::note_using_decl_target); 14008 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 14009 << 0; 14010 // Recover by ignoring the old declaration. 14011 Previous.clear(); 14012 goto CreateNewDecl; 14013 } 14014 } 14015 14016 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 14017 // If this is a use of a previous tag, or if the tag is already declared 14018 // in the same scope (so that the definition/declaration completes or 14019 // rementions the tag), reuse the decl. 14020 if (TUK == TUK_Reference || TUK == TUK_Friend || 14021 isDeclInScope(DirectPrevDecl, SearchDC, S, 14022 SS.isNotEmpty() || isMemberSpecialization)) { 14023 // Make sure that this wasn't declared as an enum and now used as a 14024 // struct or something similar. 14025 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14026 TUK == TUK_Definition, KWLoc, 14027 Name)) { 14028 bool SafeToContinue 14029 = (PrevTagDecl->getTagKind() != TTK_Enum && 14030 Kind != TTK_Enum); 14031 if (SafeToContinue) 14032 Diag(KWLoc, diag::err_use_with_wrong_tag) 14033 << Name 14034 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14035 PrevTagDecl->getKindName()); 14036 else 14037 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14038 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14039 14040 if (SafeToContinue) 14041 Kind = PrevTagDecl->getTagKind(); 14042 else { 14043 // Recover by making this an anonymous redefinition. 14044 Name = nullptr; 14045 Previous.clear(); 14046 Invalid = true; 14047 } 14048 } 14049 14050 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14051 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14052 14053 // If this is an elaborated-type-specifier for a scoped enumeration, 14054 // the 'class' keyword is not necessary and not permitted. 14055 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14056 if (ScopedEnum) 14057 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14058 << PrevEnum->isScoped() 14059 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14060 return PrevTagDecl; 14061 } 14062 14063 QualType EnumUnderlyingTy; 14064 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14065 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14066 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14067 EnumUnderlyingTy = QualType(T, 0); 14068 14069 // All conflicts with previous declarations are recovered by 14070 // returning the previous declaration, unless this is a definition, 14071 // in which case we want the caller to bail out. 14072 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14073 ScopedEnum, EnumUnderlyingTy, 14074 IsFixed, PrevEnum)) 14075 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14076 } 14077 14078 // C++11 [class.mem]p1: 14079 // A member shall not be declared twice in the member-specification, 14080 // except that a nested class or member class template can be declared 14081 // and then later defined. 14082 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14083 S->isDeclScope(PrevDecl)) { 14084 Diag(NameLoc, diag::ext_member_redeclared); 14085 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14086 } 14087 14088 if (!Invalid) { 14089 // If this is a use, just return the declaration we found, unless 14090 // we have attributes. 14091 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14092 if (Attr) { 14093 // FIXME: Diagnose these attributes. For now, we create a new 14094 // declaration to hold them. 14095 } else if (TUK == TUK_Reference && 14096 (PrevTagDecl->getFriendObjectKind() == 14097 Decl::FOK_Undeclared || 14098 PrevDecl->getOwningModule() != getCurrentModule()) && 14099 SS.isEmpty()) { 14100 // This declaration is a reference to an existing entity, but 14101 // has different visibility from that entity: it either makes 14102 // a friend visible or it makes a type visible in a new module. 14103 // In either case, create a new declaration. We only do this if 14104 // the declaration would have meant the same thing if no prior 14105 // declaration were found, that is, if it was found in the same 14106 // scope where we would have injected a declaration. 14107 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14108 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14109 return PrevTagDecl; 14110 // This is in the injected scope, create a new declaration in 14111 // that scope. 14112 S = getTagInjectionScope(S, getLangOpts()); 14113 } else { 14114 return PrevTagDecl; 14115 } 14116 } 14117 14118 // Diagnose attempts to redefine a tag. 14119 if (TUK == TUK_Definition) { 14120 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14121 // If we're defining a specialization and the previous definition 14122 // is from an implicit instantiation, don't emit an error 14123 // here; we'll catch this in the general case below. 14124 bool IsExplicitSpecializationAfterInstantiation = false; 14125 if (isMemberSpecialization) { 14126 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14127 IsExplicitSpecializationAfterInstantiation = 14128 RD->getTemplateSpecializationKind() != 14129 TSK_ExplicitSpecialization; 14130 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14131 IsExplicitSpecializationAfterInstantiation = 14132 ED->getTemplateSpecializationKind() != 14133 TSK_ExplicitSpecialization; 14134 } 14135 14136 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14137 // not keep more that one definition around (merge them). However, 14138 // ensure the decl passes the structural compatibility check in 14139 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14140 NamedDecl *Hidden = nullptr; 14141 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14142 // There is a definition of this tag, but it is not visible. We 14143 // explicitly make use of C++'s one definition rule here, and 14144 // assume that this definition is identical to the hidden one 14145 // we already have. Make the existing definition visible and 14146 // use it in place of this one. 14147 if (!getLangOpts().CPlusPlus) { 14148 // Postpone making the old definition visible until after we 14149 // complete parsing the new one and do the structural 14150 // comparison. 14151 SkipBody->CheckSameAsPrevious = true; 14152 SkipBody->New = createTagFromNewDecl(); 14153 SkipBody->Previous = Hidden; 14154 } else { 14155 SkipBody->ShouldSkip = true; 14156 makeMergedDefinitionVisible(Hidden); 14157 } 14158 return Def; 14159 } else if (!IsExplicitSpecializationAfterInstantiation) { 14160 // A redeclaration in function prototype scope in C isn't 14161 // visible elsewhere, so merely issue a warning. 14162 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14163 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14164 else 14165 Diag(NameLoc, diag::err_redefinition) << Name; 14166 notePreviousDefinition(Def, 14167 NameLoc.isValid() ? NameLoc : KWLoc); 14168 // If this is a redefinition, recover by making this 14169 // struct be anonymous, which will make any later 14170 // references get the previous definition. 14171 Name = nullptr; 14172 Previous.clear(); 14173 Invalid = true; 14174 } 14175 } else { 14176 // If the type is currently being defined, complain 14177 // about a nested redefinition. 14178 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14179 if (TD->isBeingDefined()) { 14180 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14181 Diag(PrevTagDecl->getLocation(), 14182 diag::note_previous_definition); 14183 Name = nullptr; 14184 Previous.clear(); 14185 Invalid = true; 14186 } 14187 } 14188 14189 // Okay, this is definition of a previously declared or referenced 14190 // tag. We're going to create a new Decl for it. 14191 } 14192 14193 // Okay, we're going to make a redeclaration. If this is some kind 14194 // of reference, make sure we build the redeclaration in the same DC 14195 // as the original, and ignore the current access specifier. 14196 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14197 SearchDC = PrevTagDecl->getDeclContext(); 14198 AS = AS_none; 14199 } 14200 } 14201 // If we get here we have (another) forward declaration or we 14202 // have a definition. Just create a new decl. 14203 14204 } else { 14205 // If we get here, this is a definition of a new tag type in a nested 14206 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14207 // new decl/type. We set PrevDecl to NULL so that the entities 14208 // have distinct types. 14209 Previous.clear(); 14210 } 14211 // If we get here, we're going to create a new Decl. If PrevDecl 14212 // is non-NULL, it's a definition of the tag declared by 14213 // PrevDecl. If it's NULL, we have a new definition. 14214 14215 // Otherwise, PrevDecl is not a tag, but was found with tag 14216 // lookup. This is only actually possible in C++, where a few 14217 // things like templates still live in the tag namespace. 14218 } else { 14219 // Use a better diagnostic if an elaborated-type-specifier 14220 // found the wrong kind of type on the first 14221 // (non-redeclaration) lookup. 14222 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14223 !Previous.isForRedeclaration()) { 14224 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14225 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14226 << Kind; 14227 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14228 Invalid = true; 14229 14230 // Otherwise, only diagnose if the declaration is in scope. 14231 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14232 SS.isNotEmpty() || isMemberSpecialization)) { 14233 // do nothing 14234 14235 // Diagnose implicit declarations introduced by elaborated types. 14236 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14237 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14238 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14239 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14240 Invalid = true; 14241 14242 // Otherwise it's a declaration. Call out a particularly common 14243 // case here. 14244 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14245 unsigned Kind = 0; 14246 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14247 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14248 << Name << Kind << TND->getUnderlyingType(); 14249 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14250 Invalid = true; 14251 14252 // Otherwise, diagnose. 14253 } else { 14254 // The tag name clashes with something else in the target scope, 14255 // issue an error and recover by making this tag be anonymous. 14256 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14257 notePreviousDefinition(PrevDecl, NameLoc); 14258 Name = nullptr; 14259 Invalid = true; 14260 } 14261 14262 // The existing declaration isn't relevant to us; we're in a 14263 // new scope, so clear out the previous declaration. 14264 Previous.clear(); 14265 } 14266 } 14267 14268 CreateNewDecl: 14269 14270 TagDecl *PrevDecl = nullptr; 14271 if (Previous.isSingleResult()) 14272 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14273 14274 // If there is an identifier, use the location of the identifier as the 14275 // location of the decl, otherwise use the location of the struct/union 14276 // keyword. 14277 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14278 14279 // Otherwise, create a new declaration. If there is a previous 14280 // declaration of the same entity, the two will be linked via 14281 // PrevDecl. 14282 TagDecl *New; 14283 14284 bool IsForwardReference = false; 14285 if (Kind == TTK_Enum) { 14286 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14287 // enum X { A, B, C } D; D should chain to X. 14288 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14289 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14290 ScopedEnumUsesClassTag, IsFixed); 14291 14292 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14293 StdAlignValT = cast<EnumDecl>(New); 14294 14295 // If this is an undefined enum, warn. 14296 if (TUK != TUK_Definition && !Invalid) { 14297 TagDecl *Def; 14298 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 14299 cast<EnumDecl>(New)->isFixed()) { 14300 // C++0x: 7.2p2: opaque-enum-declaration. 14301 // Conflicts are diagnosed above. Do nothing. 14302 } 14303 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14304 Diag(Loc, diag::ext_forward_ref_enum_def) 14305 << New; 14306 Diag(Def->getLocation(), diag::note_previous_definition); 14307 } else { 14308 unsigned DiagID = diag::ext_forward_ref_enum; 14309 if (getLangOpts().MSVCCompat) 14310 DiagID = diag::ext_ms_forward_ref_enum; 14311 else if (getLangOpts().CPlusPlus) 14312 DiagID = diag::err_forward_ref_enum; 14313 Diag(Loc, DiagID); 14314 14315 // If this is a forward-declared reference to an enumeration, make a 14316 // note of it; we won't actually be introducing the declaration into 14317 // the declaration context. 14318 if (TUK == TUK_Reference) 14319 IsForwardReference = true; 14320 } 14321 } 14322 14323 if (EnumUnderlying) { 14324 EnumDecl *ED = cast<EnumDecl>(New); 14325 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14326 ED->setIntegerTypeSourceInfo(TI); 14327 else 14328 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14329 ED->setPromotionType(ED->getIntegerType()); 14330 assert(ED->isComplete() && "enum with type should be complete"); 14331 } 14332 } else { 14333 // struct/union/class 14334 14335 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14336 // struct X { int A; } D; D should chain to X. 14337 if (getLangOpts().CPlusPlus) { 14338 // FIXME: Look for a way to use RecordDecl for simple structs. 14339 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14340 cast_or_null<CXXRecordDecl>(PrevDecl)); 14341 14342 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14343 StdBadAlloc = cast<CXXRecordDecl>(New); 14344 } else 14345 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14346 cast_or_null<RecordDecl>(PrevDecl)); 14347 } 14348 14349 // C++11 [dcl.type]p3: 14350 // A type-specifier-seq shall not define a class or enumeration [...]. 14351 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14352 TUK == TUK_Definition) { 14353 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14354 << Context.getTagDeclType(New); 14355 Invalid = true; 14356 } 14357 14358 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14359 DC->getDeclKind() == Decl::Enum) { 14360 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14361 << Context.getTagDeclType(New); 14362 Invalid = true; 14363 } 14364 14365 // Maybe add qualifier info. 14366 if (SS.isNotEmpty()) { 14367 if (SS.isSet()) { 14368 // If this is either a declaration or a definition, check the 14369 // nested-name-specifier against the current context. 14370 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14371 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14372 isMemberSpecialization)) 14373 Invalid = true; 14374 14375 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14376 if (TemplateParameterLists.size() > 0) { 14377 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14378 } 14379 } 14380 else 14381 Invalid = true; 14382 } 14383 14384 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14385 // Add alignment attributes if necessary; these attributes are checked when 14386 // the ASTContext lays out the structure. 14387 // 14388 // It is important for implementing the correct semantics that this 14389 // happen here (in ActOnTag). The #pragma pack stack is 14390 // maintained as a result of parser callbacks which can occur at 14391 // many points during the parsing of a struct declaration (because 14392 // the #pragma tokens are effectively skipped over during the 14393 // parsing of the struct). 14394 if (TUK == TUK_Definition) { 14395 AddAlignmentAttributesForRecord(RD); 14396 AddMsStructLayoutForRecord(RD); 14397 } 14398 } 14399 14400 if (ModulePrivateLoc.isValid()) { 14401 if (isMemberSpecialization) 14402 Diag(New->getLocation(), diag::err_module_private_specialization) 14403 << 2 14404 << FixItHint::CreateRemoval(ModulePrivateLoc); 14405 // __module_private__ does not apply to local classes. However, we only 14406 // diagnose this as an error when the declaration specifiers are 14407 // freestanding. Here, we just ignore the __module_private__. 14408 else if (!SearchDC->isFunctionOrMethod()) 14409 New->setModulePrivate(); 14410 } 14411 14412 // If this is a specialization of a member class (of a class template), 14413 // check the specialization. 14414 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14415 Invalid = true; 14416 14417 // If we're declaring or defining a tag in function prototype scope in C, 14418 // note that this type can only be used within the function and add it to 14419 // the list of decls to inject into the function definition scope. 14420 if ((Name || Kind == TTK_Enum) && 14421 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14422 if (getLangOpts().CPlusPlus) { 14423 // C++ [dcl.fct]p6: 14424 // Types shall not be defined in return or parameter types. 14425 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14426 Diag(Loc, diag::err_type_defined_in_param_type) 14427 << Name; 14428 Invalid = true; 14429 } 14430 } else if (!PrevDecl) { 14431 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14432 } 14433 } 14434 14435 if (Invalid) 14436 New->setInvalidDecl(); 14437 14438 // Set the lexical context. If the tag has a C++ scope specifier, the 14439 // lexical context will be different from the semantic context. 14440 New->setLexicalDeclContext(CurContext); 14441 14442 // Mark this as a friend decl if applicable. 14443 // In Microsoft mode, a friend declaration also acts as a forward 14444 // declaration so we always pass true to setObjectOfFriendDecl to make 14445 // the tag name visible. 14446 if (TUK == TUK_Friend) 14447 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14448 14449 // Set the access specifier. 14450 if (!Invalid && SearchDC->isRecord()) 14451 SetMemberAccessSpecifier(New, PrevDecl, AS); 14452 14453 if (PrevDecl) 14454 CheckRedeclarationModuleOwnership(New, PrevDecl); 14455 14456 if (TUK == TUK_Definition) 14457 New->startDefinition(); 14458 14459 if (Attr) 14460 ProcessDeclAttributeList(S, New, Attr); 14461 AddPragmaAttributes(S, New); 14462 14463 // If this has an identifier, add it to the scope stack. 14464 if (TUK == TUK_Friend) { 14465 // We might be replacing an existing declaration in the lookup tables; 14466 // if so, borrow its access specifier. 14467 if (PrevDecl) 14468 New->setAccess(PrevDecl->getAccess()); 14469 14470 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14471 DC->makeDeclVisibleInContext(New); 14472 if (Name) // can be null along some error paths 14473 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14474 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14475 } else if (Name) { 14476 S = getNonFieldDeclScope(S); 14477 PushOnScopeChains(New, S, !IsForwardReference); 14478 if (IsForwardReference) 14479 SearchDC->makeDeclVisibleInContext(New); 14480 } else { 14481 CurContext->addDecl(New); 14482 } 14483 14484 // If this is the C FILE type, notify the AST context. 14485 if (IdentifierInfo *II = New->getIdentifier()) 14486 if (!New->isInvalidDecl() && 14487 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14488 II->isStr("FILE")) 14489 Context.setFILEDecl(New); 14490 14491 if (PrevDecl) 14492 mergeDeclAttributes(New, PrevDecl); 14493 14494 // If there's a #pragma GCC visibility in scope, set the visibility of this 14495 // record. 14496 AddPushedVisibilityAttribute(New); 14497 14498 if (isMemberSpecialization && !New->isInvalidDecl()) 14499 CompleteMemberSpecialization(New, Previous); 14500 14501 OwnedDecl = true; 14502 // In C++, don't return an invalid declaration. We can't recover well from 14503 // the cases where we make the type anonymous. 14504 if (Invalid && getLangOpts().CPlusPlus) { 14505 if (New->isBeingDefined()) 14506 if (auto RD = dyn_cast<RecordDecl>(New)) 14507 RD->completeDefinition(); 14508 return nullptr; 14509 } else { 14510 return New; 14511 } 14512 } 14513 14514 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14515 AdjustDeclIfTemplate(TagD); 14516 TagDecl *Tag = cast<TagDecl>(TagD); 14517 14518 // Enter the tag context. 14519 PushDeclContext(S, Tag); 14520 14521 ActOnDocumentableDecl(TagD); 14522 14523 // If there's a #pragma GCC visibility in scope, set the visibility of this 14524 // record. 14525 AddPushedVisibilityAttribute(Tag); 14526 } 14527 14528 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14529 SkipBodyInfo &SkipBody) { 14530 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14531 return false; 14532 14533 // Make the previous decl visible. 14534 makeMergedDefinitionVisible(SkipBody.Previous); 14535 return true; 14536 } 14537 14538 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14539 assert(isa<ObjCContainerDecl>(IDecl) && 14540 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14541 DeclContext *OCD = cast<DeclContext>(IDecl); 14542 assert(getContainingDC(OCD) == CurContext && 14543 "The next DeclContext should be lexically contained in the current one."); 14544 CurContext = OCD; 14545 return IDecl; 14546 } 14547 14548 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14549 SourceLocation FinalLoc, 14550 bool IsFinalSpelledSealed, 14551 SourceLocation LBraceLoc) { 14552 AdjustDeclIfTemplate(TagD); 14553 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14554 14555 FieldCollector->StartClass(); 14556 14557 if (!Record->getIdentifier()) 14558 return; 14559 14560 if (FinalLoc.isValid()) 14561 Record->addAttr(new (Context) 14562 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14563 14564 // C++ [class]p2: 14565 // [...] The class-name is also inserted into the scope of the 14566 // class itself; this is known as the injected-class-name. For 14567 // purposes of access checking, the injected-class-name is treated 14568 // as if it were a public member name. 14569 CXXRecordDecl *InjectedClassName 14570 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14571 Record->getLocStart(), Record->getLocation(), 14572 Record->getIdentifier(), 14573 /*PrevDecl=*/nullptr, 14574 /*DelayTypeCreation=*/true); 14575 Context.getTypeDeclType(InjectedClassName, Record); 14576 InjectedClassName->setImplicit(); 14577 InjectedClassName->setAccess(AS_public); 14578 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14579 InjectedClassName->setDescribedClassTemplate(Template); 14580 PushOnScopeChains(InjectedClassName, S); 14581 assert(InjectedClassName->isInjectedClassName() && 14582 "Broken injected-class-name"); 14583 } 14584 14585 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14586 SourceRange BraceRange) { 14587 AdjustDeclIfTemplate(TagD); 14588 TagDecl *Tag = cast<TagDecl>(TagD); 14589 Tag->setBraceRange(BraceRange); 14590 14591 // Make sure we "complete" the definition even it is invalid. 14592 if (Tag->isBeingDefined()) { 14593 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14594 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14595 RD->completeDefinition(); 14596 } 14597 14598 if (isa<CXXRecordDecl>(Tag)) { 14599 FieldCollector->FinishClass(); 14600 } 14601 14602 // Exit this scope of this tag's definition. 14603 PopDeclContext(); 14604 14605 if (getCurLexicalContext()->isObjCContainer() && 14606 Tag->getDeclContext()->isFileContext()) 14607 Tag->setTopLevelDeclInObjCContainer(); 14608 14609 // Notify the consumer that we've defined a tag. 14610 if (!Tag->isInvalidDecl()) 14611 Consumer.HandleTagDeclDefinition(Tag); 14612 } 14613 14614 void Sema::ActOnObjCContainerFinishDefinition() { 14615 // Exit this scope of this interface definition. 14616 PopDeclContext(); 14617 } 14618 14619 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14620 assert(DC == CurContext && "Mismatch of container contexts"); 14621 OriginalLexicalContext = DC; 14622 ActOnObjCContainerFinishDefinition(); 14623 } 14624 14625 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14626 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14627 OriginalLexicalContext = nullptr; 14628 } 14629 14630 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14631 AdjustDeclIfTemplate(TagD); 14632 TagDecl *Tag = cast<TagDecl>(TagD); 14633 Tag->setInvalidDecl(); 14634 14635 // Make sure we "complete" the definition even it is invalid. 14636 if (Tag->isBeingDefined()) { 14637 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14638 RD->completeDefinition(); 14639 } 14640 14641 // We're undoing ActOnTagStartDefinition here, not 14642 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14643 // the FieldCollector. 14644 14645 PopDeclContext(); 14646 } 14647 14648 // Note that FieldName may be null for anonymous bitfields. 14649 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14650 IdentifierInfo *FieldName, 14651 QualType FieldTy, bool IsMsStruct, 14652 Expr *BitWidth, bool *ZeroWidth) { 14653 // Default to true; that shouldn't confuse checks for emptiness 14654 if (ZeroWidth) 14655 *ZeroWidth = true; 14656 14657 // C99 6.7.2.1p4 - verify the field type. 14658 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14659 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14660 // Handle incomplete types with specific error. 14661 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14662 return ExprError(); 14663 if (FieldName) 14664 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14665 << FieldName << FieldTy << BitWidth->getSourceRange(); 14666 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14667 << FieldTy << BitWidth->getSourceRange(); 14668 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14669 UPPC_BitFieldWidth)) 14670 return ExprError(); 14671 14672 // If the bit-width is type- or value-dependent, don't try to check 14673 // it now. 14674 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14675 return BitWidth; 14676 14677 llvm::APSInt Value; 14678 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14679 if (ICE.isInvalid()) 14680 return ICE; 14681 BitWidth = ICE.get(); 14682 14683 if (Value != 0 && ZeroWidth) 14684 *ZeroWidth = false; 14685 14686 // Zero-width bitfield is ok for anonymous field. 14687 if (Value == 0 && FieldName) 14688 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14689 14690 if (Value.isSigned() && Value.isNegative()) { 14691 if (FieldName) 14692 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14693 << FieldName << Value.toString(10); 14694 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14695 << Value.toString(10); 14696 } 14697 14698 if (!FieldTy->isDependentType()) { 14699 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14700 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14701 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14702 14703 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14704 // ABI. 14705 bool CStdConstraintViolation = 14706 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14707 bool MSBitfieldViolation = 14708 Value.ugt(TypeStorageSize) && 14709 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14710 if (CStdConstraintViolation || MSBitfieldViolation) { 14711 unsigned DiagWidth = 14712 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14713 if (FieldName) 14714 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14715 << FieldName << (unsigned)Value.getZExtValue() 14716 << !CStdConstraintViolation << DiagWidth; 14717 14718 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14719 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14720 << DiagWidth; 14721 } 14722 14723 // Warn on types where the user might conceivably expect to get all 14724 // specified bits as value bits: that's all integral types other than 14725 // 'bool'. 14726 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14727 if (FieldName) 14728 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14729 << FieldName << (unsigned)Value.getZExtValue() 14730 << (unsigned)TypeWidth; 14731 else 14732 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14733 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14734 } 14735 } 14736 14737 return BitWidth; 14738 } 14739 14740 /// ActOnField - Each field of a C struct/union is passed into this in order 14741 /// to create a FieldDecl object for it. 14742 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14743 Declarator &D, Expr *BitfieldWidth) { 14744 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14745 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14746 /*InitStyle=*/ICIS_NoInit, AS_public); 14747 return Res; 14748 } 14749 14750 /// HandleField - Analyze a field of a C struct or a C++ data member. 14751 /// 14752 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14753 SourceLocation DeclStart, 14754 Declarator &D, Expr *BitWidth, 14755 InClassInitStyle InitStyle, 14756 AccessSpecifier AS) { 14757 if (D.isDecompositionDeclarator()) { 14758 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14759 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14760 << Decomp.getSourceRange(); 14761 return nullptr; 14762 } 14763 14764 IdentifierInfo *II = D.getIdentifier(); 14765 SourceLocation Loc = DeclStart; 14766 if (II) Loc = D.getIdentifierLoc(); 14767 14768 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14769 QualType T = TInfo->getType(); 14770 if (getLangOpts().CPlusPlus) { 14771 CheckExtraCXXDefaultArguments(D); 14772 14773 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14774 UPPC_DataMemberType)) { 14775 D.setInvalidType(); 14776 T = Context.IntTy; 14777 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14778 } 14779 } 14780 14781 // TR 18037 does not allow fields to be declared with address spaces. 14782 if (T.getQualifiers().hasAddressSpace() || 14783 T->isDependentAddressSpaceType() || 14784 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 14785 Diag(Loc, diag::err_field_with_address_space); 14786 D.setInvalidType(); 14787 } 14788 14789 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14790 // used as structure or union field: image, sampler, event or block types. 14791 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14792 T->isSamplerT() || T->isBlockPointerType())) { 14793 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14794 D.setInvalidType(); 14795 } 14796 14797 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14798 14799 if (D.getDeclSpec().isInlineSpecified()) 14800 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14801 << getLangOpts().CPlusPlus17; 14802 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14803 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14804 diag::err_invalid_thread) 14805 << DeclSpec::getSpecifierName(TSCS); 14806 14807 // Check to see if this name was declared as a member previously 14808 NamedDecl *PrevDecl = nullptr; 14809 LookupResult Previous(*this, II, Loc, LookupMemberName, 14810 ForVisibleRedeclaration); 14811 LookupName(Previous, S); 14812 switch (Previous.getResultKind()) { 14813 case LookupResult::Found: 14814 case LookupResult::FoundUnresolvedValue: 14815 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14816 break; 14817 14818 case LookupResult::FoundOverloaded: 14819 PrevDecl = Previous.getRepresentativeDecl(); 14820 break; 14821 14822 case LookupResult::NotFound: 14823 case LookupResult::NotFoundInCurrentInstantiation: 14824 case LookupResult::Ambiguous: 14825 break; 14826 } 14827 Previous.suppressDiagnostics(); 14828 14829 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14830 // Maybe we will complain about the shadowed template parameter. 14831 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14832 // Just pretend that we didn't see the previous declaration. 14833 PrevDecl = nullptr; 14834 } 14835 14836 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14837 PrevDecl = nullptr; 14838 14839 bool Mutable 14840 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14841 SourceLocation TSSL = D.getLocStart(); 14842 FieldDecl *NewFD 14843 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14844 TSSL, AS, PrevDecl, &D); 14845 14846 if (NewFD->isInvalidDecl()) 14847 Record->setInvalidDecl(); 14848 14849 if (D.getDeclSpec().isModulePrivateSpecified()) 14850 NewFD->setModulePrivate(); 14851 14852 if (NewFD->isInvalidDecl() && PrevDecl) { 14853 // Don't introduce NewFD into scope; there's already something 14854 // with the same name in the same scope. 14855 } else if (II) { 14856 PushOnScopeChains(NewFD, S); 14857 } else 14858 Record->addDecl(NewFD); 14859 14860 return NewFD; 14861 } 14862 14863 /// Build a new FieldDecl and check its well-formedness. 14864 /// 14865 /// This routine builds a new FieldDecl given the fields name, type, 14866 /// record, etc. \p PrevDecl should refer to any previous declaration 14867 /// with the same name and in the same scope as the field to be 14868 /// created. 14869 /// 14870 /// \returns a new FieldDecl. 14871 /// 14872 /// \todo The Declarator argument is a hack. It will be removed once 14873 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14874 TypeSourceInfo *TInfo, 14875 RecordDecl *Record, SourceLocation Loc, 14876 bool Mutable, Expr *BitWidth, 14877 InClassInitStyle InitStyle, 14878 SourceLocation TSSL, 14879 AccessSpecifier AS, NamedDecl *PrevDecl, 14880 Declarator *D) { 14881 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14882 bool InvalidDecl = false; 14883 if (D) InvalidDecl = D->isInvalidType(); 14884 14885 // If we receive a broken type, recover by assuming 'int' and 14886 // marking this declaration as invalid. 14887 if (T.isNull()) { 14888 InvalidDecl = true; 14889 T = Context.IntTy; 14890 } 14891 14892 QualType EltTy = Context.getBaseElementType(T); 14893 if (!EltTy->isDependentType()) { 14894 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14895 // Fields of incomplete type force their record to be invalid. 14896 Record->setInvalidDecl(); 14897 InvalidDecl = true; 14898 } else { 14899 NamedDecl *Def; 14900 EltTy->isIncompleteType(&Def); 14901 if (Def && Def->isInvalidDecl()) { 14902 Record->setInvalidDecl(); 14903 InvalidDecl = true; 14904 } 14905 } 14906 } 14907 14908 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14909 if (BitWidth && getLangOpts().OpenCL) { 14910 Diag(Loc, diag::err_opencl_bitfields); 14911 InvalidDecl = true; 14912 } 14913 14914 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 14915 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 14916 T.hasQualifiers()) { 14917 InvalidDecl = true; 14918 Diag(Loc, diag::err_anon_bitfield_qualifiers); 14919 } 14920 14921 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14922 // than a variably modified type. 14923 if (!InvalidDecl && T->isVariablyModifiedType()) { 14924 bool SizeIsNegative; 14925 llvm::APSInt Oversized; 14926 14927 TypeSourceInfo *FixedTInfo = 14928 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14929 SizeIsNegative, 14930 Oversized); 14931 if (FixedTInfo) { 14932 Diag(Loc, diag::warn_illegal_constant_array_size); 14933 TInfo = FixedTInfo; 14934 T = FixedTInfo->getType(); 14935 } else { 14936 if (SizeIsNegative) 14937 Diag(Loc, diag::err_typecheck_negative_array_size); 14938 else if (Oversized.getBoolValue()) 14939 Diag(Loc, diag::err_array_too_large) 14940 << Oversized.toString(10); 14941 else 14942 Diag(Loc, diag::err_typecheck_field_variable_size); 14943 InvalidDecl = true; 14944 } 14945 } 14946 14947 // Fields can not have abstract class types 14948 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14949 diag::err_abstract_type_in_decl, 14950 AbstractFieldType)) 14951 InvalidDecl = true; 14952 14953 bool ZeroWidth = false; 14954 if (InvalidDecl) 14955 BitWidth = nullptr; 14956 // If this is declared as a bit-field, check the bit-field. 14957 if (BitWidth) { 14958 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14959 &ZeroWidth).get(); 14960 if (!BitWidth) { 14961 InvalidDecl = true; 14962 BitWidth = nullptr; 14963 ZeroWidth = false; 14964 } 14965 } 14966 14967 // Check that 'mutable' is consistent with the type of the declaration. 14968 if (!InvalidDecl && Mutable) { 14969 unsigned DiagID = 0; 14970 if (T->isReferenceType()) 14971 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14972 : diag::err_mutable_reference; 14973 else if (T.isConstQualified()) 14974 DiagID = diag::err_mutable_const; 14975 14976 if (DiagID) { 14977 SourceLocation ErrLoc = Loc; 14978 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14979 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14980 Diag(ErrLoc, DiagID); 14981 if (DiagID != diag::ext_mutable_reference) { 14982 Mutable = false; 14983 InvalidDecl = true; 14984 } 14985 } 14986 } 14987 14988 // C++11 [class.union]p8 (DR1460): 14989 // At most one variant member of a union may have a 14990 // brace-or-equal-initializer. 14991 if (InitStyle != ICIS_NoInit) 14992 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14993 14994 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14995 BitWidth, Mutable, InitStyle); 14996 if (InvalidDecl) 14997 NewFD->setInvalidDecl(); 14998 14999 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 15000 Diag(Loc, diag::err_duplicate_member) << II; 15001 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15002 NewFD->setInvalidDecl(); 15003 } 15004 15005 if (!InvalidDecl && getLangOpts().CPlusPlus) { 15006 if (Record->isUnion()) { 15007 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15008 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15009 if (RDecl->getDefinition()) { 15010 // C++ [class.union]p1: An object of a class with a non-trivial 15011 // constructor, a non-trivial copy constructor, a non-trivial 15012 // destructor, or a non-trivial copy assignment operator 15013 // cannot be a member of a union, nor can an array of such 15014 // objects. 15015 if (CheckNontrivialField(NewFD)) 15016 NewFD->setInvalidDecl(); 15017 } 15018 } 15019 15020 // C++ [class.union]p1: If a union contains a member of reference type, 15021 // the program is ill-formed, except when compiling with MSVC extensions 15022 // enabled. 15023 if (EltTy->isReferenceType()) { 15024 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15025 diag::ext_union_member_of_reference_type : 15026 diag::err_union_member_of_reference_type) 15027 << NewFD->getDeclName() << EltTy; 15028 if (!getLangOpts().MicrosoftExt) 15029 NewFD->setInvalidDecl(); 15030 } 15031 } 15032 } 15033 15034 // FIXME: We need to pass in the attributes given an AST 15035 // representation, not a parser representation. 15036 if (D) { 15037 // FIXME: The current scope is almost... but not entirely... correct here. 15038 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15039 15040 if (NewFD->hasAttrs()) 15041 CheckAlignasUnderalignment(NewFD); 15042 } 15043 15044 // In auto-retain/release, infer strong retension for fields of 15045 // retainable type. 15046 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15047 NewFD->setInvalidDecl(); 15048 15049 if (T.isObjCGCWeak()) 15050 Diag(Loc, diag::warn_attribute_weak_on_field); 15051 15052 NewFD->setAccess(AS); 15053 return NewFD; 15054 } 15055 15056 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15057 assert(FD); 15058 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15059 15060 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15061 return false; 15062 15063 QualType EltTy = Context.getBaseElementType(FD->getType()); 15064 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15065 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15066 if (RDecl->getDefinition()) { 15067 // We check for copy constructors before constructors 15068 // because otherwise we'll never get complaints about 15069 // copy constructors. 15070 15071 CXXSpecialMember member = CXXInvalid; 15072 // We're required to check for any non-trivial constructors. Since the 15073 // implicit default constructor is suppressed if there are any 15074 // user-declared constructors, we just need to check that there is a 15075 // trivial default constructor and a trivial copy constructor. (We don't 15076 // worry about move constructors here, since this is a C++98 check.) 15077 if (RDecl->hasNonTrivialCopyConstructor()) 15078 member = CXXCopyConstructor; 15079 else if (!RDecl->hasTrivialDefaultConstructor()) 15080 member = CXXDefaultConstructor; 15081 else if (RDecl->hasNonTrivialCopyAssignment()) 15082 member = CXXCopyAssignment; 15083 else if (RDecl->hasNonTrivialDestructor()) 15084 member = CXXDestructor; 15085 15086 if (member != CXXInvalid) { 15087 if (!getLangOpts().CPlusPlus11 && 15088 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15089 // Objective-C++ ARC: it is an error to have a non-trivial field of 15090 // a union. However, system headers in Objective-C programs 15091 // occasionally have Objective-C lifetime objects within unions, 15092 // and rather than cause the program to fail, we make those 15093 // members unavailable. 15094 SourceLocation Loc = FD->getLocation(); 15095 if (getSourceManager().isInSystemHeader(Loc)) { 15096 if (!FD->hasAttr<UnavailableAttr>()) 15097 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15098 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15099 return false; 15100 } 15101 } 15102 15103 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15104 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15105 diag::err_illegal_union_or_anon_struct_member) 15106 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15107 DiagnoseNontrivial(RDecl, member); 15108 return !getLangOpts().CPlusPlus11; 15109 } 15110 } 15111 } 15112 15113 return false; 15114 } 15115 15116 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15117 /// AST enum value. 15118 static ObjCIvarDecl::AccessControl 15119 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15120 switch (ivarVisibility) { 15121 default: llvm_unreachable("Unknown visitibility kind"); 15122 case tok::objc_private: return ObjCIvarDecl::Private; 15123 case tok::objc_public: return ObjCIvarDecl::Public; 15124 case tok::objc_protected: return ObjCIvarDecl::Protected; 15125 case tok::objc_package: return ObjCIvarDecl::Package; 15126 } 15127 } 15128 15129 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15130 /// in order to create an IvarDecl object for it. 15131 Decl *Sema::ActOnIvar(Scope *S, 15132 SourceLocation DeclStart, 15133 Declarator &D, Expr *BitfieldWidth, 15134 tok::ObjCKeywordKind Visibility) { 15135 15136 IdentifierInfo *II = D.getIdentifier(); 15137 Expr *BitWidth = (Expr*)BitfieldWidth; 15138 SourceLocation Loc = DeclStart; 15139 if (II) Loc = D.getIdentifierLoc(); 15140 15141 // FIXME: Unnamed fields can be handled in various different ways, for 15142 // example, unnamed unions inject all members into the struct namespace! 15143 15144 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15145 QualType T = TInfo->getType(); 15146 15147 if (BitWidth) { 15148 // 6.7.2.1p3, 6.7.2.1p4 15149 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15150 if (!BitWidth) 15151 D.setInvalidType(); 15152 } else { 15153 // Not a bitfield. 15154 15155 // validate II. 15156 15157 } 15158 if (T->isReferenceType()) { 15159 Diag(Loc, diag::err_ivar_reference_type); 15160 D.setInvalidType(); 15161 } 15162 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15163 // than a variably modified type. 15164 else if (T->isVariablyModifiedType()) { 15165 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15166 D.setInvalidType(); 15167 } 15168 15169 // Get the visibility (access control) for this ivar. 15170 ObjCIvarDecl::AccessControl ac = 15171 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15172 : ObjCIvarDecl::None; 15173 // Must set ivar's DeclContext to its enclosing interface. 15174 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15175 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15176 return nullptr; 15177 ObjCContainerDecl *EnclosingContext; 15178 if (ObjCImplementationDecl *IMPDecl = 15179 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15180 if (LangOpts.ObjCRuntime.isFragile()) { 15181 // Case of ivar declared in an implementation. Context is that of its class. 15182 EnclosingContext = IMPDecl->getClassInterface(); 15183 assert(EnclosingContext && "Implementation has no class interface!"); 15184 } 15185 else 15186 EnclosingContext = EnclosingDecl; 15187 } else { 15188 if (ObjCCategoryDecl *CDecl = 15189 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15190 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15191 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15192 return nullptr; 15193 } 15194 } 15195 EnclosingContext = EnclosingDecl; 15196 } 15197 15198 // Construct the decl. 15199 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15200 DeclStart, Loc, II, T, 15201 TInfo, ac, (Expr *)BitfieldWidth); 15202 15203 if (II) { 15204 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15205 ForVisibleRedeclaration); 15206 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15207 && !isa<TagDecl>(PrevDecl)) { 15208 Diag(Loc, diag::err_duplicate_member) << II; 15209 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15210 NewID->setInvalidDecl(); 15211 } 15212 } 15213 15214 // Process attributes attached to the ivar. 15215 ProcessDeclAttributes(S, NewID, D); 15216 15217 if (D.isInvalidType()) 15218 NewID->setInvalidDecl(); 15219 15220 // In ARC, infer 'retaining' for ivars of retainable type. 15221 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15222 NewID->setInvalidDecl(); 15223 15224 if (D.getDeclSpec().isModulePrivateSpecified()) 15225 NewID->setModulePrivate(); 15226 15227 if (II) { 15228 // FIXME: When interfaces are DeclContexts, we'll need to add 15229 // these to the interface. 15230 S->AddDecl(NewID); 15231 IdResolver.AddDecl(NewID); 15232 } 15233 15234 if (LangOpts.ObjCRuntime.isNonFragile() && 15235 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15236 Diag(Loc, diag::warn_ivars_in_interface); 15237 15238 return NewID; 15239 } 15240 15241 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15242 /// class and class extensions. For every class \@interface and class 15243 /// extension \@interface, if the last ivar is a bitfield of any type, 15244 /// then add an implicit `char :0` ivar to the end of that interface. 15245 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15246 SmallVectorImpl<Decl *> &AllIvarDecls) { 15247 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15248 return; 15249 15250 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15251 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15252 15253 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15254 return; 15255 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15256 if (!ID) { 15257 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15258 if (!CD->IsClassExtension()) 15259 return; 15260 } 15261 // No need to add this to end of @implementation. 15262 else 15263 return; 15264 } 15265 // All conditions are met. Add a new bitfield to the tail end of ivars. 15266 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15267 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15268 15269 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15270 DeclLoc, DeclLoc, nullptr, 15271 Context.CharTy, 15272 Context.getTrivialTypeSourceInfo(Context.CharTy, 15273 DeclLoc), 15274 ObjCIvarDecl::Private, BW, 15275 true); 15276 AllIvarDecls.push_back(Ivar); 15277 } 15278 15279 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15280 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15281 SourceLocation RBrac, AttributeList *Attr) { 15282 assert(EnclosingDecl && "missing record or interface decl"); 15283 15284 // If this is an Objective-C @implementation or category and we have 15285 // new fields here we should reset the layout of the interface since 15286 // it will now change. 15287 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15288 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15289 switch (DC->getKind()) { 15290 default: break; 15291 case Decl::ObjCCategory: 15292 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15293 break; 15294 case Decl::ObjCImplementation: 15295 Context. 15296 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15297 break; 15298 } 15299 } 15300 15301 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15302 15303 // Start counting up the number of named members; make sure to include 15304 // members of anonymous structs and unions in the total. 15305 unsigned NumNamedMembers = 0; 15306 if (Record) { 15307 for (const auto *I : Record->decls()) { 15308 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15309 if (IFD->getDeclName()) 15310 ++NumNamedMembers; 15311 } 15312 } 15313 15314 // Verify that all the fields are okay. 15315 SmallVector<FieldDecl*, 32> RecFields; 15316 15317 bool ObjCFieldLifetimeErrReported = false; 15318 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15319 i != end; ++i) { 15320 FieldDecl *FD = cast<FieldDecl>(*i); 15321 15322 // Get the type for the field. 15323 const Type *FDTy = FD->getType().getTypePtr(); 15324 15325 if (!FD->isAnonymousStructOrUnion()) { 15326 // Remember all fields written by the user. 15327 RecFields.push_back(FD); 15328 } 15329 15330 // If the field is already invalid for some reason, don't emit more 15331 // diagnostics about it. 15332 if (FD->isInvalidDecl()) { 15333 EnclosingDecl->setInvalidDecl(); 15334 continue; 15335 } 15336 15337 // C99 6.7.2.1p2: 15338 // A structure or union shall not contain a member with 15339 // incomplete or function type (hence, a structure shall not 15340 // contain an instance of itself, but may contain a pointer to 15341 // an instance of itself), except that the last member of a 15342 // structure with more than one named member may have incomplete 15343 // array type; such a structure (and any union containing, 15344 // possibly recursively, a member that is such a structure) 15345 // shall not be a member of a structure or an element of an 15346 // array. 15347 bool IsLastField = (i + 1 == Fields.end()); 15348 if (FDTy->isFunctionType()) { 15349 // Field declared as a function. 15350 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15351 << FD->getDeclName(); 15352 FD->setInvalidDecl(); 15353 EnclosingDecl->setInvalidDecl(); 15354 continue; 15355 } else if (FDTy->isIncompleteArrayType() && 15356 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15357 if (Record) { 15358 // Flexible array member. 15359 // Microsoft and g++ is more permissive regarding flexible array. 15360 // It will accept flexible array in union and also 15361 // as the sole element of a struct/class. 15362 unsigned DiagID = 0; 15363 if (!Record->isUnion() && !IsLastField) { 15364 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15365 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15366 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15367 FD->setInvalidDecl(); 15368 EnclosingDecl->setInvalidDecl(); 15369 continue; 15370 } else if (Record->isUnion()) 15371 DiagID = getLangOpts().MicrosoftExt 15372 ? diag::ext_flexible_array_union_ms 15373 : getLangOpts().CPlusPlus 15374 ? diag::ext_flexible_array_union_gnu 15375 : diag::err_flexible_array_union; 15376 else if (NumNamedMembers < 1) 15377 DiagID = getLangOpts().MicrosoftExt 15378 ? diag::ext_flexible_array_empty_aggregate_ms 15379 : getLangOpts().CPlusPlus 15380 ? diag::ext_flexible_array_empty_aggregate_gnu 15381 : diag::err_flexible_array_empty_aggregate; 15382 15383 if (DiagID) 15384 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15385 << Record->getTagKind(); 15386 // While the layout of types that contain virtual bases is not specified 15387 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15388 // virtual bases after the derived members. This would make a flexible 15389 // array member declared at the end of an object not adjacent to the end 15390 // of the type. 15391 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 15392 if (RD->getNumVBases() != 0) 15393 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15394 << FD->getDeclName() << Record->getTagKind(); 15395 if (!getLangOpts().C99) 15396 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15397 << FD->getDeclName() << Record->getTagKind(); 15398 15399 // If the element type has a non-trivial destructor, we would not 15400 // implicitly destroy the elements, so disallow it for now. 15401 // 15402 // FIXME: GCC allows this. We should probably either implicitly delete 15403 // the destructor of the containing class, or just allow this. 15404 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15405 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15406 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15407 << FD->getDeclName() << FD->getType(); 15408 FD->setInvalidDecl(); 15409 EnclosingDecl->setInvalidDecl(); 15410 continue; 15411 } 15412 // Okay, we have a legal flexible array member at the end of the struct. 15413 Record->setHasFlexibleArrayMember(true); 15414 } else { 15415 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15416 // unless they are followed by another ivar. That check is done 15417 // elsewhere, after synthesized ivars are known. 15418 } 15419 } else if (!FDTy->isDependentType() && 15420 RequireCompleteType(FD->getLocation(), FD->getType(), 15421 diag::err_field_incomplete)) { 15422 // Incomplete type 15423 FD->setInvalidDecl(); 15424 EnclosingDecl->setInvalidDecl(); 15425 continue; 15426 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15427 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15428 // A type which contains a flexible array member is considered to be a 15429 // flexible array member. 15430 Record->setHasFlexibleArrayMember(true); 15431 if (!Record->isUnion()) { 15432 // If this is a struct/class and this is not the last element, reject 15433 // it. Note that GCC supports variable sized arrays in the middle of 15434 // structures. 15435 if (!IsLastField) 15436 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15437 << FD->getDeclName() << FD->getType(); 15438 else { 15439 // We support flexible arrays at the end of structs in 15440 // other structs as an extension. 15441 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15442 << FD->getDeclName(); 15443 } 15444 } 15445 } 15446 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15447 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15448 diag::err_abstract_type_in_decl, 15449 AbstractIvarType)) { 15450 // Ivars can not have abstract class types 15451 FD->setInvalidDecl(); 15452 } 15453 if (Record && FDTTy->getDecl()->hasObjectMember()) 15454 Record->setHasObjectMember(true); 15455 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15456 Record->setHasVolatileMember(true); 15457 } else if (FDTy->isObjCObjectType()) { 15458 /// A field cannot be an Objective-c object 15459 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15460 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15461 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15462 FD->setType(T); 15463 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15464 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { 15465 // It's an error in ARC or Weak if a field has lifetime. 15466 // We don't want to report this in a system header, though, 15467 // so we just make the field unavailable. 15468 // FIXME: that's really not sufficient; we need to make the type 15469 // itself invalid to, say, initialize or copy. 15470 QualType T = FD->getType(); 15471 if (T.hasNonTrivialObjCLifetime()) { 15472 SourceLocation loc = FD->getLocation(); 15473 if (getSourceManager().isInSystemHeader(loc)) { 15474 if (!FD->hasAttr<UnavailableAttr>()) { 15475 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15476 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15477 } 15478 } else { 15479 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15480 << T->isBlockPointerType() << Record->getTagKind(); 15481 } 15482 ObjCFieldLifetimeErrReported = true; 15483 } 15484 } else if (getLangOpts().ObjC1 && 15485 getLangOpts().getGC() != LangOptions::NonGC && 15486 Record && !Record->hasObjectMember()) { 15487 if (FD->getType()->isObjCObjectPointerType() || 15488 FD->getType().isObjCGCStrong()) 15489 Record->setHasObjectMember(true); 15490 else if (Context.getAsArrayType(FD->getType())) { 15491 QualType BaseType = Context.getBaseElementType(FD->getType()); 15492 if (BaseType->isRecordType() && 15493 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15494 Record->setHasObjectMember(true); 15495 else if (BaseType->isObjCObjectPointerType() || 15496 BaseType.isObjCGCStrong()) 15497 Record->setHasObjectMember(true); 15498 } 15499 } 15500 15501 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 15502 QualType FT = FD->getType(); 15503 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 15504 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 15505 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 15506 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 15507 Record->setNonTrivialToPrimitiveCopy(true); 15508 if (FT.isDestructedType()) { 15509 Record->setNonTrivialToPrimitiveDestroy(true); 15510 Record->setParamDestroyedInCallee(true); 15511 } 15512 15513 if (const auto *RT = FT->getAs<RecordType>()) { 15514 if (RT->getDecl()->getArgPassingRestrictions() == 15515 RecordDecl::APK_CanNeverPassInRegs) 15516 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15517 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 15518 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15519 } 15520 15521 if (Record && FD->getType().isVolatileQualified()) 15522 Record->setHasVolatileMember(true); 15523 // Keep track of the number of named members. 15524 if (FD->getIdentifier()) 15525 ++NumNamedMembers; 15526 } 15527 15528 // Okay, we successfully defined 'Record'. 15529 if (Record) { 15530 bool Completed = false; 15531 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15532 if (!CXXRecord->isInvalidDecl()) { 15533 // Set access bits correctly on the directly-declared conversions. 15534 for (CXXRecordDecl::conversion_iterator 15535 I = CXXRecord->conversion_begin(), 15536 E = CXXRecord->conversion_end(); I != E; ++I) 15537 I.setAccess((*I)->getAccess()); 15538 } 15539 15540 if (!CXXRecord->isDependentType()) { 15541 if (CXXRecord->hasUserDeclaredDestructor()) { 15542 // Adjust user-defined destructor exception spec. 15543 if (getLangOpts().CPlusPlus11) 15544 AdjustDestructorExceptionSpec(CXXRecord, 15545 CXXRecord->getDestructor()); 15546 } 15547 15548 // Add any implicitly-declared members to this class. 15549 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15550 15551 if (!CXXRecord->isInvalidDecl()) { 15552 // If we have virtual base classes, we may end up finding multiple 15553 // final overriders for a given virtual function. Check for this 15554 // problem now. 15555 if (CXXRecord->getNumVBases()) { 15556 CXXFinalOverriderMap FinalOverriders; 15557 CXXRecord->getFinalOverriders(FinalOverriders); 15558 15559 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15560 MEnd = FinalOverriders.end(); 15561 M != MEnd; ++M) { 15562 for (OverridingMethods::iterator SO = M->second.begin(), 15563 SOEnd = M->second.end(); 15564 SO != SOEnd; ++SO) { 15565 assert(SO->second.size() > 0 && 15566 "Virtual function without overriding functions?"); 15567 if (SO->second.size() == 1) 15568 continue; 15569 15570 // C++ [class.virtual]p2: 15571 // In a derived class, if a virtual member function of a base 15572 // class subobject has more than one final overrider the 15573 // program is ill-formed. 15574 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15575 << (const NamedDecl *)M->first << Record; 15576 Diag(M->first->getLocation(), 15577 diag::note_overridden_virtual_function); 15578 for (OverridingMethods::overriding_iterator 15579 OM = SO->second.begin(), 15580 OMEnd = SO->second.end(); 15581 OM != OMEnd; ++OM) 15582 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15583 << (const NamedDecl *)M->first << OM->Method->getParent(); 15584 15585 Record->setInvalidDecl(); 15586 } 15587 } 15588 CXXRecord->completeDefinition(&FinalOverriders); 15589 Completed = true; 15590 } 15591 } 15592 } 15593 } 15594 15595 if (!Completed) 15596 Record->completeDefinition(); 15597 15598 // Handle attributes before checking the layout. 15599 if (Attr) 15600 ProcessDeclAttributeList(S, Record, Attr); 15601 15602 // We may have deferred checking for a deleted destructor. Check now. 15603 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15604 auto *Dtor = CXXRecord->getDestructor(); 15605 if (Dtor && Dtor->isImplicit() && 15606 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 15607 CXXRecord->setImplicitDestructorIsDeleted(); 15608 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15609 } 15610 } 15611 15612 if (Record->hasAttrs()) { 15613 CheckAlignasUnderalignment(Record); 15614 15615 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15616 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15617 IA->getRange(), IA->getBestCase(), 15618 IA->getSemanticSpelling()); 15619 } 15620 15621 // Check if the structure/union declaration is a type that can have zero 15622 // size in C. For C this is a language extension, for C++ it may cause 15623 // compatibility problems. 15624 bool CheckForZeroSize; 15625 if (!getLangOpts().CPlusPlus) { 15626 CheckForZeroSize = true; 15627 } else { 15628 // For C++ filter out types that cannot be referenced in C code. 15629 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15630 CheckForZeroSize = 15631 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15632 !CXXRecord->isDependentType() && 15633 CXXRecord->isCLike(); 15634 } 15635 if (CheckForZeroSize) { 15636 bool ZeroSize = true; 15637 bool IsEmpty = true; 15638 unsigned NonBitFields = 0; 15639 for (RecordDecl::field_iterator I = Record->field_begin(), 15640 E = Record->field_end(); 15641 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15642 IsEmpty = false; 15643 if (I->isUnnamedBitfield()) { 15644 if (!I->isZeroLengthBitField(Context)) 15645 ZeroSize = false; 15646 } else { 15647 ++NonBitFields; 15648 QualType FieldType = I->getType(); 15649 if (FieldType->isIncompleteType() || 15650 !Context.getTypeSizeInChars(FieldType).isZero()) 15651 ZeroSize = false; 15652 } 15653 } 15654 15655 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15656 // allowed in C++, but warn if its declaration is inside 15657 // extern "C" block. 15658 if (ZeroSize) { 15659 Diag(RecLoc, getLangOpts().CPlusPlus ? 15660 diag::warn_zero_size_struct_union_in_extern_c : 15661 diag::warn_zero_size_struct_union_compat) 15662 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15663 } 15664 15665 // Structs without named members are extension in C (C99 6.7.2.1p7), 15666 // but are accepted by GCC. 15667 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15668 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15669 diag::ext_no_named_members_in_struct_union) 15670 << Record->isUnion(); 15671 } 15672 } 15673 } else { 15674 ObjCIvarDecl **ClsFields = 15675 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15676 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15677 ID->setEndOfDefinitionLoc(RBrac); 15678 // Add ivar's to class's DeclContext. 15679 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15680 ClsFields[i]->setLexicalDeclContext(ID); 15681 ID->addDecl(ClsFields[i]); 15682 } 15683 // Must enforce the rule that ivars in the base classes may not be 15684 // duplicates. 15685 if (ID->getSuperClass()) 15686 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15687 } else if (ObjCImplementationDecl *IMPDecl = 15688 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15689 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15690 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15691 // Ivar declared in @implementation never belongs to the implementation. 15692 // Only it is in implementation's lexical context. 15693 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15694 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15695 IMPDecl->setIvarLBraceLoc(LBrac); 15696 IMPDecl->setIvarRBraceLoc(RBrac); 15697 } else if (ObjCCategoryDecl *CDecl = 15698 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15699 // case of ivars in class extension; all other cases have been 15700 // reported as errors elsewhere. 15701 // FIXME. Class extension does not have a LocEnd field. 15702 // CDecl->setLocEnd(RBrac); 15703 // Add ivar's to class extension's DeclContext. 15704 // Diagnose redeclaration of private ivars. 15705 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15706 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15707 if (IDecl) { 15708 if (const ObjCIvarDecl *ClsIvar = 15709 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15710 Diag(ClsFields[i]->getLocation(), 15711 diag::err_duplicate_ivar_declaration); 15712 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15713 continue; 15714 } 15715 for (const auto *Ext : IDecl->known_extensions()) { 15716 if (const ObjCIvarDecl *ClsExtIvar 15717 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15718 Diag(ClsFields[i]->getLocation(), 15719 diag::err_duplicate_ivar_declaration); 15720 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15721 continue; 15722 } 15723 } 15724 } 15725 ClsFields[i]->setLexicalDeclContext(CDecl); 15726 CDecl->addDecl(ClsFields[i]); 15727 } 15728 CDecl->setIvarLBraceLoc(LBrac); 15729 CDecl->setIvarRBraceLoc(RBrac); 15730 } 15731 } 15732 } 15733 15734 /// Determine whether the given integral value is representable within 15735 /// the given type T. 15736 static bool isRepresentableIntegerValue(ASTContext &Context, 15737 llvm::APSInt &Value, 15738 QualType T) { 15739 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 15740 "Integral type required!"); 15741 unsigned BitWidth = Context.getIntWidth(T); 15742 15743 if (Value.isUnsigned() || Value.isNonNegative()) { 15744 if (T->isSignedIntegerOrEnumerationType()) 15745 --BitWidth; 15746 return Value.getActiveBits() <= BitWidth; 15747 } 15748 return Value.getMinSignedBits() <= BitWidth; 15749 } 15750 15751 // Given an integral type, return the next larger integral type 15752 // (or a NULL type of no such type exists). 15753 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15754 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15755 // enum checking below. 15756 assert((T->isIntegralType(Context) || 15757 T->isEnumeralType()) && "Integral type required!"); 15758 const unsigned NumTypes = 4; 15759 QualType SignedIntegralTypes[NumTypes] = { 15760 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15761 }; 15762 QualType UnsignedIntegralTypes[NumTypes] = { 15763 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15764 Context.UnsignedLongLongTy 15765 }; 15766 15767 unsigned BitWidth = Context.getTypeSize(T); 15768 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15769 : UnsignedIntegralTypes; 15770 for (unsigned I = 0; I != NumTypes; ++I) 15771 if (Context.getTypeSize(Types[I]) > BitWidth) 15772 return Types[I]; 15773 15774 return QualType(); 15775 } 15776 15777 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15778 EnumConstantDecl *LastEnumConst, 15779 SourceLocation IdLoc, 15780 IdentifierInfo *Id, 15781 Expr *Val) { 15782 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15783 llvm::APSInt EnumVal(IntWidth); 15784 QualType EltTy; 15785 15786 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15787 Val = nullptr; 15788 15789 if (Val) 15790 Val = DefaultLvalueConversion(Val).get(); 15791 15792 if (Val) { 15793 if (Enum->isDependentType() || Val->isTypeDependent()) 15794 EltTy = Context.DependentTy; 15795 else { 15796 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15797 !getLangOpts().MSVCCompat) { 15798 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15799 // constant-expression in the enumerator-definition shall be a converted 15800 // constant expression of the underlying type. 15801 EltTy = Enum->getIntegerType(); 15802 ExprResult Converted = 15803 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15804 CCEK_Enumerator); 15805 if (Converted.isInvalid()) 15806 Val = nullptr; 15807 else 15808 Val = Converted.get(); 15809 } else if (!Val->isValueDependent() && 15810 !(Val = VerifyIntegerConstantExpression(Val, 15811 &EnumVal).get())) { 15812 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15813 } else { 15814 if (Enum->isComplete()) { 15815 EltTy = Enum->getIntegerType(); 15816 15817 // In Obj-C and Microsoft mode, require the enumeration value to be 15818 // representable in the underlying type of the enumeration. In C++11, 15819 // we perform a non-narrowing conversion as part of converted constant 15820 // expression checking. 15821 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15822 if (getLangOpts().MSVCCompat) { 15823 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15824 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15825 } else 15826 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15827 } else 15828 Val = ImpCastExprToType(Val, EltTy, 15829 EltTy->isBooleanType() ? 15830 CK_IntegralToBoolean : CK_IntegralCast) 15831 .get(); 15832 } else if (getLangOpts().CPlusPlus) { 15833 // C++11 [dcl.enum]p5: 15834 // If the underlying type is not fixed, the type of each enumerator 15835 // is the type of its initializing value: 15836 // - If an initializer is specified for an enumerator, the 15837 // initializing value has the same type as the expression. 15838 EltTy = Val->getType(); 15839 } else { 15840 // C99 6.7.2.2p2: 15841 // The expression that defines the value of an enumeration constant 15842 // shall be an integer constant expression that has a value 15843 // representable as an int. 15844 15845 // Complain if the value is not representable in an int. 15846 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15847 Diag(IdLoc, diag::ext_enum_value_not_int) 15848 << EnumVal.toString(10) << Val->getSourceRange() 15849 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15850 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15851 // Force the type of the expression to 'int'. 15852 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15853 } 15854 EltTy = Val->getType(); 15855 } 15856 } 15857 } 15858 } 15859 15860 if (!Val) { 15861 if (Enum->isDependentType()) 15862 EltTy = Context.DependentTy; 15863 else if (!LastEnumConst) { 15864 // C++0x [dcl.enum]p5: 15865 // If the underlying type is not fixed, the type of each enumerator 15866 // is the type of its initializing value: 15867 // - If no initializer is specified for the first enumerator, the 15868 // initializing value has an unspecified integral type. 15869 // 15870 // GCC uses 'int' for its unspecified integral type, as does 15871 // C99 6.7.2.2p3. 15872 if (Enum->isFixed()) { 15873 EltTy = Enum->getIntegerType(); 15874 } 15875 else { 15876 EltTy = Context.IntTy; 15877 } 15878 } else { 15879 // Assign the last value + 1. 15880 EnumVal = LastEnumConst->getInitVal(); 15881 ++EnumVal; 15882 EltTy = LastEnumConst->getType(); 15883 15884 // Check for overflow on increment. 15885 if (EnumVal < LastEnumConst->getInitVal()) { 15886 // C++0x [dcl.enum]p5: 15887 // If the underlying type is not fixed, the type of each enumerator 15888 // is the type of its initializing value: 15889 // 15890 // - Otherwise the type of the initializing value is the same as 15891 // the type of the initializing value of the preceding enumerator 15892 // unless the incremented value is not representable in that type, 15893 // in which case the type is an unspecified integral type 15894 // sufficient to contain the incremented value. If no such type 15895 // exists, the program is ill-formed. 15896 QualType T = getNextLargerIntegralType(Context, EltTy); 15897 if (T.isNull() || Enum->isFixed()) { 15898 // There is no integral type larger enough to represent this 15899 // value. Complain, then allow the value to wrap around. 15900 EnumVal = LastEnumConst->getInitVal(); 15901 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15902 ++EnumVal; 15903 if (Enum->isFixed()) 15904 // When the underlying type is fixed, this is ill-formed. 15905 Diag(IdLoc, diag::err_enumerator_wrapped) 15906 << EnumVal.toString(10) 15907 << EltTy; 15908 else 15909 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15910 << EnumVal.toString(10); 15911 } else { 15912 EltTy = T; 15913 } 15914 15915 // Retrieve the last enumerator's value, extent that type to the 15916 // type that is supposed to be large enough to represent the incremented 15917 // value, then increment. 15918 EnumVal = LastEnumConst->getInitVal(); 15919 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15920 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15921 ++EnumVal; 15922 15923 // If we're not in C++, diagnose the overflow of enumerator values, 15924 // which in C99 means that the enumerator value is not representable in 15925 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15926 // permits enumerator values that are representable in some larger 15927 // integral type. 15928 if (!getLangOpts().CPlusPlus && !T.isNull()) 15929 Diag(IdLoc, diag::warn_enum_value_overflow); 15930 } else if (!getLangOpts().CPlusPlus && 15931 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15932 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15933 Diag(IdLoc, diag::ext_enum_value_not_int) 15934 << EnumVal.toString(10) << 1; 15935 } 15936 } 15937 } 15938 15939 if (!EltTy->isDependentType()) { 15940 // Make the enumerator value match the signedness and size of the 15941 // enumerator's type. 15942 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15943 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15944 } 15945 15946 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15947 Val, EnumVal); 15948 } 15949 15950 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15951 SourceLocation IILoc) { 15952 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15953 !getLangOpts().CPlusPlus) 15954 return SkipBodyInfo(); 15955 15956 // We have an anonymous enum definition. Look up the first enumerator to 15957 // determine if we should merge the definition with an existing one and 15958 // skip the body. 15959 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15960 forRedeclarationInCurContext()); 15961 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15962 if (!PrevECD) 15963 return SkipBodyInfo(); 15964 15965 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15966 NamedDecl *Hidden; 15967 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15968 SkipBodyInfo Skip; 15969 Skip.Previous = Hidden; 15970 return Skip; 15971 } 15972 15973 return SkipBodyInfo(); 15974 } 15975 15976 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15977 SourceLocation IdLoc, IdentifierInfo *Id, 15978 AttributeList *Attr, 15979 SourceLocation EqualLoc, Expr *Val) { 15980 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15981 EnumConstantDecl *LastEnumConst = 15982 cast_or_null<EnumConstantDecl>(lastEnumConst); 15983 15984 // The scope passed in may not be a decl scope. Zip up the scope tree until 15985 // we find one that is. 15986 S = getNonFieldDeclScope(S); 15987 15988 // Verify that there isn't already something declared with this name in this 15989 // scope. 15990 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15991 ForVisibleRedeclaration); 15992 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15993 // Maybe we will complain about the shadowed template parameter. 15994 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15995 // Just pretend that we didn't see the previous declaration. 15996 PrevDecl = nullptr; 15997 } 15998 15999 // C++ [class.mem]p15: 16000 // If T is the name of a class, then each of the following shall have a name 16001 // different from T: 16002 // - every enumerator of every member of class T that is an unscoped 16003 // enumerated type 16004 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 16005 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 16006 DeclarationNameInfo(Id, IdLoc)); 16007 16008 EnumConstantDecl *New = 16009 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 16010 if (!New) 16011 return nullptr; 16012 16013 if (PrevDecl) { 16014 // When in C++, we may get a TagDecl with the same name; in this case the 16015 // enum constant will 'hide' the tag. 16016 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 16017 "Received TagDecl when not in C++!"); 16018 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 16019 if (isa<EnumConstantDecl>(PrevDecl)) 16020 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 16021 else 16022 Diag(IdLoc, diag::err_redefinition) << Id; 16023 notePreviousDefinition(PrevDecl, IdLoc); 16024 return nullptr; 16025 } 16026 } 16027 16028 // Process attributes. 16029 if (Attr) ProcessDeclAttributeList(S, New, Attr); 16030 AddPragmaAttributes(S, New); 16031 16032 // Register this decl in the current scope stack. 16033 New->setAccess(TheEnumDecl->getAccess()); 16034 PushOnScopeChains(New, S); 16035 16036 ActOnDocumentableDecl(New); 16037 16038 return New; 16039 } 16040 16041 // Returns true when the enum initial expression does not trigger the 16042 // duplicate enum warning. A few common cases are exempted as follows: 16043 // Element2 = Element1 16044 // Element2 = Element1 + 1 16045 // Element2 = Element1 - 1 16046 // Where Element2 and Element1 are from the same enum. 16047 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16048 Expr *InitExpr = ECD->getInitExpr(); 16049 if (!InitExpr) 16050 return true; 16051 InitExpr = InitExpr->IgnoreImpCasts(); 16052 16053 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16054 if (!BO->isAdditiveOp()) 16055 return true; 16056 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16057 if (!IL) 16058 return true; 16059 if (IL->getValue() != 1) 16060 return true; 16061 16062 InitExpr = BO->getLHS(); 16063 } 16064 16065 // This checks if the elements are from the same enum. 16066 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16067 if (!DRE) 16068 return true; 16069 16070 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16071 if (!EnumConstant) 16072 return true; 16073 16074 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16075 Enum) 16076 return true; 16077 16078 return false; 16079 } 16080 16081 // Emits a warning when an element is implicitly set a value that 16082 // a previous element has already been set to. 16083 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16084 EnumDecl *Enum, QualType EnumType) { 16085 // Avoid anonymous enums 16086 if (!Enum->getIdentifier()) 16087 return; 16088 16089 // Only check for small enums. 16090 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16091 return; 16092 16093 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16094 return; 16095 16096 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16097 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16098 16099 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16100 typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap; 16101 16102 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16103 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16104 llvm::APSInt Val = D->getInitVal(); 16105 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16106 }; 16107 16108 DuplicatesVector DupVector; 16109 ValueToVectorMap EnumMap; 16110 16111 // Populate the EnumMap with all values represented by enum constants without 16112 // an initializer. 16113 for (auto *Element : Elements) { 16114 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16115 16116 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16117 // this constant. Skip this enum since it may be ill-formed. 16118 if (!ECD) { 16119 return; 16120 } 16121 16122 // Constants with initalizers are handled in the next loop. 16123 if (ECD->getInitExpr()) 16124 continue; 16125 16126 // Duplicate values are handled in the next loop. 16127 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16128 } 16129 16130 if (EnumMap.size() == 0) 16131 return; 16132 16133 // Create vectors for any values that has duplicates. 16134 for (auto *Element : Elements) { 16135 // The last loop returned if any constant was null. 16136 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16137 if (!ValidDuplicateEnum(ECD, Enum)) 16138 continue; 16139 16140 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16141 if (Iter == EnumMap.end()) 16142 continue; 16143 16144 DeclOrVector& Entry = Iter->second; 16145 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16146 // Ensure constants are different. 16147 if (D == ECD) 16148 continue; 16149 16150 // Create new vector and push values onto it. 16151 auto Vec = llvm::make_unique<ECDVector>(); 16152 Vec->push_back(D); 16153 Vec->push_back(ECD); 16154 16155 // Update entry to point to the duplicates vector. 16156 Entry = Vec.get(); 16157 16158 // Store the vector somewhere we can consult later for quick emission of 16159 // diagnostics. 16160 DupVector.emplace_back(std::move(Vec)); 16161 continue; 16162 } 16163 16164 ECDVector *Vec = Entry.get<ECDVector*>(); 16165 // Make sure constants are not added more than once. 16166 if (*Vec->begin() == ECD) 16167 continue; 16168 16169 Vec->push_back(ECD); 16170 } 16171 16172 // Emit diagnostics. 16173 for (const auto &Vec : DupVector) { 16174 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16175 16176 // Emit warning for one enum constant. 16177 auto *FirstECD = Vec->front(); 16178 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16179 << FirstECD << FirstECD->getInitVal().toString(10) 16180 << FirstECD->getSourceRange(); 16181 16182 // Emit one note for each of the remaining enum constants with 16183 // the same value. 16184 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16185 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16186 << ECD << ECD->getInitVal().toString(10) 16187 << ECD->getSourceRange(); 16188 } 16189 } 16190 16191 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16192 bool AllowMask) const { 16193 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16194 assert(ED->isCompleteDefinition() && "expected enum definition"); 16195 16196 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16197 llvm::APInt &FlagBits = R.first->second; 16198 16199 if (R.second) { 16200 for (auto *E : ED->enumerators()) { 16201 const auto &EVal = E->getInitVal(); 16202 // Only single-bit enumerators introduce new flag values. 16203 if (EVal.isPowerOf2()) 16204 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16205 } 16206 } 16207 16208 // A value is in a flag enum if either its bits are a subset of the enum's 16209 // flag bits (the first condition) or we are allowing masks and the same is 16210 // true of its complement (the second condition). When masks are allowed, we 16211 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16212 // 16213 // While it's true that any value could be used as a mask, the assumption is 16214 // that a mask will have all of the insignificant bits set. Anything else is 16215 // likely a logic error. 16216 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16217 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16218 } 16219 16220 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16221 Decl *EnumDeclX, 16222 ArrayRef<Decl *> Elements, 16223 Scope *S, AttributeList *Attr) { 16224 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16225 QualType EnumType = Context.getTypeDeclType(Enum); 16226 16227 if (Attr) 16228 ProcessDeclAttributeList(S, Enum, Attr); 16229 16230 if (Enum->isDependentType()) { 16231 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16232 EnumConstantDecl *ECD = 16233 cast_or_null<EnumConstantDecl>(Elements[i]); 16234 if (!ECD) continue; 16235 16236 ECD->setType(EnumType); 16237 } 16238 16239 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16240 return; 16241 } 16242 16243 // TODO: If the result value doesn't fit in an int, it must be a long or long 16244 // long value. ISO C does not support this, but GCC does as an extension, 16245 // emit a warning. 16246 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16247 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16248 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16249 16250 // Verify that all the values are okay, compute the size of the values, and 16251 // reverse the list. 16252 unsigned NumNegativeBits = 0; 16253 unsigned NumPositiveBits = 0; 16254 16255 // Keep track of whether all elements have type int. 16256 bool AllElementsInt = true; 16257 16258 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16259 EnumConstantDecl *ECD = 16260 cast_or_null<EnumConstantDecl>(Elements[i]); 16261 if (!ECD) continue; // Already issued a diagnostic. 16262 16263 const llvm::APSInt &InitVal = ECD->getInitVal(); 16264 16265 // Keep track of the size of positive and negative values. 16266 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16267 NumPositiveBits = std::max(NumPositiveBits, 16268 (unsigned)InitVal.getActiveBits()); 16269 else 16270 NumNegativeBits = std::max(NumNegativeBits, 16271 (unsigned)InitVal.getMinSignedBits()); 16272 16273 // Keep track of whether every enum element has type int (very commmon). 16274 if (AllElementsInt) 16275 AllElementsInt = ECD->getType() == Context.IntTy; 16276 } 16277 16278 // Figure out the type that should be used for this enum. 16279 QualType BestType; 16280 unsigned BestWidth; 16281 16282 // C++0x N3000 [conv.prom]p3: 16283 // An rvalue of an unscoped enumeration type whose underlying 16284 // type is not fixed can be converted to an rvalue of the first 16285 // of the following types that can represent all the values of 16286 // the enumeration: int, unsigned int, long int, unsigned long 16287 // int, long long int, or unsigned long long int. 16288 // C99 6.4.4.3p2: 16289 // An identifier declared as an enumeration constant has type int. 16290 // The C99 rule is modified by a gcc extension 16291 QualType BestPromotionType; 16292 16293 bool Packed = Enum->hasAttr<PackedAttr>(); 16294 // -fshort-enums is the equivalent to specifying the packed attribute on all 16295 // enum definitions. 16296 if (LangOpts.ShortEnums) 16297 Packed = true; 16298 16299 // If the enum already has a type because it is fixed or dictated by the 16300 // target, promote that type instead of analyzing the enumerators. 16301 if (Enum->isComplete()) { 16302 BestType = Enum->getIntegerType(); 16303 if (BestType->isPromotableIntegerType()) 16304 BestPromotionType = Context.getPromotedIntegerType(BestType); 16305 else 16306 BestPromotionType = BestType; 16307 16308 BestWidth = Context.getIntWidth(BestType); 16309 } 16310 else if (NumNegativeBits) { 16311 // If there is a negative value, figure out the smallest integer type (of 16312 // int/long/longlong) that fits. 16313 // If it's packed, check also if it fits a char or a short. 16314 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16315 BestType = Context.SignedCharTy; 16316 BestWidth = CharWidth; 16317 } else if (Packed && NumNegativeBits <= ShortWidth && 16318 NumPositiveBits < ShortWidth) { 16319 BestType = Context.ShortTy; 16320 BestWidth = ShortWidth; 16321 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16322 BestType = Context.IntTy; 16323 BestWidth = IntWidth; 16324 } else { 16325 BestWidth = Context.getTargetInfo().getLongWidth(); 16326 16327 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16328 BestType = Context.LongTy; 16329 } else { 16330 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16331 16332 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16333 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16334 BestType = Context.LongLongTy; 16335 } 16336 } 16337 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16338 } else { 16339 // If there is no negative value, figure out the smallest type that fits 16340 // all of the enumerator values. 16341 // If it's packed, check also if it fits a char or a short. 16342 if (Packed && NumPositiveBits <= CharWidth) { 16343 BestType = Context.UnsignedCharTy; 16344 BestPromotionType = Context.IntTy; 16345 BestWidth = CharWidth; 16346 } else if (Packed && NumPositiveBits <= ShortWidth) { 16347 BestType = Context.UnsignedShortTy; 16348 BestPromotionType = Context.IntTy; 16349 BestWidth = ShortWidth; 16350 } else if (NumPositiveBits <= IntWidth) { 16351 BestType = Context.UnsignedIntTy; 16352 BestWidth = IntWidth; 16353 BestPromotionType 16354 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16355 ? Context.UnsignedIntTy : Context.IntTy; 16356 } else if (NumPositiveBits <= 16357 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16358 BestType = Context.UnsignedLongTy; 16359 BestPromotionType 16360 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16361 ? Context.UnsignedLongTy : Context.LongTy; 16362 } else { 16363 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16364 assert(NumPositiveBits <= BestWidth && 16365 "How could an initializer get larger than ULL?"); 16366 BestType = Context.UnsignedLongLongTy; 16367 BestPromotionType 16368 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16369 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16370 } 16371 } 16372 16373 // Loop over all of the enumerator constants, changing their types to match 16374 // the type of the enum if needed. 16375 for (auto *D : Elements) { 16376 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16377 if (!ECD) continue; // Already issued a diagnostic. 16378 16379 // Standard C says the enumerators have int type, but we allow, as an 16380 // extension, the enumerators to be larger than int size. If each 16381 // enumerator value fits in an int, type it as an int, otherwise type it the 16382 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16383 // that X has type 'int', not 'unsigned'. 16384 16385 // Determine whether the value fits into an int. 16386 llvm::APSInt InitVal = ECD->getInitVal(); 16387 16388 // If it fits into an integer type, force it. Otherwise force it to match 16389 // the enum decl type. 16390 QualType NewTy; 16391 unsigned NewWidth; 16392 bool NewSign; 16393 if (!getLangOpts().CPlusPlus && 16394 !Enum->isFixed() && 16395 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16396 NewTy = Context.IntTy; 16397 NewWidth = IntWidth; 16398 NewSign = true; 16399 } else if (ECD->getType() == BestType) { 16400 // Already the right type! 16401 if (getLangOpts().CPlusPlus) 16402 // C++ [dcl.enum]p4: Following the closing brace of an 16403 // enum-specifier, each enumerator has the type of its 16404 // enumeration. 16405 ECD->setType(EnumType); 16406 continue; 16407 } else { 16408 NewTy = BestType; 16409 NewWidth = BestWidth; 16410 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16411 } 16412 16413 // Adjust the APSInt value. 16414 InitVal = InitVal.extOrTrunc(NewWidth); 16415 InitVal.setIsSigned(NewSign); 16416 ECD->setInitVal(InitVal); 16417 16418 // Adjust the Expr initializer and type. 16419 if (ECD->getInitExpr() && 16420 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16421 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16422 CK_IntegralCast, 16423 ECD->getInitExpr(), 16424 /*base paths*/ nullptr, 16425 VK_RValue)); 16426 if (getLangOpts().CPlusPlus) 16427 // C++ [dcl.enum]p4: Following the closing brace of an 16428 // enum-specifier, each enumerator has the type of its 16429 // enumeration. 16430 ECD->setType(EnumType); 16431 else 16432 ECD->setType(NewTy); 16433 } 16434 16435 Enum->completeDefinition(BestType, BestPromotionType, 16436 NumPositiveBits, NumNegativeBits); 16437 16438 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16439 16440 if (Enum->isClosedFlag()) { 16441 for (Decl *D : Elements) { 16442 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16443 if (!ECD) continue; // Already issued a diagnostic. 16444 16445 llvm::APSInt InitVal = ECD->getInitVal(); 16446 if (InitVal != 0 && !InitVal.isPowerOf2() && 16447 !IsValueInFlagEnum(Enum, InitVal, true)) 16448 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16449 << ECD << Enum; 16450 } 16451 } 16452 16453 // Now that the enum type is defined, ensure it's not been underaligned. 16454 if (Enum->hasAttrs()) 16455 CheckAlignasUnderalignment(Enum); 16456 } 16457 16458 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16459 SourceLocation StartLoc, 16460 SourceLocation EndLoc) { 16461 StringLiteral *AsmString = cast<StringLiteral>(expr); 16462 16463 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16464 AsmString, StartLoc, 16465 EndLoc); 16466 CurContext->addDecl(New); 16467 return New; 16468 } 16469 16470 static void checkModuleImportContext(Sema &S, Module *M, 16471 SourceLocation ImportLoc, DeclContext *DC, 16472 bool FromInclude = false) { 16473 SourceLocation ExternCLoc; 16474 16475 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16476 switch (LSD->getLanguage()) { 16477 case LinkageSpecDecl::lang_c: 16478 if (ExternCLoc.isInvalid()) 16479 ExternCLoc = LSD->getLocStart(); 16480 break; 16481 case LinkageSpecDecl::lang_cxx: 16482 break; 16483 } 16484 DC = LSD->getParent(); 16485 } 16486 16487 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 16488 DC = DC->getParent(); 16489 16490 if (!isa<TranslationUnitDecl>(DC)) { 16491 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16492 ? diag::ext_module_import_not_at_top_level_noop 16493 : diag::err_module_import_not_at_top_level_fatal) 16494 << M->getFullModuleName() << DC; 16495 S.Diag(cast<Decl>(DC)->getLocStart(), 16496 diag::note_module_import_not_at_top_level) << DC; 16497 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16498 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16499 << M->getFullModuleName(); 16500 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16501 } 16502 } 16503 16504 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16505 SourceLocation ModuleLoc, 16506 ModuleDeclKind MDK, 16507 ModuleIdPath Path) { 16508 assert(getLangOpts().ModulesTS && 16509 "should only have module decl in modules TS"); 16510 16511 // A module implementation unit requires that we are not compiling a module 16512 // of any kind. A module interface unit requires that we are not compiling a 16513 // module map. 16514 switch (getLangOpts().getCompilingModule()) { 16515 case LangOptions::CMK_None: 16516 // It's OK to compile a module interface as a normal translation unit. 16517 break; 16518 16519 case LangOptions::CMK_ModuleInterface: 16520 if (MDK != ModuleDeclKind::Implementation) 16521 break; 16522 16523 // We were asked to compile a module interface unit but this is a module 16524 // implementation unit. That indicates the 'export' is missing. 16525 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16526 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16527 MDK = ModuleDeclKind::Interface; 16528 break; 16529 16530 case LangOptions::CMK_ModuleMap: 16531 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16532 return nullptr; 16533 } 16534 16535 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16536 16537 // FIXME: Most of this work should be done by the preprocessor rather than 16538 // here, in order to support macro import. 16539 16540 // Only one module-declaration is permitted per source file. 16541 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16542 Diag(ModuleLoc, diag::err_module_redeclaration); 16543 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16544 diag::note_prev_module_declaration); 16545 return nullptr; 16546 } 16547 16548 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16549 // modules, the dots here are just another character that can appear in a 16550 // module name. 16551 std::string ModuleName; 16552 for (auto &Piece : Path) { 16553 if (!ModuleName.empty()) 16554 ModuleName += "."; 16555 ModuleName += Piece.first->getName(); 16556 } 16557 16558 // If a module name was explicitly specified on the command line, it must be 16559 // correct. 16560 if (!getLangOpts().CurrentModule.empty() && 16561 getLangOpts().CurrentModule != ModuleName) { 16562 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16563 << SourceRange(Path.front().second, Path.back().second) 16564 << getLangOpts().CurrentModule; 16565 return nullptr; 16566 } 16567 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16568 16569 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16570 Module *Mod; 16571 16572 switch (MDK) { 16573 case ModuleDeclKind::Interface: { 16574 // We can't have parsed or imported a definition of this module or parsed a 16575 // module map defining it already. 16576 if (auto *M = Map.findModule(ModuleName)) { 16577 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16578 if (M->DefinitionLoc.isValid()) 16579 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16580 else if (const auto *FE = M->getASTFile()) 16581 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16582 << FE->getName(); 16583 Mod = M; 16584 break; 16585 } 16586 16587 // Create a Module for the module that we're defining. 16588 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16589 ModuleScopes.front().Module); 16590 assert(Mod && "module creation should not fail"); 16591 break; 16592 } 16593 16594 case ModuleDeclKind::Partition: 16595 // FIXME: Check we are in a submodule of the named module. 16596 return nullptr; 16597 16598 case ModuleDeclKind::Implementation: 16599 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16600 PP.getIdentifierInfo(ModuleName), Path[0].second); 16601 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16602 /*IsIncludeDirective=*/false); 16603 if (!Mod) { 16604 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 16605 // Create an empty module interface unit for error recovery. 16606 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16607 ModuleScopes.front().Module); 16608 } 16609 break; 16610 } 16611 16612 // Switch from the global module to the named module. 16613 ModuleScopes.back().Module = Mod; 16614 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 16615 VisibleModules.setVisible(Mod, ModuleLoc); 16616 16617 // From now on, we have an owning module for all declarations we see. 16618 // However, those declarations are module-private unless explicitly 16619 // exported. 16620 auto *TU = Context.getTranslationUnitDecl(); 16621 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16622 TU->setLocalOwningModule(Mod); 16623 16624 // FIXME: Create a ModuleDecl. 16625 return nullptr; 16626 } 16627 16628 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16629 SourceLocation ImportLoc, 16630 ModuleIdPath Path) { 16631 Module *Mod = 16632 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16633 /*IsIncludeDirective=*/false); 16634 if (!Mod) 16635 return true; 16636 16637 VisibleModules.setVisible(Mod, ImportLoc); 16638 16639 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16640 16641 // FIXME: we should support importing a submodule within a different submodule 16642 // of the same top-level module. Until we do, make it an error rather than 16643 // silently ignoring the import. 16644 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16645 // warn on a redundant import of the current module? 16646 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16647 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16648 Diag(ImportLoc, getLangOpts().isCompilingModule() 16649 ? diag::err_module_self_import 16650 : diag::err_module_import_in_implementation) 16651 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16652 16653 SmallVector<SourceLocation, 2> IdentifierLocs; 16654 Module *ModCheck = Mod; 16655 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16656 // If we've run out of module parents, just drop the remaining identifiers. 16657 // We need the length to be consistent. 16658 if (!ModCheck) 16659 break; 16660 ModCheck = ModCheck->Parent; 16661 16662 IdentifierLocs.push_back(Path[I].second); 16663 } 16664 16665 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 16666 Mod, IdentifierLocs); 16667 if (!ModuleScopes.empty()) 16668 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16669 CurContext->addDecl(Import); 16670 16671 // Re-export the module if needed. 16672 if (Import->isExported() && 16673 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) 16674 getCurrentModule()->Exports.emplace_back(Mod, false); 16675 16676 return Import; 16677 } 16678 16679 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16680 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16681 BuildModuleInclude(DirectiveLoc, Mod); 16682 } 16683 16684 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16685 // Determine whether we're in the #include buffer for a module. The #includes 16686 // in that buffer do not qualify as module imports; they're just an 16687 // implementation detail of us building the module. 16688 // 16689 // FIXME: Should we even get ActOnModuleInclude calls for those? 16690 bool IsInModuleIncludes = 16691 TUKind == TU_Module && 16692 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16693 16694 bool ShouldAddImport = !IsInModuleIncludes; 16695 16696 // If this module import was due to an inclusion directive, create an 16697 // implicit import declaration to capture it in the AST. 16698 if (ShouldAddImport) { 16699 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16700 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16701 DirectiveLoc, Mod, 16702 DirectiveLoc); 16703 if (!ModuleScopes.empty()) 16704 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16705 TU->addDecl(ImportD); 16706 Consumer.HandleImplicitImportDecl(ImportD); 16707 } 16708 16709 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16710 VisibleModules.setVisible(Mod, DirectiveLoc); 16711 } 16712 16713 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16714 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16715 16716 ModuleScopes.push_back({}); 16717 ModuleScopes.back().Module = Mod; 16718 if (getLangOpts().ModulesLocalVisibility) 16719 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16720 16721 VisibleModules.setVisible(Mod, DirectiveLoc); 16722 16723 // The enclosing context is now part of this module. 16724 // FIXME: Consider creating a child DeclContext to hold the entities 16725 // lexically within the module. 16726 if (getLangOpts().trackLocalOwningModule()) { 16727 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16728 cast<Decl>(DC)->setModuleOwnershipKind( 16729 getLangOpts().ModulesLocalVisibility 16730 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16731 : Decl::ModuleOwnershipKind::Visible); 16732 cast<Decl>(DC)->setLocalOwningModule(Mod); 16733 } 16734 } 16735 } 16736 16737 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16738 if (getLangOpts().ModulesLocalVisibility) { 16739 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16740 // Leaving a module hides namespace names, so our visible namespace cache 16741 // is now out of date. 16742 VisibleNamespaceCache.clear(); 16743 } 16744 16745 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16746 "left the wrong module scope"); 16747 ModuleScopes.pop_back(); 16748 16749 // We got to the end of processing a local module. Create an 16750 // ImportDecl as we would for an imported module. 16751 FileID File = getSourceManager().getFileID(EomLoc); 16752 SourceLocation DirectiveLoc; 16753 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16754 // We reached the end of a #included module header. Use the #include loc. 16755 assert(File != getSourceManager().getMainFileID() && 16756 "end of submodule in main source file"); 16757 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16758 } else { 16759 // We reached an EOM pragma. Use the pragma location. 16760 DirectiveLoc = EomLoc; 16761 } 16762 BuildModuleInclude(DirectiveLoc, Mod); 16763 16764 // Any further declarations are in whatever module we returned to. 16765 if (getLangOpts().trackLocalOwningModule()) { 16766 // The parser guarantees that this is the same context that we entered 16767 // the module within. 16768 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16769 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16770 if (!getCurrentModule()) 16771 cast<Decl>(DC)->setModuleOwnershipKind( 16772 Decl::ModuleOwnershipKind::Unowned); 16773 } 16774 } 16775 } 16776 16777 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16778 Module *Mod) { 16779 // Bail if we're not allowed to implicitly import a module here. 16780 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16781 VisibleModules.isVisible(Mod)) 16782 return; 16783 16784 // Create the implicit import declaration. 16785 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16786 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16787 Loc, Mod, Loc); 16788 TU->addDecl(ImportD); 16789 Consumer.HandleImplicitImportDecl(ImportD); 16790 16791 // Make the module visible. 16792 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16793 VisibleModules.setVisible(Mod, Loc); 16794 } 16795 16796 /// We have parsed the start of an export declaration, including the '{' 16797 /// (if present). 16798 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16799 SourceLocation LBraceLoc) { 16800 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16801 16802 // C++ Modules TS draft: 16803 // An export-declaration shall appear in the purview of a module other than 16804 // the global module. 16805 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 16806 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16807 16808 // An export-declaration [...] shall not contain more than one 16809 // export keyword. 16810 // 16811 // The intent here is that an export-declaration cannot appear within another 16812 // export-declaration. 16813 if (D->isExported()) 16814 Diag(ExportLoc, diag::err_export_within_export); 16815 16816 CurContext->addDecl(D); 16817 PushDeclContext(S, D); 16818 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16819 return D; 16820 } 16821 16822 /// Complete the definition of an export declaration. 16823 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16824 auto *ED = cast<ExportDecl>(D); 16825 if (RBraceLoc.isValid()) 16826 ED->setRBraceLoc(RBraceLoc); 16827 16828 // FIXME: Diagnose export of internal-linkage declaration (including 16829 // anonymous namespace). 16830 16831 PopDeclContext(); 16832 return D; 16833 } 16834 16835 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16836 IdentifierInfo* AliasName, 16837 SourceLocation PragmaLoc, 16838 SourceLocation NameLoc, 16839 SourceLocation AliasNameLoc) { 16840 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16841 LookupOrdinaryName); 16842 AsmLabelAttr *Attr = 16843 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16844 16845 // If a declaration that: 16846 // 1) declares a function or a variable 16847 // 2) has external linkage 16848 // already exists, add a label attribute to it. 16849 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16850 if (isDeclExternC(PrevDecl)) 16851 PrevDecl->addAttr(Attr); 16852 else 16853 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16854 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16855 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16856 } else 16857 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16858 } 16859 16860 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16861 SourceLocation PragmaLoc, 16862 SourceLocation NameLoc) { 16863 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16864 16865 if (PrevDecl) { 16866 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16867 } else { 16868 (void)WeakUndeclaredIdentifiers.insert( 16869 std::pair<IdentifierInfo*,WeakInfo> 16870 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16871 } 16872 } 16873 16874 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16875 IdentifierInfo* AliasName, 16876 SourceLocation PragmaLoc, 16877 SourceLocation NameLoc, 16878 SourceLocation AliasNameLoc) { 16879 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16880 LookupOrdinaryName); 16881 WeakInfo W = WeakInfo(Name, NameLoc); 16882 16883 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16884 if (!PrevDecl->hasAttr<AliasAttr>()) 16885 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16886 DeclApplyPragmaWeak(TUScope, ND, W); 16887 } else { 16888 (void)WeakUndeclaredIdentifiers.insert( 16889 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16890 } 16891 } 16892 16893 Decl *Sema::getObjCDeclContext() const { 16894 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16895 } 16896