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 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7297 QualType T = TInfo->getType(); 7298 7299 // Defer checking an 'auto' type until its initializer is attached. 7300 if (T->isUndeducedType()) 7301 return; 7302 7303 if (NewVD->hasAttrs()) 7304 CheckAlignasUnderalignment(NewVD); 7305 7306 if (T->isObjCObjectType()) { 7307 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7308 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7309 T = Context.getObjCObjectPointerType(T); 7310 NewVD->setType(T); 7311 } 7312 7313 // Emit an error if an address space was applied to decl with local storage. 7314 // This includes arrays of objects with address space qualifiers, but not 7315 // automatic variables that point to other address spaces. 7316 // ISO/IEC TR 18037 S5.1.2 7317 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7318 T.getAddressSpace() != LangAS::Default) { 7319 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7320 NewVD->setInvalidDecl(); 7321 return; 7322 } 7323 7324 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7325 // scope. 7326 if (getLangOpts().OpenCLVersion == 120 && 7327 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7328 NewVD->isStaticLocal()) { 7329 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7330 NewVD->setInvalidDecl(); 7331 return; 7332 } 7333 7334 if (getLangOpts().OpenCL) { 7335 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7336 if (NewVD->hasAttr<BlocksAttr>()) { 7337 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7338 return; 7339 } 7340 7341 if (T->isBlockPointerType()) { 7342 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7343 // can't use 'extern' storage class. 7344 if (!T.isConstQualified()) { 7345 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7346 << 0 /*const*/; 7347 NewVD->setInvalidDecl(); 7348 return; 7349 } 7350 if (NewVD->hasExternalStorage()) { 7351 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7352 NewVD->setInvalidDecl(); 7353 return; 7354 } 7355 } 7356 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7357 // __constant address space. 7358 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7359 // variables inside a function can also be declared in the global 7360 // address space. 7361 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7362 NewVD->hasExternalStorage()) { 7363 if (!T->isSamplerT() && 7364 !(T.getAddressSpace() == LangAS::opencl_constant || 7365 (T.getAddressSpace() == LangAS::opencl_global && 7366 getLangOpts().OpenCLVersion == 200))) { 7367 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7368 if (getLangOpts().OpenCLVersion == 200) 7369 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7370 << Scope << "global or constant"; 7371 else 7372 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7373 << Scope << "constant"; 7374 NewVD->setInvalidDecl(); 7375 return; 7376 } 7377 } else { 7378 if (T.getAddressSpace() == LangAS::opencl_global) { 7379 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7380 << 1 /*is any function*/ << "global"; 7381 NewVD->setInvalidDecl(); 7382 return; 7383 } 7384 if (T.getAddressSpace() == LangAS::opencl_constant || 7385 T.getAddressSpace() == LangAS::opencl_local) { 7386 FunctionDecl *FD = getCurFunctionDecl(); 7387 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7388 // in functions. 7389 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7390 if (T.getAddressSpace() == LangAS::opencl_constant) 7391 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7392 << 0 /*non-kernel only*/ << "constant"; 7393 else 7394 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7395 << 0 /*non-kernel only*/ << "local"; 7396 NewVD->setInvalidDecl(); 7397 return; 7398 } 7399 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7400 // in the outermost scope of a kernel function. 7401 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7402 if (!getCurScope()->isFunctionScope()) { 7403 if (T.getAddressSpace() == LangAS::opencl_constant) 7404 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7405 << "constant"; 7406 else 7407 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7408 << "local"; 7409 NewVD->setInvalidDecl(); 7410 return; 7411 } 7412 } 7413 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7414 // Do not allow other address spaces on automatic variable. 7415 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7416 NewVD->setInvalidDecl(); 7417 return; 7418 } 7419 } 7420 } 7421 7422 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7423 && !NewVD->hasAttr<BlocksAttr>()) { 7424 if (getLangOpts().getGC() != LangOptions::NonGC) 7425 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7426 else { 7427 assert(!getLangOpts().ObjCAutoRefCount); 7428 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7429 } 7430 } 7431 7432 bool isVM = T->isVariablyModifiedType(); 7433 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7434 NewVD->hasAttr<BlocksAttr>()) 7435 setFunctionHasBranchProtectedScope(); 7436 7437 if ((isVM && NewVD->hasLinkage()) || 7438 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7439 bool SizeIsNegative; 7440 llvm::APSInt Oversized; 7441 TypeSourceInfo *FixedTInfo = 7442 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7443 SizeIsNegative, Oversized); 7444 if (!FixedTInfo && T->isVariableArrayType()) { 7445 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7446 // FIXME: This won't give the correct result for 7447 // int a[10][n]; 7448 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7449 7450 if (NewVD->isFileVarDecl()) 7451 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7452 << SizeRange; 7453 else if (NewVD->isStaticLocal()) 7454 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7455 << SizeRange; 7456 else 7457 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7458 << SizeRange; 7459 NewVD->setInvalidDecl(); 7460 return; 7461 } 7462 7463 if (!FixedTInfo) { 7464 if (NewVD->isFileVarDecl()) 7465 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7466 else 7467 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7468 NewVD->setInvalidDecl(); 7469 return; 7470 } 7471 7472 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7473 NewVD->setType(FixedTInfo->getType()); 7474 NewVD->setTypeSourceInfo(FixedTInfo); 7475 } 7476 7477 if (T->isVoidType()) { 7478 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7479 // of objects and functions. 7480 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7481 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7482 << T; 7483 NewVD->setInvalidDecl(); 7484 return; 7485 } 7486 } 7487 7488 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7489 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7490 NewVD->setInvalidDecl(); 7491 return; 7492 } 7493 7494 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7495 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7496 NewVD->setInvalidDecl(); 7497 return; 7498 } 7499 7500 if (NewVD->isConstexpr() && !T->isDependentType() && 7501 RequireLiteralType(NewVD->getLocation(), T, 7502 diag::err_constexpr_var_non_literal)) { 7503 NewVD->setInvalidDecl(); 7504 return; 7505 } 7506 } 7507 7508 /// Perform semantic checking on a newly-created variable 7509 /// declaration. 7510 /// 7511 /// This routine performs all of the type-checking required for a 7512 /// variable declaration once it has been built. It is used both to 7513 /// check variables after they have been parsed and their declarators 7514 /// have been translated into a declaration, and to check variables 7515 /// that have been instantiated from a template. 7516 /// 7517 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7518 /// 7519 /// Returns true if the variable declaration is a redeclaration. 7520 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7521 CheckVariableDeclarationType(NewVD); 7522 7523 // If the decl is already known invalid, don't check it. 7524 if (NewVD->isInvalidDecl()) 7525 return false; 7526 7527 // If we did not find anything by this name, look for a non-visible 7528 // extern "C" declaration with the same name. 7529 if (Previous.empty() && 7530 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7531 Previous.setShadowed(); 7532 7533 if (!Previous.empty()) { 7534 MergeVarDecl(NewVD, Previous); 7535 return true; 7536 } 7537 return false; 7538 } 7539 7540 namespace { 7541 struct FindOverriddenMethod { 7542 Sema *S; 7543 CXXMethodDecl *Method; 7544 7545 /// Member lookup function that determines whether a given C++ 7546 /// method overrides a method in a base class, to be used with 7547 /// CXXRecordDecl::lookupInBases(). 7548 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7549 RecordDecl *BaseRecord = 7550 Specifier->getType()->getAs<RecordType>()->getDecl(); 7551 7552 DeclarationName Name = Method->getDeclName(); 7553 7554 // FIXME: Do we care about other names here too? 7555 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7556 // We really want to find the base class destructor here. 7557 QualType T = S->Context.getTypeDeclType(BaseRecord); 7558 CanQualType CT = S->Context.getCanonicalType(T); 7559 7560 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7561 } 7562 7563 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7564 Path.Decls = Path.Decls.slice(1)) { 7565 NamedDecl *D = Path.Decls.front(); 7566 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7567 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7568 return true; 7569 } 7570 } 7571 7572 return false; 7573 } 7574 }; 7575 7576 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7577 } // end anonymous namespace 7578 7579 /// Report an error regarding overriding, along with any relevant 7580 /// overridden methods. 7581 /// 7582 /// \param DiagID the primary error to report. 7583 /// \param MD the overriding method. 7584 /// \param OEK which overrides to include as notes. 7585 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7586 OverrideErrorKind OEK = OEK_All) { 7587 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7588 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7589 // This check (& the OEK parameter) could be replaced by a predicate, but 7590 // without lambdas that would be overkill. This is still nicer than writing 7591 // out the diag loop 3 times. 7592 if ((OEK == OEK_All) || 7593 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7594 (OEK == OEK_Deleted && O->isDeleted())) 7595 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7596 } 7597 } 7598 7599 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7600 /// and if so, check that it's a valid override and remember it. 7601 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7602 // Look for methods in base classes that this method might override. 7603 CXXBasePaths Paths; 7604 FindOverriddenMethod FOM; 7605 FOM.Method = MD; 7606 FOM.S = this; 7607 bool hasDeletedOverridenMethods = false; 7608 bool hasNonDeletedOverridenMethods = false; 7609 bool AddedAny = false; 7610 if (DC->lookupInBases(FOM, Paths)) { 7611 for (auto *I : Paths.found_decls()) { 7612 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7613 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7614 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7615 !CheckOverridingFunctionAttributes(MD, OldMD) && 7616 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7617 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7618 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7619 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7620 AddedAny = true; 7621 } 7622 } 7623 } 7624 } 7625 7626 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7627 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7628 } 7629 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7630 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7631 } 7632 7633 return AddedAny; 7634 } 7635 7636 namespace { 7637 // Struct for holding all of the extra arguments needed by 7638 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7639 struct ActOnFDArgs { 7640 Scope *S; 7641 Declarator &D; 7642 MultiTemplateParamsArg TemplateParamLists; 7643 bool AddToScope; 7644 }; 7645 } // end anonymous namespace 7646 7647 namespace { 7648 7649 // Callback to only accept typo corrections that have a non-zero edit distance. 7650 // Also only accept corrections that have the same parent decl. 7651 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7652 public: 7653 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7654 CXXRecordDecl *Parent) 7655 : Context(Context), OriginalFD(TypoFD), 7656 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7657 7658 bool ValidateCandidate(const TypoCorrection &candidate) override { 7659 if (candidate.getEditDistance() == 0) 7660 return false; 7661 7662 SmallVector<unsigned, 1> MismatchedParams; 7663 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7664 CDeclEnd = candidate.end(); 7665 CDecl != CDeclEnd; ++CDecl) { 7666 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7667 7668 if (FD && !FD->hasBody() && 7669 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7670 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7671 CXXRecordDecl *Parent = MD->getParent(); 7672 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7673 return true; 7674 } else if (!ExpectedParent) { 7675 return true; 7676 } 7677 } 7678 } 7679 7680 return false; 7681 } 7682 7683 private: 7684 ASTContext &Context; 7685 FunctionDecl *OriginalFD; 7686 CXXRecordDecl *ExpectedParent; 7687 }; 7688 7689 } // end anonymous namespace 7690 7691 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7692 TypoCorrectedFunctionDefinitions.insert(F); 7693 } 7694 7695 /// Generate diagnostics for an invalid function redeclaration. 7696 /// 7697 /// This routine handles generating the diagnostic messages for an invalid 7698 /// function redeclaration, including finding possible similar declarations 7699 /// or performing typo correction if there are no previous declarations with 7700 /// the same name. 7701 /// 7702 /// Returns a NamedDecl iff typo correction was performed and substituting in 7703 /// the new declaration name does not cause new errors. 7704 static NamedDecl *DiagnoseInvalidRedeclaration( 7705 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7706 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7707 DeclarationName Name = NewFD->getDeclName(); 7708 DeclContext *NewDC = NewFD->getDeclContext(); 7709 SmallVector<unsigned, 1> MismatchedParams; 7710 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7711 TypoCorrection Correction; 7712 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7713 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7714 : diag::err_member_decl_does_not_match; 7715 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7716 IsLocalFriend ? Sema::LookupLocalFriendName 7717 : Sema::LookupOrdinaryName, 7718 Sema::ForVisibleRedeclaration); 7719 7720 NewFD->setInvalidDecl(); 7721 if (IsLocalFriend) 7722 SemaRef.LookupName(Prev, S); 7723 else 7724 SemaRef.LookupQualifiedName(Prev, NewDC); 7725 assert(!Prev.isAmbiguous() && 7726 "Cannot have an ambiguity in previous-declaration lookup"); 7727 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7728 if (!Prev.empty()) { 7729 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7730 Func != FuncEnd; ++Func) { 7731 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7732 if (FD && 7733 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7734 // Add 1 to the index so that 0 can mean the mismatch didn't 7735 // involve a parameter 7736 unsigned ParamNum = 7737 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7738 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7739 } 7740 } 7741 // If the qualified name lookup yielded nothing, try typo correction 7742 } else if ((Correction = SemaRef.CorrectTypo( 7743 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7744 &ExtraArgs.D.getCXXScopeSpec(), 7745 llvm::make_unique<DifferentNameValidatorCCC>( 7746 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7747 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7748 // Set up everything for the call to ActOnFunctionDeclarator 7749 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7750 ExtraArgs.D.getIdentifierLoc()); 7751 Previous.clear(); 7752 Previous.setLookupName(Correction.getCorrection()); 7753 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7754 CDeclEnd = Correction.end(); 7755 CDecl != CDeclEnd; ++CDecl) { 7756 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7757 if (FD && !FD->hasBody() && 7758 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7759 Previous.addDecl(FD); 7760 } 7761 } 7762 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7763 7764 NamedDecl *Result; 7765 // Retry building the function declaration with the new previous 7766 // declarations, and with errors suppressed. 7767 { 7768 // Trap errors. 7769 Sema::SFINAETrap Trap(SemaRef); 7770 7771 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7772 // pieces need to verify the typo-corrected C++ declaration and hopefully 7773 // eliminate the need for the parameter pack ExtraArgs. 7774 Result = SemaRef.ActOnFunctionDeclarator( 7775 ExtraArgs.S, ExtraArgs.D, 7776 Correction.getCorrectionDecl()->getDeclContext(), 7777 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7778 ExtraArgs.AddToScope); 7779 7780 if (Trap.hasErrorOccurred()) 7781 Result = nullptr; 7782 } 7783 7784 if (Result) { 7785 // Determine which correction we picked. 7786 Decl *Canonical = Result->getCanonicalDecl(); 7787 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7788 I != E; ++I) 7789 if ((*I)->getCanonicalDecl() == Canonical) 7790 Correction.setCorrectionDecl(*I); 7791 7792 // Let Sema know about the correction. 7793 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7794 SemaRef.diagnoseTypo( 7795 Correction, 7796 SemaRef.PDiag(IsLocalFriend 7797 ? diag::err_no_matching_local_friend_suggest 7798 : diag::err_member_decl_does_not_match_suggest) 7799 << Name << NewDC << IsDefinition); 7800 return Result; 7801 } 7802 7803 // Pretend the typo correction never occurred 7804 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7805 ExtraArgs.D.getIdentifierLoc()); 7806 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7807 Previous.clear(); 7808 Previous.setLookupName(Name); 7809 } 7810 7811 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7812 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7813 7814 bool NewFDisConst = false; 7815 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7816 NewFDisConst = NewMD->isConst(); 7817 7818 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7819 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7820 NearMatch != NearMatchEnd; ++NearMatch) { 7821 FunctionDecl *FD = NearMatch->first; 7822 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7823 bool FDisConst = MD && MD->isConst(); 7824 bool IsMember = MD || !IsLocalFriend; 7825 7826 // FIXME: These notes are poorly worded for the local friend case. 7827 if (unsigned Idx = NearMatch->second) { 7828 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7829 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7830 if (Loc.isInvalid()) Loc = FD->getLocation(); 7831 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7832 : diag::note_local_decl_close_param_match) 7833 << Idx << FDParam->getType() 7834 << NewFD->getParamDecl(Idx - 1)->getType(); 7835 } else if (FDisConst != NewFDisConst) { 7836 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7837 << NewFDisConst << FD->getSourceRange().getEnd(); 7838 } else 7839 SemaRef.Diag(FD->getLocation(), 7840 IsMember ? diag::note_member_def_close_match 7841 : diag::note_local_decl_close_match); 7842 } 7843 return nullptr; 7844 } 7845 7846 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7847 switch (D.getDeclSpec().getStorageClassSpec()) { 7848 default: llvm_unreachable("Unknown storage class!"); 7849 case DeclSpec::SCS_auto: 7850 case DeclSpec::SCS_register: 7851 case DeclSpec::SCS_mutable: 7852 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7853 diag::err_typecheck_sclass_func); 7854 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7855 D.setInvalidType(); 7856 break; 7857 case DeclSpec::SCS_unspecified: break; 7858 case DeclSpec::SCS_extern: 7859 if (D.getDeclSpec().isExternInLinkageSpec()) 7860 return SC_None; 7861 return SC_Extern; 7862 case DeclSpec::SCS_static: { 7863 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7864 // C99 6.7.1p5: 7865 // The declaration of an identifier for a function that has 7866 // block scope shall have no explicit storage-class specifier 7867 // other than extern 7868 // See also (C++ [dcl.stc]p4). 7869 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7870 diag::err_static_block_func); 7871 break; 7872 } else 7873 return SC_Static; 7874 } 7875 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7876 } 7877 7878 // No explicit storage class has already been returned 7879 return SC_None; 7880 } 7881 7882 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7883 DeclContext *DC, QualType &R, 7884 TypeSourceInfo *TInfo, 7885 StorageClass SC, 7886 bool &IsVirtualOkay) { 7887 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7888 DeclarationName Name = NameInfo.getName(); 7889 7890 FunctionDecl *NewFD = nullptr; 7891 bool isInline = D.getDeclSpec().isInlineSpecified(); 7892 7893 if (!SemaRef.getLangOpts().CPlusPlus) { 7894 // Determine whether the function was written with a 7895 // prototype. This true when: 7896 // - there is a prototype in the declarator, or 7897 // - the type R of the function is some kind of typedef or other non- 7898 // attributed reference to a type name (which eventually refers to a 7899 // function type). 7900 bool HasPrototype = 7901 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7902 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7903 7904 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7905 D.getLocStart(), NameInfo, R, 7906 TInfo, SC, isInline, 7907 HasPrototype, false); 7908 if (D.isInvalidType()) 7909 NewFD->setInvalidDecl(); 7910 7911 return NewFD; 7912 } 7913 7914 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7915 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7916 7917 // Check that the return type is not an abstract class type. 7918 // For record types, this is done by the AbstractClassUsageDiagnoser once 7919 // the class has been completely parsed. 7920 if (!DC->isRecord() && 7921 SemaRef.RequireNonAbstractType( 7922 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7923 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7924 D.setInvalidType(); 7925 7926 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7927 // This is a C++ constructor declaration. 7928 assert(DC->isRecord() && 7929 "Constructors can only be declared in a member context"); 7930 7931 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7932 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7933 D.getLocStart(), NameInfo, 7934 R, TInfo, isExplicit, isInline, 7935 /*isImplicitlyDeclared=*/false, 7936 isConstexpr); 7937 7938 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7939 // This is a C++ destructor declaration. 7940 if (DC->isRecord()) { 7941 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7942 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7943 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7944 SemaRef.Context, Record, 7945 D.getLocStart(), 7946 NameInfo, R, TInfo, isInline, 7947 /*isImplicitlyDeclared=*/false); 7948 7949 // If the class is complete, then we now create the implicit exception 7950 // specification. If the class is incomplete or dependent, we can't do 7951 // it yet. 7952 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7953 Record->getDefinition() && !Record->isBeingDefined() && 7954 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7955 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7956 } 7957 7958 IsVirtualOkay = true; 7959 return NewDD; 7960 7961 } else { 7962 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7963 D.setInvalidType(); 7964 7965 // Create a FunctionDecl to satisfy the function definition parsing 7966 // code path. 7967 return FunctionDecl::Create(SemaRef.Context, DC, 7968 D.getLocStart(), 7969 D.getIdentifierLoc(), Name, R, TInfo, 7970 SC, isInline, 7971 /*hasPrototype=*/true, isConstexpr); 7972 } 7973 7974 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7975 if (!DC->isRecord()) { 7976 SemaRef.Diag(D.getIdentifierLoc(), 7977 diag::err_conv_function_not_member); 7978 return nullptr; 7979 } 7980 7981 SemaRef.CheckConversionDeclarator(D, R, SC); 7982 IsVirtualOkay = true; 7983 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7984 D.getLocStart(), NameInfo, 7985 R, TInfo, isInline, isExplicit, 7986 isConstexpr, SourceLocation()); 7987 7988 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7989 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7990 7991 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7992 isExplicit, NameInfo, R, TInfo, 7993 D.getLocEnd()); 7994 } else if (DC->isRecord()) { 7995 // If the name of the function is the same as the name of the record, 7996 // then this must be an invalid constructor that has a return type. 7997 // (The parser checks for a return type and makes the declarator a 7998 // constructor if it has no return type). 7999 if (Name.getAsIdentifierInfo() && 8000 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8001 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8002 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8003 << SourceRange(D.getIdentifierLoc()); 8004 return nullptr; 8005 } 8006 8007 // This is a C++ method declaration. 8008 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 8009 cast<CXXRecordDecl>(DC), 8010 D.getLocStart(), NameInfo, R, 8011 TInfo, SC, isInline, 8012 isConstexpr, SourceLocation()); 8013 IsVirtualOkay = !Ret->isStatic(); 8014 return Ret; 8015 } else { 8016 bool isFriend = 8017 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8018 if (!isFriend && SemaRef.CurContext->isRecord()) 8019 return nullptr; 8020 8021 // Determine whether the function was written with a 8022 // prototype. This true when: 8023 // - we're in C++ (where every function has a prototype), 8024 return FunctionDecl::Create(SemaRef.Context, DC, 8025 D.getLocStart(), 8026 NameInfo, R, TInfo, SC, isInline, 8027 true/*HasPrototype*/, isConstexpr); 8028 } 8029 } 8030 8031 enum OpenCLParamType { 8032 ValidKernelParam, 8033 PtrPtrKernelParam, 8034 PtrKernelParam, 8035 InvalidAddrSpacePtrKernelParam, 8036 InvalidKernelParam, 8037 RecordKernelParam 8038 }; 8039 8040 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8041 if (PT->isPointerType()) { 8042 QualType PointeeType = PT->getPointeeType(); 8043 if (PointeeType->isPointerType()) 8044 return PtrPtrKernelParam; 8045 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8046 PointeeType.getAddressSpace() == LangAS::opencl_private || 8047 PointeeType.getAddressSpace() == LangAS::Default) 8048 return InvalidAddrSpacePtrKernelParam; 8049 return PtrKernelParam; 8050 } 8051 8052 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 8053 // be used as builtin types. 8054 8055 if (PT->isImageType()) 8056 return PtrKernelParam; 8057 8058 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8059 return InvalidKernelParam; 8060 8061 // OpenCL extension spec v1.2 s9.5: 8062 // This extension adds support for half scalar and vector types as built-in 8063 // types that can be used for arithmetic operations, conversions etc. 8064 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8065 return InvalidKernelParam; 8066 8067 if (PT->isRecordType()) 8068 return RecordKernelParam; 8069 8070 return ValidKernelParam; 8071 } 8072 8073 static void checkIsValidOpenCLKernelParameter( 8074 Sema &S, 8075 Declarator &D, 8076 ParmVarDecl *Param, 8077 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8078 QualType PT = Param->getType(); 8079 8080 // Cache the valid types we encounter to avoid rechecking structs that are 8081 // used again 8082 if (ValidTypes.count(PT.getTypePtr())) 8083 return; 8084 8085 switch (getOpenCLKernelParameterType(S, PT)) { 8086 case PtrPtrKernelParam: 8087 // OpenCL v1.2 s6.9.a: 8088 // A kernel function argument cannot be declared as a 8089 // pointer to a pointer type. 8090 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8091 D.setInvalidType(); 8092 return; 8093 8094 case InvalidAddrSpacePtrKernelParam: 8095 // OpenCL v1.0 s6.5: 8096 // __kernel function arguments declared to be a pointer of a type can point 8097 // to one of the following address spaces only : __global, __local or 8098 // __constant. 8099 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8100 D.setInvalidType(); 8101 return; 8102 8103 // OpenCL v1.2 s6.9.k: 8104 // Arguments to kernel functions in a program cannot be declared with the 8105 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8106 // uintptr_t or a struct and/or union that contain fields declared to be 8107 // one of these built-in scalar types. 8108 8109 case InvalidKernelParam: 8110 // OpenCL v1.2 s6.8 n: 8111 // A kernel function argument cannot be declared 8112 // of event_t type. 8113 // Do not diagnose half type since it is diagnosed as invalid argument 8114 // type for any function elsewhere. 8115 if (!PT->isHalfType()) 8116 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8117 D.setInvalidType(); 8118 return; 8119 8120 case PtrKernelParam: 8121 case ValidKernelParam: 8122 ValidTypes.insert(PT.getTypePtr()); 8123 return; 8124 8125 case RecordKernelParam: 8126 break; 8127 } 8128 8129 // Track nested structs we will inspect 8130 SmallVector<const Decl *, 4> VisitStack; 8131 8132 // Track where we are in the nested structs. Items will migrate from 8133 // VisitStack to HistoryStack as we do the DFS for bad field. 8134 SmallVector<const FieldDecl *, 4> HistoryStack; 8135 HistoryStack.push_back(nullptr); 8136 8137 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8138 VisitStack.push_back(PD); 8139 8140 assert(VisitStack.back() && "First decl null?"); 8141 8142 do { 8143 const Decl *Next = VisitStack.pop_back_val(); 8144 if (!Next) { 8145 assert(!HistoryStack.empty()); 8146 // Found a marker, we have gone up a level 8147 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8148 ValidTypes.insert(Hist->getType().getTypePtr()); 8149 8150 continue; 8151 } 8152 8153 // Adds everything except the original parameter declaration (which is not a 8154 // field itself) to the history stack. 8155 const RecordDecl *RD; 8156 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8157 HistoryStack.push_back(Field); 8158 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8159 } else { 8160 RD = cast<RecordDecl>(Next); 8161 } 8162 8163 // Add a null marker so we know when we've gone back up a level 8164 VisitStack.push_back(nullptr); 8165 8166 for (const auto *FD : RD->fields()) { 8167 QualType QT = FD->getType(); 8168 8169 if (ValidTypes.count(QT.getTypePtr())) 8170 continue; 8171 8172 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8173 if (ParamType == ValidKernelParam) 8174 continue; 8175 8176 if (ParamType == RecordKernelParam) { 8177 VisitStack.push_back(FD); 8178 continue; 8179 } 8180 8181 // OpenCL v1.2 s6.9.p: 8182 // Arguments to kernel functions that are declared to be a struct or union 8183 // do not allow OpenCL objects to be passed as elements of the struct or 8184 // union. 8185 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8186 ParamType == InvalidAddrSpacePtrKernelParam) { 8187 S.Diag(Param->getLocation(), 8188 diag::err_record_with_pointers_kernel_param) 8189 << PT->isUnionType() 8190 << PT; 8191 } else { 8192 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8193 } 8194 8195 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8196 << PD->getDeclName(); 8197 8198 // We have an error, now let's go back up through history and show where 8199 // the offending field came from 8200 for (ArrayRef<const FieldDecl *>::const_iterator 8201 I = HistoryStack.begin() + 1, 8202 E = HistoryStack.end(); 8203 I != E; ++I) { 8204 const FieldDecl *OuterField = *I; 8205 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8206 << OuterField->getType(); 8207 } 8208 8209 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8210 << QT->isPointerType() 8211 << QT; 8212 D.setInvalidType(); 8213 return; 8214 } 8215 } while (!VisitStack.empty()); 8216 } 8217 8218 /// Find the DeclContext in which a tag is implicitly declared if we see an 8219 /// elaborated type specifier in the specified context, and lookup finds 8220 /// nothing. 8221 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8222 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8223 DC = DC->getParent(); 8224 return DC; 8225 } 8226 8227 /// Find the Scope in which a tag is implicitly declared if we see an 8228 /// elaborated type specifier in the specified context, and lookup finds 8229 /// nothing. 8230 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8231 while (S->isClassScope() || 8232 (LangOpts.CPlusPlus && 8233 S->isFunctionPrototypeScope()) || 8234 ((S->getFlags() & Scope::DeclScope) == 0) || 8235 (S->getEntity() && S->getEntity()->isTransparentContext())) 8236 S = S->getParent(); 8237 return S; 8238 } 8239 8240 NamedDecl* 8241 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8242 TypeSourceInfo *TInfo, LookupResult &Previous, 8243 MultiTemplateParamsArg TemplateParamLists, 8244 bool &AddToScope) { 8245 QualType R = TInfo->getType(); 8246 8247 assert(R.getTypePtr()->isFunctionType()); 8248 8249 // TODO: consider using NameInfo for diagnostic. 8250 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8251 DeclarationName Name = NameInfo.getName(); 8252 StorageClass SC = getFunctionStorageClass(*this, D); 8253 8254 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8255 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8256 diag::err_invalid_thread) 8257 << DeclSpec::getSpecifierName(TSCS); 8258 8259 if (D.isFirstDeclarationOfMember()) 8260 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8261 D.getIdentifierLoc()); 8262 8263 bool isFriend = false; 8264 FunctionTemplateDecl *FunctionTemplate = nullptr; 8265 bool isMemberSpecialization = false; 8266 bool isFunctionTemplateSpecialization = false; 8267 8268 bool isDependentClassScopeExplicitSpecialization = false; 8269 bool HasExplicitTemplateArgs = false; 8270 TemplateArgumentListInfo TemplateArgs; 8271 8272 bool isVirtualOkay = false; 8273 8274 DeclContext *OriginalDC = DC; 8275 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8276 8277 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8278 isVirtualOkay); 8279 if (!NewFD) return nullptr; 8280 8281 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8282 NewFD->setTopLevelDeclInObjCContainer(); 8283 8284 // Set the lexical context. If this is a function-scope declaration, or has a 8285 // C++ scope specifier, or is the object of a friend declaration, the lexical 8286 // context will be different from the semantic context. 8287 NewFD->setLexicalDeclContext(CurContext); 8288 8289 if (IsLocalExternDecl) 8290 NewFD->setLocalExternDecl(); 8291 8292 if (getLangOpts().CPlusPlus) { 8293 bool isInline = D.getDeclSpec().isInlineSpecified(); 8294 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8295 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8296 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8297 isFriend = D.getDeclSpec().isFriendSpecified(); 8298 if (isFriend && !isInline && D.isFunctionDefinition()) { 8299 // C++ [class.friend]p5 8300 // A function can be defined in a friend declaration of a 8301 // class . . . . Such a function is implicitly inline. 8302 NewFD->setImplicitlyInline(); 8303 } 8304 8305 // If this is a method defined in an __interface, and is not a constructor 8306 // or an overloaded operator, then set the pure flag (isVirtual will already 8307 // return true). 8308 if (const CXXRecordDecl *Parent = 8309 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8310 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8311 NewFD->setPure(true); 8312 8313 // C++ [class.union]p2 8314 // A union can have member functions, but not virtual functions. 8315 if (isVirtual && Parent->isUnion()) 8316 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8317 } 8318 8319 SetNestedNameSpecifier(NewFD, D); 8320 isMemberSpecialization = false; 8321 isFunctionTemplateSpecialization = false; 8322 if (D.isInvalidType()) 8323 NewFD->setInvalidDecl(); 8324 8325 // Match up the template parameter lists with the scope specifier, then 8326 // determine whether we have a template or a template specialization. 8327 bool Invalid = false; 8328 if (TemplateParameterList *TemplateParams = 8329 MatchTemplateParametersToScopeSpecifier( 8330 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8331 D.getCXXScopeSpec(), 8332 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8333 ? D.getName().TemplateId 8334 : nullptr, 8335 TemplateParamLists, isFriend, isMemberSpecialization, 8336 Invalid)) { 8337 if (TemplateParams->size() > 0) { 8338 // This is a function template 8339 8340 // Check that we can declare a template here. 8341 if (CheckTemplateDeclScope(S, TemplateParams)) 8342 NewFD->setInvalidDecl(); 8343 8344 // A destructor cannot be a template. 8345 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8346 Diag(NewFD->getLocation(), diag::err_destructor_template); 8347 NewFD->setInvalidDecl(); 8348 } 8349 8350 // If we're adding a template to a dependent context, we may need to 8351 // rebuilding some of the types used within the template parameter list, 8352 // now that we know what the current instantiation is. 8353 if (DC->isDependentContext()) { 8354 ContextRAII SavedContext(*this, DC); 8355 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8356 Invalid = true; 8357 } 8358 8359 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8360 NewFD->getLocation(), 8361 Name, TemplateParams, 8362 NewFD); 8363 FunctionTemplate->setLexicalDeclContext(CurContext); 8364 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8365 8366 // For source fidelity, store the other template param lists. 8367 if (TemplateParamLists.size() > 1) { 8368 NewFD->setTemplateParameterListsInfo(Context, 8369 TemplateParamLists.drop_back(1)); 8370 } 8371 } else { 8372 // This is a function template specialization. 8373 isFunctionTemplateSpecialization = true; 8374 // For source fidelity, store all the template param lists. 8375 if (TemplateParamLists.size() > 0) 8376 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8377 8378 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8379 if (isFriend) { 8380 // We want to remove the "template<>", found here. 8381 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8382 8383 // If we remove the template<> and the name is not a 8384 // template-id, we're actually silently creating a problem: 8385 // the friend declaration will refer to an untemplated decl, 8386 // and clearly the user wants a template specialization. So 8387 // we need to insert '<>' after the name. 8388 SourceLocation InsertLoc; 8389 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8390 InsertLoc = D.getName().getSourceRange().getEnd(); 8391 InsertLoc = getLocForEndOfToken(InsertLoc); 8392 } 8393 8394 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8395 << Name << RemoveRange 8396 << FixItHint::CreateRemoval(RemoveRange) 8397 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8398 } 8399 } 8400 } 8401 else { 8402 // All template param lists were matched against the scope specifier: 8403 // this is NOT (an explicit specialization of) a template. 8404 if (TemplateParamLists.size() > 0) 8405 // For source fidelity, store all the template param lists. 8406 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8407 } 8408 8409 if (Invalid) { 8410 NewFD->setInvalidDecl(); 8411 if (FunctionTemplate) 8412 FunctionTemplate->setInvalidDecl(); 8413 } 8414 8415 // C++ [dcl.fct.spec]p5: 8416 // The virtual specifier shall only be used in declarations of 8417 // nonstatic class member functions that appear within a 8418 // member-specification of a class declaration; see 10.3. 8419 // 8420 if (isVirtual && !NewFD->isInvalidDecl()) { 8421 if (!isVirtualOkay) { 8422 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8423 diag::err_virtual_non_function); 8424 } else if (!CurContext->isRecord()) { 8425 // 'virtual' was specified outside of the class. 8426 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8427 diag::err_virtual_out_of_class) 8428 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8429 } else if (NewFD->getDescribedFunctionTemplate()) { 8430 // C++ [temp.mem]p3: 8431 // A member function template shall not be virtual. 8432 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8433 diag::err_virtual_member_function_template) 8434 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8435 } else { 8436 // Okay: Add virtual to the method. 8437 NewFD->setVirtualAsWritten(true); 8438 } 8439 8440 if (getLangOpts().CPlusPlus14 && 8441 NewFD->getReturnType()->isUndeducedType()) 8442 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8443 } 8444 8445 if (getLangOpts().CPlusPlus14 && 8446 (NewFD->isDependentContext() || 8447 (isFriend && CurContext->isDependentContext())) && 8448 NewFD->getReturnType()->isUndeducedType()) { 8449 // If the function template is referenced directly (for instance, as a 8450 // member of the current instantiation), pretend it has a dependent type. 8451 // This is not really justified by the standard, but is the only sane 8452 // thing to do. 8453 // FIXME: For a friend function, we have not marked the function as being 8454 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8455 const FunctionProtoType *FPT = 8456 NewFD->getType()->castAs<FunctionProtoType>(); 8457 QualType Result = 8458 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8459 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8460 FPT->getExtProtoInfo())); 8461 } 8462 8463 // C++ [dcl.fct.spec]p3: 8464 // The inline specifier shall not appear on a block scope function 8465 // declaration. 8466 if (isInline && !NewFD->isInvalidDecl()) { 8467 if (CurContext->isFunctionOrMethod()) { 8468 // 'inline' is not allowed on block scope function declaration. 8469 Diag(D.getDeclSpec().getInlineSpecLoc(), 8470 diag::err_inline_declaration_block_scope) << Name 8471 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8472 } 8473 } 8474 8475 // C++ [dcl.fct.spec]p6: 8476 // The explicit specifier shall be used only in the declaration of a 8477 // constructor or conversion function within its class definition; 8478 // see 12.3.1 and 12.3.2. 8479 if (isExplicit && !NewFD->isInvalidDecl() && 8480 !isa<CXXDeductionGuideDecl>(NewFD)) { 8481 if (!CurContext->isRecord()) { 8482 // 'explicit' was specified outside of the class. 8483 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8484 diag::err_explicit_out_of_class) 8485 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8486 } else if (!isa<CXXConstructorDecl>(NewFD) && 8487 !isa<CXXConversionDecl>(NewFD)) { 8488 // 'explicit' was specified on a function that wasn't a constructor 8489 // or conversion function. 8490 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8491 diag::err_explicit_non_ctor_or_conv_function) 8492 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8493 } 8494 } 8495 8496 if (isConstexpr) { 8497 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8498 // are implicitly inline. 8499 NewFD->setImplicitlyInline(); 8500 8501 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8502 // be either constructors or to return a literal type. Therefore, 8503 // destructors cannot be declared constexpr. 8504 if (isa<CXXDestructorDecl>(NewFD)) 8505 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8506 } 8507 8508 // If __module_private__ was specified, mark the function accordingly. 8509 if (D.getDeclSpec().isModulePrivateSpecified()) { 8510 if (isFunctionTemplateSpecialization) { 8511 SourceLocation ModulePrivateLoc 8512 = D.getDeclSpec().getModulePrivateSpecLoc(); 8513 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8514 << 0 8515 << FixItHint::CreateRemoval(ModulePrivateLoc); 8516 } else { 8517 NewFD->setModulePrivate(); 8518 if (FunctionTemplate) 8519 FunctionTemplate->setModulePrivate(); 8520 } 8521 } 8522 8523 if (isFriend) { 8524 if (FunctionTemplate) { 8525 FunctionTemplate->setObjectOfFriendDecl(); 8526 FunctionTemplate->setAccess(AS_public); 8527 } 8528 NewFD->setObjectOfFriendDecl(); 8529 NewFD->setAccess(AS_public); 8530 } 8531 8532 // If a function is defined as defaulted or deleted, mark it as such now. 8533 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8534 // definition kind to FDK_Definition. 8535 switch (D.getFunctionDefinitionKind()) { 8536 case FDK_Declaration: 8537 case FDK_Definition: 8538 break; 8539 8540 case FDK_Defaulted: 8541 NewFD->setDefaulted(); 8542 break; 8543 8544 case FDK_Deleted: 8545 NewFD->setDeletedAsWritten(); 8546 break; 8547 } 8548 8549 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8550 D.isFunctionDefinition()) { 8551 // C++ [class.mfct]p2: 8552 // A member function may be defined (8.4) in its class definition, in 8553 // which case it is an inline member function (7.1.2) 8554 NewFD->setImplicitlyInline(); 8555 } 8556 8557 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8558 !CurContext->isRecord()) { 8559 // C++ [class.static]p1: 8560 // A data or function member of a class may be declared static 8561 // in a class definition, in which case it is a static member of 8562 // the class. 8563 8564 // Complain about the 'static' specifier if it's on an out-of-line 8565 // member function definition. 8566 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8567 diag::err_static_out_of_line) 8568 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8569 } 8570 8571 // C++11 [except.spec]p15: 8572 // A deallocation function with no exception-specification is treated 8573 // as if it were specified with noexcept(true). 8574 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8575 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8576 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8577 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8578 NewFD->setType(Context.getFunctionType( 8579 FPT->getReturnType(), FPT->getParamTypes(), 8580 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8581 } 8582 8583 // Filter out previous declarations that don't match the scope. 8584 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8585 D.getCXXScopeSpec().isNotEmpty() || 8586 isMemberSpecialization || 8587 isFunctionTemplateSpecialization); 8588 8589 // Handle GNU asm-label extension (encoded as an attribute). 8590 if (Expr *E = (Expr*) D.getAsmLabel()) { 8591 // The parser guarantees this is a string. 8592 StringLiteral *SE = cast<StringLiteral>(E); 8593 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8594 SE->getString(), 0)); 8595 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8596 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8597 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8598 if (I != ExtnameUndeclaredIdentifiers.end()) { 8599 if (isDeclExternC(NewFD)) { 8600 NewFD->addAttr(I->second); 8601 ExtnameUndeclaredIdentifiers.erase(I); 8602 } else 8603 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8604 << /*Variable*/0 << NewFD; 8605 } 8606 } 8607 8608 // Copy the parameter declarations from the declarator D to the function 8609 // declaration NewFD, if they are available. First scavenge them into Params. 8610 SmallVector<ParmVarDecl*, 16> Params; 8611 unsigned FTIIdx; 8612 if (D.isFunctionDeclarator(FTIIdx)) { 8613 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8614 8615 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8616 // function that takes no arguments, not a function that takes a 8617 // single void argument. 8618 // We let through "const void" here because Sema::GetTypeForDeclarator 8619 // already checks for that case. 8620 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8621 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8622 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8623 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8624 Param->setDeclContext(NewFD); 8625 Params.push_back(Param); 8626 8627 if (Param->isInvalidDecl()) 8628 NewFD->setInvalidDecl(); 8629 } 8630 } 8631 8632 if (!getLangOpts().CPlusPlus) { 8633 // In C, find all the tag declarations from the prototype and move them 8634 // into the function DeclContext. Remove them from the surrounding tag 8635 // injection context of the function, which is typically but not always 8636 // the TU. 8637 DeclContext *PrototypeTagContext = 8638 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8639 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8640 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8641 8642 // We don't want to reparent enumerators. Look at their parent enum 8643 // instead. 8644 if (!TD) { 8645 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8646 TD = cast<EnumDecl>(ECD->getDeclContext()); 8647 } 8648 if (!TD) 8649 continue; 8650 DeclContext *TagDC = TD->getLexicalDeclContext(); 8651 if (!TagDC->containsDecl(TD)) 8652 continue; 8653 TagDC->removeDecl(TD); 8654 TD->setDeclContext(NewFD); 8655 NewFD->addDecl(TD); 8656 8657 // Preserve the lexical DeclContext if it is not the surrounding tag 8658 // injection context of the FD. In this example, the semantic context of 8659 // E will be f and the lexical context will be S, while both the 8660 // semantic and lexical contexts of S will be f: 8661 // void f(struct S { enum E { a } f; } s); 8662 if (TagDC != PrototypeTagContext) 8663 TD->setLexicalDeclContext(TagDC); 8664 } 8665 } 8666 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8667 // When we're declaring a function with a typedef, typeof, etc as in the 8668 // following example, we'll need to synthesize (unnamed) 8669 // parameters for use in the declaration. 8670 // 8671 // @code 8672 // typedef void fn(int); 8673 // fn f; 8674 // @endcode 8675 8676 // Synthesize a parameter for each argument type. 8677 for (const auto &AI : FT->param_types()) { 8678 ParmVarDecl *Param = 8679 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8680 Param->setScopeInfo(0, Params.size()); 8681 Params.push_back(Param); 8682 } 8683 } else { 8684 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8685 "Should not need args for typedef of non-prototype fn"); 8686 } 8687 8688 // Finally, we know we have the right number of parameters, install them. 8689 NewFD->setParams(Params); 8690 8691 if (D.getDeclSpec().isNoreturnSpecified()) 8692 NewFD->addAttr( 8693 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8694 Context, 0)); 8695 8696 // Functions returning a variably modified type violate C99 6.7.5.2p2 8697 // because all functions have linkage. 8698 if (!NewFD->isInvalidDecl() && 8699 NewFD->getReturnType()->isVariablyModifiedType()) { 8700 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8701 NewFD->setInvalidDecl(); 8702 } 8703 8704 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8705 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8706 !NewFD->hasAttr<SectionAttr>()) { 8707 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8708 PragmaClangTextSection.SectionName, 8709 PragmaClangTextSection.PragmaLocation)); 8710 } 8711 8712 // Apply an implicit SectionAttr if #pragma code_seg is active. 8713 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8714 !NewFD->hasAttr<SectionAttr>()) { 8715 NewFD->addAttr( 8716 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8717 CodeSegStack.CurrentValue->getString(), 8718 CodeSegStack.CurrentPragmaLocation)); 8719 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8720 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8721 ASTContext::PSF_Read, 8722 NewFD)) 8723 NewFD->dropAttr<SectionAttr>(); 8724 } 8725 8726 // Handle attributes. 8727 ProcessDeclAttributes(S, NewFD, D); 8728 8729 if (getLangOpts().OpenCL) { 8730 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8731 // type declaration will generate a compilation error. 8732 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8733 if (AddressSpace != LangAS::Default) { 8734 Diag(NewFD->getLocation(), 8735 diag::err_opencl_return_value_with_address_space); 8736 NewFD->setInvalidDecl(); 8737 } 8738 } 8739 8740 if (!getLangOpts().CPlusPlus) { 8741 // Perform semantic checking on the function declaration. 8742 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8743 CheckMain(NewFD, D.getDeclSpec()); 8744 8745 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8746 CheckMSVCRTEntryPoint(NewFD); 8747 8748 if (!NewFD->isInvalidDecl()) 8749 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8750 isMemberSpecialization)); 8751 else if (!Previous.empty()) 8752 // Recover gracefully from an invalid redeclaration. 8753 D.setRedeclaration(true); 8754 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8755 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8756 "previous declaration set still overloaded"); 8757 8758 // Diagnose no-prototype function declarations with calling conventions that 8759 // don't support variadic calls. Only do this in C and do it after merging 8760 // possibly prototyped redeclarations. 8761 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8762 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8763 CallingConv CC = FT->getExtInfo().getCC(); 8764 if (!supportsVariadicCall(CC)) { 8765 // Windows system headers sometimes accidentally use stdcall without 8766 // (void) parameters, so we relax this to a warning. 8767 int DiagID = 8768 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8769 Diag(NewFD->getLocation(), DiagID) 8770 << FunctionType::getNameForCallConv(CC); 8771 } 8772 } 8773 } else { 8774 // C++11 [replacement.functions]p3: 8775 // The program's definitions shall not be specified as inline. 8776 // 8777 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8778 // 8779 // Suppress the diagnostic if the function is __attribute__((used)), since 8780 // that forces an external definition to be emitted. 8781 if (D.getDeclSpec().isInlineSpecified() && 8782 NewFD->isReplaceableGlobalAllocationFunction() && 8783 !NewFD->hasAttr<UsedAttr>()) 8784 Diag(D.getDeclSpec().getInlineSpecLoc(), 8785 diag::ext_operator_new_delete_declared_inline) 8786 << NewFD->getDeclName(); 8787 8788 // If the declarator is a template-id, translate the parser's template 8789 // argument list into our AST format. 8790 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8791 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8792 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8793 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8794 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8795 TemplateId->NumArgs); 8796 translateTemplateArguments(TemplateArgsPtr, 8797 TemplateArgs); 8798 8799 HasExplicitTemplateArgs = true; 8800 8801 if (NewFD->isInvalidDecl()) { 8802 HasExplicitTemplateArgs = false; 8803 } else if (FunctionTemplate) { 8804 // Function template with explicit template arguments. 8805 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8806 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8807 8808 HasExplicitTemplateArgs = false; 8809 } else { 8810 assert((isFunctionTemplateSpecialization || 8811 D.getDeclSpec().isFriendSpecified()) && 8812 "should have a 'template<>' for this decl"); 8813 // "friend void foo<>(int);" is an implicit specialization decl. 8814 isFunctionTemplateSpecialization = true; 8815 } 8816 } else if (isFriend && isFunctionTemplateSpecialization) { 8817 // This combination is only possible in a recovery case; the user 8818 // wrote something like: 8819 // template <> friend void foo(int); 8820 // which we're recovering from as if the user had written: 8821 // friend void foo<>(int); 8822 // Go ahead and fake up a template id. 8823 HasExplicitTemplateArgs = true; 8824 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8825 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8826 } 8827 8828 // We do not add HD attributes to specializations here because 8829 // they may have different constexpr-ness compared to their 8830 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8831 // may end up with different effective targets. Instead, a 8832 // specialization inherits its target attributes from its template 8833 // in the CheckFunctionTemplateSpecialization() call below. 8834 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8835 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8836 8837 // If it's a friend (and only if it's a friend), it's possible 8838 // that either the specialized function type or the specialized 8839 // template is dependent, and therefore matching will fail. In 8840 // this case, don't check the specialization yet. 8841 bool InstantiationDependent = false; 8842 if (isFunctionTemplateSpecialization && isFriend && 8843 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8844 TemplateSpecializationType::anyDependentTemplateArguments( 8845 TemplateArgs, 8846 InstantiationDependent))) { 8847 assert(HasExplicitTemplateArgs && 8848 "friend function specialization without template args"); 8849 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8850 Previous)) 8851 NewFD->setInvalidDecl(); 8852 } else if (isFunctionTemplateSpecialization) { 8853 if (CurContext->isDependentContext() && CurContext->isRecord() 8854 && !isFriend) { 8855 isDependentClassScopeExplicitSpecialization = true; 8856 } else if (!NewFD->isInvalidDecl() && 8857 CheckFunctionTemplateSpecialization( 8858 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8859 Previous)) 8860 NewFD->setInvalidDecl(); 8861 8862 // C++ [dcl.stc]p1: 8863 // A storage-class-specifier shall not be specified in an explicit 8864 // specialization (14.7.3) 8865 FunctionTemplateSpecializationInfo *Info = 8866 NewFD->getTemplateSpecializationInfo(); 8867 if (Info && SC != SC_None) { 8868 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8869 Diag(NewFD->getLocation(), 8870 diag::err_explicit_specialization_inconsistent_storage_class) 8871 << SC 8872 << FixItHint::CreateRemoval( 8873 D.getDeclSpec().getStorageClassSpecLoc()); 8874 8875 else 8876 Diag(NewFD->getLocation(), 8877 diag::ext_explicit_specialization_storage_class) 8878 << FixItHint::CreateRemoval( 8879 D.getDeclSpec().getStorageClassSpecLoc()); 8880 } 8881 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8882 if (CheckMemberSpecialization(NewFD, Previous)) 8883 NewFD->setInvalidDecl(); 8884 } 8885 8886 // Perform semantic checking on the function declaration. 8887 if (!isDependentClassScopeExplicitSpecialization) { 8888 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8889 CheckMain(NewFD, D.getDeclSpec()); 8890 8891 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8892 CheckMSVCRTEntryPoint(NewFD); 8893 8894 if (!NewFD->isInvalidDecl()) 8895 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8896 isMemberSpecialization)); 8897 else if (!Previous.empty()) 8898 // Recover gracefully from an invalid redeclaration. 8899 D.setRedeclaration(true); 8900 } 8901 8902 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8903 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8904 "previous declaration set still overloaded"); 8905 8906 NamedDecl *PrincipalDecl = (FunctionTemplate 8907 ? cast<NamedDecl>(FunctionTemplate) 8908 : NewFD); 8909 8910 if (isFriend && NewFD->getPreviousDecl()) { 8911 AccessSpecifier Access = AS_public; 8912 if (!NewFD->isInvalidDecl()) 8913 Access = NewFD->getPreviousDecl()->getAccess(); 8914 8915 NewFD->setAccess(Access); 8916 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8917 } 8918 8919 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8920 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8921 PrincipalDecl->setNonMemberOperator(); 8922 8923 // If we have a function template, check the template parameter 8924 // list. This will check and merge default template arguments. 8925 if (FunctionTemplate) { 8926 FunctionTemplateDecl *PrevTemplate = 8927 FunctionTemplate->getPreviousDecl(); 8928 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8929 PrevTemplate ? PrevTemplate->getTemplateParameters() 8930 : nullptr, 8931 D.getDeclSpec().isFriendSpecified() 8932 ? (D.isFunctionDefinition() 8933 ? TPC_FriendFunctionTemplateDefinition 8934 : TPC_FriendFunctionTemplate) 8935 : (D.getCXXScopeSpec().isSet() && 8936 DC && DC->isRecord() && 8937 DC->isDependentContext()) 8938 ? TPC_ClassTemplateMember 8939 : TPC_FunctionTemplate); 8940 } 8941 8942 if (NewFD->isInvalidDecl()) { 8943 // Ignore all the rest of this. 8944 } else if (!D.isRedeclaration()) { 8945 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8946 AddToScope }; 8947 // Fake up an access specifier if it's supposed to be a class member. 8948 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8949 NewFD->setAccess(AS_public); 8950 8951 // Qualified decls generally require a previous declaration. 8952 if (D.getCXXScopeSpec().isSet()) { 8953 // ...with the major exception of templated-scope or 8954 // dependent-scope friend declarations. 8955 8956 // TODO: we currently also suppress this check in dependent 8957 // contexts because (1) the parameter depth will be off when 8958 // matching friend templates and (2) we might actually be 8959 // selecting a friend based on a dependent factor. But there 8960 // are situations where these conditions don't apply and we 8961 // can actually do this check immediately. 8962 if (isFriend && 8963 (TemplateParamLists.size() || 8964 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8965 CurContext->isDependentContext())) { 8966 // ignore these 8967 } else { 8968 // The user tried to provide an out-of-line definition for a 8969 // function that is a member of a class or namespace, but there 8970 // was no such member function declared (C++ [class.mfct]p2, 8971 // C++ [namespace.memdef]p2). For example: 8972 // 8973 // class X { 8974 // void f() const; 8975 // }; 8976 // 8977 // void X::f() { } // ill-formed 8978 // 8979 // Complain about this problem, and attempt to suggest close 8980 // matches (e.g., those that differ only in cv-qualifiers and 8981 // whether the parameter types are references). 8982 8983 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8984 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8985 AddToScope = ExtraArgs.AddToScope; 8986 return Result; 8987 } 8988 } 8989 8990 // Unqualified local friend declarations are required to resolve 8991 // to something. 8992 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8993 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8994 *this, Previous, NewFD, ExtraArgs, true, S)) { 8995 AddToScope = ExtraArgs.AddToScope; 8996 return Result; 8997 } 8998 } 8999 } else if (!D.isFunctionDefinition() && 9000 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9001 !isFriend && !isFunctionTemplateSpecialization && 9002 !isMemberSpecialization) { 9003 // An out-of-line member function declaration must also be a 9004 // definition (C++ [class.mfct]p2). 9005 // Note that this is not the case for explicit specializations of 9006 // function templates or member functions of class templates, per 9007 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9008 // extension for compatibility with old SWIG code which likes to 9009 // generate them. 9010 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9011 << D.getCXXScopeSpec().getRange(); 9012 } 9013 } 9014 9015 ProcessPragmaWeak(S, NewFD); 9016 checkAttributesAfterMerging(*this, *NewFD); 9017 9018 AddKnownFunctionAttributes(NewFD); 9019 9020 if (NewFD->hasAttr<OverloadableAttr>() && 9021 !NewFD->getType()->getAs<FunctionProtoType>()) { 9022 Diag(NewFD->getLocation(), 9023 diag::err_attribute_overloadable_no_prototype) 9024 << NewFD; 9025 9026 // Turn this into a variadic function with no parameters. 9027 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9028 FunctionProtoType::ExtProtoInfo EPI( 9029 Context.getDefaultCallingConvention(true, false)); 9030 EPI.Variadic = true; 9031 EPI.ExtInfo = FT->getExtInfo(); 9032 9033 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9034 NewFD->setType(R); 9035 } 9036 9037 // If there's a #pragma GCC visibility in scope, and this isn't a class 9038 // member, set the visibility of this function. 9039 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9040 AddPushedVisibilityAttribute(NewFD); 9041 9042 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9043 // marking the function. 9044 AddCFAuditedAttribute(NewFD); 9045 9046 // If this is a function definition, check if we have to apply optnone due to 9047 // a pragma. 9048 if(D.isFunctionDefinition()) 9049 AddRangeBasedOptnone(NewFD); 9050 9051 // If this is the first declaration of an extern C variable, update 9052 // the map of such variables. 9053 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9054 isIncompleteDeclExternC(*this, NewFD)) 9055 RegisterLocallyScopedExternCDecl(NewFD, S); 9056 9057 // Set this FunctionDecl's range up to the right paren. 9058 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9059 9060 if (D.isRedeclaration() && !Previous.empty()) { 9061 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9062 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9063 isMemberSpecialization || 9064 isFunctionTemplateSpecialization, 9065 D.isFunctionDefinition()); 9066 } 9067 9068 if (getLangOpts().CUDA) { 9069 IdentifierInfo *II = NewFD->getIdentifier(); 9070 if (II && 9071 II->isStr(getLangOpts().HIP ? "hipConfigureCall" 9072 : "cudaConfigureCall") && 9073 !NewFD->isInvalidDecl() && 9074 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9075 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9076 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9077 Context.setcudaConfigureCallDecl(NewFD); 9078 } 9079 9080 // Variadic functions, other than a *declaration* of printf, are not allowed 9081 // in device-side CUDA code, unless someone passed 9082 // -fcuda-allow-variadic-functions. 9083 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9084 (NewFD->hasAttr<CUDADeviceAttr>() || 9085 NewFD->hasAttr<CUDAGlobalAttr>()) && 9086 !(II && II->isStr("printf") && NewFD->isExternC() && 9087 !D.isFunctionDefinition())) { 9088 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9089 } 9090 } 9091 9092 MarkUnusedFileScopedDecl(NewFD); 9093 9094 if (getLangOpts().CPlusPlus) { 9095 if (FunctionTemplate) { 9096 if (NewFD->isInvalidDecl()) 9097 FunctionTemplate->setInvalidDecl(); 9098 return FunctionTemplate; 9099 } 9100 9101 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9102 CompleteMemberSpecialization(NewFD, Previous); 9103 } 9104 9105 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9106 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9107 if ((getLangOpts().OpenCLVersion >= 120) 9108 && (SC == SC_Static)) { 9109 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9110 D.setInvalidType(); 9111 } 9112 9113 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9114 if (!NewFD->getReturnType()->isVoidType()) { 9115 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9116 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9117 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9118 : FixItHint()); 9119 D.setInvalidType(); 9120 } 9121 9122 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9123 for (auto Param : NewFD->parameters()) 9124 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9125 } 9126 for (const ParmVarDecl *Param : NewFD->parameters()) { 9127 QualType PT = Param->getType(); 9128 9129 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9130 // types. 9131 if (getLangOpts().OpenCLVersion >= 200) { 9132 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9133 QualType ElemTy = PipeTy->getElementType(); 9134 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9135 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9136 D.setInvalidType(); 9137 } 9138 } 9139 } 9140 } 9141 9142 // Here we have an function template explicit specialization at class scope. 9143 // The actual specialization will be postponed to template instatiation 9144 // time via the ClassScopeFunctionSpecializationDecl node. 9145 if (isDependentClassScopeExplicitSpecialization) { 9146 ClassScopeFunctionSpecializationDecl *NewSpec = 9147 ClassScopeFunctionSpecializationDecl::Create( 9148 Context, CurContext, NewFD->getLocation(), 9149 cast<CXXMethodDecl>(NewFD), 9150 HasExplicitTemplateArgs, TemplateArgs); 9151 CurContext->addDecl(NewSpec); 9152 AddToScope = false; 9153 } 9154 9155 // Diagnose availability attributes. Availability cannot be used on functions 9156 // that are run during load/unload. 9157 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9158 if (NewFD->hasAttr<ConstructorAttr>()) { 9159 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9160 << 1; 9161 NewFD->dropAttr<AvailabilityAttr>(); 9162 } 9163 if (NewFD->hasAttr<DestructorAttr>()) { 9164 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9165 << 2; 9166 NewFD->dropAttr<AvailabilityAttr>(); 9167 } 9168 } 9169 9170 return NewFD; 9171 } 9172 9173 /// Checks if the new declaration declared in dependent context must be 9174 /// put in the same redeclaration chain as the specified declaration. 9175 /// 9176 /// \param D Declaration that is checked. 9177 /// \param PrevDecl Previous declaration found with proper lookup method for the 9178 /// same declaration name. 9179 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9180 /// belongs to. 9181 /// 9182 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9183 // Any declarations should be put into redeclaration chains except for 9184 // friend declaration in a dependent context that names a function in 9185 // namespace scope. 9186 // 9187 // This allows to compile code like: 9188 // 9189 // void func(); 9190 // template<typename T> class C1 { friend void func() { } }; 9191 // template<typename T> class C2 { friend void func() { } }; 9192 // 9193 // This code snippet is a valid code unless both templates are instantiated. 9194 return !(D->getLexicalDeclContext()->isDependentContext() && 9195 D->getDeclContext()->isFileContext() && 9196 D->getFriendObjectKind() != Decl::FOK_None); 9197 } 9198 9199 /// Check the target attribute of the function for MultiVersion 9200 /// validity. 9201 /// 9202 /// Returns true if there was an error, false otherwise. 9203 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9204 const auto *TA = FD->getAttr<TargetAttr>(); 9205 assert(TA && "MultiVersion Candidate requires a target attribute"); 9206 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9207 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9208 enum ErrType { Feature = 0, Architecture = 1 }; 9209 9210 if (!ParseInfo.Architecture.empty() && 9211 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9212 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9213 << Architecture << ParseInfo.Architecture; 9214 return true; 9215 } 9216 9217 for (const auto &Feat : ParseInfo.Features) { 9218 auto BareFeat = StringRef{Feat}.substr(1); 9219 if (Feat[0] == '-') { 9220 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9221 << Feature << ("no-" + BareFeat).str(); 9222 return true; 9223 } 9224 9225 if (!TargetInfo.validateCpuSupports(BareFeat) || 9226 !TargetInfo.isValidFeatureName(BareFeat)) { 9227 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9228 << Feature << BareFeat; 9229 return true; 9230 } 9231 } 9232 return false; 9233 } 9234 9235 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9236 const FunctionDecl *NewFD, 9237 bool CausesMV) { 9238 enum DoesntSupport { 9239 FuncTemplates = 0, 9240 VirtFuncs = 1, 9241 DeducedReturn = 2, 9242 Constructors = 3, 9243 Destructors = 4, 9244 DeletedFuncs = 5, 9245 DefaultedFuncs = 6 9246 }; 9247 enum Different { 9248 CallingConv = 0, 9249 ReturnType = 1, 9250 ConstexprSpec = 2, 9251 InlineSpec = 3, 9252 StorageClass = 4, 9253 Linkage = 5 9254 }; 9255 9256 // For now, disallow all other attributes. These should be opt-in, but 9257 // an analysis of all of them is a future FIXME. 9258 if (CausesMV && OldFD && 9259 std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) { 9260 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs); 9261 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9262 return true; 9263 } 9264 9265 if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1) 9266 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs); 9267 9268 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9269 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9270 << FuncTemplates; 9271 9272 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9273 if (NewCXXFD->isVirtual()) 9274 return S.Diag(NewCXXFD->getLocation(), 9275 diag::err_multiversion_doesnt_support) 9276 << VirtFuncs; 9277 9278 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9279 return S.Diag(NewCXXCtor->getLocation(), 9280 diag::err_multiversion_doesnt_support) 9281 << Constructors; 9282 9283 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9284 return S.Diag(NewCXXDtor->getLocation(), 9285 diag::err_multiversion_doesnt_support) 9286 << Destructors; 9287 } 9288 9289 if (NewFD->isDeleted()) 9290 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9291 << DeletedFuncs; 9292 9293 if (NewFD->isDefaulted()) 9294 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9295 << DefaultedFuncs; 9296 9297 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9298 const auto *NewType = cast<FunctionType>(NewQType); 9299 QualType NewReturnType = NewType->getReturnType(); 9300 9301 if (NewReturnType->isUndeducedType()) 9302 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9303 << DeducedReturn; 9304 9305 // Only allow transition to MultiVersion if it hasn't been used. 9306 if (OldFD && CausesMV && OldFD->isUsed(false)) 9307 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9308 9309 // Ensure the return type is identical. 9310 if (OldFD) { 9311 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9312 const auto *OldType = cast<FunctionType>(OldQType); 9313 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9314 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9315 9316 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9317 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9318 << CallingConv; 9319 9320 QualType OldReturnType = OldType->getReturnType(); 9321 9322 if (OldReturnType != NewReturnType) 9323 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9324 << ReturnType; 9325 9326 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9327 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9328 << ConstexprSpec; 9329 9330 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9331 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9332 << InlineSpec; 9333 9334 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9335 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9336 << StorageClass; 9337 9338 if (OldFD->isExternC() != NewFD->isExternC()) 9339 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9340 << Linkage; 9341 9342 if (S.CheckEquivalentExceptionSpec( 9343 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9344 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9345 return true; 9346 } 9347 return false; 9348 } 9349 9350 /// Check the validity of a mulitversion function declaration. 9351 /// Also sets the multiversion'ness' of the function itself. 9352 /// 9353 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9354 /// 9355 /// Returns true if there was an error, false otherwise. 9356 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9357 bool &Redeclaration, NamedDecl *&OldDecl, 9358 bool &MergeTypeWithPrevious, 9359 LookupResult &Previous) { 9360 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9361 if (NewFD->isMain()) { 9362 if (NewTA && NewTA->isDefaultVersion()) { 9363 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9364 NewFD->setInvalidDecl(); 9365 return true; 9366 } 9367 return false; 9368 } 9369 9370 // If there is no matching previous decl, only 'default' can 9371 // cause MultiVersioning. 9372 if (!OldDecl) { 9373 if (NewTA && NewTA->isDefaultVersion()) { 9374 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 9375 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9376 NewFD->setInvalidDecl(); 9377 return true; 9378 } 9379 if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) { 9380 NewFD->setInvalidDecl(); 9381 return true; 9382 } 9383 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9384 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9385 NewFD->setInvalidDecl(); 9386 return true; 9387 } 9388 9389 NewFD->setIsMultiVersion(); 9390 } 9391 return false; 9392 } 9393 9394 if (OldDecl->getDeclContext()->getRedeclContext() != 9395 NewFD->getDeclContext()->getRedeclContext()) 9396 return false; 9397 9398 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9399 // Unresolved 'using' statements (the other way OldDecl can be not a function) 9400 // likely cannot cause a problem here. 9401 if (!OldFD) 9402 return false; 9403 9404 if (!OldFD->isMultiVersion() && !NewTA) 9405 return false; 9406 9407 if (OldFD->isMultiVersion() && !NewTA) { 9408 S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl); 9409 NewFD->setInvalidDecl(); 9410 return true; 9411 } 9412 9413 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9414 // Sort order doesn't matter, it just needs to be consistent. 9415 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end()); 9416 9417 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9418 if (!OldFD->isMultiVersion()) { 9419 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9420 // to change, this is a simple redeclaration. 9421 if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()) 9422 return false; 9423 9424 // Otherwise, this decl causes MultiVersioning. 9425 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9426 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9427 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9428 NewFD->setInvalidDecl(); 9429 return true; 9430 } 9431 9432 if (!OldFD->getType()->getAs<FunctionProtoType>()) { 9433 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9434 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9435 NewFD->setInvalidDecl(); 9436 return true; 9437 } 9438 9439 if (CheckMultiVersionValue(S, NewFD)) { 9440 NewFD->setInvalidDecl(); 9441 return true; 9442 } 9443 9444 if (CheckMultiVersionValue(S, OldFD)) { 9445 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9446 NewFD->setInvalidDecl(); 9447 return true; 9448 } 9449 9450 TargetAttr::ParsedTargetAttr OldParsed = 9451 OldTA->parse(std::less<std::string>()); 9452 9453 if (OldParsed == NewParsed) { 9454 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9455 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9456 NewFD->setInvalidDecl(); 9457 return true; 9458 } 9459 9460 for (const auto *FD : OldFD->redecls()) { 9461 const auto *CurTA = FD->getAttr<TargetAttr>(); 9462 if (!CurTA || CurTA->isInherited()) { 9463 S.Diag(FD->getLocation(), diag::err_target_required_in_redecl); 9464 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9465 NewFD->setInvalidDecl(); 9466 return true; 9467 } 9468 } 9469 9470 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) { 9471 NewFD->setInvalidDecl(); 9472 return true; 9473 } 9474 9475 OldFD->setIsMultiVersion(); 9476 NewFD->setIsMultiVersion(); 9477 Redeclaration = false; 9478 MergeTypeWithPrevious = false; 9479 OldDecl = nullptr; 9480 Previous.clear(); 9481 return false; 9482 } 9483 9484 bool UseMemberUsingDeclRules = 9485 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9486 9487 // Next, check ALL non-overloads to see if this is a redeclaration of a 9488 // previous member of the MultiVersion set. 9489 for (NamedDecl *ND : Previous) { 9490 FunctionDecl *CurFD = ND->getAsFunction(); 9491 if (!CurFD) 9492 continue; 9493 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9494 continue; 9495 9496 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9497 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9498 NewFD->setIsMultiVersion(); 9499 Redeclaration = true; 9500 OldDecl = ND; 9501 return false; 9502 } 9503 9504 TargetAttr::ParsedTargetAttr CurParsed = 9505 CurTA->parse(std::less<std::string>()); 9506 9507 if (CurParsed == NewParsed) { 9508 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9509 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9510 NewFD->setInvalidDecl(); 9511 return true; 9512 } 9513 } 9514 9515 // Else, this is simply a non-redecl case. 9516 if (CheckMultiVersionValue(S, NewFD)) { 9517 NewFD->setInvalidDecl(); 9518 return true; 9519 } 9520 9521 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) { 9522 NewFD->setInvalidDecl(); 9523 return true; 9524 } 9525 9526 NewFD->setIsMultiVersion(); 9527 Redeclaration = false; 9528 MergeTypeWithPrevious = false; 9529 OldDecl = nullptr; 9530 Previous.clear(); 9531 return false; 9532 } 9533 9534 /// Perform semantic checking of a new function declaration. 9535 /// 9536 /// Performs semantic analysis of the new function declaration 9537 /// NewFD. This routine performs all semantic checking that does not 9538 /// require the actual declarator involved in the declaration, and is 9539 /// used both for the declaration of functions as they are parsed 9540 /// (called via ActOnDeclarator) and for the declaration of functions 9541 /// that have been instantiated via C++ template instantiation (called 9542 /// via InstantiateDecl). 9543 /// 9544 /// \param IsMemberSpecialization whether this new function declaration is 9545 /// a member specialization (that replaces any definition provided by the 9546 /// previous declaration). 9547 /// 9548 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9549 /// 9550 /// \returns true if the function declaration is a redeclaration. 9551 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9552 LookupResult &Previous, 9553 bool IsMemberSpecialization) { 9554 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9555 "Variably modified return types are not handled here"); 9556 9557 // Determine whether the type of this function should be merged with 9558 // a previous visible declaration. This never happens for functions in C++, 9559 // and always happens in C if the previous declaration was visible. 9560 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9561 !Previous.isShadowed(); 9562 9563 bool Redeclaration = false; 9564 NamedDecl *OldDecl = nullptr; 9565 bool MayNeedOverloadableChecks = false; 9566 9567 // Merge or overload the declaration with an existing declaration of 9568 // the same name, if appropriate. 9569 if (!Previous.empty()) { 9570 // Determine whether NewFD is an overload of PrevDecl or 9571 // a declaration that requires merging. If it's an overload, 9572 // there's no more work to do here; we'll just add the new 9573 // function to the scope. 9574 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9575 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9576 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9577 Redeclaration = true; 9578 OldDecl = Candidate; 9579 } 9580 } else { 9581 MayNeedOverloadableChecks = true; 9582 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9583 /*NewIsUsingDecl*/ false)) { 9584 case Ovl_Match: 9585 Redeclaration = true; 9586 break; 9587 9588 case Ovl_NonFunction: 9589 Redeclaration = true; 9590 break; 9591 9592 case Ovl_Overload: 9593 Redeclaration = false; 9594 break; 9595 } 9596 } 9597 } 9598 9599 // Check for a previous extern "C" declaration with this name. 9600 if (!Redeclaration && 9601 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9602 if (!Previous.empty()) { 9603 // This is an extern "C" declaration with the same name as a previous 9604 // declaration, and thus redeclares that entity... 9605 Redeclaration = true; 9606 OldDecl = Previous.getFoundDecl(); 9607 MergeTypeWithPrevious = false; 9608 9609 // ... except in the presence of __attribute__((overloadable)). 9610 if (OldDecl->hasAttr<OverloadableAttr>() || 9611 NewFD->hasAttr<OverloadableAttr>()) { 9612 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9613 MayNeedOverloadableChecks = true; 9614 Redeclaration = false; 9615 OldDecl = nullptr; 9616 } 9617 } 9618 } 9619 } 9620 9621 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 9622 MergeTypeWithPrevious, Previous)) 9623 return Redeclaration; 9624 9625 // C++11 [dcl.constexpr]p8: 9626 // A constexpr specifier for a non-static member function that is not 9627 // a constructor declares that member function to be const. 9628 // 9629 // This needs to be delayed until we know whether this is an out-of-line 9630 // definition of a static member function. 9631 // 9632 // This rule is not present in C++1y, so we produce a backwards 9633 // compatibility warning whenever it happens in C++11. 9634 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9635 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9636 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9637 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9638 CXXMethodDecl *OldMD = nullptr; 9639 if (OldDecl) 9640 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9641 if (!OldMD || !OldMD->isStatic()) { 9642 const FunctionProtoType *FPT = 9643 MD->getType()->castAs<FunctionProtoType>(); 9644 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9645 EPI.TypeQuals |= Qualifiers::Const; 9646 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9647 FPT->getParamTypes(), EPI)); 9648 9649 // Warn that we did this, if we're not performing template instantiation. 9650 // In that case, we'll have warned already when the template was defined. 9651 if (!inTemplateInstantiation()) { 9652 SourceLocation AddConstLoc; 9653 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9654 .IgnoreParens().getAs<FunctionTypeLoc>()) 9655 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9656 9657 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9658 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9659 } 9660 } 9661 } 9662 9663 if (Redeclaration) { 9664 // NewFD and OldDecl represent declarations that need to be 9665 // merged. 9666 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9667 NewFD->setInvalidDecl(); 9668 return Redeclaration; 9669 } 9670 9671 Previous.clear(); 9672 Previous.addDecl(OldDecl); 9673 9674 if (FunctionTemplateDecl *OldTemplateDecl = 9675 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9676 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 9677 NewFD->setPreviousDeclaration(OldFD); 9678 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9679 FunctionTemplateDecl *NewTemplateDecl 9680 = NewFD->getDescribedFunctionTemplate(); 9681 assert(NewTemplateDecl && "Template/non-template mismatch"); 9682 if (NewFD->isCXXClassMember()) { 9683 NewFD->setAccess(OldTemplateDecl->getAccess()); 9684 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9685 } 9686 9687 // If this is an explicit specialization of a member that is a function 9688 // template, mark it as a member specialization. 9689 if (IsMemberSpecialization && 9690 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9691 NewTemplateDecl->setMemberSpecialization(); 9692 assert(OldTemplateDecl->isMemberSpecialization()); 9693 // Explicit specializations of a member template do not inherit deleted 9694 // status from the parent member template that they are specializing. 9695 if (OldFD->isDeleted()) { 9696 // FIXME: This assert will not hold in the presence of modules. 9697 assert(OldFD->getCanonicalDecl() == OldFD); 9698 // FIXME: We need an update record for this AST mutation. 9699 OldFD->setDeletedAsWritten(false); 9700 } 9701 } 9702 9703 } else { 9704 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9705 auto *OldFD = cast<FunctionDecl>(OldDecl); 9706 // This needs to happen first so that 'inline' propagates. 9707 NewFD->setPreviousDeclaration(OldFD); 9708 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9709 if (NewFD->isCXXClassMember()) 9710 NewFD->setAccess(OldFD->getAccess()); 9711 } 9712 } 9713 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9714 !NewFD->getAttr<OverloadableAttr>()) { 9715 assert((Previous.empty() || 9716 llvm::any_of(Previous, 9717 [](const NamedDecl *ND) { 9718 return ND->hasAttr<OverloadableAttr>(); 9719 })) && 9720 "Non-redecls shouldn't happen without overloadable present"); 9721 9722 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9723 const auto *FD = dyn_cast<FunctionDecl>(ND); 9724 return FD && !FD->hasAttr<OverloadableAttr>(); 9725 }); 9726 9727 if (OtherUnmarkedIter != Previous.end()) { 9728 Diag(NewFD->getLocation(), 9729 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9730 Diag((*OtherUnmarkedIter)->getLocation(), 9731 diag::note_attribute_overloadable_prev_overload) 9732 << false; 9733 9734 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9735 } 9736 } 9737 9738 // Semantic checking for this function declaration (in isolation). 9739 9740 if (getLangOpts().CPlusPlus) { 9741 // C++-specific checks. 9742 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9743 CheckConstructor(Constructor); 9744 } else if (CXXDestructorDecl *Destructor = 9745 dyn_cast<CXXDestructorDecl>(NewFD)) { 9746 CXXRecordDecl *Record = Destructor->getParent(); 9747 QualType ClassType = Context.getTypeDeclType(Record); 9748 9749 // FIXME: Shouldn't we be able to perform this check even when the class 9750 // type is dependent? Both gcc and edg can handle that. 9751 if (!ClassType->isDependentType()) { 9752 DeclarationName Name 9753 = Context.DeclarationNames.getCXXDestructorName( 9754 Context.getCanonicalType(ClassType)); 9755 if (NewFD->getDeclName() != Name) { 9756 Diag(NewFD->getLocation(), diag::err_destructor_name); 9757 NewFD->setInvalidDecl(); 9758 return Redeclaration; 9759 } 9760 } 9761 } else if (CXXConversionDecl *Conversion 9762 = dyn_cast<CXXConversionDecl>(NewFD)) { 9763 ActOnConversionDeclarator(Conversion); 9764 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9765 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9766 CheckDeductionGuideTemplate(TD); 9767 9768 // A deduction guide is not on the list of entities that can be 9769 // explicitly specialized. 9770 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9771 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9772 << /*explicit specialization*/ 1; 9773 } 9774 9775 // Find any virtual functions that this function overrides. 9776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9777 if (!Method->isFunctionTemplateSpecialization() && 9778 !Method->getDescribedFunctionTemplate() && 9779 Method->isCanonicalDecl()) { 9780 if (AddOverriddenMethods(Method->getParent(), Method)) { 9781 // If the function was marked as "static", we have a problem. 9782 if (NewFD->getStorageClass() == SC_Static) { 9783 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9784 } 9785 } 9786 } 9787 9788 if (Method->isStatic()) 9789 checkThisInStaticMemberFunctionType(Method); 9790 } 9791 9792 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9793 if (NewFD->isOverloadedOperator() && 9794 CheckOverloadedOperatorDeclaration(NewFD)) { 9795 NewFD->setInvalidDecl(); 9796 return Redeclaration; 9797 } 9798 9799 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9800 if (NewFD->getLiteralIdentifier() && 9801 CheckLiteralOperatorDeclaration(NewFD)) { 9802 NewFD->setInvalidDecl(); 9803 return Redeclaration; 9804 } 9805 9806 // In C++, check default arguments now that we have merged decls. Unless 9807 // the lexical context is the class, because in this case this is done 9808 // during delayed parsing anyway. 9809 if (!CurContext->isRecord()) 9810 CheckCXXDefaultArguments(NewFD); 9811 9812 // If this function declares a builtin function, check the type of this 9813 // declaration against the expected type for the builtin. 9814 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9815 ASTContext::GetBuiltinTypeError Error; 9816 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9817 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9818 // If the type of the builtin differs only in its exception 9819 // specification, that's OK. 9820 // FIXME: If the types do differ in this way, it would be better to 9821 // retain the 'noexcept' form of the type. 9822 if (!T.isNull() && 9823 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9824 NewFD->getType())) 9825 // The type of this function differs from the type of the builtin, 9826 // so forget about the builtin entirely. 9827 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9828 } 9829 9830 // If this function is declared as being extern "C", then check to see if 9831 // the function returns a UDT (class, struct, or union type) that is not C 9832 // compatible, and if it does, warn the user. 9833 // But, issue any diagnostic on the first declaration only. 9834 if (Previous.empty() && NewFD->isExternC()) { 9835 QualType R = NewFD->getReturnType(); 9836 if (R->isIncompleteType() && !R->isVoidType()) 9837 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9838 << NewFD << R; 9839 else if (!R.isPODType(Context) && !R->isVoidType() && 9840 !R->isObjCObjectPointerType()) 9841 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9842 } 9843 9844 // C++1z [dcl.fct]p6: 9845 // [...] whether the function has a non-throwing exception-specification 9846 // [is] part of the function type 9847 // 9848 // This results in an ABI break between C++14 and C++17 for functions whose 9849 // declared type includes an exception-specification in a parameter or 9850 // return type. (Exception specifications on the function itself are OK in 9851 // most cases, and exception specifications are not permitted in most other 9852 // contexts where they could make it into a mangling.) 9853 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 9854 auto HasNoexcept = [&](QualType T) -> bool { 9855 // Strip off declarator chunks that could be between us and a function 9856 // type. We don't need to look far, exception specifications are very 9857 // restricted prior to C++17. 9858 if (auto *RT = T->getAs<ReferenceType>()) 9859 T = RT->getPointeeType(); 9860 else if (T->isAnyPointerType()) 9861 T = T->getPointeeType(); 9862 else if (auto *MPT = T->getAs<MemberPointerType>()) 9863 T = MPT->getPointeeType(); 9864 if (auto *FPT = T->getAs<FunctionProtoType>()) 9865 if (FPT->isNothrow()) 9866 return true; 9867 return false; 9868 }; 9869 9870 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9871 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9872 for (QualType T : FPT->param_types()) 9873 AnyNoexcept |= HasNoexcept(T); 9874 if (AnyNoexcept) 9875 Diag(NewFD->getLocation(), 9876 diag::warn_cxx17_compat_exception_spec_in_signature) 9877 << NewFD; 9878 } 9879 9880 if (!Redeclaration && LangOpts.CUDA) 9881 checkCUDATargetOverload(NewFD, Previous); 9882 } 9883 return Redeclaration; 9884 } 9885 9886 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9887 // C++11 [basic.start.main]p3: 9888 // A program that [...] declares main to be inline, static or 9889 // constexpr is ill-formed. 9890 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9891 // appear in a declaration of main. 9892 // static main is not an error under C99, but we should warn about it. 9893 // We accept _Noreturn main as an extension. 9894 if (FD->getStorageClass() == SC_Static) 9895 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9896 ? diag::err_static_main : diag::warn_static_main) 9897 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9898 if (FD->isInlineSpecified()) 9899 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9900 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9901 if (DS.isNoreturnSpecified()) { 9902 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9903 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9904 Diag(NoreturnLoc, diag::ext_noreturn_main); 9905 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9906 << FixItHint::CreateRemoval(NoreturnRange); 9907 } 9908 if (FD->isConstexpr()) { 9909 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9910 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9911 FD->setConstexpr(false); 9912 } 9913 9914 if (getLangOpts().OpenCL) { 9915 Diag(FD->getLocation(), diag::err_opencl_no_main) 9916 << FD->hasAttr<OpenCLKernelAttr>(); 9917 FD->setInvalidDecl(); 9918 return; 9919 } 9920 9921 QualType T = FD->getType(); 9922 assert(T->isFunctionType() && "function decl is not of function type"); 9923 const FunctionType* FT = T->castAs<FunctionType>(); 9924 9925 // Set default calling convention for main() 9926 if (FT->getCallConv() != CC_C) { 9927 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 9928 FD->setType(QualType(FT, 0)); 9929 T = Context.getCanonicalType(FD->getType()); 9930 } 9931 9932 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9933 // In C with GNU extensions we allow main() to have non-integer return 9934 // type, but we should warn about the extension, and we disable the 9935 // implicit-return-zero rule. 9936 9937 // GCC in C mode accepts qualified 'int'. 9938 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9939 FD->setHasImplicitReturnZero(true); 9940 else { 9941 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9942 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9943 if (RTRange.isValid()) 9944 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9945 << FixItHint::CreateReplacement(RTRange, "int"); 9946 } 9947 } else { 9948 // In C and C++, main magically returns 0 if you fall off the end; 9949 // set the flag which tells us that. 9950 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9951 9952 // All the standards say that main() should return 'int'. 9953 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9954 FD->setHasImplicitReturnZero(true); 9955 else { 9956 // Otherwise, this is just a flat-out error. 9957 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9958 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9959 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9960 : FixItHint()); 9961 FD->setInvalidDecl(true); 9962 } 9963 } 9964 9965 // Treat protoless main() as nullary. 9966 if (isa<FunctionNoProtoType>(FT)) return; 9967 9968 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9969 unsigned nparams = FTP->getNumParams(); 9970 assert(FD->getNumParams() == nparams); 9971 9972 bool HasExtraParameters = (nparams > 3); 9973 9974 if (FTP->isVariadic()) { 9975 Diag(FD->getLocation(), diag::ext_variadic_main); 9976 // FIXME: if we had information about the location of the ellipsis, we 9977 // could add a FixIt hint to remove it as a parameter. 9978 } 9979 9980 // Darwin passes an undocumented fourth argument of type char**. If 9981 // other platforms start sprouting these, the logic below will start 9982 // getting shifty. 9983 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9984 HasExtraParameters = false; 9985 9986 if (HasExtraParameters) { 9987 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9988 FD->setInvalidDecl(true); 9989 nparams = 3; 9990 } 9991 9992 // FIXME: a lot of the following diagnostics would be improved 9993 // if we had some location information about types. 9994 9995 QualType CharPP = 9996 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9997 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9998 9999 for (unsigned i = 0; i < nparams; ++i) { 10000 QualType AT = FTP->getParamType(i); 10001 10002 bool mismatch = true; 10003 10004 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10005 mismatch = false; 10006 else if (Expected[i] == CharPP) { 10007 // As an extension, the following forms are okay: 10008 // char const ** 10009 // char const * const * 10010 // char * const * 10011 10012 QualifierCollector qs; 10013 const PointerType* PT; 10014 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10015 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10016 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10017 Context.CharTy)) { 10018 qs.removeConst(); 10019 mismatch = !qs.empty(); 10020 } 10021 } 10022 10023 if (mismatch) { 10024 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10025 // TODO: suggest replacing given type with expected type 10026 FD->setInvalidDecl(true); 10027 } 10028 } 10029 10030 if (nparams == 1 && !FD->isInvalidDecl()) { 10031 Diag(FD->getLocation(), diag::warn_main_one_arg); 10032 } 10033 10034 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10035 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10036 FD->setInvalidDecl(); 10037 } 10038 } 10039 10040 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10041 QualType T = FD->getType(); 10042 assert(T->isFunctionType() && "function decl is not of function type"); 10043 const FunctionType *FT = T->castAs<FunctionType>(); 10044 10045 // Set an implicit return of 'zero' if the function can return some integral, 10046 // enumeration, pointer or nullptr type. 10047 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10048 FT->getReturnType()->isAnyPointerType() || 10049 FT->getReturnType()->isNullPtrType()) 10050 // DllMain is exempt because a return value of zero means it failed. 10051 if (FD->getName() != "DllMain") 10052 FD->setHasImplicitReturnZero(true); 10053 10054 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10055 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10056 FD->setInvalidDecl(); 10057 } 10058 } 10059 10060 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10061 // FIXME: Need strict checking. In C89, we need to check for 10062 // any assignment, increment, decrement, function-calls, or 10063 // commas outside of a sizeof. In C99, it's the same list, 10064 // except that the aforementioned are allowed in unevaluated 10065 // expressions. Everything else falls under the 10066 // "may accept other forms of constant expressions" exception. 10067 // (We never end up here for C++, so the constant expression 10068 // rules there don't matter.) 10069 const Expr *Culprit; 10070 if (Init->isConstantInitializer(Context, false, &Culprit)) 10071 return false; 10072 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10073 << Culprit->getSourceRange(); 10074 return true; 10075 } 10076 10077 namespace { 10078 // Visits an initialization expression to see if OrigDecl is evaluated in 10079 // its own initialization and throws a warning if it does. 10080 class SelfReferenceChecker 10081 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10082 Sema &S; 10083 Decl *OrigDecl; 10084 bool isRecordType; 10085 bool isPODType; 10086 bool isReferenceType; 10087 10088 bool isInitList; 10089 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10090 10091 public: 10092 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10093 10094 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10095 S(S), OrigDecl(OrigDecl) { 10096 isPODType = false; 10097 isRecordType = false; 10098 isReferenceType = false; 10099 isInitList = false; 10100 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10101 isPODType = VD->getType().isPODType(S.Context); 10102 isRecordType = VD->getType()->isRecordType(); 10103 isReferenceType = VD->getType()->isReferenceType(); 10104 } 10105 } 10106 10107 // For most expressions, just call the visitor. For initializer lists, 10108 // track the index of the field being initialized since fields are 10109 // initialized in order allowing use of previously initialized fields. 10110 void CheckExpr(Expr *E) { 10111 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10112 if (!InitList) { 10113 Visit(E); 10114 return; 10115 } 10116 10117 // Track and increment the index here. 10118 isInitList = true; 10119 InitFieldIndex.push_back(0); 10120 for (auto Child : InitList->children()) { 10121 CheckExpr(cast<Expr>(Child)); 10122 ++InitFieldIndex.back(); 10123 } 10124 InitFieldIndex.pop_back(); 10125 } 10126 10127 // Returns true if MemberExpr is checked and no further checking is needed. 10128 // Returns false if additional checking is required. 10129 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10130 llvm::SmallVector<FieldDecl*, 4> Fields; 10131 Expr *Base = E; 10132 bool ReferenceField = false; 10133 10134 // Get the field memebers used. 10135 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10136 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10137 if (!FD) 10138 return false; 10139 Fields.push_back(FD); 10140 if (FD->getType()->isReferenceType()) 10141 ReferenceField = true; 10142 Base = ME->getBase()->IgnoreParenImpCasts(); 10143 } 10144 10145 // Keep checking only if the base Decl is the same. 10146 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10147 if (!DRE || DRE->getDecl() != OrigDecl) 10148 return false; 10149 10150 // A reference field can be bound to an unininitialized field. 10151 if (CheckReference && !ReferenceField) 10152 return true; 10153 10154 // Convert FieldDecls to their index number. 10155 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10156 for (const FieldDecl *I : llvm::reverse(Fields)) 10157 UsedFieldIndex.push_back(I->getFieldIndex()); 10158 10159 // See if a warning is needed by checking the first difference in index 10160 // numbers. If field being used has index less than the field being 10161 // initialized, then the use is safe. 10162 for (auto UsedIter = UsedFieldIndex.begin(), 10163 UsedEnd = UsedFieldIndex.end(), 10164 OrigIter = InitFieldIndex.begin(), 10165 OrigEnd = InitFieldIndex.end(); 10166 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10167 if (*UsedIter < *OrigIter) 10168 return true; 10169 if (*UsedIter > *OrigIter) 10170 break; 10171 } 10172 10173 // TODO: Add a different warning which will print the field names. 10174 HandleDeclRefExpr(DRE); 10175 return true; 10176 } 10177 10178 // For most expressions, the cast is directly above the DeclRefExpr. 10179 // For conditional operators, the cast can be outside the conditional 10180 // operator if both expressions are DeclRefExpr's. 10181 void HandleValue(Expr *E) { 10182 E = E->IgnoreParens(); 10183 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10184 HandleDeclRefExpr(DRE); 10185 return; 10186 } 10187 10188 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10189 Visit(CO->getCond()); 10190 HandleValue(CO->getTrueExpr()); 10191 HandleValue(CO->getFalseExpr()); 10192 return; 10193 } 10194 10195 if (BinaryConditionalOperator *BCO = 10196 dyn_cast<BinaryConditionalOperator>(E)) { 10197 Visit(BCO->getCond()); 10198 HandleValue(BCO->getFalseExpr()); 10199 return; 10200 } 10201 10202 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10203 HandleValue(OVE->getSourceExpr()); 10204 return; 10205 } 10206 10207 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10208 if (BO->getOpcode() == BO_Comma) { 10209 Visit(BO->getLHS()); 10210 HandleValue(BO->getRHS()); 10211 return; 10212 } 10213 } 10214 10215 if (isa<MemberExpr>(E)) { 10216 if (isInitList) { 10217 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10218 false /*CheckReference*/)) 10219 return; 10220 } 10221 10222 Expr *Base = E->IgnoreParenImpCasts(); 10223 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10224 // Check for static member variables and don't warn on them. 10225 if (!isa<FieldDecl>(ME->getMemberDecl())) 10226 return; 10227 Base = ME->getBase()->IgnoreParenImpCasts(); 10228 } 10229 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10230 HandleDeclRefExpr(DRE); 10231 return; 10232 } 10233 10234 Visit(E); 10235 } 10236 10237 // Reference types not handled in HandleValue are handled here since all 10238 // uses of references are bad, not just r-value uses. 10239 void VisitDeclRefExpr(DeclRefExpr *E) { 10240 if (isReferenceType) 10241 HandleDeclRefExpr(E); 10242 } 10243 10244 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10245 if (E->getCastKind() == CK_LValueToRValue) { 10246 HandleValue(E->getSubExpr()); 10247 return; 10248 } 10249 10250 Inherited::VisitImplicitCastExpr(E); 10251 } 10252 10253 void VisitMemberExpr(MemberExpr *E) { 10254 if (isInitList) { 10255 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10256 return; 10257 } 10258 10259 // Don't warn on arrays since they can be treated as pointers. 10260 if (E->getType()->canDecayToPointerType()) return; 10261 10262 // Warn when a non-static method call is followed by non-static member 10263 // field accesses, which is followed by a DeclRefExpr. 10264 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10265 bool Warn = (MD && !MD->isStatic()); 10266 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10267 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10268 if (!isa<FieldDecl>(ME->getMemberDecl())) 10269 Warn = false; 10270 Base = ME->getBase()->IgnoreParenImpCasts(); 10271 } 10272 10273 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10274 if (Warn) 10275 HandleDeclRefExpr(DRE); 10276 return; 10277 } 10278 10279 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10280 // Visit that expression. 10281 Visit(Base); 10282 } 10283 10284 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10285 Expr *Callee = E->getCallee(); 10286 10287 if (isa<UnresolvedLookupExpr>(Callee)) 10288 return Inherited::VisitCXXOperatorCallExpr(E); 10289 10290 Visit(Callee); 10291 for (auto Arg: E->arguments()) 10292 HandleValue(Arg->IgnoreParenImpCasts()); 10293 } 10294 10295 void VisitUnaryOperator(UnaryOperator *E) { 10296 // For POD record types, addresses of its own members are well-defined. 10297 if (E->getOpcode() == UO_AddrOf && isRecordType && 10298 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10299 if (!isPODType) 10300 HandleValue(E->getSubExpr()); 10301 return; 10302 } 10303 10304 if (E->isIncrementDecrementOp()) { 10305 HandleValue(E->getSubExpr()); 10306 return; 10307 } 10308 10309 Inherited::VisitUnaryOperator(E); 10310 } 10311 10312 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10313 10314 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10315 if (E->getConstructor()->isCopyConstructor()) { 10316 Expr *ArgExpr = E->getArg(0); 10317 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10318 if (ILE->getNumInits() == 1) 10319 ArgExpr = ILE->getInit(0); 10320 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10321 if (ICE->getCastKind() == CK_NoOp) 10322 ArgExpr = ICE->getSubExpr(); 10323 HandleValue(ArgExpr); 10324 return; 10325 } 10326 Inherited::VisitCXXConstructExpr(E); 10327 } 10328 10329 void VisitCallExpr(CallExpr *E) { 10330 // Treat std::move as a use. 10331 if (E->isCallToStdMove()) { 10332 HandleValue(E->getArg(0)); 10333 return; 10334 } 10335 10336 Inherited::VisitCallExpr(E); 10337 } 10338 10339 void VisitBinaryOperator(BinaryOperator *E) { 10340 if (E->isCompoundAssignmentOp()) { 10341 HandleValue(E->getLHS()); 10342 Visit(E->getRHS()); 10343 return; 10344 } 10345 10346 Inherited::VisitBinaryOperator(E); 10347 } 10348 10349 // A custom visitor for BinaryConditionalOperator is needed because the 10350 // regular visitor would check the condition and true expression separately 10351 // but both point to the same place giving duplicate diagnostics. 10352 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10353 Visit(E->getCond()); 10354 Visit(E->getFalseExpr()); 10355 } 10356 10357 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10358 Decl* ReferenceDecl = DRE->getDecl(); 10359 if (OrigDecl != ReferenceDecl) return; 10360 unsigned diag; 10361 if (isReferenceType) { 10362 diag = diag::warn_uninit_self_reference_in_reference_init; 10363 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10364 diag = diag::warn_static_self_reference_in_init; 10365 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10366 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10367 DRE->getDecl()->getType()->isRecordType()) { 10368 diag = diag::warn_uninit_self_reference_in_init; 10369 } else { 10370 // Local variables will be handled by the CFG analysis. 10371 return; 10372 } 10373 10374 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10375 S.PDiag(diag) 10376 << DRE->getDecl() 10377 << OrigDecl->getLocation() 10378 << DRE->getSourceRange()); 10379 } 10380 }; 10381 10382 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10383 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10384 bool DirectInit) { 10385 // Parameters arguments are occassionially constructed with itself, 10386 // for instance, in recursive functions. Skip them. 10387 if (isa<ParmVarDecl>(OrigDecl)) 10388 return; 10389 10390 E = E->IgnoreParens(); 10391 10392 // Skip checking T a = a where T is not a record or reference type. 10393 // Doing so is a way to silence uninitialized warnings. 10394 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10395 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10396 if (ICE->getCastKind() == CK_LValueToRValue) 10397 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10398 if (DRE->getDecl() == OrigDecl) 10399 return; 10400 10401 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10402 } 10403 } // end anonymous namespace 10404 10405 namespace { 10406 // Simple wrapper to add the name of a variable or (if no variable is 10407 // available) a DeclarationName into a diagnostic. 10408 struct VarDeclOrName { 10409 VarDecl *VDecl; 10410 DeclarationName Name; 10411 10412 friend const Sema::SemaDiagnosticBuilder & 10413 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10414 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10415 } 10416 }; 10417 } // end anonymous namespace 10418 10419 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10420 DeclarationName Name, QualType Type, 10421 TypeSourceInfo *TSI, 10422 SourceRange Range, bool DirectInit, 10423 Expr *Init) { 10424 bool IsInitCapture = !VDecl; 10425 assert((!VDecl || !VDecl->isInitCapture()) && 10426 "init captures are expected to be deduced prior to initialization"); 10427 10428 VarDeclOrName VN{VDecl, Name}; 10429 10430 DeducedType *Deduced = Type->getContainedDeducedType(); 10431 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10432 10433 // C++11 [dcl.spec.auto]p3 10434 if (!Init) { 10435 assert(VDecl && "no init for init capture deduction?"); 10436 10437 // Except for class argument deduction, and then for an initializing 10438 // declaration only, i.e. no static at class scope or extern. 10439 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10440 VDecl->hasExternalStorage() || 10441 VDecl->isStaticDataMember()) { 10442 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10443 << VDecl->getDeclName() << Type; 10444 return QualType(); 10445 } 10446 } 10447 10448 ArrayRef<Expr*> DeduceInits; 10449 if (Init) 10450 DeduceInits = Init; 10451 10452 if (DirectInit) { 10453 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10454 DeduceInits = PL->exprs(); 10455 } 10456 10457 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10458 assert(VDecl && "non-auto type for init capture deduction?"); 10459 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10460 InitializationKind Kind = InitializationKind::CreateForInit( 10461 VDecl->getLocation(), DirectInit, Init); 10462 // FIXME: Initialization should not be taking a mutable list of inits. 10463 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10464 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10465 InitsCopy); 10466 } 10467 10468 if (DirectInit) { 10469 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10470 DeduceInits = IL->inits(); 10471 } 10472 10473 // Deduction only works if we have exactly one source expression. 10474 if (DeduceInits.empty()) { 10475 // It isn't possible to write this directly, but it is possible to 10476 // end up in this situation with "auto x(some_pack...);" 10477 Diag(Init->getLocStart(), IsInitCapture 10478 ? diag::err_init_capture_no_expression 10479 : diag::err_auto_var_init_no_expression) 10480 << VN << Type << Range; 10481 return QualType(); 10482 } 10483 10484 if (DeduceInits.size() > 1) { 10485 Diag(DeduceInits[1]->getLocStart(), 10486 IsInitCapture ? diag::err_init_capture_multiple_expressions 10487 : diag::err_auto_var_init_multiple_expressions) 10488 << VN << Type << Range; 10489 return QualType(); 10490 } 10491 10492 Expr *DeduceInit = DeduceInits[0]; 10493 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10494 Diag(Init->getLocStart(), IsInitCapture 10495 ? diag::err_init_capture_paren_braces 10496 : diag::err_auto_var_init_paren_braces) 10497 << isa<InitListExpr>(Init) << VN << Type << Range; 10498 return QualType(); 10499 } 10500 10501 // Expressions default to 'id' when we're in a debugger. 10502 bool DefaultedAnyToId = false; 10503 if (getLangOpts().DebuggerCastResultToId && 10504 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10505 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10506 if (Result.isInvalid()) { 10507 return QualType(); 10508 } 10509 Init = Result.get(); 10510 DefaultedAnyToId = true; 10511 } 10512 10513 // C++ [dcl.decomp]p1: 10514 // If the assignment-expression [...] has array type A and no ref-qualifier 10515 // is present, e has type cv A 10516 if (VDecl && isa<DecompositionDecl>(VDecl) && 10517 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10518 DeduceInit->getType()->isConstantArrayType()) 10519 return Context.getQualifiedType(DeduceInit->getType(), 10520 Type.getQualifiers()); 10521 10522 QualType DeducedType; 10523 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10524 if (!IsInitCapture) 10525 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10526 else if (isa<InitListExpr>(Init)) 10527 Diag(Range.getBegin(), 10528 diag::err_init_capture_deduction_failure_from_init_list) 10529 << VN 10530 << (DeduceInit->getType().isNull() ? TSI->getType() 10531 : DeduceInit->getType()) 10532 << DeduceInit->getSourceRange(); 10533 else 10534 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10535 << VN << TSI->getType() 10536 << (DeduceInit->getType().isNull() ? TSI->getType() 10537 : DeduceInit->getType()) 10538 << DeduceInit->getSourceRange(); 10539 } 10540 10541 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10542 // 'id' instead of a specific object type prevents most of our usual 10543 // checks. 10544 // We only want to warn outside of template instantiations, though: 10545 // inside a template, the 'id' could have come from a parameter. 10546 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10547 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10548 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10549 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10550 } 10551 10552 return DeducedType; 10553 } 10554 10555 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10556 Expr *Init) { 10557 QualType DeducedType = deduceVarTypeFromInitializer( 10558 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10559 VDecl->getSourceRange(), DirectInit, Init); 10560 if (DeducedType.isNull()) { 10561 VDecl->setInvalidDecl(); 10562 return true; 10563 } 10564 10565 VDecl->setType(DeducedType); 10566 assert(VDecl->isLinkageValid()); 10567 10568 // In ARC, infer lifetime. 10569 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10570 VDecl->setInvalidDecl(); 10571 10572 // If this is a redeclaration, check that the type we just deduced matches 10573 // the previously declared type. 10574 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10575 // We never need to merge the type, because we cannot form an incomplete 10576 // array of auto, nor deduce such a type. 10577 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10578 } 10579 10580 // Check the deduced type is valid for a variable declaration. 10581 CheckVariableDeclarationType(VDecl); 10582 return VDecl->isInvalidDecl(); 10583 } 10584 10585 /// AddInitializerToDecl - Adds the initializer Init to the 10586 /// declaration dcl. If DirectInit is true, this is C++ direct 10587 /// initialization rather than copy initialization. 10588 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10589 // If there is no declaration, there was an error parsing it. Just ignore 10590 // the initializer. 10591 if (!RealDecl || RealDecl->isInvalidDecl()) { 10592 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10593 return; 10594 } 10595 10596 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10597 // Pure-specifiers are handled in ActOnPureSpecifier. 10598 Diag(Method->getLocation(), diag::err_member_function_initialization) 10599 << Method->getDeclName() << Init->getSourceRange(); 10600 Method->setInvalidDecl(); 10601 return; 10602 } 10603 10604 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10605 if (!VDecl) { 10606 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10607 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10608 RealDecl->setInvalidDecl(); 10609 return; 10610 } 10611 10612 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10613 if (VDecl->getType()->isUndeducedType()) { 10614 // Attempt typo correction early so that the type of the init expression can 10615 // be deduced based on the chosen correction if the original init contains a 10616 // TypoExpr. 10617 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10618 if (!Res.isUsable()) { 10619 RealDecl->setInvalidDecl(); 10620 return; 10621 } 10622 Init = Res.get(); 10623 10624 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10625 return; 10626 } 10627 10628 // dllimport cannot be used on variable definitions. 10629 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10630 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10631 VDecl->setInvalidDecl(); 10632 return; 10633 } 10634 10635 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10636 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10637 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10638 VDecl->setInvalidDecl(); 10639 return; 10640 } 10641 10642 if (!VDecl->getType()->isDependentType()) { 10643 // A definition must end up with a complete type, which means it must be 10644 // complete with the restriction that an array type might be completed by 10645 // the initializer; note that later code assumes this restriction. 10646 QualType BaseDeclType = VDecl->getType(); 10647 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10648 BaseDeclType = Array->getElementType(); 10649 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10650 diag::err_typecheck_decl_incomplete_type)) { 10651 RealDecl->setInvalidDecl(); 10652 return; 10653 } 10654 10655 // The variable can not have an abstract class type. 10656 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10657 diag::err_abstract_type_in_decl, 10658 AbstractVariableType)) 10659 VDecl->setInvalidDecl(); 10660 } 10661 10662 // If adding the initializer will turn this declaration into a definition, 10663 // and we already have a definition for this variable, diagnose or otherwise 10664 // handle the situation. 10665 VarDecl *Def; 10666 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10667 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10668 !VDecl->isThisDeclarationADemotedDefinition() && 10669 checkVarDeclRedefinition(Def, VDecl)) 10670 return; 10671 10672 if (getLangOpts().CPlusPlus) { 10673 // C++ [class.static.data]p4 10674 // If a static data member is of const integral or const 10675 // enumeration type, its declaration in the class definition can 10676 // specify a constant-initializer which shall be an integral 10677 // constant expression (5.19). In that case, the member can appear 10678 // in integral constant expressions. The member shall still be 10679 // defined in a namespace scope if it is used in the program and the 10680 // namespace scope definition shall not contain an initializer. 10681 // 10682 // We already performed a redefinition check above, but for static 10683 // data members we also need to check whether there was an in-class 10684 // declaration with an initializer. 10685 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10686 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10687 << VDecl->getDeclName(); 10688 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10689 diag::note_previous_initializer) 10690 << 0; 10691 return; 10692 } 10693 10694 if (VDecl->hasLocalStorage()) 10695 setFunctionHasBranchProtectedScope(); 10696 10697 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10698 VDecl->setInvalidDecl(); 10699 return; 10700 } 10701 } 10702 10703 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10704 // a kernel function cannot be initialized." 10705 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10706 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10707 VDecl->setInvalidDecl(); 10708 return; 10709 } 10710 10711 // Get the decls type and save a reference for later, since 10712 // CheckInitializerTypes may change it. 10713 QualType DclT = VDecl->getType(), SavT = DclT; 10714 10715 // Expressions default to 'id' when we're in a debugger 10716 // and we are assigning it to a variable of Objective-C pointer type. 10717 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10718 Init->getType() == Context.UnknownAnyTy) { 10719 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10720 if (Result.isInvalid()) { 10721 VDecl->setInvalidDecl(); 10722 return; 10723 } 10724 Init = Result.get(); 10725 } 10726 10727 // Perform the initialization. 10728 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10729 if (!VDecl->isInvalidDecl()) { 10730 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10731 InitializationKind Kind = InitializationKind::CreateForInit( 10732 VDecl->getLocation(), DirectInit, Init); 10733 10734 MultiExprArg Args = Init; 10735 if (CXXDirectInit) 10736 Args = MultiExprArg(CXXDirectInit->getExprs(), 10737 CXXDirectInit->getNumExprs()); 10738 10739 // Try to correct any TypoExprs in the initialization arguments. 10740 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10741 ExprResult Res = CorrectDelayedTyposInExpr( 10742 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10743 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10744 return Init.Failed() ? ExprError() : E; 10745 }); 10746 if (Res.isInvalid()) { 10747 VDecl->setInvalidDecl(); 10748 } else if (Res.get() != Args[Idx]) { 10749 Args[Idx] = Res.get(); 10750 } 10751 } 10752 if (VDecl->isInvalidDecl()) 10753 return; 10754 10755 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10756 /*TopLevelOfInitList=*/false, 10757 /*TreatUnavailableAsInvalid=*/false); 10758 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10759 if (Result.isInvalid()) { 10760 VDecl->setInvalidDecl(); 10761 return; 10762 } 10763 10764 Init = Result.getAs<Expr>(); 10765 } 10766 10767 // Check for self-references within variable initializers. 10768 // Variables declared within a function/method body (except for references) 10769 // are handled by a dataflow analysis. 10770 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10771 VDecl->getType()->isReferenceType()) { 10772 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10773 } 10774 10775 // If the type changed, it means we had an incomplete type that was 10776 // completed by the initializer. For example: 10777 // int ary[] = { 1, 3, 5 }; 10778 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10779 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10780 VDecl->setType(DclT); 10781 10782 if (!VDecl->isInvalidDecl()) { 10783 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10784 10785 if (VDecl->hasAttr<BlocksAttr>()) 10786 checkRetainCycles(VDecl, Init); 10787 10788 // It is safe to assign a weak reference into a strong variable. 10789 // Although this code can still have problems: 10790 // id x = self.weakProp; 10791 // id y = self.weakProp; 10792 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10793 // paths through the function. This should be revisited if 10794 // -Wrepeated-use-of-weak is made flow-sensitive. 10795 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10796 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10797 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10798 Init->getLocStart())) 10799 getCurFunction()->markSafeWeakUse(Init); 10800 } 10801 10802 // The initialization is usually a full-expression. 10803 // 10804 // FIXME: If this is a braced initialization of an aggregate, it is not 10805 // an expression, and each individual field initializer is a separate 10806 // full-expression. For instance, in: 10807 // 10808 // struct Temp { ~Temp(); }; 10809 // struct S { S(Temp); }; 10810 // struct T { S a, b; } t = { Temp(), Temp() } 10811 // 10812 // we should destroy the first Temp before constructing the second. 10813 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10814 false, 10815 VDecl->isConstexpr()); 10816 if (Result.isInvalid()) { 10817 VDecl->setInvalidDecl(); 10818 return; 10819 } 10820 Init = Result.get(); 10821 10822 // Attach the initializer to the decl. 10823 VDecl->setInit(Init); 10824 10825 if (VDecl->isLocalVarDecl()) { 10826 // Don't check the initializer if the declaration is malformed. 10827 if (VDecl->isInvalidDecl()) { 10828 // do nothing 10829 10830 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10831 // This is true even in OpenCL C++. 10832 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10833 CheckForConstantInitializer(Init, DclT); 10834 10835 // Otherwise, C++ does not restrict the initializer. 10836 } else if (getLangOpts().CPlusPlus) { 10837 // do nothing 10838 10839 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10840 // static storage duration shall be constant expressions or string literals. 10841 } else if (VDecl->getStorageClass() == SC_Static) { 10842 CheckForConstantInitializer(Init, DclT); 10843 10844 // C89 is stricter than C99 for aggregate initializers. 10845 // C89 6.5.7p3: All the expressions [...] in an initializer list 10846 // for an object that has aggregate or union type shall be 10847 // constant expressions. 10848 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10849 isa<InitListExpr>(Init)) { 10850 const Expr *Culprit; 10851 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10852 Diag(Culprit->getExprLoc(), 10853 diag::ext_aggregate_init_not_constant) 10854 << Culprit->getSourceRange(); 10855 } 10856 } 10857 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10858 VDecl->getLexicalDeclContext()->isRecord()) { 10859 // This is an in-class initialization for a static data member, e.g., 10860 // 10861 // struct S { 10862 // static const int value = 17; 10863 // }; 10864 10865 // C++ [class.mem]p4: 10866 // A member-declarator can contain a constant-initializer only 10867 // if it declares a static member (9.4) of const integral or 10868 // const enumeration type, see 9.4.2. 10869 // 10870 // C++11 [class.static.data]p3: 10871 // If a non-volatile non-inline const static data member is of integral 10872 // or enumeration type, its declaration in the class definition can 10873 // specify a brace-or-equal-initializer in which every initializer-clause 10874 // that is an assignment-expression is a constant expression. A static 10875 // data member of literal type can be declared in the class definition 10876 // with the constexpr specifier; if so, its declaration shall specify a 10877 // brace-or-equal-initializer in which every initializer-clause that is 10878 // an assignment-expression is a constant expression. 10879 10880 // Do nothing on dependent types. 10881 if (DclT->isDependentType()) { 10882 10883 // Allow any 'static constexpr' members, whether or not they are of literal 10884 // type. We separately check that every constexpr variable is of literal 10885 // type. 10886 } else if (VDecl->isConstexpr()) { 10887 10888 // Require constness. 10889 } else if (!DclT.isConstQualified()) { 10890 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10891 << Init->getSourceRange(); 10892 VDecl->setInvalidDecl(); 10893 10894 // We allow integer constant expressions in all cases. 10895 } else if (DclT->isIntegralOrEnumerationType()) { 10896 // Check whether the expression is a constant expression. 10897 SourceLocation Loc; 10898 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10899 // In C++11, a non-constexpr const static data member with an 10900 // in-class initializer cannot be volatile. 10901 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10902 else if (Init->isValueDependent()) 10903 ; // Nothing to check. 10904 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10905 ; // Ok, it's an ICE! 10906 else if (Init->isEvaluatable(Context)) { 10907 // If we can constant fold the initializer through heroics, accept it, 10908 // but report this as a use of an extension for -pedantic. 10909 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10910 << Init->getSourceRange(); 10911 } else { 10912 // Otherwise, this is some crazy unknown case. Report the issue at the 10913 // location provided by the isIntegerConstantExpr failed check. 10914 Diag(Loc, diag::err_in_class_initializer_non_constant) 10915 << Init->getSourceRange(); 10916 VDecl->setInvalidDecl(); 10917 } 10918 10919 // We allow foldable floating-point constants as an extension. 10920 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10921 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10922 // it anyway and provide a fixit to add the 'constexpr'. 10923 if (getLangOpts().CPlusPlus11) { 10924 Diag(VDecl->getLocation(), 10925 diag::ext_in_class_initializer_float_type_cxx11) 10926 << DclT << Init->getSourceRange(); 10927 Diag(VDecl->getLocStart(), 10928 diag::note_in_class_initializer_float_type_cxx11) 10929 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10930 } else { 10931 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10932 << DclT << Init->getSourceRange(); 10933 10934 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10935 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10936 << Init->getSourceRange(); 10937 VDecl->setInvalidDecl(); 10938 } 10939 } 10940 10941 // Suggest adding 'constexpr' in C++11 for literal types. 10942 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10943 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10944 << DclT << Init->getSourceRange() 10945 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10946 VDecl->setConstexpr(true); 10947 10948 } else { 10949 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10950 << DclT << Init->getSourceRange(); 10951 VDecl->setInvalidDecl(); 10952 } 10953 } else if (VDecl->isFileVarDecl()) { 10954 // In C, extern is typically used to avoid tentative definitions when 10955 // declaring variables in headers, but adding an intializer makes it a 10956 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 10957 // In C++, extern is often used to give implictly static const variables 10958 // external linkage, so don't warn in that case. If selectany is present, 10959 // this might be header code intended for C and C++ inclusion, so apply the 10960 // C++ rules. 10961 if (VDecl->getStorageClass() == SC_Extern && 10962 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10963 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10964 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10965 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10966 Diag(VDecl->getLocation(), diag::warn_extern_init); 10967 10968 // C99 6.7.8p4. All file scoped initializers need to be constant. 10969 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10970 CheckForConstantInitializer(Init, DclT); 10971 } 10972 10973 // We will represent direct-initialization similarly to copy-initialization: 10974 // int x(1); -as-> int x = 1; 10975 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10976 // 10977 // Clients that want to distinguish between the two forms, can check for 10978 // direct initializer using VarDecl::getInitStyle(). 10979 // A major benefit is that clients that don't particularly care about which 10980 // exactly form was it (like the CodeGen) can handle both cases without 10981 // special case code. 10982 10983 // C++ 8.5p11: 10984 // The form of initialization (using parentheses or '=') is generally 10985 // insignificant, but does matter when the entity being initialized has a 10986 // class type. 10987 if (CXXDirectInit) { 10988 assert(DirectInit && "Call-style initializer must be direct init."); 10989 VDecl->setInitStyle(VarDecl::CallInit); 10990 } else if (DirectInit) { 10991 // This must be list-initialization. No other way is direct-initialization. 10992 VDecl->setInitStyle(VarDecl::ListInit); 10993 } 10994 10995 CheckCompleteVariableDeclaration(VDecl); 10996 } 10997 10998 /// ActOnInitializerError - Given that there was an error parsing an 10999 /// initializer for the given declaration, try to return to some form 11000 /// of sanity. 11001 void Sema::ActOnInitializerError(Decl *D) { 11002 // Our main concern here is re-establishing invariants like "a 11003 // variable's type is either dependent or complete". 11004 if (!D || D->isInvalidDecl()) return; 11005 11006 VarDecl *VD = dyn_cast<VarDecl>(D); 11007 if (!VD) return; 11008 11009 // Bindings are not usable if we can't make sense of the initializer. 11010 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 11011 for (auto *BD : DD->bindings()) 11012 BD->setInvalidDecl(); 11013 11014 // Auto types are meaningless if we can't make sense of the initializer. 11015 if (ParsingInitForAutoVars.count(D)) { 11016 D->setInvalidDecl(); 11017 return; 11018 } 11019 11020 QualType Ty = VD->getType(); 11021 if (Ty->isDependentType()) return; 11022 11023 // Require a complete type. 11024 if (RequireCompleteType(VD->getLocation(), 11025 Context.getBaseElementType(Ty), 11026 diag::err_typecheck_decl_incomplete_type)) { 11027 VD->setInvalidDecl(); 11028 return; 11029 } 11030 11031 // Require a non-abstract type. 11032 if (RequireNonAbstractType(VD->getLocation(), Ty, 11033 diag::err_abstract_type_in_decl, 11034 AbstractVariableType)) { 11035 VD->setInvalidDecl(); 11036 return; 11037 } 11038 11039 // Don't bother complaining about constructors or destructors, 11040 // though. 11041 } 11042 11043 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11044 // If there is no declaration, there was an error parsing it. Just ignore it. 11045 if (!RealDecl) 11046 return; 11047 11048 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11049 QualType Type = Var->getType(); 11050 11051 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11052 if (isa<DecompositionDecl>(RealDecl)) { 11053 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11054 Var->setInvalidDecl(); 11055 return; 11056 } 11057 11058 if (Type->isUndeducedType() && 11059 DeduceVariableDeclarationType(Var, false, nullptr)) 11060 return; 11061 11062 // C++11 [class.static.data]p3: A static data member can be declared with 11063 // the constexpr specifier; if so, its declaration shall specify 11064 // a brace-or-equal-initializer. 11065 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11066 // the definition of a variable [...] or the declaration of a static data 11067 // member. 11068 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11069 !Var->isThisDeclarationADemotedDefinition()) { 11070 if (Var->isStaticDataMember()) { 11071 // C++1z removes the relevant rule; the in-class declaration is always 11072 // a definition there. 11073 if (!getLangOpts().CPlusPlus17) { 11074 Diag(Var->getLocation(), 11075 diag::err_constexpr_static_mem_var_requires_init) 11076 << Var->getDeclName(); 11077 Var->setInvalidDecl(); 11078 return; 11079 } 11080 } else { 11081 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11082 Var->setInvalidDecl(); 11083 return; 11084 } 11085 } 11086 11087 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11088 // be initialized. 11089 if (!Var->isInvalidDecl() && 11090 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11091 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11092 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11093 Var->setInvalidDecl(); 11094 return; 11095 } 11096 11097 switch (Var->isThisDeclarationADefinition()) { 11098 case VarDecl::Definition: 11099 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11100 break; 11101 11102 // We have an out-of-line definition of a static data member 11103 // that has an in-class initializer, so we type-check this like 11104 // a declaration. 11105 // 11106 LLVM_FALLTHROUGH; 11107 11108 case VarDecl::DeclarationOnly: 11109 // It's only a declaration. 11110 11111 // Block scope. C99 6.7p7: If an identifier for an object is 11112 // declared with no linkage (C99 6.2.2p6), the type for the 11113 // object shall be complete. 11114 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11115 !Var->hasLinkage() && !Var->isInvalidDecl() && 11116 RequireCompleteType(Var->getLocation(), Type, 11117 diag::err_typecheck_decl_incomplete_type)) 11118 Var->setInvalidDecl(); 11119 11120 // Make sure that the type is not abstract. 11121 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11122 RequireNonAbstractType(Var->getLocation(), Type, 11123 diag::err_abstract_type_in_decl, 11124 AbstractVariableType)) 11125 Var->setInvalidDecl(); 11126 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11127 Var->getStorageClass() == SC_PrivateExtern) { 11128 Diag(Var->getLocation(), diag::warn_private_extern); 11129 Diag(Var->getLocation(), diag::note_private_extern); 11130 } 11131 11132 return; 11133 11134 case VarDecl::TentativeDefinition: 11135 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11136 // object that has file scope without an initializer, and without a 11137 // storage-class specifier or with the storage-class specifier "static", 11138 // constitutes a tentative definition. Note: A tentative definition with 11139 // external linkage is valid (C99 6.2.2p5). 11140 if (!Var->isInvalidDecl()) { 11141 if (const IncompleteArrayType *ArrayT 11142 = Context.getAsIncompleteArrayType(Type)) { 11143 if (RequireCompleteType(Var->getLocation(), 11144 ArrayT->getElementType(), 11145 diag::err_illegal_decl_array_incomplete_type)) 11146 Var->setInvalidDecl(); 11147 } else if (Var->getStorageClass() == SC_Static) { 11148 // C99 6.9.2p3: If the declaration of an identifier for an object is 11149 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11150 // declared type shall not be an incomplete type. 11151 // NOTE: code such as the following 11152 // static struct s; 11153 // struct s { int a; }; 11154 // is accepted by gcc. Hence here we issue a warning instead of 11155 // an error and we do not invalidate the static declaration. 11156 // NOTE: to avoid multiple warnings, only check the first declaration. 11157 if (Var->isFirstDecl()) 11158 RequireCompleteType(Var->getLocation(), Type, 11159 diag::ext_typecheck_decl_incomplete_type); 11160 } 11161 } 11162 11163 // Record the tentative definition; we're done. 11164 if (!Var->isInvalidDecl()) 11165 TentativeDefinitions.push_back(Var); 11166 return; 11167 } 11168 11169 // Provide a specific diagnostic for uninitialized variable 11170 // definitions with incomplete array type. 11171 if (Type->isIncompleteArrayType()) { 11172 Diag(Var->getLocation(), 11173 diag::err_typecheck_incomplete_array_needs_initializer); 11174 Var->setInvalidDecl(); 11175 return; 11176 } 11177 11178 // Provide a specific diagnostic for uninitialized variable 11179 // definitions with reference type. 11180 if (Type->isReferenceType()) { 11181 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11182 << Var->getDeclName() 11183 << SourceRange(Var->getLocation(), Var->getLocation()); 11184 Var->setInvalidDecl(); 11185 return; 11186 } 11187 11188 // Do not attempt to type-check the default initializer for a 11189 // variable with dependent type. 11190 if (Type->isDependentType()) 11191 return; 11192 11193 if (Var->isInvalidDecl()) 11194 return; 11195 11196 if (!Var->hasAttr<AliasAttr>()) { 11197 if (RequireCompleteType(Var->getLocation(), 11198 Context.getBaseElementType(Type), 11199 diag::err_typecheck_decl_incomplete_type)) { 11200 Var->setInvalidDecl(); 11201 return; 11202 } 11203 } else { 11204 return; 11205 } 11206 11207 // The variable can not have an abstract class type. 11208 if (RequireNonAbstractType(Var->getLocation(), Type, 11209 diag::err_abstract_type_in_decl, 11210 AbstractVariableType)) { 11211 Var->setInvalidDecl(); 11212 return; 11213 } 11214 11215 // Check for jumps past the implicit initializer. C++0x 11216 // clarifies that this applies to a "variable with automatic 11217 // storage duration", not a "local variable". 11218 // C++11 [stmt.dcl]p3 11219 // A program that jumps from a point where a variable with automatic 11220 // storage duration is not in scope to a point where it is in scope is 11221 // ill-formed unless the variable has scalar type, class type with a 11222 // trivial default constructor and a trivial destructor, a cv-qualified 11223 // version of one of these types, or an array of one of the preceding 11224 // types and is declared without an initializer. 11225 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11226 if (const RecordType *Record 11227 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11228 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11229 // Mark the function (if we're in one) for further checking even if the 11230 // looser rules of C++11 do not require such checks, so that we can 11231 // diagnose incompatibilities with C++98. 11232 if (!CXXRecord->isPOD()) 11233 setFunctionHasBranchProtectedScope(); 11234 } 11235 } 11236 11237 // C++03 [dcl.init]p9: 11238 // If no initializer is specified for an object, and the 11239 // object is of (possibly cv-qualified) non-POD class type (or 11240 // array thereof), the object shall be default-initialized; if 11241 // the object is of const-qualified type, the underlying class 11242 // type shall have a user-declared default 11243 // constructor. Otherwise, if no initializer is specified for 11244 // a non- static object, the object and its subobjects, if 11245 // any, have an indeterminate initial value); if the object 11246 // or any of its subobjects are of const-qualified type, the 11247 // program is ill-formed. 11248 // C++0x [dcl.init]p11: 11249 // If no initializer is specified for an object, the object is 11250 // default-initialized; [...]. 11251 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11252 InitializationKind Kind 11253 = InitializationKind::CreateDefault(Var->getLocation()); 11254 11255 InitializationSequence InitSeq(*this, Entity, Kind, None); 11256 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11257 if (Init.isInvalid()) 11258 Var->setInvalidDecl(); 11259 else if (Init.get()) { 11260 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11261 // This is important for template substitution. 11262 Var->setInitStyle(VarDecl::CallInit); 11263 } 11264 11265 CheckCompleteVariableDeclaration(Var); 11266 } 11267 } 11268 11269 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11270 // If there is no declaration, there was an error parsing it. Ignore it. 11271 if (!D) 11272 return; 11273 11274 VarDecl *VD = dyn_cast<VarDecl>(D); 11275 if (!VD) { 11276 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11277 D->setInvalidDecl(); 11278 return; 11279 } 11280 11281 VD->setCXXForRangeDecl(true); 11282 11283 // for-range-declaration cannot be given a storage class specifier. 11284 int Error = -1; 11285 switch (VD->getStorageClass()) { 11286 case SC_None: 11287 break; 11288 case SC_Extern: 11289 Error = 0; 11290 break; 11291 case SC_Static: 11292 Error = 1; 11293 break; 11294 case SC_PrivateExtern: 11295 Error = 2; 11296 break; 11297 case SC_Auto: 11298 Error = 3; 11299 break; 11300 case SC_Register: 11301 Error = 4; 11302 break; 11303 } 11304 if (Error != -1) { 11305 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11306 << VD->getDeclName() << Error; 11307 D->setInvalidDecl(); 11308 } 11309 } 11310 11311 StmtResult 11312 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11313 IdentifierInfo *Ident, 11314 ParsedAttributes &Attrs, 11315 SourceLocation AttrEnd) { 11316 // C++1y [stmt.iter]p1: 11317 // A range-based for statement of the form 11318 // for ( for-range-identifier : for-range-initializer ) statement 11319 // is equivalent to 11320 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11321 DeclSpec DS(Attrs.getPool().getFactory()); 11322 11323 const char *PrevSpec; 11324 unsigned DiagID; 11325 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11326 getPrintingPolicy()); 11327 11328 Declarator D(DS, DeclaratorContext::ForContext); 11329 D.SetIdentifier(Ident, IdentLoc); 11330 D.takeAttributes(Attrs, AttrEnd); 11331 11332 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11333 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 11334 EmptyAttrs, IdentLoc); 11335 Decl *Var = ActOnDeclarator(S, D); 11336 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11337 FinalizeDeclaration(Var); 11338 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11339 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11340 } 11341 11342 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11343 if (var->isInvalidDecl()) return; 11344 11345 if (getLangOpts().OpenCL) { 11346 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11347 // initialiser 11348 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11349 !var->hasInit()) { 11350 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11351 << 1 /*Init*/; 11352 var->setInvalidDecl(); 11353 return; 11354 } 11355 } 11356 11357 // In Objective-C, don't allow jumps past the implicit initialization of a 11358 // local retaining variable. 11359 if (getLangOpts().ObjC1 && 11360 var->hasLocalStorage()) { 11361 switch (var->getType().getObjCLifetime()) { 11362 case Qualifiers::OCL_None: 11363 case Qualifiers::OCL_ExplicitNone: 11364 case Qualifiers::OCL_Autoreleasing: 11365 break; 11366 11367 case Qualifiers::OCL_Weak: 11368 case Qualifiers::OCL_Strong: 11369 setFunctionHasBranchProtectedScope(); 11370 break; 11371 } 11372 } 11373 11374 if (var->hasLocalStorage() && 11375 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11376 setFunctionHasBranchProtectedScope(); 11377 11378 // Warn about externally-visible variables being defined without a 11379 // prior declaration. We only want to do this for global 11380 // declarations, but we also specifically need to avoid doing it for 11381 // class members because the linkage of an anonymous class can 11382 // change if it's later given a typedef name. 11383 if (var->isThisDeclarationADefinition() && 11384 var->getDeclContext()->getRedeclContext()->isFileContext() && 11385 var->isExternallyVisible() && var->hasLinkage() && 11386 !var->isInline() && !var->getDescribedVarTemplate() && 11387 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11388 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11389 var->getLocation())) { 11390 // Find a previous declaration that's not a definition. 11391 VarDecl *prev = var->getPreviousDecl(); 11392 while (prev && prev->isThisDeclarationADefinition()) 11393 prev = prev->getPreviousDecl(); 11394 11395 if (!prev) 11396 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11397 } 11398 11399 // Cache the result of checking for constant initialization. 11400 Optional<bool> CacheHasConstInit; 11401 const Expr *CacheCulprit; 11402 auto checkConstInit = [&]() mutable { 11403 if (!CacheHasConstInit) 11404 CacheHasConstInit = var->getInit()->isConstantInitializer( 11405 Context, var->getType()->isReferenceType(), &CacheCulprit); 11406 return *CacheHasConstInit; 11407 }; 11408 11409 if (var->getTLSKind() == VarDecl::TLS_Static) { 11410 if (var->getType().isDestructedType()) { 11411 // GNU C++98 edits for __thread, [basic.start.term]p3: 11412 // The type of an object with thread storage duration shall not 11413 // have a non-trivial destructor. 11414 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11415 if (getLangOpts().CPlusPlus11) 11416 Diag(var->getLocation(), diag::note_use_thread_local); 11417 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11418 if (!checkConstInit()) { 11419 // GNU C++98 edits for __thread, [basic.start.init]p4: 11420 // An object of thread storage duration shall not require dynamic 11421 // initialization. 11422 // FIXME: Need strict checking here. 11423 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11424 << CacheCulprit->getSourceRange(); 11425 if (getLangOpts().CPlusPlus11) 11426 Diag(var->getLocation(), diag::note_use_thread_local); 11427 } 11428 } 11429 } 11430 11431 // Apply section attributes and pragmas to global variables. 11432 bool GlobalStorage = var->hasGlobalStorage(); 11433 if (GlobalStorage && var->isThisDeclarationADefinition() && 11434 !inTemplateInstantiation()) { 11435 PragmaStack<StringLiteral *> *Stack = nullptr; 11436 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11437 if (var->getType().isConstQualified()) 11438 Stack = &ConstSegStack; 11439 else if (!var->getInit()) { 11440 Stack = &BSSSegStack; 11441 SectionFlags |= ASTContext::PSF_Write; 11442 } else { 11443 Stack = &DataSegStack; 11444 SectionFlags |= ASTContext::PSF_Write; 11445 } 11446 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11447 var->addAttr(SectionAttr::CreateImplicit( 11448 Context, SectionAttr::Declspec_allocate, 11449 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11450 } 11451 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11452 if (UnifySection(SA->getName(), SectionFlags, var)) 11453 var->dropAttr<SectionAttr>(); 11454 11455 // Apply the init_seg attribute if this has an initializer. If the 11456 // initializer turns out to not be dynamic, we'll end up ignoring this 11457 // attribute. 11458 if (CurInitSeg && var->getInit()) 11459 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11460 CurInitSegLoc)); 11461 } 11462 11463 // All the following checks are C++ only. 11464 if (!getLangOpts().CPlusPlus) { 11465 // If this variable must be emitted, add it as an initializer for the 11466 // current module. 11467 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11468 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11469 return; 11470 } 11471 11472 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11473 CheckCompleteDecompositionDeclaration(DD); 11474 11475 QualType type = var->getType(); 11476 if (type->isDependentType()) return; 11477 11478 // __block variables might require us to capture a copy-initializer. 11479 if (var->hasAttr<BlocksAttr>()) { 11480 // It's currently invalid to ever have a __block variable with an 11481 // array type; should we diagnose that here? 11482 11483 // Regardless, we don't want to ignore array nesting when 11484 // constructing this copy. 11485 if (type->isStructureOrClassType()) { 11486 EnterExpressionEvaluationContext scope( 11487 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11488 SourceLocation poi = var->getLocation(); 11489 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11490 ExprResult result 11491 = PerformMoveOrCopyInitialization( 11492 InitializedEntity::InitializeBlock(poi, type, false), 11493 var, var->getType(), varRef, /*AllowNRVO=*/true); 11494 if (!result.isInvalid()) { 11495 result = MaybeCreateExprWithCleanups(result); 11496 Expr *init = result.getAs<Expr>(); 11497 Context.setBlockVarCopyInits(var, init); 11498 } 11499 } 11500 } 11501 11502 Expr *Init = var->getInit(); 11503 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11504 QualType baseType = Context.getBaseElementType(type); 11505 11506 if (Init && !Init->isValueDependent()) { 11507 if (var->isConstexpr()) { 11508 SmallVector<PartialDiagnosticAt, 8> Notes; 11509 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11510 SourceLocation DiagLoc = var->getLocation(); 11511 // If the note doesn't add any useful information other than a source 11512 // location, fold it into the primary diagnostic. 11513 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11514 diag::note_invalid_subexpr_in_const_expr) { 11515 DiagLoc = Notes[0].first; 11516 Notes.clear(); 11517 } 11518 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11519 << var << Init->getSourceRange(); 11520 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11521 Diag(Notes[I].first, Notes[I].second); 11522 } 11523 } else if (var->isUsableInConstantExpressions(Context)) { 11524 // Check whether the initializer of a const variable of integral or 11525 // enumeration type is an ICE now, since we can't tell whether it was 11526 // initialized by a constant expression if we check later. 11527 var->checkInitIsICE(); 11528 } 11529 11530 // Don't emit further diagnostics about constexpr globals since they 11531 // were just diagnosed. 11532 if (!var->isConstexpr() && GlobalStorage && 11533 var->hasAttr<RequireConstantInitAttr>()) { 11534 // FIXME: Need strict checking in C++03 here. 11535 bool DiagErr = getLangOpts().CPlusPlus11 11536 ? !var->checkInitIsICE() : !checkConstInit(); 11537 if (DiagErr) { 11538 auto attr = var->getAttr<RequireConstantInitAttr>(); 11539 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11540 << Init->getSourceRange(); 11541 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11542 << attr->getRange(); 11543 if (getLangOpts().CPlusPlus11) { 11544 APValue Value; 11545 SmallVector<PartialDiagnosticAt, 8> Notes; 11546 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11547 for (auto &it : Notes) 11548 Diag(it.first, it.second); 11549 } else { 11550 Diag(CacheCulprit->getExprLoc(), 11551 diag::note_invalid_subexpr_in_const_expr) 11552 << CacheCulprit->getSourceRange(); 11553 } 11554 } 11555 } 11556 else if (!var->isConstexpr() && IsGlobal && 11557 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11558 var->getLocation())) { 11559 // Warn about globals which don't have a constant initializer. Don't 11560 // warn about globals with a non-trivial destructor because we already 11561 // warned about them. 11562 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11563 if (!(RD && !RD->hasTrivialDestructor())) { 11564 if (!checkConstInit()) 11565 Diag(var->getLocation(), diag::warn_global_constructor) 11566 << Init->getSourceRange(); 11567 } 11568 } 11569 } 11570 11571 // Require the destructor. 11572 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11573 FinalizeVarWithDestructor(var, recordType); 11574 11575 // If this variable must be emitted, add it as an initializer for the current 11576 // module. 11577 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11578 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11579 } 11580 11581 /// Determines if a variable's alignment is dependent. 11582 static bool hasDependentAlignment(VarDecl *VD) { 11583 if (VD->getType()->isDependentType()) 11584 return true; 11585 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11586 if (I->isAlignmentDependent()) 11587 return true; 11588 return false; 11589 } 11590 11591 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11592 /// any semantic actions necessary after any initializer has been attached. 11593 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11594 // Note that we are no longer parsing the initializer for this declaration. 11595 ParsingInitForAutoVars.erase(ThisDecl); 11596 11597 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11598 if (!VD) 11599 return; 11600 11601 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11602 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11603 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11604 if (PragmaClangBSSSection.Valid) 11605 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11606 PragmaClangBSSSection.SectionName, 11607 PragmaClangBSSSection.PragmaLocation)); 11608 if (PragmaClangDataSection.Valid) 11609 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11610 PragmaClangDataSection.SectionName, 11611 PragmaClangDataSection.PragmaLocation)); 11612 if (PragmaClangRodataSection.Valid) 11613 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11614 PragmaClangRodataSection.SectionName, 11615 PragmaClangRodataSection.PragmaLocation)); 11616 } 11617 11618 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11619 for (auto *BD : DD->bindings()) { 11620 FinalizeDeclaration(BD); 11621 } 11622 } 11623 11624 checkAttributesAfterMerging(*this, *VD); 11625 11626 // Perform TLS alignment check here after attributes attached to the variable 11627 // which may affect the alignment have been processed. Only perform the check 11628 // if the target has a maximum TLS alignment (zero means no constraints). 11629 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11630 // Protect the check so that it's not performed on dependent types and 11631 // dependent alignments (we can't determine the alignment in that case). 11632 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11633 !VD->isInvalidDecl()) { 11634 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11635 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11636 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11637 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11638 << (unsigned)MaxAlignChars.getQuantity(); 11639 } 11640 } 11641 } 11642 11643 if (VD->isStaticLocal()) { 11644 if (FunctionDecl *FD = 11645 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11646 // Static locals inherit dll attributes from their function. 11647 if (Attr *A = getDLLAttr(FD)) { 11648 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11649 NewAttr->setInherited(true); 11650 VD->addAttr(NewAttr); 11651 } 11652 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11653 // function, only __shared__ variables may be declared with 11654 // static storage class. 11655 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11656 CUDADiagIfDeviceCode(VD->getLocation(), 11657 diag::err_device_static_local_var) 11658 << CurrentCUDATarget()) 11659 VD->setInvalidDecl(); 11660 } 11661 } 11662 11663 // Perform check for initializers of device-side global variables. 11664 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11665 // 7.5). We must also apply the same checks to all __shared__ 11666 // variables whether they are local or not. CUDA also allows 11667 // constant initializers for __constant__ and __device__ variables. 11668 if (getLangOpts().CUDA) { 11669 const Expr *Init = VD->getInit(); 11670 if (Init && VD->hasGlobalStorage()) { 11671 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11672 VD->hasAttr<CUDASharedAttr>()) { 11673 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11674 bool AllowedInit = false; 11675 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11676 AllowedInit = 11677 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11678 // We'll allow constant initializers even if it's a non-empty 11679 // constructor according to CUDA rules. This deviates from NVCC, 11680 // but allows us to handle things like constexpr constructors. 11681 if (!AllowedInit && 11682 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11683 AllowedInit = VD->getInit()->isConstantInitializer( 11684 Context, VD->getType()->isReferenceType()); 11685 11686 // Also make sure that destructor, if there is one, is empty. 11687 if (AllowedInit) 11688 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11689 AllowedInit = 11690 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11691 11692 if (!AllowedInit) { 11693 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11694 ? diag::err_shared_var_init 11695 : diag::err_dynamic_var_init) 11696 << Init->getSourceRange(); 11697 VD->setInvalidDecl(); 11698 } 11699 } else { 11700 // This is a host-side global variable. Check that the initializer is 11701 // callable from the host side. 11702 const FunctionDecl *InitFn = nullptr; 11703 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11704 InitFn = CE->getConstructor(); 11705 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11706 InitFn = CE->getDirectCallee(); 11707 } 11708 if (InitFn) { 11709 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11710 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11711 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11712 << InitFnTarget << InitFn; 11713 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11714 VD->setInvalidDecl(); 11715 } 11716 } 11717 } 11718 } 11719 } 11720 11721 // Grab the dllimport or dllexport attribute off of the VarDecl. 11722 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11723 11724 // Imported static data members cannot be defined out-of-line. 11725 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11726 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11727 VD->isThisDeclarationADefinition()) { 11728 // We allow definitions of dllimport class template static data members 11729 // with a warning. 11730 CXXRecordDecl *Context = 11731 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11732 bool IsClassTemplateMember = 11733 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11734 Context->getDescribedClassTemplate(); 11735 11736 Diag(VD->getLocation(), 11737 IsClassTemplateMember 11738 ? diag::warn_attribute_dllimport_static_field_definition 11739 : diag::err_attribute_dllimport_static_field_definition); 11740 Diag(IA->getLocation(), diag::note_attribute); 11741 if (!IsClassTemplateMember) 11742 VD->setInvalidDecl(); 11743 } 11744 } 11745 11746 // dllimport/dllexport variables cannot be thread local, their TLS index 11747 // isn't exported with the variable. 11748 if (DLLAttr && VD->getTLSKind()) { 11749 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11750 if (F && getDLLAttr(F)) { 11751 assert(VD->isStaticLocal()); 11752 // But if this is a static local in a dlimport/dllexport function, the 11753 // function will never be inlined, which means the var would never be 11754 // imported, so having it marked import/export is safe. 11755 } else { 11756 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11757 << DLLAttr; 11758 VD->setInvalidDecl(); 11759 } 11760 } 11761 11762 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11763 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11764 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11765 VD->dropAttr<UsedAttr>(); 11766 } 11767 } 11768 11769 const DeclContext *DC = VD->getDeclContext(); 11770 // If there's a #pragma GCC visibility in scope, and this isn't a class 11771 // member, set the visibility of this variable. 11772 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11773 AddPushedVisibilityAttribute(VD); 11774 11775 // FIXME: Warn on unused var template partial specializations. 11776 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11777 MarkUnusedFileScopedDecl(VD); 11778 11779 // Now we have parsed the initializer and can update the table of magic 11780 // tag values. 11781 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11782 !VD->getType()->isIntegralOrEnumerationType()) 11783 return; 11784 11785 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11786 const Expr *MagicValueExpr = VD->getInit(); 11787 if (!MagicValueExpr) { 11788 continue; 11789 } 11790 llvm::APSInt MagicValueInt; 11791 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11792 Diag(I->getRange().getBegin(), 11793 diag::err_type_tag_for_datatype_not_ice) 11794 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11795 continue; 11796 } 11797 if (MagicValueInt.getActiveBits() > 64) { 11798 Diag(I->getRange().getBegin(), 11799 diag::err_type_tag_for_datatype_too_large) 11800 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11801 continue; 11802 } 11803 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11804 RegisterTypeTagForDatatype(I->getArgumentKind(), 11805 MagicValue, 11806 I->getMatchingCType(), 11807 I->getLayoutCompatible(), 11808 I->getMustBeNull()); 11809 } 11810 } 11811 11812 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11813 auto *VD = dyn_cast<VarDecl>(DD); 11814 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11815 } 11816 11817 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11818 ArrayRef<Decl *> Group) { 11819 SmallVector<Decl*, 8> Decls; 11820 11821 if (DS.isTypeSpecOwned()) 11822 Decls.push_back(DS.getRepAsDecl()); 11823 11824 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11825 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11826 bool DiagnosedMultipleDecomps = false; 11827 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11828 bool DiagnosedNonDeducedAuto = false; 11829 11830 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11831 if (Decl *D = Group[i]) { 11832 // For declarators, there are some additional syntactic-ish checks we need 11833 // to perform. 11834 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11835 if (!FirstDeclaratorInGroup) 11836 FirstDeclaratorInGroup = DD; 11837 if (!FirstDecompDeclaratorInGroup) 11838 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11839 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11840 !hasDeducedAuto(DD)) 11841 FirstNonDeducedAutoInGroup = DD; 11842 11843 if (FirstDeclaratorInGroup != DD) { 11844 // A decomposition declaration cannot be combined with any other 11845 // declaration in the same group. 11846 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11847 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11848 diag::err_decomp_decl_not_alone) 11849 << FirstDeclaratorInGroup->getSourceRange() 11850 << DD->getSourceRange(); 11851 DiagnosedMultipleDecomps = true; 11852 } 11853 11854 // A declarator that uses 'auto' in any way other than to declare a 11855 // variable with a deduced type cannot be combined with any other 11856 // declarator in the same group. 11857 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11858 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11859 diag::err_auto_non_deduced_not_alone) 11860 << FirstNonDeducedAutoInGroup->getType() 11861 ->hasAutoForTrailingReturnType() 11862 << FirstDeclaratorInGroup->getSourceRange() 11863 << DD->getSourceRange(); 11864 DiagnosedNonDeducedAuto = true; 11865 } 11866 } 11867 } 11868 11869 Decls.push_back(D); 11870 } 11871 } 11872 11873 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11874 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11875 handleTagNumbering(Tag, S); 11876 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11877 getLangOpts().CPlusPlus) 11878 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11879 } 11880 } 11881 11882 return BuildDeclaratorGroup(Decls); 11883 } 11884 11885 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11886 /// group, performing any necessary semantic checking. 11887 Sema::DeclGroupPtrTy 11888 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11889 // C++14 [dcl.spec.auto]p7: (DR1347) 11890 // If the type that replaces the placeholder type is not the same in each 11891 // deduction, the program is ill-formed. 11892 if (Group.size() > 1) { 11893 QualType Deduced; 11894 VarDecl *DeducedDecl = nullptr; 11895 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11896 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11897 if (!D || D->isInvalidDecl()) 11898 break; 11899 DeducedType *DT = D->getType()->getContainedDeducedType(); 11900 if (!DT || DT->getDeducedType().isNull()) 11901 continue; 11902 if (Deduced.isNull()) { 11903 Deduced = DT->getDeducedType(); 11904 DeducedDecl = D; 11905 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11906 auto *AT = dyn_cast<AutoType>(DT); 11907 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11908 diag::err_auto_different_deductions) 11909 << (AT ? (unsigned)AT->getKeyword() : 3) 11910 << Deduced << DeducedDecl->getDeclName() 11911 << DT->getDeducedType() << D->getDeclName() 11912 << DeducedDecl->getInit()->getSourceRange() 11913 << D->getInit()->getSourceRange(); 11914 D->setInvalidDecl(); 11915 break; 11916 } 11917 } 11918 } 11919 11920 ActOnDocumentableDecls(Group); 11921 11922 return DeclGroupPtrTy::make( 11923 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11924 } 11925 11926 void Sema::ActOnDocumentableDecl(Decl *D) { 11927 ActOnDocumentableDecls(D); 11928 } 11929 11930 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11931 // Don't parse the comment if Doxygen diagnostics are ignored. 11932 if (Group.empty() || !Group[0]) 11933 return; 11934 11935 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11936 Group[0]->getLocation()) && 11937 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11938 Group[0]->getLocation())) 11939 return; 11940 11941 if (Group.size() >= 2) { 11942 // This is a decl group. Normally it will contain only declarations 11943 // produced from declarator list. But in case we have any definitions or 11944 // additional declaration references: 11945 // 'typedef struct S {} S;' 11946 // 'typedef struct S *S;' 11947 // 'struct S *pS;' 11948 // FinalizeDeclaratorGroup adds these as separate declarations. 11949 Decl *MaybeTagDecl = Group[0]; 11950 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11951 Group = Group.slice(1); 11952 } 11953 } 11954 11955 // See if there are any new comments that are not attached to a decl. 11956 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11957 if (!Comments.empty() && 11958 !Comments.back()->isAttached()) { 11959 // There is at least one comment that not attached to a decl. 11960 // Maybe it should be attached to one of these decls? 11961 // 11962 // Note that this way we pick up not only comments that precede the 11963 // declaration, but also comments that *follow* the declaration -- thanks to 11964 // the lookahead in the lexer: we've consumed the semicolon and looked 11965 // ahead through comments. 11966 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11967 Context.getCommentForDecl(Group[i], &PP); 11968 } 11969 } 11970 11971 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11972 /// to introduce parameters into function prototype scope. 11973 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11974 const DeclSpec &DS = D.getDeclSpec(); 11975 11976 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11977 11978 // C++03 [dcl.stc]p2 also permits 'auto'. 11979 StorageClass SC = SC_None; 11980 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11981 SC = SC_Register; 11982 // In C++11, the 'register' storage class specifier is deprecated. 11983 // In C++17, it is not allowed, but we tolerate it as an extension. 11984 if (getLangOpts().CPlusPlus11) { 11985 Diag(DS.getStorageClassSpecLoc(), 11986 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 11987 : diag::warn_deprecated_register) 11988 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11989 } 11990 } else if (getLangOpts().CPlusPlus && 11991 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11992 SC = SC_Auto; 11993 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11994 Diag(DS.getStorageClassSpecLoc(), 11995 diag::err_invalid_storage_class_in_func_decl); 11996 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11997 } 11998 11999 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 12000 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 12001 << DeclSpec::getSpecifierName(TSCS); 12002 if (DS.isInlineSpecified()) 12003 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 12004 << getLangOpts().CPlusPlus17; 12005 if (DS.isConstexprSpecified()) 12006 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 12007 << 0; 12008 12009 DiagnoseFunctionSpecifiers(DS); 12010 12011 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12012 QualType parmDeclType = TInfo->getType(); 12013 12014 if (getLangOpts().CPlusPlus) { 12015 // Check that there are no default arguments inside the type of this 12016 // parameter. 12017 CheckExtraCXXDefaultArguments(D); 12018 12019 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12020 if (D.getCXXScopeSpec().isSet()) { 12021 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12022 << D.getCXXScopeSpec().getRange(); 12023 D.getCXXScopeSpec().clear(); 12024 } 12025 } 12026 12027 // Ensure we have a valid name 12028 IdentifierInfo *II = nullptr; 12029 if (D.hasName()) { 12030 II = D.getIdentifier(); 12031 if (!II) { 12032 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12033 << GetNameForDeclarator(D).getName(); 12034 D.setInvalidType(true); 12035 } 12036 } 12037 12038 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12039 if (II) { 12040 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12041 ForVisibleRedeclaration); 12042 LookupName(R, S); 12043 if (R.isSingleResult()) { 12044 NamedDecl *PrevDecl = R.getFoundDecl(); 12045 if (PrevDecl->isTemplateParameter()) { 12046 // Maybe we will complain about the shadowed template parameter. 12047 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12048 // Just pretend that we didn't see the previous declaration. 12049 PrevDecl = nullptr; 12050 } else if (S->isDeclScope(PrevDecl)) { 12051 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12052 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12053 12054 // Recover by removing the name 12055 II = nullptr; 12056 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12057 D.setInvalidType(true); 12058 } 12059 } 12060 } 12061 12062 // Temporarily put parameter variables in the translation unit, not 12063 // the enclosing context. This prevents them from accidentally 12064 // looking like class members in C++. 12065 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 12066 D.getLocStart(), 12067 D.getIdentifierLoc(), II, 12068 parmDeclType, TInfo, 12069 SC); 12070 12071 if (D.isInvalidType()) 12072 New->setInvalidDecl(); 12073 12074 assert(S->isFunctionPrototypeScope()); 12075 assert(S->getFunctionPrototypeDepth() >= 1); 12076 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12077 S->getNextFunctionPrototypeIndex()); 12078 12079 // Add the parameter declaration into this scope. 12080 S->AddDecl(New); 12081 if (II) 12082 IdResolver.AddDecl(New); 12083 12084 ProcessDeclAttributes(S, New, D); 12085 12086 if (D.getDeclSpec().isModulePrivateSpecified()) 12087 Diag(New->getLocation(), diag::err_module_private_local) 12088 << 1 << New->getDeclName() 12089 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12090 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12091 12092 if (New->hasAttr<BlocksAttr>()) { 12093 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12094 } 12095 return New; 12096 } 12097 12098 /// Synthesizes a variable for a parameter arising from a 12099 /// typedef. 12100 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12101 SourceLocation Loc, 12102 QualType T) { 12103 /* FIXME: setting StartLoc == Loc. 12104 Would it be worth to modify callers so as to provide proper source 12105 location for the unnamed parameters, embedding the parameter's type? */ 12106 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12107 T, Context.getTrivialTypeSourceInfo(T, Loc), 12108 SC_None, nullptr); 12109 Param->setImplicit(); 12110 return Param; 12111 } 12112 12113 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12114 // Don't diagnose unused-parameter errors in template instantiations; we 12115 // will already have done so in the template itself. 12116 if (inTemplateInstantiation()) 12117 return; 12118 12119 for (const ParmVarDecl *Parameter : Parameters) { 12120 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12121 !Parameter->hasAttr<UnusedAttr>()) { 12122 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12123 << Parameter->getDeclName(); 12124 } 12125 } 12126 } 12127 12128 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12129 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12130 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12131 return; 12132 12133 // Warn if the return value is pass-by-value and larger than the specified 12134 // threshold. 12135 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12136 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12137 if (Size > LangOpts.NumLargeByValueCopy) 12138 Diag(D->getLocation(), diag::warn_return_value_size) 12139 << D->getDeclName() << Size; 12140 } 12141 12142 // Warn if any parameter is pass-by-value and larger than the specified 12143 // threshold. 12144 for (const ParmVarDecl *Parameter : Parameters) { 12145 QualType T = Parameter->getType(); 12146 if (T->isDependentType() || !T.isPODType(Context)) 12147 continue; 12148 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12149 if (Size > LangOpts.NumLargeByValueCopy) 12150 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12151 << Parameter->getDeclName() << Size; 12152 } 12153 } 12154 12155 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12156 SourceLocation NameLoc, IdentifierInfo *Name, 12157 QualType T, TypeSourceInfo *TSInfo, 12158 StorageClass SC) { 12159 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12160 if (getLangOpts().ObjCAutoRefCount && 12161 T.getObjCLifetime() == Qualifiers::OCL_None && 12162 T->isObjCLifetimeType()) { 12163 12164 Qualifiers::ObjCLifetime lifetime; 12165 12166 // Special cases for arrays: 12167 // - if it's const, use __unsafe_unretained 12168 // - otherwise, it's an error 12169 if (T->isArrayType()) { 12170 if (!T.isConstQualified()) { 12171 DelayedDiagnostics.add( 12172 sema::DelayedDiagnostic::makeForbiddenType( 12173 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12174 } 12175 lifetime = Qualifiers::OCL_ExplicitNone; 12176 } else { 12177 lifetime = T->getObjCARCImplicitLifetime(); 12178 } 12179 T = Context.getLifetimeQualifiedType(T, lifetime); 12180 } 12181 12182 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12183 Context.getAdjustedParameterType(T), 12184 TSInfo, SC, nullptr); 12185 12186 // Parameters can not be abstract class types. 12187 // For record types, this is done by the AbstractClassUsageDiagnoser once 12188 // the class has been completely parsed. 12189 if (!CurContext->isRecord() && 12190 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12191 AbstractParamType)) 12192 New->setInvalidDecl(); 12193 12194 // Parameter declarators cannot be interface types. All ObjC objects are 12195 // passed by reference. 12196 if (T->isObjCObjectType()) { 12197 SourceLocation TypeEndLoc = 12198 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 12199 Diag(NameLoc, 12200 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12201 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12202 T = Context.getObjCObjectPointerType(T); 12203 New->setType(T); 12204 } 12205 12206 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12207 // duration shall not be qualified by an address-space qualifier." 12208 // Since all parameters have automatic store duration, they can not have 12209 // an address space. 12210 if (T.getAddressSpace() != LangAS::Default && 12211 // OpenCL allows function arguments declared to be an array of a type 12212 // to be qualified with an address space. 12213 !(getLangOpts().OpenCL && 12214 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12215 Diag(NameLoc, diag::err_arg_with_address_space); 12216 New->setInvalidDecl(); 12217 } 12218 12219 return New; 12220 } 12221 12222 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12223 SourceLocation LocAfterDecls) { 12224 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12225 12226 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12227 // for a K&R function. 12228 if (!FTI.hasPrototype) { 12229 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12230 --i; 12231 if (FTI.Params[i].Param == nullptr) { 12232 SmallString<256> Code; 12233 llvm::raw_svector_ostream(Code) 12234 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12235 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12236 << FTI.Params[i].Ident 12237 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12238 12239 // Implicitly declare the argument as type 'int' for lack of a better 12240 // type. 12241 AttributeFactory attrs; 12242 DeclSpec DS(attrs); 12243 const char* PrevSpec; // unused 12244 unsigned DiagID; // unused 12245 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12246 DiagID, Context.getPrintingPolicy()); 12247 // Use the identifier location for the type source range. 12248 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12249 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12250 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12251 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12252 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12253 } 12254 } 12255 } 12256 } 12257 12258 Decl * 12259 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12260 MultiTemplateParamsArg TemplateParameterLists, 12261 SkipBodyInfo *SkipBody) { 12262 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12263 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12264 Scope *ParentScope = FnBodyScope->getParent(); 12265 12266 D.setFunctionDefinitionKind(FDK_Definition); 12267 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12268 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12269 } 12270 12271 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12272 Consumer.HandleInlineFunctionDefinition(D); 12273 } 12274 12275 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12276 const FunctionDecl*& PossibleZeroParamPrototype) { 12277 // Don't warn about invalid declarations. 12278 if (FD->isInvalidDecl()) 12279 return false; 12280 12281 // Or declarations that aren't global. 12282 if (!FD->isGlobal()) 12283 return false; 12284 12285 // Don't warn about C++ member functions. 12286 if (isa<CXXMethodDecl>(FD)) 12287 return false; 12288 12289 // Don't warn about 'main'. 12290 if (FD->isMain()) 12291 return false; 12292 12293 // Don't warn about inline functions. 12294 if (FD->isInlined()) 12295 return false; 12296 12297 // Don't warn about function templates. 12298 if (FD->getDescribedFunctionTemplate()) 12299 return false; 12300 12301 // Don't warn about function template specializations. 12302 if (FD->isFunctionTemplateSpecialization()) 12303 return false; 12304 12305 // Don't warn for OpenCL kernels. 12306 if (FD->hasAttr<OpenCLKernelAttr>()) 12307 return false; 12308 12309 // Don't warn on explicitly deleted functions. 12310 if (FD->isDeleted()) 12311 return false; 12312 12313 bool MissingPrototype = true; 12314 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12315 Prev; Prev = Prev->getPreviousDecl()) { 12316 // Ignore any declarations that occur in function or method 12317 // scope, because they aren't visible from the header. 12318 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12319 continue; 12320 12321 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12322 if (FD->getNumParams() == 0) 12323 PossibleZeroParamPrototype = Prev; 12324 break; 12325 } 12326 12327 return MissingPrototype; 12328 } 12329 12330 void 12331 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12332 const FunctionDecl *EffectiveDefinition, 12333 SkipBodyInfo *SkipBody) { 12334 const FunctionDecl *Definition = EffectiveDefinition; 12335 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12336 // If this is a friend function defined in a class template, it does not 12337 // have a body until it is used, nevertheless it is a definition, see 12338 // [temp.inst]p2: 12339 // 12340 // ... for the purpose of determining whether an instantiated redeclaration 12341 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12342 // corresponds to a definition in the template is considered to be a 12343 // definition. 12344 // 12345 // The following code must produce redefinition error: 12346 // 12347 // template<typename T> struct C20 { friend void func_20() {} }; 12348 // C20<int> c20i; 12349 // void func_20() {} 12350 // 12351 for (auto I : FD->redecls()) { 12352 if (I != FD && !I->isInvalidDecl() && 12353 I->getFriendObjectKind() != Decl::FOK_None) { 12354 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12355 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12356 // A merged copy of the same function, instantiated as a member of 12357 // the same class, is OK. 12358 if (declaresSameEntity(OrigFD, Original) && 12359 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12360 cast<Decl>(FD->getLexicalDeclContext()))) 12361 continue; 12362 } 12363 12364 if (Original->isThisDeclarationADefinition()) { 12365 Definition = I; 12366 break; 12367 } 12368 } 12369 } 12370 } 12371 } 12372 if (!Definition) 12373 return; 12374 12375 if (canRedefineFunction(Definition, getLangOpts())) 12376 return; 12377 12378 // Don't emit an error when this is redefinition of a typo-corrected 12379 // definition. 12380 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12381 return; 12382 12383 // If we don't have a visible definition of the function, and it's inline or 12384 // a template, skip the new definition. 12385 if (SkipBody && !hasVisibleDefinition(Definition) && 12386 (Definition->getFormalLinkage() == InternalLinkage || 12387 Definition->isInlined() || 12388 Definition->getDescribedFunctionTemplate() || 12389 Definition->getNumTemplateParameterLists())) { 12390 SkipBody->ShouldSkip = true; 12391 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12392 makeMergedDefinitionVisible(TD); 12393 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12394 return; 12395 } 12396 12397 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12398 Definition->getStorageClass() == SC_Extern) 12399 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12400 << FD->getDeclName() << getLangOpts().CPlusPlus; 12401 else 12402 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12403 12404 Diag(Definition->getLocation(), diag::note_previous_definition); 12405 FD->setInvalidDecl(); 12406 } 12407 12408 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12409 Sema &S) { 12410 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12411 12412 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12413 LSI->CallOperator = CallOperator; 12414 LSI->Lambda = LambdaClass; 12415 LSI->ReturnType = CallOperator->getReturnType(); 12416 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12417 12418 if (LCD == LCD_None) 12419 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12420 else if (LCD == LCD_ByCopy) 12421 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12422 else if (LCD == LCD_ByRef) 12423 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12424 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12425 12426 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12427 LSI->Mutable = !CallOperator->isConst(); 12428 12429 // Add the captures to the LSI so they can be noted as already 12430 // captured within tryCaptureVar. 12431 auto I = LambdaClass->field_begin(); 12432 for (const auto &C : LambdaClass->captures()) { 12433 if (C.capturesVariable()) { 12434 VarDecl *VD = C.getCapturedVar(); 12435 if (VD->isInitCapture()) 12436 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12437 QualType CaptureType = VD->getType(); 12438 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12439 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12440 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12441 /*EllipsisLoc*/C.isPackExpansion() 12442 ? C.getEllipsisLoc() : SourceLocation(), 12443 CaptureType, /*Expr*/ nullptr); 12444 12445 } else if (C.capturesThis()) { 12446 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12447 /*Expr*/ nullptr, 12448 C.getCaptureKind() == LCK_StarThis); 12449 } else { 12450 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12451 } 12452 ++I; 12453 } 12454 } 12455 12456 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12457 SkipBodyInfo *SkipBody) { 12458 if (!D) { 12459 // Parsing the function declaration failed in some way. Push on a fake scope 12460 // anyway so we can try to parse the function body. 12461 PushFunctionScope(); 12462 return D; 12463 } 12464 12465 FunctionDecl *FD = nullptr; 12466 12467 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12468 FD = FunTmpl->getTemplatedDecl(); 12469 else 12470 FD = cast<FunctionDecl>(D); 12471 12472 // Check for defining attributes before the check for redefinition. 12473 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12474 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12475 FD->dropAttr<AliasAttr>(); 12476 FD->setInvalidDecl(); 12477 } 12478 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12479 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12480 FD->dropAttr<IFuncAttr>(); 12481 FD->setInvalidDecl(); 12482 } 12483 12484 // See if this is a redefinition. If 'will have body' is already set, then 12485 // these checks were already performed when it was set. 12486 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12487 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12488 12489 // If we're skipping the body, we're done. Don't enter the scope. 12490 if (SkipBody && SkipBody->ShouldSkip) 12491 return D; 12492 } 12493 12494 // Mark this function as "will have a body eventually". This lets users to 12495 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12496 // this function. 12497 FD->setWillHaveBody(); 12498 12499 // If we are instantiating a generic lambda call operator, push 12500 // a LambdaScopeInfo onto the function stack. But use the information 12501 // that's already been calculated (ActOnLambdaExpr) to prime the current 12502 // LambdaScopeInfo. 12503 // When the template operator is being specialized, the LambdaScopeInfo, 12504 // has to be properly restored so that tryCaptureVariable doesn't try 12505 // and capture any new variables. In addition when calculating potential 12506 // captures during transformation of nested lambdas, it is necessary to 12507 // have the LSI properly restored. 12508 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12509 assert(inTemplateInstantiation() && 12510 "There should be an active template instantiation on the stack " 12511 "when instantiating a generic lambda!"); 12512 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12513 } else { 12514 // Enter a new function scope 12515 PushFunctionScope(); 12516 } 12517 12518 // Builtin functions cannot be defined. 12519 if (unsigned BuiltinID = FD->getBuiltinID()) { 12520 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12521 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12522 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12523 FD->setInvalidDecl(); 12524 } 12525 } 12526 12527 // The return type of a function definition must be complete 12528 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12529 QualType ResultType = FD->getReturnType(); 12530 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12531 !FD->isInvalidDecl() && 12532 RequireCompleteType(FD->getLocation(), ResultType, 12533 diag::err_func_def_incomplete_result)) 12534 FD->setInvalidDecl(); 12535 12536 if (FnBodyScope) 12537 PushDeclContext(FnBodyScope, FD); 12538 12539 // Check the validity of our function parameters 12540 CheckParmsForFunctionDef(FD->parameters(), 12541 /*CheckParameterNames=*/true); 12542 12543 // Add non-parameter declarations already in the function to the current 12544 // scope. 12545 if (FnBodyScope) { 12546 for (Decl *NPD : FD->decls()) { 12547 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12548 if (!NonParmDecl) 12549 continue; 12550 assert(!isa<ParmVarDecl>(NonParmDecl) && 12551 "parameters should not be in newly created FD yet"); 12552 12553 // If the decl has a name, make it accessible in the current scope. 12554 if (NonParmDecl->getDeclName()) 12555 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12556 12557 // Similarly, dive into enums and fish their constants out, making them 12558 // accessible in this scope. 12559 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12560 for (auto *EI : ED->enumerators()) 12561 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12562 } 12563 } 12564 } 12565 12566 // Introduce our parameters into the function scope 12567 for (auto Param : FD->parameters()) { 12568 Param->setOwningFunction(FD); 12569 12570 // If this has an identifier, add it to the scope stack. 12571 if (Param->getIdentifier() && FnBodyScope) { 12572 CheckShadow(FnBodyScope, Param); 12573 12574 PushOnScopeChains(Param, FnBodyScope); 12575 } 12576 } 12577 12578 // Ensure that the function's exception specification is instantiated. 12579 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12580 ResolveExceptionSpec(D->getLocation(), FPT); 12581 12582 // dllimport cannot be applied to non-inline function definitions. 12583 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12584 !FD->isTemplateInstantiation()) { 12585 assert(!FD->hasAttr<DLLExportAttr>()); 12586 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12587 FD->setInvalidDecl(); 12588 return D; 12589 } 12590 // We want to attach documentation to original Decl (which might be 12591 // a function template). 12592 ActOnDocumentableDecl(D); 12593 if (getCurLexicalContext()->isObjCContainer() && 12594 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12595 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12596 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12597 12598 return D; 12599 } 12600 12601 /// Given the set of return statements within a function body, 12602 /// compute the variables that are subject to the named return value 12603 /// optimization. 12604 /// 12605 /// Each of the variables that is subject to the named return value 12606 /// optimization will be marked as NRVO variables in the AST, and any 12607 /// return statement that has a marked NRVO variable as its NRVO candidate can 12608 /// use the named return value optimization. 12609 /// 12610 /// This function applies a very simplistic algorithm for NRVO: if every return 12611 /// statement in the scope of a variable has the same NRVO candidate, that 12612 /// candidate is an NRVO variable. 12613 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12614 ReturnStmt **Returns = Scope->Returns.data(); 12615 12616 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12617 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12618 if (!NRVOCandidate->isNRVOVariable()) 12619 Returns[I]->setNRVOCandidate(nullptr); 12620 } 12621 } 12622 } 12623 12624 bool Sema::canDelayFunctionBody(const Declarator &D) { 12625 // We can't delay parsing the body of a constexpr function template (yet). 12626 if (D.getDeclSpec().isConstexprSpecified()) 12627 return false; 12628 12629 // We can't delay parsing the body of a function template with a deduced 12630 // return type (yet). 12631 if (D.getDeclSpec().hasAutoTypeSpec()) { 12632 // If the placeholder introduces a non-deduced trailing return type, 12633 // we can still delay parsing it. 12634 if (D.getNumTypeObjects()) { 12635 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12636 if (Outer.Kind == DeclaratorChunk::Function && 12637 Outer.Fun.hasTrailingReturnType()) { 12638 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12639 return Ty.isNull() || !Ty->isUndeducedType(); 12640 } 12641 } 12642 return false; 12643 } 12644 12645 return true; 12646 } 12647 12648 bool Sema::canSkipFunctionBody(Decl *D) { 12649 // We cannot skip the body of a function (or function template) which is 12650 // constexpr, since we may need to evaluate its body in order to parse the 12651 // rest of the file. 12652 // We cannot skip the body of a function with an undeduced return type, 12653 // because any callers of that function need to know the type. 12654 if (const FunctionDecl *FD = D->getAsFunction()) 12655 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12656 return false; 12657 return Consumer.shouldSkipFunctionBody(D); 12658 } 12659 12660 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12661 if (!Decl) 12662 return nullptr; 12663 if (FunctionDecl *FD = Decl->getAsFunction()) 12664 FD->setHasSkippedBody(); 12665 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 12666 MD->setHasSkippedBody(); 12667 return Decl; 12668 } 12669 12670 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12671 return ActOnFinishFunctionBody(D, BodyArg, false); 12672 } 12673 12674 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12675 bool IsInstantiation) { 12676 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12677 12678 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12679 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12680 12681 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12682 CheckCompletedCoroutineBody(FD, Body); 12683 12684 if (FD) { 12685 FD->setBody(Body); 12686 FD->setWillHaveBody(false); 12687 12688 if (getLangOpts().CPlusPlus14) { 12689 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12690 FD->getReturnType()->isUndeducedType()) { 12691 // If the function has a deduced result type but contains no 'return' 12692 // statements, the result type as written must be exactly 'auto', and 12693 // the deduced result type is 'void'. 12694 if (!FD->getReturnType()->getAs<AutoType>()) { 12695 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12696 << FD->getReturnType(); 12697 FD->setInvalidDecl(); 12698 } else { 12699 // Substitute 'void' for the 'auto' in the type. 12700 TypeLoc ResultType = getReturnTypeLoc(FD); 12701 Context.adjustDeducedFunctionResultType( 12702 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12703 } 12704 } 12705 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12706 // In C++11, we don't use 'auto' deduction rules for lambda call 12707 // operators because we don't support return type deduction. 12708 auto *LSI = getCurLambda(); 12709 if (LSI->HasImplicitReturnType) { 12710 deduceClosureReturnType(*LSI); 12711 12712 // C++11 [expr.prim.lambda]p4: 12713 // [...] if there are no return statements in the compound-statement 12714 // [the deduced type is] the type void 12715 QualType RetType = 12716 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12717 12718 // Update the return type to the deduced type. 12719 const FunctionProtoType *Proto = 12720 FD->getType()->getAs<FunctionProtoType>(); 12721 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12722 Proto->getExtProtoInfo())); 12723 } 12724 } 12725 12726 // If the function implicitly returns zero (like 'main') or is naked, 12727 // don't complain about missing return statements. 12728 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12729 WP.disableCheckFallThrough(); 12730 12731 // MSVC permits the use of pure specifier (=0) on function definition, 12732 // defined at class scope, warn about this non-standard construct. 12733 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12734 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12735 12736 if (!FD->isInvalidDecl()) { 12737 // Don't diagnose unused parameters of defaulted or deleted functions. 12738 if (!FD->isDeleted() && !FD->isDefaulted()) 12739 DiagnoseUnusedParameters(FD->parameters()); 12740 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12741 FD->getReturnType(), FD); 12742 12743 // If this is a structor, we need a vtable. 12744 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12745 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12746 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12747 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12748 12749 // Try to apply the named return value optimization. We have to check 12750 // if we can do this here because lambdas keep return statements around 12751 // to deduce an implicit return type. 12752 if (FD->getReturnType()->isRecordType() && 12753 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 12754 computeNRVO(Body, getCurFunction()); 12755 } 12756 12757 // GNU warning -Wmissing-prototypes: 12758 // Warn if a global function is defined without a previous 12759 // prototype declaration. This warning is issued even if the 12760 // definition itself provides a prototype. The aim is to detect 12761 // global functions that fail to be declared in header files. 12762 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12763 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12764 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12765 12766 if (PossibleZeroParamPrototype) { 12767 // We found a declaration that is not a prototype, 12768 // but that could be a zero-parameter prototype 12769 if (TypeSourceInfo *TI = 12770 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12771 TypeLoc TL = TI->getTypeLoc(); 12772 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12773 Diag(PossibleZeroParamPrototype->getLocation(), 12774 diag::note_declaration_not_a_prototype) 12775 << PossibleZeroParamPrototype 12776 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12777 } 12778 } 12779 12780 // GNU warning -Wstrict-prototypes 12781 // Warn if K&R function is defined without a previous declaration. 12782 // This warning is issued only if the definition itself does not provide 12783 // a prototype. Only K&R definitions do not provide a prototype. 12784 // An empty list in a function declarator that is part of a definition 12785 // of that function specifies that the function has no parameters 12786 // (C99 6.7.5.3p14) 12787 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12788 !LangOpts.CPlusPlus) { 12789 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12790 TypeLoc TL = TI->getTypeLoc(); 12791 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12792 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12793 } 12794 } 12795 12796 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12797 const CXXMethodDecl *KeyFunction; 12798 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12799 MD->isVirtual() && 12800 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12801 MD == KeyFunction->getCanonicalDecl()) { 12802 // Update the key-function state if necessary for this ABI. 12803 if (FD->isInlined() && 12804 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12805 Context.setNonKeyFunction(MD); 12806 12807 // If the newly-chosen key function is already defined, then we 12808 // need to mark the vtable as used retroactively. 12809 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12810 const FunctionDecl *Definition; 12811 if (KeyFunction && KeyFunction->isDefined(Definition)) 12812 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12813 } else { 12814 // We just defined they key function; mark the vtable as used. 12815 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12816 } 12817 } 12818 } 12819 12820 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12821 "Function parsing confused"); 12822 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12823 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12824 MD->setBody(Body); 12825 if (!MD->isInvalidDecl()) { 12826 DiagnoseUnusedParameters(MD->parameters()); 12827 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12828 MD->getReturnType(), MD); 12829 12830 if (Body) 12831 computeNRVO(Body, getCurFunction()); 12832 } 12833 if (getCurFunction()->ObjCShouldCallSuper) { 12834 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12835 << MD->getSelector().getAsString(); 12836 getCurFunction()->ObjCShouldCallSuper = false; 12837 } 12838 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12839 const ObjCMethodDecl *InitMethod = nullptr; 12840 bool isDesignated = 12841 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12842 assert(isDesignated && InitMethod); 12843 (void)isDesignated; 12844 12845 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12846 auto IFace = MD->getClassInterface(); 12847 if (!IFace) 12848 return false; 12849 auto SuperD = IFace->getSuperClass(); 12850 if (!SuperD) 12851 return false; 12852 return SuperD->getIdentifier() == 12853 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12854 }; 12855 // Don't issue this warning for unavailable inits or direct subclasses 12856 // of NSObject. 12857 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12858 Diag(MD->getLocation(), 12859 diag::warn_objc_designated_init_missing_super_call); 12860 Diag(InitMethod->getLocation(), 12861 diag::note_objc_designated_init_marked_here); 12862 } 12863 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12864 } 12865 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12866 // Don't issue this warning for unavaialable inits. 12867 if (!MD->isUnavailable()) 12868 Diag(MD->getLocation(), 12869 diag::warn_objc_secondary_init_missing_init_call); 12870 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12871 } 12872 } else { 12873 // Parsing the function declaration failed in some way. Pop the fake scope 12874 // we pushed on. 12875 PopFunctionScopeInfo(ActivePolicy, dcl); 12876 return nullptr; 12877 } 12878 12879 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12880 DiagnoseUnguardedAvailabilityViolations(dcl); 12881 12882 assert(!getCurFunction()->ObjCShouldCallSuper && 12883 "This should only be set for ObjC methods, which should have been " 12884 "handled in the block above."); 12885 12886 // Verify and clean out per-function state. 12887 if (Body && (!FD || !FD->isDefaulted())) { 12888 // C++ constructors that have function-try-blocks can't have return 12889 // statements in the handlers of that block. (C++ [except.handle]p14) 12890 // Verify this. 12891 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12892 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12893 12894 // Verify that gotos and switch cases don't jump into scopes illegally. 12895 if (getCurFunction()->NeedsScopeChecking() && 12896 !PP.isCodeCompletionEnabled()) 12897 DiagnoseInvalidJumps(Body); 12898 12899 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12900 if (!Destructor->getParent()->isDependentType()) 12901 CheckDestructor(Destructor); 12902 12903 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12904 Destructor->getParent()); 12905 } 12906 12907 // If any errors have occurred, clear out any temporaries that may have 12908 // been leftover. This ensures that these temporaries won't be picked up for 12909 // deletion in some later function. 12910 if (getDiagnostics().hasErrorOccurred() || 12911 getDiagnostics().getSuppressAllDiagnostics()) { 12912 DiscardCleanupsInEvaluationContext(); 12913 } 12914 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12915 !isa<FunctionTemplateDecl>(dcl)) { 12916 // Since the body is valid, issue any analysis-based warnings that are 12917 // enabled. 12918 ActivePolicy = &WP; 12919 } 12920 12921 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12922 (!CheckConstexprFunctionDecl(FD) || 12923 !CheckConstexprFunctionBody(FD, Body))) 12924 FD->setInvalidDecl(); 12925 12926 if (FD && FD->hasAttr<NakedAttr>()) { 12927 for (const Stmt *S : Body->children()) { 12928 // Allow local register variables without initializer as they don't 12929 // require prologue. 12930 bool RegisterVariables = false; 12931 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12932 for (const auto *Decl : DS->decls()) { 12933 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12934 RegisterVariables = 12935 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12936 if (!RegisterVariables) 12937 break; 12938 } 12939 } 12940 } 12941 if (RegisterVariables) 12942 continue; 12943 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12944 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12945 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12946 FD->setInvalidDecl(); 12947 break; 12948 } 12949 } 12950 } 12951 12952 assert(ExprCleanupObjects.size() == 12953 ExprEvalContexts.back().NumCleanupObjects && 12954 "Leftover temporaries in function"); 12955 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12956 assert(MaybeODRUseExprs.empty() && 12957 "Leftover expressions for odr-use checking"); 12958 } 12959 12960 if (!IsInstantiation) 12961 PopDeclContext(); 12962 12963 PopFunctionScopeInfo(ActivePolicy, dcl); 12964 // If any errors have occurred, clear out any temporaries that may have 12965 // been leftover. This ensures that these temporaries won't be picked up for 12966 // deletion in some later function. 12967 if (getDiagnostics().hasErrorOccurred()) { 12968 DiscardCleanupsInEvaluationContext(); 12969 } 12970 12971 return dcl; 12972 } 12973 12974 /// When we finish delayed parsing of an attribute, we must attach it to the 12975 /// relevant Decl. 12976 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12977 ParsedAttributes &Attrs) { 12978 // Always attach attributes to the underlying decl. 12979 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12980 D = TD->getTemplatedDecl(); 12981 ProcessDeclAttributeList(S, D, Attrs.getList()); 12982 12983 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12984 if (Method->isStatic()) 12985 checkThisInStaticMemberFunctionAttributes(Method); 12986 } 12987 12988 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12989 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12990 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12991 IdentifierInfo &II, Scope *S) { 12992 // Find the scope in which the identifier is injected and the corresponding 12993 // DeclContext. 12994 // FIXME: C89 does not say what happens if there is no enclosing block scope. 12995 // In that case, we inject the declaration into the translation unit scope 12996 // instead. 12997 Scope *BlockScope = S; 12998 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 12999 BlockScope = BlockScope->getParent(); 13000 13001 Scope *ContextScope = BlockScope; 13002 while (!ContextScope->getEntity()) 13003 ContextScope = ContextScope->getParent(); 13004 ContextRAII SavedContext(*this, ContextScope->getEntity()); 13005 13006 // Before we produce a declaration for an implicitly defined 13007 // function, see whether there was a locally-scoped declaration of 13008 // this name as a function or variable. If so, use that 13009 // (non-visible) declaration, and complain about it. 13010 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 13011 if (ExternCPrev) { 13012 // We still need to inject the function into the enclosing block scope so 13013 // that later (non-call) uses can see it. 13014 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 13015 13016 // C89 footnote 38: 13017 // If in fact it is not defined as having type "function returning int", 13018 // the behavior is undefined. 13019 if (!isa<FunctionDecl>(ExternCPrev) || 13020 !Context.typesAreCompatible( 13021 cast<FunctionDecl>(ExternCPrev)->getType(), 13022 Context.getFunctionNoProtoType(Context.IntTy))) { 13023 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13024 << ExternCPrev << !getLangOpts().C99; 13025 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13026 return ExternCPrev; 13027 } 13028 } 13029 13030 // Extension in C99. Legal in C90, but warn about it. 13031 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13032 unsigned diag_id; 13033 if (II.getName().startswith("__builtin_")) 13034 diag_id = diag::warn_builtin_unknown; 13035 else if (getLangOpts().C99 || getLangOpts().OpenCL) 13036 diag_id = diag::ext_implicit_function_decl; 13037 else 13038 diag_id = diag::warn_implicit_function_decl; 13039 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL; 13040 13041 // If we found a prior declaration of this function, don't bother building 13042 // another one. We've already pushed that one into scope, so there's nothing 13043 // more to do. 13044 if (ExternCPrev) 13045 return ExternCPrev; 13046 13047 // Because typo correction is expensive, only do it if the implicit 13048 // function declaration is going to be treated as an error. 13049 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13050 TypoCorrection Corrected; 13051 if (S && 13052 (Corrected = CorrectTypo( 13053 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 13054 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 13055 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13056 /*ErrorRecovery*/false); 13057 } 13058 13059 // Set a Declarator for the implicit definition: int foo(); 13060 const char *Dummy; 13061 AttributeFactory attrFactory; 13062 DeclSpec DS(attrFactory); 13063 unsigned DiagID; 13064 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13065 Context.getPrintingPolicy()); 13066 (void)Error; // Silence warning. 13067 assert(!Error && "Error setting up implicit decl!"); 13068 SourceLocation NoLoc; 13069 Declarator D(DS, DeclaratorContext::BlockContext); 13070 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13071 /*IsAmbiguous=*/false, 13072 /*LParenLoc=*/NoLoc, 13073 /*Params=*/nullptr, 13074 /*NumParams=*/0, 13075 /*EllipsisLoc=*/NoLoc, 13076 /*RParenLoc=*/NoLoc, 13077 /*TypeQuals=*/0, 13078 /*RefQualifierIsLvalueRef=*/true, 13079 /*RefQualifierLoc=*/NoLoc, 13080 /*ConstQualifierLoc=*/NoLoc, 13081 /*VolatileQualifierLoc=*/NoLoc, 13082 /*RestrictQualifierLoc=*/NoLoc, 13083 /*MutableLoc=*/NoLoc, 13084 EST_None, 13085 /*ESpecRange=*/SourceRange(), 13086 /*Exceptions=*/nullptr, 13087 /*ExceptionRanges=*/nullptr, 13088 /*NumExceptions=*/0, 13089 /*NoexceptExpr=*/nullptr, 13090 /*ExceptionSpecTokens=*/nullptr, 13091 /*DeclsInPrototype=*/None, 13092 Loc, Loc, D), 13093 DS.getAttributes(), 13094 SourceLocation()); 13095 D.SetIdentifier(&II, Loc); 13096 13097 // Insert this function into the enclosing block scope. 13098 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13099 FD->setImplicit(); 13100 13101 AddKnownFunctionAttributes(FD); 13102 13103 return FD; 13104 } 13105 13106 /// Adds any function attributes that we know a priori based on 13107 /// the declaration of this function. 13108 /// 13109 /// These attributes can apply both to implicitly-declared builtins 13110 /// (like __builtin___printf_chk) or to library-declared functions 13111 /// like NSLog or printf. 13112 /// 13113 /// We need to check for duplicate attributes both here and where user-written 13114 /// attributes are applied to declarations. 13115 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13116 if (FD->isInvalidDecl()) 13117 return; 13118 13119 // If this is a built-in function, map its builtin attributes to 13120 // actual attributes. 13121 if (unsigned BuiltinID = FD->getBuiltinID()) { 13122 // Handle printf-formatting attributes. 13123 unsigned FormatIdx; 13124 bool HasVAListArg; 13125 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13126 if (!FD->hasAttr<FormatAttr>()) { 13127 const char *fmt = "printf"; 13128 unsigned int NumParams = FD->getNumParams(); 13129 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13130 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13131 fmt = "NSString"; 13132 FD->addAttr(FormatAttr::CreateImplicit(Context, 13133 &Context.Idents.get(fmt), 13134 FormatIdx+1, 13135 HasVAListArg ? 0 : FormatIdx+2, 13136 FD->getLocation())); 13137 } 13138 } 13139 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13140 HasVAListArg)) { 13141 if (!FD->hasAttr<FormatAttr>()) 13142 FD->addAttr(FormatAttr::CreateImplicit(Context, 13143 &Context.Idents.get("scanf"), 13144 FormatIdx+1, 13145 HasVAListArg ? 0 : FormatIdx+2, 13146 FD->getLocation())); 13147 } 13148 13149 // Mark const if we don't care about errno and that is the only thing 13150 // preventing the function from being const. This allows IRgen to use LLVM 13151 // intrinsics for such functions. 13152 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13153 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13154 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13155 13156 // We make "fma" on some platforms const because we know it does not set 13157 // errno in those environments even though it could set errno based on the 13158 // C standard. 13159 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13160 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13161 !FD->hasAttr<ConstAttr>()) { 13162 switch (BuiltinID) { 13163 case Builtin::BI__builtin_fma: 13164 case Builtin::BI__builtin_fmaf: 13165 case Builtin::BI__builtin_fmal: 13166 case Builtin::BIfma: 13167 case Builtin::BIfmaf: 13168 case Builtin::BIfmal: 13169 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13170 break; 13171 default: 13172 break; 13173 } 13174 } 13175 13176 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13177 !FD->hasAttr<ReturnsTwiceAttr>()) 13178 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13179 FD->getLocation())); 13180 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13181 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13182 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13183 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13184 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13185 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13186 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13187 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13188 // Add the appropriate attribute, depending on the CUDA compilation mode 13189 // and which target the builtin belongs to. For example, during host 13190 // compilation, aux builtins are __device__, while the rest are __host__. 13191 if (getLangOpts().CUDAIsDevice != 13192 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13193 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13194 else 13195 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13196 } 13197 } 13198 13199 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13200 // throw, add an implicit nothrow attribute to any extern "C" function we come 13201 // across. 13202 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13203 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13204 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13205 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13206 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13207 } 13208 13209 IdentifierInfo *Name = FD->getIdentifier(); 13210 if (!Name) 13211 return; 13212 if ((!getLangOpts().CPlusPlus && 13213 FD->getDeclContext()->isTranslationUnit()) || 13214 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13215 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13216 LinkageSpecDecl::lang_c)) { 13217 // Okay: this could be a libc/libm/Objective-C function we know 13218 // about. 13219 } else 13220 return; 13221 13222 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13223 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13224 // target-specific builtins, perhaps? 13225 if (!FD->hasAttr<FormatAttr>()) 13226 FD->addAttr(FormatAttr::CreateImplicit(Context, 13227 &Context.Idents.get("printf"), 2, 13228 Name->isStr("vasprintf") ? 0 : 3, 13229 FD->getLocation())); 13230 } 13231 13232 if (Name->isStr("__CFStringMakeConstantString")) { 13233 // We already have a __builtin___CFStringMakeConstantString, 13234 // but builds that use -fno-constant-cfstrings don't go through that. 13235 if (!FD->hasAttr<FormatArgAttr>()) 13236 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13237 FD->getLocation())); 13238 } 13239 } 13240 13241 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13242 TypeSourceInfo *TInfo) { 13243 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13244 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13245 13246 if (!TInfo) { 13247 assert(D.isInvalidType() && "no declarator info for valid type"); 13248 TInfo = Context.getTrivialTypeSourceInfo(T); 13249 } 13250 13251 // Scope manipulation handled by caller. 13252 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 13253 D.getLocStart(), 13254 D.getIdentifierLoc(), 13255 D.getIdentifier(), 13256 TInfo); 13257 13258 // Bail out immediately if we have an invalid declaration. 13259 if (D.isInvalidType()) { 13260 NewTD->setInvalidDecl(); 13261 return NewTD; 13262 } 13263 13264 if (D.getDeclSpec().isModulePrivateSpecified()) { 13265 if (CurContext->isFunctionOrMethod()) 13266 Diag(NewTD->getLocation(), diag::err_module_private_local) 13267 << 2 << NewTD->getDeclName() 13268 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13269 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13270 else 13271 NewTD->setModulePrivate(); 13272 } 13273 13274 // C++ [dcl.typedef]p8: 13275 // If the typedef declaration defines an unnamed class (or 13276 // enum), the first typedef-name declared by the declaration 13277 // to be that class type (or enum type) is used to denote the 13278 // class type (or enum type) for linkage purposes only. 13279 // We need to check whether the type was declared in the declaration. 13280 switch (D.getDeclSpec().getTypeSpecType()) { 13281 case TST_enum: 13282 case TST_struct: 13283 case TST_interface: 13284 case TST_union: 13285 case TST_class: { 13286 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13287 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13288 break; 13289 } 13290 13291 default: 13292 break; 13293 } 13294 13295 return NewTD; 13296 } 13297 13298 /// Check that this is a valid underlying type for an enum declaration. 13299 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13300 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13301 QualType T = TI->getType(); 13302 13303 if (T->isDependentType()) 13304 return false; 13305 13306 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13307 if (BT->isInteger()) 13308 return false; 13309 13310 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13311 return true; 13312 } 13313 13314 /// Check whether this is a valid redeclaration of a previous enumeration. 13315 /// \return true if the redeclaration was invalid. 13316 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13317 QualType EnumUnderlyingTy, bool IsFixed, 13318 const EnumDecl *Prev) { 13319 if (IsScoped != Prev->isScoped()) { 13320 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13321 << Prev->isScoped(); 13322 Diag(Prev->getLocation(), diag::note_previous_declaration); 13323 return true; 13324 } 13325 13326 if (IsFixed && Prev->isFixed()) { 13327 if (!EnumUnderlyingTy->isDependentType() && 13328 !Prev->getIntegerType()->isDependentType() && 13329 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13330 Prev->getIntegerType())) { 13331 // TODO: Highlight the underlying type of the redeclaration. 13332 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13333 << EnumUnderlyingTy << Prev->getIntegerType(); 13334 Diag(Prev->getLocation(), diag::note_previous_declaration) 13335 << Prev->getIntegerTypeRange(); 13336 return true; 13337 } 13338 } else if (IsFixed != Prev->isFixed()) { 13339 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13340 << Prev->isFixed(); 13341 Diag(Prev->getLocation(), diag::note_previous_declaration); 13342 return true; 13343 } 13344 13345 return false; 13346 } 13347 13348 /// Get diagnostic %select index for tag kind for 13349 /// redeclaration diagnostic message. 13350 /// WARNING: Indexes apply to particular diagnostics only! 13351 /// 13352 /// \returns diagnostic %select index. 13353 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13354 switch (Tag) { 13355 case TTK_Struct: return 0; 13356 case TTK_Interface: return 1; 13357 case TTK_Class: return 2; 13358 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13359 } 13360 } 13361 13362 /// Determine if tag kind is a class-key compatible with 13363 /// class for redeclaration (class, struct, or __interface). 13364 /// 13365 /// \returns true iff the tag kind is compatible. 13366 static bool isClassCompatTagKind(TagTypeKind Tag) 13367 { 13368 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13369 } 13370 13371 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13372 TagTypeKind TTK) { 13373 if (isa<TypedefDecl>(PrevDecl)) 13374 return NTK_Typedef; 13375 else if (isa<TypeAliasDecl>(PrevDecl)) 13376 return NTK_TypeAlias; 13377 else if (isa<ClassTemplateDecl>(PrevDecl)) 13378 return NTK_Template; 13379 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13380 return NTK_TypeAliasTemplate; 13381 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13382 return NTK_TemplateTemplateArgument; 13383 switch (TTK) { 13384 case TTK_Struct: 13385 case TTK_Interface: 13386 case TTK_Class: 13387 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13388 case TTK_Union: 13389 return NTK_NonUnion; 13390 case TTK_Enum: 13391 return NTK_NonEnum; 13392 } 13393 llvm_unreachable("invalid TTK"); 13394 } 13395 13396 /// Determine whether a tag with a given kind is acceptable 13397 /// as a redeclaration of the given tag declaration. 13398 /// 13399 /// \returns true if the new tag kind is acceptable, false otherwise. 13400 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13401 TagTypeKind NewTag, bool isDefinition, 13402 SourceLocation NewTagLoc, 13403 const IdentifierInfo *Name) { 13404 // C++ [dcl.type.elab]p3: 13405 // The class-key or enum keyword present in the 13406 // elaborated-type-specifier shall agree in kind with the 13407 // declaration to which the name in the elaborated-type-specifier 13408 // refers. This rule also applies to the form of 13409 // elaborated-type-specifier that declares a class-name or 13410 // friend class since it can be construed as referring to the 13411 // definition of the class. Thus, in any 13412 // elaborated-type-specifier, the enum keyword shall be used to 13413 // refer to an enumeration (7.2), the union class-key shall be 13414 // used to refer to a union (clause 9), and either the class or 13415 // struct class-key shall be used to refer to a class (clause 9) 13416 // declared using the class or struct class-key. 13417 TagTypeKind OldTag = Previous->getTagKind(); 13418 if (!isDefinition || !isClassCompatTagKind(NewTag)) 13419 if (OldTag == NewTag) 13420 return true; 13421 13422 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13423 // Warn about the struct/class tag mismatch. 13424 bool isTemplate = false; 13425 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13426 isTemplate = Record->getDescribedClassTemplate(); 13427 13428 if (inTemplateInstantiation()) { 13429 // In a template instantiation, do not offer fix-its for tag mismatches 13430 // since they usually mess up the template instead of fixing the problem. 13431 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13432 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13433 << getRedeclDiagFromTagKind(OldTag); 13434 return true; 13435 } 13436 13437 if (isDefinition) { 13438 // On definitions, check previous tags and issue a fix-it for each 13439 // one that doesn't match the current tag. 13440 if (Previous->getDefinition()) { 13441 // Don't suggest fix-its for redefinitions. 13442 return true; 13443 } 13444 13445 bool previousMismatch = false; 13446 for (auto I : Previous->redecls()) { 13447 if (I->getTagKind() != NewTag) { 13448 if (!previousMismatch) { 13449 previousMismatch = true; 13450 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13451 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13452 << getRedeclDiagFromTagKind(I->getTagKind()); 13453 } 13454 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13455 << getRedeclDiagFromTagKind(NewTag) 13456 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13457 TypeWithKeyword::getTagTypeKindName(NewTag)); 13458 } 13459 } 13460 return true; 13461 } 13462 13463 // Check for a previous definition. If current tag and definition 13464 // are same type, do nothing. If no definition, but disagree with 13465 // with previous tag type, give a warning, but no fix-it. 13466 const TagDecl *Redecl = Previous->getDefinition() ? 13467 Previous->getDefinition() : Previous; 13468 if (Redecl->getTagKind() == NewTag) { 13469 return true; 13470 } 13471 13472 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13473 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13474 << getRedeclDiagFromTagKind(OldTag); 13475 Diag(Redecl->getLocation(), diag::note_previous_use); 13476 13477 // If there is a previous definition, suggest a fix-it. 13478 if (Previous->getDefinition()) { 13479 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13480 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13481 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13482 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13483 } 13484 13485 return true; 13486 } 13487 return false; 13488 } 13489 13490 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13491 /// from an outer enclosing namespace or file scope inside a friend declaration. 13492 /// This should provide the commented out code in the following snippet: 13493 /// namespace N { 13494 /// struct X; 13495 /// namespace M { 13496 /// struct Y { friend struct /*N::*/ X; }; 13497 /// } 13498 /// } 13499 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13500 SourceLocation NameLoc) { 13501 // While the decl is in a namespace, do repeated lookup of that name and see 13502 // if we get the same namespace back. If we do not, continue until 13503 // translation unit scope, at which point we have a fully qualified NNS. 13504 SmallVector<IdentifierInfo *, 4> Namespaces; 13505 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13506 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13507 // This tag should be declared in a namespace, which can only be enclosed by 13508 // other namespaces. Bail if there's an anonymous namespace in the chain. 13509 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13510 if (!Namespace || Namespace->isAnonymousNamespace()) 13511 return FixItHint(); 13512 IdentifierInfo *II = Namespace->getIdentifier(); 13513 Namespaces.push_back(II); 13514 NamedDecl *Lookup = SemaRef.LookupSingleName( 13515 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13516 if (Lookup == Namespace) 13517 break; 13518 } 13519 13520 // Once we have all the namespaces, reverse them to go outermost first, and 13521 // build an NNS. 13522 SmallString<64> Insertion; 13523 llvm::raw_svector_ostream OS(Insertion); 13524 if (DC->isTranslationUnit()) 13525 OS << "::"; 13526 std::reverse(Namespaces.begin(), Namespaces.end()); 13527 for (auto *II : Namespaces) 13528 OS << II->getName() << "::"; 13529 return FixItHint::CreateInsertion(NameLoc, Insertion); 13530 } 13531 13532 /// Determine whether a tag originally declared in context \p OldDC can 13533 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 13534 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13535 /// using-declaration). 13536 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13537 DeclContext *NewDC) { 13538 OldDC = OldDC->getRedeclContext(); 13539 NewDC = NewDC->getRedeclContext(); 13540 13541 if (OldDC->Equals(NewDC)) 13542 return true; 13543 13544 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13545 // encloses the other). 13546 if (S.getLangOpts().MSVCCompat && 13547 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13548 return true; 13549 13550 return false; 13551 } 13552 13553 /// This is invoked when we see 'struct foo' or 'struct {'. In the 13554 /// former case, Name will be non-null. In the later case, Name will be null. 13555 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13556 /// reference/declaration/definition of a tag. 13557 /// 13558 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13559 /// trailing-type-specifier) other than one in an alias-declaration. 13560 /// 13561 /// \param SkipBody If non-null, will be set to indicate if the caller should 13562 /// skip the definition of this tag and treat it as if it were a declaration. 13563 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13564 SourceLocation KWLoc, CXXScopeSpec &SS, 13565 IdentifierInfo *Name, SourceLocation NameLoc, 13566 AttributeList *Attr, AccessSpecifier AS, 13567 SourceLocation ModulePrivateLoc, 13568 MultiTemplateParamsArg TemplateParameterLists, 13569 bool &OwnedDecl, bool &IsDependent, 13570 SourceLocation ScopedEnumKWLoc, 13571 bool ScopedEnumUsesClassTag, 13572 TypeResult UnderlyingType, 13573 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13574 SkipBodyInfo *SkipBody) { 13575 // If this is not a definition, it must have a name. 13576 IdentifierInfo *OrigName = Name; 13577 assert((Name != nullptr || TUK == TUK_Definition) && 13578 "Nameless record must be a definition!"); 13579 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13580 13581 OwnedDecl = false; 13582 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13583 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13584 13585 // FIXME: Check member specializations more carefully. 13586 bool isMemberSpecialization = false; 13587 bool Invalid = false; 13588 13589 // We only need to do this matching if we have template parameters 13590 // or a scope specifier, which also conveniently avoids this work 13591 // for non-C++ cases. 13592 if (TemplateParameterLists.size() > 0 || 13593 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13594 if (TemplateParameterList *TemplateParams = 13595 MatchTemplateParametersToScopeSpecifier( 13596 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13597 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13598 if (Kind == TTK_Enum) { 13599 Diag(KWLoc, diag::err_enum_template); 13600 return nullptr; 13601 } 13602 13603 if (TemplateParams->size() > 0) { 13604 // This is a declaration or definition of a class template (which may 13605 // be a member of another template). 13606 13607 if (Invalid) 13608 return nullptr; 13609 13610 OwnedDecl = false; 13611 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13612 SS, Name, NameLoc, Attr, 13613 TemplateParams, AS, 13614 ModulePrivateLoc, 13615 /*FriendLoc*/SourceLocation(), 13616 TemplateParameterLists.size()-1, 13617 TemplateParameterLists.data(), 13618 SkipBody); 13619 return Result.get(); 13620 } else { 13621 // The "template<>" header is extraneous. 13622 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13623 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13624 isMemberSpecialization = true; 13625 } 13626 } 13627 } 13628 13629 // Figure out the underlying type if this a enum declaration. We need to do 13630 // this early, because it's needed to detect if this is an incompatible 13631 // redeclaration. 13632 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13633 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 13634 13635 if (Kind == TTK_Enum) { 13636 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 13637 // No underlying type explicitly specified, or we failed to parse the 13638 // type, default to int. 13639 EnumUnderlying = Context.IntTy.getTypePtr(); 13640 } else if (UnderlyingType.get()) { 13641 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13642 // integral type; any cv-qualification is ignored. 13643 TypeSourceInfo *TI = nullptr; 13644 GetTypeFromParser(UnderlyingType.get(), &TI); 13645 EnumUnderlying = TI; 13646 13647 if (CheckEnumUnderlyingType(TI)) 13648 // Recover by falling back to int. 13649 EnumUnderlying = Context.IntTy.getTypePtr(); 13650 13651 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13652 UPPC_FixedUnderlyingType)) 13653 EnumUnderlying = Context.IntTy.getTypePtr(); 13654 13655 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13656 // For MSVC ABI compatibility, unfixed enums must use an underlying type 13657 // of 'int'. However, if this is an unfixed forward declaration, don't set 13658 // the underlying type unless the user enables -fms-compatibility. This 13659 // makes unfixed forward declared enums incomplete and is more conforming. 13660 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 13661 EnumUnderlying = Context.IntTy.getTypePtr(); 13662 } 13663 } 13664 13665 DeclContext *SearchDC = CurContext; 13666 DeclContext *DC = CurContext; 13667 bool isStdBadAlloc = false; 13668 bool isStdAlignValT = false; 13669 13670 RedeclarationKind Redecl = forRedeclarationInCurContext(); 13671 if (TUK == TUK_Friend || TUK == TUK_Reference) 13672 Redecl = NotForRedeclaration; 13673 13674 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13675 /// implemented asks for structural equivalence checking, the returned decl 13676 /// here is passed back to the parser, allowing the tag body to be parsed. 13677 auto createTagFromNewDecl = [&]() -> TagDecl * { 13678 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13679 // If there is an identifier, use the location of the identifier as the 13680 // location of the decl, otherwise use the location of the struct/union 13681 // keyword. 13682 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13683 TagDecl *New = nullptr; 13684 13685 if (Kind == TTK_Enum) { 13686 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13687 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 13688 // If this is an undefined enum, bail. 13689 if (TUK != TUK_Definition && !Invalid) 13690 return nullptr; 13691 if (EnumUnderlying) { 13692 EnumDecl *ED = cast<EnumDecl>(New); 13693 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13694 ED->setIntegerTypeSourceInfo(TI); 13695 else 13696 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13697 ED->setPromotionType(ED->getIntegerType()); 13698 } 13699 } else { // struct/union 13700 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13701 nullptr); 13702 } 13703 13704 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13705 // Add alignment attributes if necessary; these attributes are checked 13706 // when the ASTContext lays out the structure. 13707 // 13708 // It is important for implementing the correct semantics that this 13709 // happen here (in ActOnTag). The #pragma pack stack is 13710 // maintained as a result of parser callbacks which can occur at 13711 // many points during the parsing of a struct declaration (because 13712 // the #pragma tokens are effectively skipped over during the 13713 // parsing of the struct). 13714 if (TUK == TUK_Definition) { 13715 AddAlignmentAttributesForRecord(RD); 13716 AddMsStructLayoutForRecord(RD); 13717 } 13718 } 13719 New->setLexicalDeclContext(CurContext); 13720 return New; 13721 }; 13722 13723 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13724 if (Name && SS.isNotEmpty()) { 13725 // We have a nested-name tag ('struct foo::bar'). 13726 13727 // Check for invalid 'foo::'. 13728 if (SS.isInvalid()) { 13729 Name = nullptr; 13730 goto CreateNewDecl; 13731 } 13732 13733 // If this is a friend or a reference to a class in a dependent 13734 // context, don't try to make a decl for it. 13735 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13736 DC = computeDeclContext(SS, false); 13737 if (!DC) { 13738 IsDependent = true; 13739 return nullptr; 13740 } 13741 } else { 13742 DC = computeDeclContext(SS, true); 13743 if (!DC) { 13744 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13745 << SS.getRange(); 13746 return nullptr; 13747 } 13748 } 13749 13750 if (RequireCompleteDeclContext(SS, DC)) 13751 return nullptr; 13752 13753 SearchDC = DC; 13754 // Look-up name inside 'foo::'. 13755 LookupQualifiedName(Previous, DC); 13756 13757 if (Previous.isAmbiguous()) 13758 return nullptr; 13759 13760 if (Previous.empty()) { 13761 // Name lookup did not find anything. However, if the 13762 // nested-name-specifier refers to the current instantiation, 13763 // and that current instantiation has any dependent base 13764 // classes, we might find something at instantiation time: treat 13765 // this as a dependent elaborated-type-specifier. 13766 // But this only makes any sense for reference-like lookups. 13767 if (Previous.wasNotFoundInCurrentInstantiation() && 13768 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13769 IsDependent = true; 13770 return nullptr; 13771 } 13772 13773 // A tag 'foo::bar' must already exist. 13774 Diag(NameLoc, diag::err_not_tag_in_scope) 13775 << Kind << Name << DC << SS.getRange(); 13776 Name = nullptr; 13777 Invalid = true; 13778 goto CreateNewDecl; 13779 } 13780 } else if (Name) { 13781 // C++14 [class.mem]p14: 13782 // If T is the name of a class, then each of the following shall have a 13783 // name different from T: 13784 // -- every member of class T that is itself a type 13785 if (TUK != TUK_Reference && TUK != TUK_Friend && 13786 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13787 return nullptr; 13788 13789 // If this is a named struct, check to see if there was a previous forward 13790 // declaration or definition. 13791 // FIXME: We're looking into outer scopes here, even when we 13792 // shouldn't be. Doing so can result in ambiguities that we 13793 // shouldn't be diagnosing. 13794 LookupName(Previous, S); 13795 13796 // When declaring or defining a tag, ignore ambiguities introduced 13797 // by types using'ed into this scope. 13798 if (Previous.isAmbiguous() && 13799 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13800 LookupResult::Filter F = Previous.makeFilter(); 13801 while (F.hasNext()) { 13802 NamedDecl *ND = F.next(); 13803 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13804 SearchDC->getRedeclContext())) 13805 F.erase(); 13806 } 13807 F.done(); 13808 } 13809 13810 // C++11 [namespace.memdef]p3: 13811 // If the name in a friend declaration is neither qualified nor 13812 // a template-id and the declaration is a function or an 13813 // elaborated-type-specifier, the lookup to determine whether 13814 // the entity has been previously declared shall not consider 13815 // any scopes outside the innermost enclosing namespace. 13816 // 13817 // MSVC doesn't implement the above rule for types, so a friend tag 13818 // declaration may be a redeclaration of a type declared in an enclosing 13819 // scope. They do implement this rule for friend functions. 13820 // 13821 // Does it matter that this should be by scope instead of by 13822 // semantic context? 13823 if (!Previous.empty() && TUK == TUK_Friend) { 13824 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13825 LookupResult::Filter F = Previous.makeFilter(); 13826 bool FriendSawTagOutsideEnclosingNamespace = false; 13827 while (F.hasNext()) { 13828 NamedDecl *ND = F.next(); 13829 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13830 if (DC->isFileContext() && 13831 !EnclosingNS->Encloses(ND->getDeclContext())) { 13832 if (getLangOpts().MSVCCompat) 13833 FriendSawTagOutsideEnclosingNamespace = true; 13834 else 13835 F.erase(); 13836 } 13837 } 13838 F.done(); 13839 13840 // Diagnose this MSVC extension in the easy case where lookup would have 13841 // unambiguously found something outside the enclosing namespace. 13842 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13843 NamedDecl *ND = Previous.getFoundDecl(); 13844 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13845 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13846 } 13847 } 13848 13849 // Note: there used to be some attempt at recovery here. 13850 if (Previous.isAmbiguous()) 13851 return nullptr; 13852 13853 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13854 // FIXME: This makes sure that we ignore the contexts associated 13855 // with C structs, unions, and enums when looking for a matching 13856 // tag declaration or definition. See the similar lookup tweak 13857 // in Sema::LookupName; is there a better way to deal with this? 13858 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13859 SearchDC = SearchDC->getParent(); 13860 } 13861 } 13862 13863 if (Previous.isSingleResult() && 13864 Previous.getFoundDecl()->isTemplateParameter()) { 13865 // Maybe we will complain about the shadowed template parameter. 13866 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13867 // Just pretend that we didn't see the previous declaration. 13868 Previous.clear(); 13869 } 13870 13871 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13872 DC->Equals(getStdNamespace())) { 13873 if (Name->isStr("bad_alloc")) { 13874 // This is a declaration of or a reference to "std::bad_alloc". 13875 isStdBadAlloc = true; 13876 13877 // If std::bad_alloc has been implicitly declared (but made invisible to 13878 // name lookup), fill in this implicit declaration as the previous 13879 // declaration, so that the declarations get chained appropriately. 13880 if (Previous.empty() && StdBadAlloc) 13881 Previous.addDecl(getStdBadAlloc()); 13882 } else if (Name->isStr("align_val_t")) { 13883 isStdAlignValT = true; 13884 if (Previous.empty() && StdAlignValT) 13885 Previous.addDecl(getStdAlignValT()); 13886 } 13887 } 13888 13889 // If we didn't find a previous declaration, and this is a reference 13890 // (or friend reference), move to the correct scope. In C++, we 13891 // also need to do a redeclaration lookup there, just in case 13892 // there's a shadow friend decl. 13893 if (Name && Previous.empty() && 13894 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13895 if (Invalid) goto CreateNewDecl; 13896 assert(SS.isEmpty()); 13897 13898 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13899 // C++ [basic.scope.pdecl]p5: 13900 // -- for an elaborated-type-specifier of the form 13901 // 13902 // class-key identifier 13903 // 13904 // if the elaborated-type-specifier is used in the 13905 // decl-specifier-seq or parameter-declaration-clause of a 13906 // function defined in namespace scope, the identifier is 13907 // declared as a class-name in the namespace that contains 13908 // the declaration; otherwise, except as a friend 13909 // declaration, the identifier is declared in the smallest 13910 // non-class, non-function-prototype scope that contains the 13911 // declaration. 13912 // 13913 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13914 // C structs and unions. 13915 // 13916 // It is an error in C++ to declare (rather than define) an enum 13917 // type, including via an elaborated type specifier. We'll 13918 // diagnose that later; for now, declare the enum in the same 13919 // scope as we would have picked for any other tag type. 13920 // 13921 // GNU C also supports this behavior as part of its incomplete 13922 // enum types extension, while GNU C++ does not. 13923 // 13924 // Find the context where we'll be declaring the tag. 13925 // FIXME: We would like to maintain the current DeclContext as the 13926 // lexical context, 13927 SearchDC = getTagInjectionContext(SearchDC); 13928 13929 // Find the scope where we'll be declaring the tag. 13930 S = getTagInjectionScope(S, getLangOpts()); 13931 } else { 13932 assert(TUK == TUK_Friend); 13933 // C++ [namespace.memdef]p3: 13934 // If a friend declaration in a non-local class first declares a 13935 // class or function, the friend class or function is a member of 13936 // the innermost enclosing namespace. 13937 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13938 } 13939 13940 // In C++, we need to do a redeclaration lookup to properly 13941 // diagnose some problems. 13942 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13943 // hidden declaration so that we don't get ambiguity errors when using a 13944 // type declared by an elaborated-type-specifier. In C that is not correct 13945 // and we should instead merge compatible types found by lookup. 13946 if (getLangOpts().CPlusPlus) { 13947 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13948 LookupQualifiedName(Previous, SearchDC); 13949 } else { 13950 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13951 LookupName(Previous, S); 13952 } 13953 } 13954 13955 // If we have a known previous declaration to use, then use it. 13956 if (Previous.empty() && SkipBody && SkipBody->Previous) 13957 Previous.addDecl(SkipBody->Previous); 13958 13959 if (!Previous.empty()) { 13960 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13961 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13962 13963 // It's okay to have a tag decl in the same scope as a typedef 13964 // which hides a tag decl in the same scope. Finding this 13965 // insanity with a redeclaration lookup can only actually happen 13966 // in C++. 13967 // 13968 // This is also okay for elaborated-type-specifiers, which is 13969 // technically forbidden by the current standard but which is 13970 // okay according to the likely resolution of an open issue; 13971 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13972 if (getLangOpts().CPlusPlus) { 13973 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13974 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13975 TagDecl *Tag = TT->getDecl(); 13976 if (Tag->getDeclName() == Name && 13977 Tag->getDeclContext()->getRedeclContext() 13978 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13979 PrevDecl = Tag; 13980 Previous.clear(); 13981 Previous.addDecl(Tag); 13982 Previous.resolveKind(); 13983 } 13984 } 13985 } 13986 } 13987 13988 // If this is a redeclaration of a using shadow declaration, it must 13989 // declare a tag in the same context. In MSVC mode, we allow a 13990 // redefinition if either context is within the other. 13991 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13992 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13993 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13994 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13995 !(OldTag && isAcceptableTagRedeclContext( 13996 *this, OldTag->getDeclContext(), SearchDC))) { 13997 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13998 Diag(Shadow->getTargetDecl()->getLocation(), 13999 diag::note_using_decl_target); 14000 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 14001 << 0; 14002 // Recover by ignoring the old declaration. 14003 Previous.clear(); 14004 goto CreateNewDecl; 14005 } 14006 } 14007 14008 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 14009 // If this is a use of a previous tag, or if the tag is already declared 14010 // in the same scope (so that the definition/declaration completes or 14011 // rementions the tag), reuse the decl. 14012 if (TUK == TUK_Reference || TUK == TUK_Friend || 14013 isDeclInScope(DirectPrevDecl, SearchDC, S, 14014 SS.isNotEmpty() || isMemberSpecialization)) { 14015 // Make sure that this wasn't declared as an enum and now used as a 14016 // struct or something similar. 14017 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14018 TUK == TUK_Definition, KWLoc, 14019 Name)) { 14020 bool SafeToContinue 14021 = (PrevTagDecl->getTagKind() != TTK_Enum && 14022 Kind != TTK_Enum); 14023 if (SafeToContinue) 14024 Diag(KWLoc, diag::err_use_with_wrong_tag) 14025 << Name 14026 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14027 PrevTagDecl->getKindName()); 14028 else 14029 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14030 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14031 14032 if (SafeToContinue) 14033 Kind = PrevTagDecl->getTagKind(); 14034 else { 14035 // Recover by making this an anonymous redefinition. 14036 Name = nullptr; 14037 Previous.clear(); 14038 Invalid = true; 14039 } 14040 } 14041 14042 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14043 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14044 14045 // If this is an elaborated-type-specifier for a scoped enumeration, 14046 // the 'class' keyword is not necessary and not permitted. 14047 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14048 if (ScopedEnum) 14049 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14050 << PrevEnum->isScoped() 14051 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14052 return PrevTagDecl; 14053 } 14054 14055 QualType EnumUnderlyingTy; 14056 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14057 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14058 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14059 EnumUnderlyingTy = QualType(T, 0); 14060 14061 // All conflicts with previous declarations are recovered by 14062 // returning the previous declaration, unless this is a definition, 14063 // in which case we want the caller to bail out. 14064 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14065 ScopedEnum, EnumUnderlyingTy, 14066 IsFixed, PrevEnum)) 14067 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14068 } 14069 14070 // C++11 [class.mem]p1: 14071 // A member shall not be declared twice in the member-specification, 14072 // except that a nested class or member class template can be declared 14073 // and then later defined. 14074 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14075 S->isDeclScope(PrevDecl)) { 14076 Diag(NameLoc, diag::ext_member_redeclared); 14077 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14078 } 14079 14080 if (!Invalid) { 14081 // If this is a use, just return the declaration we found, unless 14082 // we have attributes. 14083 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14084 if (Attr) { 14085 // FIXME: Diagnose these attributes. For now, we create a new 14086 // declaration to hold them. 14087 } else if (TUK == TUK_Reference && 14088 (PrevTagDecl->getFriendObjectKind() == 14089 Decl::FOK_Undeclared || 14090 PrevDecl->getOwningModule() != getCurrentModule()) && 14091 SS.isEmpty()) { 14092 // This declaration is a reference to an existing entity, but 14093 // has different visibility from that entity: it either makes 14094 // a friend visible or it makes a type visible in a new module. 14095 // In either case, create a new declaration. We only do this if 14096 // the declaration would have meant the same thing if no prior 14097 // declaration were found, that is, if it was found in the same 14098 // scope where we would have injected a declaration. 14099 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14100 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14101 return PrevTagDecl; 14102 // This is in the injected scope, create a new declaration in 14103 // that scope. 14104 S = getTagInjectionScope(S, getLangOpts()); 14105 } else { 14106 return PrevTagDecl; 14107 } 14108 } 14109 14110 // Diagnose attempts to redefine a tag. 14111 if (TUK == TUK_Definition) { 14112 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14113 // If we're defining a specialization and the previous definition 14114 // is from an implicit instantiation, don't emit an error 14115 // here; we'll catch this in the general case below. 14116 bool IsExplicitSpecializationAfterInstantiation = false; 14117 if (isMemberSpecialization) { 14118 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14119 IsExplicitSpecializationAfterInstantiation = 14120 RD->getTemplateSpecializationKind() != 14121 TSK_ExplicitSpecialization; 14122 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14123 IsExplicitSpecializationAfterInstantiation = 14124 ED->getTemplateSpecializationKind() != 14125 TSK_ExplicitSpecialization; 14126 } 14127 14128 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14129 // not keep more that one definition around (merge them). However, 14130 // ensure the decl passes the structural compatibility check in 14131 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14132 NamedDecl *Hidden = nullptr; 14133 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14134 // There is a definition of this tag, but it is not visible. We 14135 // explicitly make use of C++'s one definition rule here, and 14136 // assume that this definition is identical to the hidden one 14137 // we already have. Make the existing definition visible and 14138 // use it in place of this one. 14139 if (!getLangOpts().CPlusPlus) { 14140 // Postpone making the old definition visible until after we 14141 // complete parsing the new one and do the structural 14142 // comparison. 14143 SkipBody->CheckSameAsPrevious = true; 14144 SkipBody->New = createTagFromNewDecl(); 14145 SkipBody->Previous = Hidden; 14146 } else { 14147 SkipBody->ShouldSkip = true; 14148 makeMergedDefinitionVisible(Hidden); 14149 } 14150 return Def; 14151 } else if (!IsExplicitSpecializationAfterInstantiation) { 14152 // A redeclaration in function prototype scope in C isn't 14153 // visible elsewhere, so merely issue a warning. 14154 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14155 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14156 else 14157 Diag(NameLoc, diag::err_redefinition) << Name; 14158 notePreviousDefinition(Def, 14159 NameLoc.isValid() ? NameLoc : KWLoc); 14160 // If this is a redefinition, recover by making this 14161 // struct be anonymous, which will make any later 14162 // references get the previous definition. 14163 Name = nullptr; 14164 Previous.clear(); 14165 Invalid = true; 14166 } 14167 } else { 14168 // If the type is currently being defined, complain 14169 // about a nested redefinition. 14170 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14171 if (TD->isBeingDefined()) { 14172 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14173 Diag(PrevTagDecl->getLocation(), 14174 diag::note_previous_definition); 14175 Name = nullptr; 14176 Previous.clear(); 14177 Invalid = true; 14178 } 14179 } 14180 14181 // Okay, this is definition of a previously declared or referenced 14182 // tag. We're going to create a new Decl for it. 14183 } 14184 14185 // Okay, we're going to make a redeclaration. If this is some kind 14186 // of reference, make sure we build the redeclaration in the same DC 14187 // as the original, and ignore the current access specifier. 14188 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14189 SearchDC = PrevTagDecl->getDeclContext(); 14190 AS = AS_none; 14191 } 14192 } 14193 // If we get here we have (another) forward declaration or we 14194 // have a definition. Just create a new decl. 14195 14196 } else { 14197 // If we get here, this is a definition of a new tag type in a nested 14198 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14199 // new decl/type. We set PrevDecl to NULL so that the entities 14200 // have distinct types. 14201 Previous.clear(); 14202 } 14203 // If we get here, we're going to create a new Decl. If PrevDecl 14204 // is non-NULL, it's a definition of the tag declared by 14205 // PrevDecl. If it's NULL, we have a new definition. 14206 14207 // Otherwise, PrevDecl is not a tag, but was found with tag 14208 // lookup. This is only actually possible in C++, where a few 14209 // things like templates still live in the tag namespace. 14210 } else { 14211 // Use a better diagnostic if an elaborated-type-specifier 14212 // found the wrong kind of type on the first 14213 // (non-redeclaration) lookup. 14214 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14215 !Previous.isForRedeclaration()) { 14216 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14217 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14218 << Kind; 14219 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14220 Invalid = true; 14221 14222 // Otherwise, only diagnose if the declaration is in scope. 14223 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14224 SS.isNotEmpty() || isMemberSpecialization)) { 14225 // do nothing 14226 14227 // Diagnose implicit declarations introduced by elaborated types. 14228 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14229 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14230 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14231 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14232 Invalid = true; 14233 14234 // Otherwise it's a declaration. Call out a particularly common 14235 // case here. 14236 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14237 unsigned Kind = 0; 14238 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14239 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14240 << Name << Kind << TND->getUnderlyingType(); 14241 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14242 Invalid = true; 14243 14244 // Otherwise, diagnose. 14245 } else { 14246 // The tag name clashes with something else in the target scope, 14247 // issue an error and recover by making this tag be anonymous. 14248 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14249 notePreviousDefinition(PrevDecl, NameLoc); 14250 Name = nullptr; 14251 Invalid = true; 14252 } 14253 14254 // The existing declaration isn't relevant to us; we're in a 14255 // new scope, so clear out the previous declaration. 14256 Previous.clear(); 14257 } 14258 } 14259 14260 CreateNewDecl: 14261 14262 TagDecl *PrevDecl = nullptr; 14263 if (Previous.isSingleResult()) 14264 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14265 14266 // If there is an identifier, use the location of the identifier as the 14267 // location of the decl, otherwise use the location of the struct/union 14268 // keyword. 14269 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14270 14271 // Otherwise, create a new declaration. If there is a previous 14272 // declaration of the same entity, the two will be linked via 14273 // PrevDecl. 14274 TagDecl *New; 14275 14276 bool IsForwardReference = false; 14277 if (Kind == TTK_Enum) { 14278 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14279 // enum X { A, B, C } D; D should chain to X. 14280 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14281 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14282 ScopedEnumUsesClassTag, IsFixed); 14283 14284 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14285 StdAlignValT = cast<EnumDecl>(New); 14286 14287 // If this is an undefined enum, warn. 14288 if (TUK != TUK_Definition && !Invalid) { 14289 TagDecl *Def; 14290 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 14291 cast<EnumDecl>(New)->isFixed()) { 14292 // C++0x: 7.2p2: opaque-enum-declaration. 14293 // Conflicts are diagnosed above. Do nothing. 14294 } 14295 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14296 Diag(Loc, diag::ext_forward_ref_enum_def) 14297 << New; 14298 Diag(Def->getLocation(), diag::note_previous_definition); 14299 } else { 14300 unsigned DiagID = diag::ext_forward_ref_enum; 14301 if (getLangOpts().MSVCCompat) 14302 DiagID = diag::ext_ms_forward_ref_enum; 14303 else if (getLangOpts().CPlusPlus) 14304 DiagID = diag::err_forward_ref_enum; 14305 Diag(Loc, DiagID); 14306 14307 // If this is a forward-declared reference to an enumeration, make a 14308 // note of it; we won't actually be introducing the declaration into 14309 // the declaration context. 14310 if (TUK == TUK_Reference) 14311 IsForwardReference = true; 14312 } 14313 } 14314 14315 if (EnumUnderlying) { 14316 EnumDecl *ED = cast<EnumDecl>(New); 14317 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14318 ED->setIntegerTypeSourceInfo(TI); 14319 else 14320 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14321 ED->setPromotionType(ED->getIntegerType()); 14322 assert(ED->isComplete() && "enum with type should be complete"); 14323 } 14324 } else { 14325 // struct/union/class 14326 14327 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14328 // struct X { int A; } D; D should chain to X. 14329 if (getLangOpts().CPlusPlus) { 14330 // FIXME: Look for a way to use RecordDecl for simple structs. 14331 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14332 cast_or_null<CXXRecordDecl>(PrevDecl)); 14333 14334 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14335 StdBadAlloc = cast<CXXRecordDecl>(New); 14336 } else 14337 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14338 cast_or_null<RecordDecl>(PrevDecl)); 14339 } 14340 14341 // C++11 [dcl.type]p3: 14342 // A type-specifier-seq shall not define a class or enumeration [...]. 14343 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14344 TUK == TUK_Definition) { 14345 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14346 << Context.getTagDeclType(New); 14347 Invalid = true; 14348 } 14349 14350 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14351 DC->getDeclKind() == Decl::Enum) { 14352 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14353 << Context.getTagDeclType(New); 14354 Invalid = true; 14355 } 14356 14357 // Maybe add qualifier info. 14358 if (SS.isNotEmpty()) { 14359 if (SS.isSet()) { 14360 // If this is either a declaration or a definition, check the 14361 // nested-name-specifier against the current context. 14362 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14363 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14364 isMemberSpecialization)) 14365 Invalid = true; 14366 14367 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14368 if (TemplateParameterLists.size() > 0) { 14369 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14370 } 14371 } 14372 else 14373 Invalid = true; 14374 } 14375 14376 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14377 // Add alignment attributes if necessary; these attributes are checked when 14378 // the ASTContext lays out the structure. 14379 // 14380 // It is important for implementing the correct semantics that this 14381 // happen here (in ActOnTag). The #pragma pack stack is 14382 // maintained as a result of parser callbacks which can occur at 14383 // many points during the parsing of a struct declaration (because 14384 // the #pragma tokens are effectively skipped over during the 14385 // parsing of the struct). 14386 if (TUK == TUK_Definition) { 14387 AddAlignmentAttributesForRecord(RD); 14388 AddMsStructLayoutForRecord(RD); 14389 } 14390 } 14391 14392 if (ModulePrivateLoc.isValid()) { 14393 if (isMemberSpecialization) 14394 Diag(New->getLocation(), diag::err_module_private_specialization) 14395 << 2 14396 << FixItHint::CreateRemoval(ModulePrivateLoc); 14397 // __module_private__ does not apply to local classes. However, we only 14398 // diagnose this as an error when the declaration specifiers are 14399 // freestanding. Here, we just ignore the __module_private__. 14400 else if (!SearchDC->isFunctionOrMethod()) 14401 New->setModulePrivate(); 14402 } 14403 14404 // If this is a specialization of a member class (of a class template), 14405 // check the specialization. 14406 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14407 Invalid = true; 14408 14409 // If we're declaring or defining a tag in function prototype scope in C, 14410 // note that this type can only be used within the function and add it to 14411 // the list of decls to inject into the function definition scope. 14412 if ((Name || Kind == TTK_Enum) && 14413 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14414 if (getLangOpts().CPlusPlus) { 14415 // C++ [dcl.fct]p6: 14416 // Types shall not be defined in return or parameter types. 14417 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14418 Diag(Loc, diag::err_type_defined_in_param_type) 14419 << Name; 14420 Invalid = true; 14421 } 14422 } else if (!PrevDecl) { 14423 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14424 } 14425 } 14426 14427 if (Invalid) 14428 New->setInvalidDecl(); 14429 14430 // Set the lexical context. If the tag has a C++ scope specifier, the 14431 // lexical context will be different from the semantic context. 14432 New->setLexicalDeclContext(CurContext); 14433 14434 // Mark this as a friend decl if applicable. 14435 // In Microsoft mode, a friend declaration also acts as a forward 14436 // declaration so we always pass true to setObjectOfFriendDecl to make 14437 // the tag name visible. 14438 if (TUK == TUK_Friend) 14439 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14440 14441 // Set the access specifier. 14442 if (!Invalid && SearchDC->isRecord()) 14443 SetMemberAccessSpecifier(New, PrevDecl, AS); 14444 14445 if (PrevDecl) 14446 CheckRedeclarationModuleOwnership(New, PrevDecl); 14447 14448 if (TUK == TUK_Definition) 14449 New->startDefinition(); 14450 14451 if (Attr) 14452 ProcessDeclAttributeList(S, New, Attr); 14453 AddPragmaAttributes(S, New); 14454 14455 // If this has an identifier, add it to the scope stack. 14456 if (TUK == TUK_Friend) { 14457 // We might be replacing an existing declaration in the lookup tables; 14458 // if so, borrow its access specifier. 14459 if (PrevDecl) 14460 New->setAccess(PrevDecl->getAccess()); 14461 14462 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14463 DC->makeDeclVisibleInContext(New); 14464 if (Name) // can be null along some error paths 14465 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14466 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14467 } else if (Name) { 14468 S = getNonFieldDeclScope(S); 14469 PushOnScopeChains(New, S, !IsForwardReference); 14470 if (IsForwardReference) 14471 SearchDC->makeDeclVisibleInContext(New); 14472 } else { 14473 CurContext->addDecl(New); 14474 } 14475 14476 // If this is the C FILE type, notify the AST context. 14477 if (IdentifierInfo *II = New->getIdentifier()) 14478 if (!New->isInvalidDecl() && 14479 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14480 II->isStr("FILE")) 14481 Context.setFILEDecl(New); 14482 14483 if (PrevDecl) 14484 mergeDeclAttributes(New, PrevDecl); 14485 14486 // If there's a #pragma GCC visibility in scope, set the visibility of this 14487 // record. 14488 AddPushedVisibilityAttribute(New); 14489 14490 if (isMemberSpecialization && !New->isInvalidDecl()) 14491 CompleteMemberSpecialization(New, Previous); 14492 14493 OwnedDecl = true; 14494 // In C++, don't return an invalid declaration. We can't recover well from 14495 // the cases where we make the type anonymous. 14496 if (Invalid && getLangOpts().CPlusPlus) { 14497 if (New->isBeingDefined()) 14498 if (auto RD = dyn_cast<RecordDecl>(New)) 14499 RD->completeDefinition(); 14500 return nullptr; 14501 } else { 14502 return New; 14503 } 14504 } 14505 14506 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14507 AdjustDeclIfTemplate(TagD); 14508 TagDecl *Tag = cast<TagDecl>(TagD); 14509 14510 // Enter the tag context. 14511 PushDeclContext(S, Tag); 14512 14513 ActOnDocumentableDecl(TagD); 14514 14515 // If there's a #pragma GCC visibility in scope, set the visibility of this 14516 // record. 14517 AddPushedVisibilityAttribute(Tag); 14518 } 14519 14520 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14521 SkipBodyInfo &SkipBody) { 14522 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14523 return false; 14524 14525 // Make the previous decl visible. 14526 makeMergedDefinitionVisible(SkipBody.Previous); 14527 return true; 14528 } 14529 14530 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14531 assert(isa<ObjCContainerDecl>(IDecl) && 14532 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14533 DeclContext *OCD = cast<DeclContext>(IDecl); 14534 assert(getContainingDC(OCD) == CurContext && 14535 "The next DeclContext should be lexically contained in the current one."); 14536 CurContext = OCD; 14537 return IDecl; 14538 } 14539 14540 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14541 SourceLocation FinalLoc, 14542 bool IsFinalSpelledSealed, 14543 SourceLocation LBraceLoc) { 14544 AdjustDeclIfTemplate(TagD); 14545 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14546 14547 FieldCollector->StartClass(); 14548 14549 if (!Record->getIdentifier()) 14550 return; 14551 14552 if (FinalLoc.isValid()) 14553 Record->addAttr(new (Context) 14554 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14555 14556 // C++ [class]p2: 14557 // [...] The class-name is also inserted into the scope of the 14558 // class itself; this is known as the injected-class-name. For 14559 // purposes of access checking, the injected-class-name is treated 14560 // as if it were a public member name. 14561 CXXRecordDecl *InjectedClassName 14562 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14563 Record->getLocStart(), Record->getLocation(), 14564 Record->getIdentifier(), 14565 /*PrevDecl=*/nullptr, 14566 /*DelayTypeCreation=*/true); 14567 Context.getTypeDeclType(InjectedClassName, Record); 14568 InjectedClassName->setImplicit(); 14569 InjectedClassName->setAccess(AS_public); 14570 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14571 InjectedClassName->setDescribedClassTemplate(Template); 14572 PushOnScopeChains(InjectedClassName, S); 14573 assert(InjectedClassName->isInjectedClassName() && 14574 "Broken injected-class-name"); 14575 } 14576 14577 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14578 SourceRange BraceRange) { 14579 AdjustDeclIfTemplate(TagD); 14580 TagDecl *Tag = cast<TagDecl>(TagD); 14581 Tag->setBraceRange(BraceRange); 14582 14583 // Make sure we "complete" the definition even it is invalid. 14584 if (Tag->isBeingDefined()) { 14585 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14586 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14587 RD->completeDefinition(); 14588 } 14589 14590 if (isa<CXXRecordDecl>(Tag)) { 14591 FieldCollector->FinishClass(); 14592 } 14593 14594 // Exit this scope of this tag's definition. 14595 PopDeclContext(); 14596 14597 if (getCurLexicalContext()->isObjCContainer() && 14598 Tag->getDeclContext()->isFileContext()) 14599 Tag->setTopLevelDeclInObjCContainer(); 14600 14601 // Notify the consumer that we've defined a tag. 14602 if (!Tag->isInvalidDecl()) 14603 Consumer.HandleTagDeclDefinition(Tag); 14604 } 14605 14606 void Sema::ActOnObjCContainerFinishDefinition() { 14607 // Exit this scope of this interface definition. 14608 PopDeclContext(); 14609 } 14610 14611 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14612 assert(DC == CurContext && "Mismatch of container contexts"); 14613 OriginalLexicalContext = DC; 14614 ActOnObjCContainerFinishDefinition(); 14615 } 14616 14617 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14618 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14619 OriginalLexicalContext = nullptr; 14620 } 14621 14622 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14623 AdjustDeclIfTemplate(TagD); 14624 TagDecl *Tag = cast<TagDecl>(TagD); 14625 Tag->setInvalidDecl(); 14626 14627 // Make sure we "complete" the definition even it is invalid. 14628 if (Tag->isBeingDefined()) { 14629 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14630 RD->completeDefinition(); 14631 } 14632 14633 // We're undoing ActOnTagStartDefinition here, not 14634 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14635 // the FieldCollector. 14636 14637 PopDeclContext(); 14638 } 14639 14640 // Note that FieldName may be null for anonymous bitfields. 14641 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14642 IdentifierInfo *FieldName, 14643 QualType FieldTy, bool IsMsStruct, 14644 Expr *BitWidth, bool *ZeroWidth) { 14645 // Default to true; that shouldn't confuse checks for emptiness 14646 if (ZeroWidth) 14647 *ZeroWidth = true; 14648 14649 // C99 6.7.2.1p4 - verify the field type. 14650 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14651 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14652 // Handle incomplete types with specific error. 14653 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14654 return ExprError(); 14655 if (FieldName) 14656 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14657 << FieldName << FieldTy << BitWidth->getSourceRange(); 14658 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14659 << FieldTy << BitWidth->getSourceRange(); 14660 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14661 UPPC_BitFieldWidth)) 14662 return ExprError(); 14663 14664 // If the bit-width is type- or value-dependent, don't try to check 14665 // it now. 14666 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14667 return BitWidth; 14668 14669 llvm::APSInt Value; 14670 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14671 if (ICE.isInvalid()) 14672 return ICE; 14673 BitWidth = ICE.get(); 14674 14675 if (Value != 0 && ZeroWidth) 14676 *ZeroWidth = false; 14677 14678 // Zero-width bitfield is ok for anonymous field. 14679 if (Value == 0 && FieldName) 14680 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14681 14682 if (Value.isSigned() && Value.isNegative()) { 14683 if (FieldName) 14684 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14685 << FieldName << Value.toString(10); 14686 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14687 << Value.toString(10); 14688 } 14689 14690 if (!FieldTy->isDependentType()) { 14691 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14692 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14693 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14694 14695 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14696 // ABI. 14697 bool CStdConstraintViolation = 14698 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14699 bool MSBitfieldViolation = 14700 Value.ugt(TypeStorageSize) && 14701 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14702 if (CStdConstraintViolation || MSBitfieldViolation) { 14703 unsigned DiagWidth = 14704 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14705 if (FieldName) 14706 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14707 << FieldName << (unsigned)Value.getZExtValue() 14708 << !CStdConstraintViolation << DiagWidth; 14709 14710 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14711 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14712 << DiagWidth; 14713 } 14714 14715 // Warn on types where the user might conceivably expect to get all 14716 // specified bits as value bits: that's all integral types other than 14717 // 'bool'. 14718 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14719 if (FieldName) 14720 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14721 << FieldName << (unsigned)Value.getZExtValue() 14722 << (unsigned)TypeWidth; 14723 else 14724 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14725 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14726 } 14727 } 14728 14729 return BitWidth; 14730 } 14731 14732 /// ActOnField - Each field of a C struct/union is passed into this in order 14733 /// to create a FieldDecl object for it. 14734 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14735 Declarator &D, Expr *BitfieldWidth) { 14736 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14737 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14738 /*InitStyle=*/ICIS_NoInit, AS_public); 14739 return Res; 14740 } 14741 14742 /// HandleField - Analyze a field of a C struct or a C++ data member. 14743 /// 14744 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14745 SourceLocation DeclStart, 14746 Declarator &D, Expr *BitWidth, 14747 InClassInitStyle InitStyle, 14748 AccessSpecifier AS) { 14749 if (D.isDecompositionDeclarator()) { 14750 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14751 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14752 << Decomp.getSourceRange(); 14753 return nullptr; 14754 } 14755 14756 IdentifierInfo *II = D.getIdentifier(); 14757 SourceLocation Loc = DeclStart; 14758 if (II) Loc = D.getIdentifierLoc(); 14759 14760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14761 QualType T = TInfo->getType(); 14762 if (getLangOpts().CPlusPlus) { 14763 CheckExtraCXXDefaultArguments(D); 14764 14765 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14766 UPPC_DataMemberType)) { 14767 D.setInvalidType(); 14768 T = Context.IntTy; 14769 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14770 } 14771 } 14772 14773 // TR 18037 does not allow fields to be declared with address spaces. 14774 if (T.getQualifiers().hasAddressSpace() || 14775 T->isDependentAddressSpaceType() || 14776 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 14777 Diag(Loc, diag::err_field_with_address_space); 14778 D.setInvalidType(); 14779 } 14780 14781 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14782 // used as structure or union field: image, sampler, event or block types. 14783 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14784 T->isSamplerT() || T->isBlockPointerType())) { 14785 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14786 D.setInvalidType(); 14787 } 14788 14789 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14790 14791 if (D.getDeclSpec().isInlineSpecified()) 14792 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14793 << getLangOpts().CPlusPlus17; 14794 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14795 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14796 diag::err_invalid_thread) 14797 << DeclSpec::getSpecifierName(TSCS); 14798 14799 // Check to see if this name was declared as a member previously 14800 NamedDecl *PrevDecl = nullptr; 14801 LookupResult Previous(*this, II, Loc, LookupMemberName, 14802 ForVisibleRedeclaration); 14803 LookupName(Previous, S); 14804 switch (Previous.getResultKind()) { 14805 case LookupResult::Found: 14806 case LookupResult::FoundUnresolvedValue: 14807 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14808 break; 14809 14810 case LookupResult::FoundOverloaded: 14811 PrevDecl = Previous.getRepresentativeDecl(); 14812 break; 14813 14814 case LookupResult::NotFound: 14815 case LookupResult::NotFoundInCurrentInstantiation: 14816 case LookupResult::Ambiguous: 14817 break; 14818 } 14819 Previous.suppressDiagnostics(); 14820 14821 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14822 // Maybe we will complain about the shadowed template parameter. 14823 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14824 // Just pretend that we didn't see the previous declaration. 14825 PrevDecl = nullptr; 14826 } 14827 14828 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14829 PrevDecl = nullptr; 14830 14831 bool Mutable 14832 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14833 SourceLocation TSSL = D.getLocStart(); 14834 FieldDecl *NewFD 14835 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14836 TSSL, AS, PrevDecl, &D); 14837 14838 if (NewFD->isInvalidDecl()) 14839 Record->setInvalidDecl(); 14840 14841 if (D.getDeclSpec().isModulePrivateSpecified()) 14842 NewFD->setModulePrivate(); 14843 14844 if (NewFD->isInvalidDecl() && PrevDecl) { 14845 // Don't introduce NewFD into scope; there's already something 14846 // with the same name in the same scope. 14847 } else if (II) { 14848 PushOnScopeChains(NewFD, S); 14849 } else 14850 Record->addDecl(NewFD); 14851 14852 return NewFD; 14853 } 14854 14855 /// Build a new FieldDecl and check its well-formedness. 14856 /// 14857 /// This routine builds a new FieldDecl given the fields name, type, 14858 /// record, etc. \p PrevDecl should refer to any previous declaration 14859 /// with the same name and in the same scope as the field to be 14860 /// created. 14861 /// 14862 /// \returns a new FieldDecl. 14863 /// 14864 /// \todo The Declarator argument is a hack. It will be removed once 14865 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14866 TypeSourceInfo *TInfo, 14867 RecordDecl *Record, SourceLocation Loc, 14868 bool Mutable, Expr *BitWidth, 14869 InClassInitStyle InitStyle, 14870 SourceLocation TSSL, 14871 AccessSpecifier AS, NamedDecl *PrevDecl, 14872 Declarator *D) { 14873 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14874 bool InvalidDecl = false; 14875 if (D) InvalidDecl = D->isInvalidType(); 14876 14877 // If we receive a broken type, recover by assuming 'int' and 14878 // marking this declaration as invalid. 14879 if (T.isNull()) { 14880 InvalidDecl = true; 14881 T = Context.IntTy; 14882 } 14883 14884 QualType EltTy = Context.getBaseElementType(T); 14885 if (!EltTy->isDependentType()) { 14886 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14887 // Fields of incomplete type force their record to be invalid. 14888 Record->setInvalidDecl(); 14889 InvalidDecl = true; 14890 } else { 14891 NamedDecl *Def; 14892 EltTy->isIncompleteType(&Def); 14893 if (Def && Def->isInvalidDecl()) { 14894 Record->setInvalidDecl(); 14895 InvalidDecl = true; 14896 } 14897 } 14898 } 14899 14900 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14901 if (BitWidth && getLangOpts().OpenCL) { 14902 Diag(Loc, diag::err_opencl_bitfields); 14903 InvalidDecl = true; 14904 } 14905 14906 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 14907 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 14908 T.hasQualifiers()) { 14909 InvalidDecl = true; 14910 Diag(Loc, diag::err_anon_bitfield_qualifiers); 14911 } 14912 14913 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14914 // than a variably modified type. 14915 if (!InvalidDecl && T->isVariablyModifiedType()) { 14916 bool SizeIsNegative; 14917 llvm::APSInt Oversized; 14918 14919 TypeSourceInfo *FixedTInfo = 14920 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14921 SizeIsNegative, 14922 Oversized); 14923 if (FixedTInfo) { 14924 Diag(Loc, diag::warn_illegal_constant_array_size); 14925 TInfo = FixedTInfo; 14926 T = FixedTInfo->getType(); 14927 } else { 14928 if (SizeIsNegative) 14929 Diag(Loc, diag::err_typecheck_negative_array_size); 14930 else if (Oversized.getBoolValue()) 14931 Diag(Loc, diag::err_array_too_large) 14932 << Oversized.toString(10); 14933 else 14934 Diag(Loc, diag::err_typecheck_field_variable_size); 14935 InvalidDecl = true; 14936 } 14937 } 14938 14939 // Fields can not have abstract class types 14940 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14941 diag::err_abstract_type_in_decl, 14942 AbstractFieldType)) 14943 InvalidDecl = true; 14944 14945 bool ZeroWidth = false; 14946 if (InvalidDecl) 14947 BitWidth = nullptr; 14948 // If this is declared as a bit-field, check the bit-field. 14949 if (BitWidth) { 14950 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14951 &ZeroWidth).get(); 14952 if (!BitWidth) { 14953 InvalidDecl = true; 14954 BitWidth = nullptr; 14955 ZeroWidth = false; 14956 } 14957 } 14958 14959 // Check that 'mutable' is consistent with the type of the declaration. 14960 if (!InvalidDecl && Mutable) { 14961 unsigned DiagID = 0; 14962 if (T->isReferenceType()) 14963 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14964 : diag::err_mutable_reference; 14965 else if (T.isConstQualified()) 14966 DiagID = diag::err_mutable_const; 14967 14968 if (DiagID) { 14969 SourceLocation ErrLoc = Loc; 14970 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14971 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14972 Diag(ErrLoc, DiagID); 14973 if (DiagID != diag::ext_mutable_reference) { 14974 Mutable = false; 14975 InvalidDecl = true; 14976 } 14977 } 14978 } 14979 14980 // C++11 [class.union]p8 (DR1460): 14981 // At most one variant member of a union may have a 14982 // brace-or-equal-initializer. 14983 if (InitStyle != ICIS_NoInit) 14984 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14985 14986 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14987 BitWidth, Mutable, InitStyle); 14988 if (InvalidDecl) 14989 NewFD->setInvalidDecl(); 14990 14991 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14992 Diag(Loc, diag::err_duplicate_member) << II; 14993 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14994 NewFD->setInvalidDecl(); 14995 } 14996 14997 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14998 if (Record->isUnion()) { 14999 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15000 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15001 if (RDecl->getDefinition()) { 15002 // C++ [class.union]p1: An object of a class with a non-trivial 15003 // constructor, a non-trivial copy constructor, a non-trivial 15004 // destructor, or a non-trivial copy assignment operator 15005 // cannot be a member of a union, nor can an array of such 15006 // objects. 15007 if (CheckNontrivialField(NewFD)) 15008 NewFD->setInvalidDecl(); 15009 } 15010 } 15011 15012 // C++ [class.union]p1: If a union contains a member of reference type, 15013 // the program is ill-formed, except when compiling with MSVC extensions 15014 // enabled. 15015 if (EltTy->isReferenceType()) { 15016 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15017 diag::ext_union_member_of_reference_type : 15018 diag::err_union_member_of_reference_type) 15019 << NewFD->getDeclName() << EltTy; 15020 if (!getLangOpts().MicrosoftExt) 15021 NewFD->setInvalidDecl(); 15022 } 15023 } 15024 } 15025 15026 // FIXME: We need to pass in the attributes given an AST 15027 // representation, not a parser representation. 15028 if (D) { 15029 // FIXME: The current scope is almost... but not entirely... correct here. 15030 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15031 15032 if (NewFD->hasAttrs()) 15033 CheckAlignasUnderalignment(NewFD); 15034 } 15035 15036 // In auto-retain/release, infer strong retension for fields of 15037 // retainable type. 15038 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15039 NewFD->setInvalidDecl(); 15040 15041 if (T.isObjCGCWeak()) 15042 Diag(Loc, diag::warn_attribute_weak_on_field); 15043 15044 NewFD->setAccess(AS); 15045 return NewFD; 15046 } 15047 15048 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15049 assert(FD); 15050 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15051 15052 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15053 return false; 15054 15055 QualType EltTy = Context.getBaseElementType(FD->getType()); 15056 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15057 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15058 if (RDecl->getDefinition()) { 15059 // We check for copy constructors before constructors 15060 // because otherwise we'll never get complaints about 15061 // copy constructors. 15062 15063 CXXSpecialMember member = CXXInvalid; 15064 // We're required to check for any non-trivial constructors. Since the 15065 // implicit default constructor is suppressed if there are any 15066 // user-declared constructors, we just need to check that there is a 15067 // trivial default constructor and a trivial copy constructor. (We don't 15068 // worry about move constructors here, since this is a C++98 check.) 15069 if (RDecl->hasNonTrivialCopyConstructor()) 15070 member = CXXCopyConstructor; 15071 else if (!RDecl->hasTrivialDefaultConstructor()) 15072 member = CXXDefaultConstructor; 15073 else if (RDecl->hasNonTrivialCopyAssignment()) 15074 member = CXXCopyAssignment; 15075 else if (RDecl->hasNonTrivialDestructor()) 15076 member = CXXDestructor; 15077 15078 if (member != CXXInvalid) { 15079 if (!getLangOpts().CPlusPlus11 && 15080 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15081 // Objective-C++ ARC: it is an error to have a non-trivial field of 15082 // a union. However, system headers in Objective-C programs 15083 // occasionally have Objective-C lifetime objects within unions, 15084 // and rather than cause the program to fail, we make those 15085 // members unavailable. 15086 SourceLocation Loc = FD->getLocation(); 15087 if (getSourceManager().isInSystemHeader(Loc)) { 15088 if (!FD->hasAttr<UnavailableAttr>()) 15089 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15090 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15091 return false; 15092 } 15093 } 15094 15095 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15096 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15097 diag::err_illegal_union_or_anon_struct_member) 15098 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15099 DiagnoseNontrivial(RDecl, member); 15100 return !getLangOpts().CPlusPlus11; 15101 } 15102 } 15103 } 15104 15105 return false; 15106 } 15107 15108 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15109 /// AST enum value. 15110 static ObjCIvarDecl::AccessControl 15111 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15112 switch (ivarVisibility) { 15113 default: llvm_unreachable("Unknown visitibility kind"); 15114 case tok::objc_private: return ObjCIvarDecl::Private; 15115 case tok::objc_public: return ObjCIvarDecl::Public; 15116 case tok::objc_protected: return ObjCIvarDecl::Protected; 15117 case tok::objc_package: return ObjCIvarDecl::Package; 15118 } 15119 } 15120 15121 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15122 /// in order to create an IvarDecl object for it. 15123 Decl *Sema::ActOnIvar(Scope *S, 15124 SourceLocation DeclStart, 15125 Declarator &D, Expr *BitfieldWidth, 15126 tok::ObjCKeywordKind Visibility) { 15127 15128 IdentifierInfo *II = D.getIdentifier(); 15129 Expr *BitWidth = (Expr*)BitfieldWidth; 15130 SourceLocation Loc = DeclStart; 15131 if (II) Loc = D.getIdentifierLoc(); 15132 15133 // FIXME: Unnamed fields can be handled in various different ways, for 15134 // example, unnamed unions inject all members into the struct namespace! 15135 15136 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15137 QualType T = TInfo->getType(); 15138 15139 if (BitWidth) { 15140 // 6.7.2.1p3, 6.7.2.1p4 15141 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15142 if (!BitWidth) 15143 D.setInvalidType(); 15144 } else { 15145 // Not a bitfield. 15146 15147 // validate II. 15148 15149 } 15150 if (T->isReferenceType()) { 15151 Diag(Loc, diag::err_ivar_reference_type); 15152 D.setInvalidType(); 15153 } 15154 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15155 // than a variably modified type. 15156 else if (T->isVariablyModifiedType()) { 15157 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15158 D.setInvalidType(); 15159 } 15160 15161 // Get the visibility (access control) for this ivar. 15162 ObjCIvarDecl::AccessControl ac = 15163 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15164 : ObjCIvarDecl::None; 15165 // Must set ivar's DeclContext to its enclosing interface. 15166 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15167 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15168 return nullptr; 15169 ObjCContainerDecl *EnclosingContext; 15170 if (ObjCImplementationDecl *IMPDecl = 15171 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15172 if (LangOpts.ObjCRuntime.isFragile()) { 15173 // Case of ivar declared in an implementation. Context is that of its class. 15174 EnclosingContext = IMPDecl->getClassInterface(); 15175 assert(EnclosingContext && "Implementation has no class interface!"); 15176 } 15177 else 15178 EnclosingContext = EnclosingDecl; 15179 } else { 15180 if (ObjCCategoryDecl *CDecl = 15181 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15182 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15183 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15184 return nullptr; 15185 } 15186 } 15187 EnclosingContext = EnclosingDecl; 15188 } 15189 15190 // Construct the decl. 15191 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15192 DeclStart, Loc, II, T, 15193 TInfo, ac, (Expr *)BitfieldWidth); 15194 15195 if (II) { 15196 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15197 ForVisibleRedeclaration); 15198 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15199 && !isa<TagDecl>(PrevDecl)) { 15200 Diag(Loc, diag::err_duplicate_member) << II; 15201 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15202 NewID->setInvalidDecl(); 15203 } 15204 } 15205 15206 // Process attributes attached to the ivar. 15207 ProcessDeclAttributes(S, NewID, D); 15208 15209 if (D.isInvalidType()) 15210 NewID->setInvalidDecl(); 15211 15212 // In ARC, infer 'retaining' for ivars of retainable type. 15213 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15214 NewID->setInvalidDecl(); 15215 15216 if (D.getDeclSpec().isModulePrivateSpecified()) 15217 NewID->setModulePrivate(); 15218 15219 if (II) { 15220 // FIXME: When interfaces are DeclContexts, we'll need to add 15221 // these to the interface. 15222 S->AddDecl(NewID); 15223 IdResolver.AddDecl(NewID); 15224 } 15225 15226 if (LangOpts.ObjCRuntime.isNonFragile() && 15227 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15228 Diag(Loc, diag::warn_ivars_in_interface); 15229 15230 return NewID; 15231 } 15232 15233 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15234 /// class and class extensions. For every class \@interface and class 15235 /// extension \@interface, if the last ivar is a bitfield of any type, 15236 /// then add an implicit `char :0` ivar to the end of that interface. 15237 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15238 SmallVectorImpl<Decl *> &AllIvarDecls) { 15239 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15240 return; 15241 15242 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15243 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15244 15245 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15246 return; 15247 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15248 if (!ID) { 15249 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15250 if (!CD->IsClassExtension()) 15251 return; 15252 } 15253 // No need to add this to end of @implementation. 15254 else 15255 return; 15256 } 15257 // All conditions are met. Add a new bitfield to the tail end of ivars. 15258 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15259 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15260 15261 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15262 DeclLoc, DeclLoc, nullptr, 15263 Context.CharTy, 15264 Context.getTrivialTypeSourceInfo(Context.CharTy, 15265 DeclLoc), 15266 ObjCIvarDecl::Private, BW, 15267 true); 15268 AllIvarDecls.push_back(Ivar); 15269 } 15270 15271 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15272 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15273 SourceLocation RBrac, AttributeList *Attr) { 15274 assert(EnclosingDecl && "missing record or interface decl"); 15275 15276 // If this is an Objective-C @implementation or category and we have 15277 // new fields here we should reset the layout of the interface since 15278 // it will now change. 15279 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15280 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15281 switch (DC->getKind()) { 15282 default: break; 15283 case Decl::ObjCCategory: 15284 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15285 break; 15286 case Decl::ObjCImplementation: 15287 Context. 15288 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15289 break; 15290 } 15291 } 15292 15293 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15294 15295 // Start counting up the number of named members; make sure to include 15296 // members of anonymous structs and unions in the total. 15297 unsigned NumNamedMembers = 0; 15298 if (Record) { 15299 for (const auto *I : Record->decls()) { 15300 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15301 if (IFD->getDeclName()) 15302 ++NumNamedMembers; 15303 } 15304 } 15305 15306 // Verify that all the fields are okay. 15307 SmallVector<FieldDecl*, 32> RecFields; 15308 15309 bool ObjCFieldLifetimeErrReported = false; 15310 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15311 i != end; ++i) { 15312 FieldDecl *FD = cast<FieldDecl>(*i); 15313 15314 // Get the type for the field. 15315 const Type *FDTy = FD->getType().getTypePtr(); 15316 15317 if (!FD->isAnonymousStructOrUnion()) { 15318 // Remember all fields written by the user. 15319 RecFields.push_back(FD); 15320 } 15321 15322 // If the field is already invalid for some reason, don't emit more 15323 // diagnostics about it. 15324 if (FD->isInvalidDecl()) { 15325 EnclosingDecl->setInvalidDecl(); 15326 continue; 15327 } 15328 15329 // C99 6.7.2.1p2: 15330 // A structure or union shall not contain a member with 15331 // incomplete or function type (hence, a structure shall not 15332 // contain an instance of itself, but may contain a pointer to 15333 // an instance of itself), except that the last member of a 15334 // structure with more than one named member may have incomplete 15335 // array type; such a structure (and any union containing, 15336 // possibly recursively, a member that is such a structure) 15337 // shall not be a member of a structure or an element of an 15338 // array. 15339 bool IsLastField = (i + 1 == Fields.end()); 15340 if (FDTy->isFunctionType()) { 15341 // Field declared as a function. 15342 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15343 << FD->getDeclName(); 15344 FD->setInvalidDecl(); 15345 EnclosingDecl->setInvalidDecl(); 15346 continue; 15347 } else if (FDTy->isIncompleteArrayType() && 15348 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15349 if (Record) { 15350 // Flexible array member. 15351 // Microsoft and g++ is more permissive regarding flexible array. 15352 // It will accept flexible array in union and also 15353 // as the sole element of a struct/class. 15354 unsigned DiagID = 0; 15355 if (!Record->isUnion() && !IsLastField) { 15356 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15357 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15358 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15359 FD->setInvalidDecl(); 15360 EnclosingDecl->setInvalidDecl(); 15361 continue; 15362 } else if (Record->isUnion()) 15363 DiagID = getLangOpts().MicrosoftExt 15364 ? diag::ext_flexible_array_union_ms 15365 : getLangOpts().CPlusPlus 15366 ? diag::ext_flexible_array_union_gnu 15367 : diag::err_flexible_array_union; 15368 else if (NumNamedMembers < 1) 15369 DiagID = getLangOpts().MicrosoftExt 15370 ? diag::ext_flexible_array_empty_aggregate_ms 15371 : getLangOpts().CPlusPlus 15372 ? diag::ext_flexible_array_empty_aggregate_gnu 15373 : diag::err_flexible_array_empty_aggregate; 15374 15375 if (DiagID) 15376 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15377 << Record->getTagKind(); 15378 // While the layout of types that contain virtual bases is not specified 15379 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15380 // virtual bases after the derived members. This would make a flexible 15381 // array member declared at the end of an object not adjacent to the end 15382 // of the type. 15383 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 15384 if (RD->getNumVBases() != 0) 15385 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15386 << FD->getDeclName() << Record->getTagKind(); 15387 if (!getLangOpts().C99) 15388 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15389 << FD->getDeclName() << Record->getTagKind(); 15390 15391 // If the element type has a non-trivial destructor, we would not 15392 // implicitly destroy the elements, so disallow it for now. 15393 // 15394 // FIXME: GCC allows this. We should probably either implicitly delete 15395 // the destructor of the containing class, or just allow this. 15396 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15397 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15398 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15399 << FD->getDeclName() << FD->getType(); 15400 FD->setInvalidDecl(); 15401 EnclosingDecl->setInvalidDecl(); 15402 continue; 15403 } 15404 // Okay, we have a legal flexible array member at the end of the struct. 15405 Record->setHasFlexibleArrayMember(true); 15406 } else { 15407 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15408 // unless they are followed by another ivar. That check is done 15409 // elsewhere, after synthesized ivars are known. 15410 } 15411 } else if (!FDTy->isDependentType() && 15412 RequireCompleteType(FD->getLocation(), FD->getType(), 15413 diag::err_field_incomplete)) { 15414 // Incomplete type 15415 FD->setInvalidDecl(); 15416 EnclosingDecl->setInvalidDecl(); 15417 continue; 15418 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15419 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15420 // A type which contains a flexible array member is considered to be a 15421 // flexible array member. 15422 Record->setHasFlexibleArrayMember(true); 15423 if (!Record->isUnion()) { 15424 // If this is a struct/class and this is not the last element, reject 15425 // it. Note that GCC supports variable sized arrays in the middle of 15426 // structures. 15427 if (!IsLastField) 15428 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15429 << FD->getDeclName() << FD->getType(); 15430 else { 15431 // We support flexible arrays at the end of structs in 15432 // other structs as an extension. 15433 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15434 << FD->getDeclName(); 15435 } 15436 } 15437 } 15438 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15439 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15440 diag::err_abstract_type_in_decl, 15441 AbstractIvarType)) { 15442 // Ivars can not have abstract class types 15443 FD->setInvalidDecl(); 15444 } 15445 if (Record && FDTTy->getDecl()->hasObjectMember()) 15446 Record->setHasObjectMember(true); 15447 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15448 Record->setHasVolatileMember(true); 15449 } else if (FDTy->isObjCObjectType()) { 15450 /// A field cannot be an Objective-c object 15451 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15452 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15453 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15454 FD->setType(T); 15455 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15456 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { 15457 // It's an error in ARC or Weak if a field has lifetime. 15458 // We don't want to report this in a system header, though, 15459 // so we just make the field unavailable. 15460 // FIXME: that's really not sufficient; we need to make the type 15461 // itself invalid to, say, initialize or copy. 15462 QualType T = FD->getType(); 15463 if (T.hasNonTrivialObjCLifetime()) { 15464 SourceLocation loc = FD->getLocation(); 15465 if (getSourceManager().isInSystemHeader(loc)) { 15466 if (!FD->hasAttr<UnavailableAttr>()) { 15467 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15468 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15469 } 15470 } else { 15471 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15472 << T->isBlockPointerType() << Record->getTagKind(); 15473 } 15474 ObjCFieldLifetimeErrReported = true; 15475 } 15476 } else if (getLangOpts().ObjC1 && 15477 getLangOpts().getGC() != LangOptions::NonGC && 15478 Record && !Record->hasObjectMember()) { 15479 if (FD->getType()->isObjCObjectPointerType() || 15480 FD->getType().isObjCGCStrong()) 15481 Record->setHasObjectMember(true); 15482 else if (Context.getAsArrayType(FD->getType())) { 15483 QualType BaseType = Context.getBaseElementType(FD->getType()); 15484 if (BaseType->isRecordType() && 15485 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15486 Record->setHasObjectMember(true); 15487 else if (BaseType->isObjCObjectPointerType() || 15488 BaseType.isObjCGCStrong()) 15489 Record->setHasObjectMember(true); 15490 } 15491 } 15492 15493 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 15494 QualType FT = FD->getType(); 15495 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 15496 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 15497 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 15498 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 15499 Record->setNonTrivialToPrimitiveCopy(true); 15500 if (FT.isDestructedType()) { 15501 Record->setNonTrivialToPrimitiveDestroy(true); 15502 Record->setParamDestroyedInCallee(true); 15503 } 15504 15505 if (const auto *RT = FT->getAs<RecordType>()) { 15506 if (RT->getDecl()->getArgPassingRestrictions() == 15507 RecordDecl::APK_CanNeverPassInRegs) 15508 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15509 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 15510 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15511 } 15512 15513 if (Record && FD->getType().isVolatileQualified()) 15514 Record->setHasVolatileMember(true); 15515 // Keep track of the number of named members. 15516 if (FD->getIdentifier()) 15517 ++NumNamedMembers; 15518 } 15519 15520 // Okay, we successfully defined 'Record'. 15521 if (Record) { 15522 bool Completed = false; 15523 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15524 if (!CXXRecord->isInvalidDecl()) { 15525 // Set access bits correctly on the directly-declared conversions. 15526 for (CXXRecordDecl::conversion_iterator 15527 I = CXXRecord->conversion_begin(), 15528 E = CXXRecord->conversion_end(); I != E; ++I) 15529 I.setAccess((*I)->getAccess()); 15530 } 15531 15532 if (!CXXRecord->isDependentType()) { 15533 if (CXXRecord->hasUserDeclaredDestructor()) { 15534 // Adjust user-defined destructor exception spec. 15535 if (getLangOpts().CPlusPlus11) 15536 AdjustDestructorExceptionSpec(CXXRecord, 15537 CXXRecord->getDestructor()); 15538 } 15539 15540 // Add any implicitly-declared members to this class. 15541 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15542 15543 if (!CXXRecord->isInvalidDecl()) { 15544 // If we have virtual base classes, we may end up finding multiple 15545 // final overriders for a given virtual function. Check for this 15546 // problem now. 15547 if (CXXRecord->getNumVBases()) { 15548 CXXFinalOverriderMap FinalOverriders; 15549 CXXRecord->getFinalOverriders(FinalOverriders); 15550 15551 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15552 MEnd = FinalOverriders.end(); 15553 M != MEnd; ++M) { 15554 for (OverridingMethods::iterator SO = M->second.begin(), 15555 SOEnd = M->second.end(); 15556 SO != SOEnd; ++SO) { 15557 assert(SO->second.size() > 0 && 15558 "Virtual function without overriding functions?"); 15559 if (SO->second.size() == 1) 15560 continue; 15561 15562 // C++ [class.virtual]p2: 15563 // In a derived class, if a virtual member function of a base 15564 // class subobject has more than one final overrider the 15565 // program is ill-formed. 15566 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15567 << (const NamedDecl *)M->first << Record; 15568 Diag(M->first->getLocation(), 15569 diag::note_overridden_virtual_function); 15570 for (OverridingMethods::overriding_iterator 15571 OM = SO->second.begin(), 15572 OMEnd = SO->second.end(); 15573 OM != OMEnd; ++OM) 15574 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15575 << (const NamedDecl *)M->first << OM->Method->getParent(); 15576 15577 Record->setInvalidDecl(); 15578 } 15579 } 15580 CXXRecord->completeDefinition(&FinalOverriders); 15581 Completed = true; 15582 } 15583 } 15584 } 15585 } 15586 15587 if (!Completed) 15588 Record->completeDefinition(); 15589 15590 // We may have deferred checking for a deleted destructor. Check now. 15591 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15592 auto *Dtor = CXXRecord->getDestructor(); 15593 if (Dtor && Dtor->isImplicit() && 15594 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 15595 CXXRecord->setImplicitDestructorIsDeleted(); 15596 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15597 } 15598 } 15599 15600 if (Record->hasAttrs()) { 15601 CheckAlignasUnderalignment(Record); 15602 15603 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15604 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15605 IA->getRange(), IA->getBestCase(), 15606 IA->getSemanticSpelling()); 15607 } 15608 15609 // Check if the structure/union declaration is a type that can have zero 15610 // size in C. For C this is a language extension, for C++ it may cause 15611 // compatibility problems. 15612 bool CheckForZeroSize; 15613 if (!getLangOpts().CPlusPlus) { 15614 CheckForZeroSize = true; 15615 } else { 15616 // For C++ filter out types that cannot be referenced in C code. 15617 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15618 CheckForZeroSize = 15619 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15620 !CXXRecord->isDependentType() && 15621 CXXRecord->isCLike(); 15622 } 15623 if (CheckForZeroSize) { 15624 bool ZeroSize = true; 15625 bool IsEmpty = true; 15626 unsigned NonBitFields = 0; 15627 for (RecordDecl::field_iterator I = Record->field_begin(), 15628 E = Record->field_end(); 15629 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15630 IsEmpty = false; 15631 if (I->isUnnamedBitfield()) { 15632 if (!I->isZeroLengthBitField(Context)) 15633 ZeroSize = false; 15634 } else { 15635 ++NonBitFields; 15636 QualType FieldType = I->getType(); 15637 if (FieldType->isIncompleteType() || 15638 !Context.getTypeSizeInChars(FieldType).isZero()) 15639 ZeroSize = false; 15640 } 15641 } 15642 15643 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15644 // allowed in C++, but warn if its declaration is inside 15645 // extern "C" block. 15646 if (ZeroSize) { 15647 Diag(RecLoc, getLangOpts().CPlusPlus ? 15648 diag::warn_zero_size_struct_union_in_extern_c : 15649 diag::warn_zero_size_struct_union_compat) 15650 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15651 } 15652 15653 // Structs without named members are extension in C (C99 6.7.2.1p7), 15654 // but are accepted by GCC. 15655 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15656 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15657 diag::ext_no_named_members_in_struct_union) 15658 << Record->isUnion(); 15659 } 15660 } 15661 } else { 15662 ObjCIvarDecl **ClsFields = 15663 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15664 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15665 ID->setEndOfDefinitionLoc(RBrac); 15666 // Add ivar's to class's DeclContext. 15667 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15668 ClsFields[i]->setLexicalDeclContext(ID); 15669 ID->addDecl(ClsFields[i]); 15670 } 15671 // Must enforce the rule that ivars in the base classes may not be 15672 // duplicates. 15673 if (ID->getSuperClass()) 15674 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15675 } else if (ObjCImplementationDecl *IMPDecl = 15676 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15677 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15678 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15679 // Ivar declared in @implementation never belongs to the implementation. 15680 // Only it is in implementation's lexical context. 15681 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15682 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15683 IMPDecl->setIvarLBraceLoc(LBrac); 15684 IMPDecl->setIvarRBraceLoc(RBrac); 15685 } else if (ObjCCategoryDecl *CDecl = 15686 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15687 // case of ivars in class extension; all other cases have been 15688 // reported as errors elsewhere. 15689 // FIXME. Class extension does not have a LocEnd field. 15690 // CDecl->setLocEnd(RBrac); 15691 // Add ivar's to class extension's DeclContext. 15692 // Diagnose redeclaration of private ivars. 15693 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15694 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15695 if (IDecl) { 15696 if (const ObjCIvarDecl *ClsIvar = 15697 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15698 Diag(ClsFields[i]->getLocation(), 15699 diag::err_duplicate_ivar_declaration); 15700 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15701 continue; 15702 } 15703 for (const auto *Ext : IDecl->known_extensions()) { 15704 if (const ObjCIvarDecl *ClsExtIvar 15705 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15706 Diag(ClsFields[i]->getLocation(), 15707 diag::err_duplicate_ivar_declaration); 15708 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15709 continue; 15710 } 15711 } 15712 } 15713 ClsFields[i]->setLexicalDeclContext(CDecl); 15714 CDecl->addDecl(ClsFields[i]); 15715 } 15716 CDecl->setIvarLBraceLoc(LBrac); 15717 CDecl->setIvarRBraceLoc(RBrac); 15718 } 15719 } 15720 15721 if (Attr) 15722 ProcessDeclAttributeList(S, Record, Attr); 15723 } 15724 15725 /// Determine whether the given integral value is representable within 15726 /// the given type T. 15727 static bool isRepresentableIntegerValue(ASTContext &Context, 15728 llvm::APSInt &Value, 15729 QualType T) { 15730 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 15731 "Integral type required!"); 15732 unsigned BitWidth = Context.getIntWidth(T); 15733 15734 if (Value.isUnsigned() || Value.isNonNegative()) { 15735 if (T->isSignedIntegerOrEnumerationType()) 15736 --BitWidth; 15737 return Value.getActiveBits() <= BitWidth; 15738 } 15739 return Value.getMinSignedBits() <= BitWidth; 15740 } 15741 15742 // Given an integral type, return the next larger integral type 15743 // (or a NULL type of no such type exists). 15744 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15745 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15746 // enum checking below. 15747 assert((T->isIntegralType(Context) || 15748 T->isEnumeralType()) && "Integral type required!"); 15749 const unsigned NumTypes = 4; 15750 QualType SignedIntegralTypes[NumTypes] = { 15751 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15752 }; 15753 QualType UnsignedIntegralTypes[NumTypes] = { 15754 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15755 Context.UnsignedLongLongTy 15756 }; 15757 15758 unsigned BitWidth = Context.getTypeSize(T); 15759 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15760 : UnsignedIntegralTypes; 15761 for (unsigned I = 0; I != NumTypes; ++I) 15762 if (Context.getTypeSize(Types[I]) > BitWidth) 15763 return Types[I]; 15764 15765 return QualType(); 15766 } 15767 15768 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15769 EnumConstantDecl *LastEnumConst, 15770 SourceLocation IdLoc, 15771 IdentifierInfo *Id, 15772 Expr *Val) { 15773 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15774 llvm::APSInt EnumVal(IntWidth); 15775 QualType EltTy; 15776 15777 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15778 Val = nullptr; 15779 15780 if (Val) 15781 Val = DefaultLvalueConversion(Val).get(); 15782 15783 if (Val) { 15784 if (Enum->isDependentType() || Val->isTypeDependent()) 15785 EltTy = Context.DependentTy; 15786 else { 15787 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15788 !getLangOpts().MSVCCompat) { 15789 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15790 // constant-expression in the enumerator-definition shall be a converted 15791 // constant expression of the underlying type. 15792 EltTy = Enum->getIntegerType(); 15793 ExprResult Converted = 15794 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15795 CCEK_Enumerator); 15796 if (Converted.isInvalid()) 15797 Val = nullptr; 15798 else 15799 Val = Converted.get(); 15800 } else if (!Val->isValueDependent() && 15801 !(Val = VerifyIntegerConstantExpression(Val, 15802 &EnumVal).get())) { 15803 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15804 } else { 15805 if (Enum->isComplete()) { 15806 EltTy = Enum->getIntegerType(); 15807 15808 // In Obj-C and Microsoft mode, require the enumeration value to be 15809 // representable in the underlying type of the enumeration. In C++11, 15810 // we perform a non-narrowing conversion as part of converted constant 15811 // expression checking. 15812 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15813 if (getLangOpts().MSVCCompat) { 15814 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15815 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15816 } else 15817 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15818 } else 15819 Val = ImpCastExprToType(Val, EltTy, 15820 EltTy->isBooleanType() ? 15821 CK_IntegralToBoolean : CK_IntegralCast) 15822 .get(); 15823 } else if (getLangOpts().CPlusPlus) { 15824 // C++11 [dcl.enum]p5: 15825 // If the underlying type is not fixed, the type of each enumerator 15826 // is the type of its initializing value: 15827 // - If an initializer is specified for an enumerator, the 15828 // initializing value has the same type as the expression. 15829 EltTy = Val->getType(); 15830 } else { 15831 // C99 6.7.2.2p2: 15832 // The expression that defines the value of an enumeration constant 15833 // shall be an integer constant expression that has a value 15834 // representable as an int. 15835 15836 // Complain if the value is not representable in an int. 15837 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15838 Diag(IdLoc, diag::ext_enum_value_not_int) 15839 << EnumVal.toString(10) << Val->getSourceRange() 15840 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15841 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15842 // Force the type of the expression to 'int'. 15843 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15844 } 15845 EltTy = Val->getType(); 15846 } 15847 } 15848 } 15849 } 15850 15851 if (!Val) { 15852 if (Enum->isDependentType()) 15853 EltTy = Context.DependentTy; 15854 else if (!LastEnumConst) { 15855 // C++0x [dcl.enum]p5: 15856 // If the underlying type is not fixed, the type of each enumerator 15857 // is the type of its initializing value: 15858 // - If no initializer is specified for the first enumerator, the 15859 // initializing value has an unspecified integral type. 15860 // 15861 // GCC uses 'int' for its unspecified integral type, as does 15862 // C99 6.7.2.2p3. 15863 if (Enum->isFixed()) { 15864 EltTy = Enum->getIntegerType(); 15865 } 15866 else { 15867 EltTy = Context.IntTy; 15868 } 15869 } else { 15870 // Assign the last value + 1. 15871 EnumVal = LastEnumConst->getInitVal(); 15872 ++EnumVal; 15873 EltTy = LastEnumConst->getType(); 15874 15875 // Check for overflow on increment. 15876 if (EnumVal < LastEnumConst->getInitVal()) { 15877 // C++0x [dcl.enum]p5: 15878 // If the underlying type is not fixed, the type of each enumerator 15879 // is the type of its initializing value: 15880 // 15881 // - Otherwise the type of the initializing value is the same as 15882 // the type of the initializing value of the preceding enumerator 15883 // unless the incremented value is not representable in that type, 15884 // in which case the type is an unspecified integral type 15885 // sufficient to contain the incremented value. If no such type 15886 // exists, the program is ill-formed. 15887 QualType T = getNextLargerIntegralType(Context, EltTy); 15888 if (T.isNull() || Enum->isFixed()) { 15889 // There is no integral type larger enough to represent this 15890 // value. Complain, then allow the value to wrap around. 15891 EnumVal = LastEnumConst->getInitVal(); 15892 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15893 ++EnumVal; 15894 if (Enum->isFixed()) 15895 // When the underlying type is fixed, this is ill-formed. 15896 Diag(IdLoc, diag::err_enumerator_wrapped) 15897 << EnumVal.toString(10) 15898 << EltTy; 15899 else 15900 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15901 << EnumVal.toString(10); 15902 } else { 15903 EltTy = T; 15904 } 15905 15906 // Retrieve the last enumerator's value, extent that type to the 15907 // type that is supposed to be large enough to represent the incremented 15908 // value, then increment. 15909 EnumVal = LastEnumConst->getInitVal(); 15910 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15911 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15912 ++EnumVal; 15913 15914 // If we're not in C++, diagnose the overflow of enumerator values, 15915 // which in C99 means that the enumerator value is not representable in 15916 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15917 // permits enumerator values that are representable in some larger 15918 // integral type. 15919 if (!getLangOpts().CPlusPlus && !T.isNull()) 15920 Diag(IdLoc, diag::warn_enum_value_overflow); 15921 } else if (!getLangOpts().CPlusPlus && 15922 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15923 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15924 Diag(IdLoc, diag::ext_enum_value_not_int) 15925 << EnumVal.toString(10) << 1; 15926 } 15927 } 15928 } 15929 15930 if (!EltTy->isDependentType()) { 15931 // Make the enumerator value match the signedness and size of the 15932 // enumerator's type. 15933 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15934 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15935 } 15936 15937 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15938 Val, EnumVal); 15939 } 15940 15941 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15942 SourceLocation IILoc) { 15943 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15944 !getLangOpts().CPlusPlus) 15945 return SkipBodyInfo(); 15946 15947 // We have an anonymous enum definition. Look up the first enumerator to 15948 // determine if we should merge the definition with an existing one and 15949 // skip the body. 15950 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15951 forRedeclarationInCurContext()); 15952 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15953 if (!PrevECD) 15954 return SkipBodyInfo(); 15955 15956 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15957 NamedDecl *Hidden; 15958 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15959 SkipBodyInfo Skip; 15960 Skip.Previous = Hidden; 15961 return Skip; 15962 } 15963 15964 return SkipBodyInfo(); 15965 } 15966 15967 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15968 SourceLocation IdLoc, IdentifierInfo *Id, 15969 AttributeList *Attr, 15970 SourceLocation EqualLoc, Expr *Val) { 15971 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15972 EnumConstantDecl *LastEnumConst = 15973 cast_or_null<EnumConstantDecl>(lastEnumConst); 15974 15975 // The scope passed in may not be a decl scope. Zip up the scope tree until 15976 // we find one that is. 15977 S = getNonFieldDeclScope(S); 15978 15979 // Verify that there isn't already something declared with this name in this 15980 // scope. 15981 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15982 ForVisibleRedeclaration); 15983 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15984 // Maybe we will complain about the shadowed template parameter. 15985 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15986 // Just pretend that we didn't see the previous declaration. 15987 PrevDecl = nullptr; 15988 } 15989 15990 // C++ [class.mem]p15: 15991 // If T is the name of a class, then each of the following shall have a name 15992 // different from T: 15993 // - every enumerator of every member of class T that is an unscoped 15994 // enumerated type 15995 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 15996 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15997 DeclarationNameInfo(Id, IdLoc)); 15998 15999 EnumConstantDecl *New = 16000 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 16001 if (!New) 16002 return nullptr; 16003 16004 if (PrevDecl) { 16005 // When in C++, we may get a TagDecl with the same name; in this case the 16006 // enum constant will 'hide' the tag. 16007 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 16008 "Received TagDecl when not in C++!"); 16009 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 16010 if (isa<EnumConstantDecl>(PrevDecl)) 16011 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 16012 else 16013 Diag(IdLoc, diag::err_redefinition) << Id; 16014 notePreviousDefinition(PrevDecl, IdLoc); 16015 return nullptr; 16016 } 16017 } 16018 16019 // Process attributes. 16020 if (Attr) ProcessDeclAttributeList(S, New, Attr); 16021 AddPragmaAttributes(S, New); 16022 16023 // Register this decl in the current scope stack. 16024 New->setAccess(TheEnumDecl->getAccess()); 16025 PushOnScopeChains(New, S); 16026 16027 ActOnDocumentableDecl(New); 16028 16029 return New; 16030 } 16031 16032 // Returns true when the enum initial expression does not trigger the 16033 // duplicate enum warning. A few common cases are exempted as follows: 16034 // Element2 = Element1 16035 // Element2 = Element1 + 1 16036 // Element2 = Element1 - 1 16037 // Where Element2 and Element1 are from the same enum. 16038 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16039 Expr *InitExpr = ECD->getInitExpr(); 16040 if (!InitExpr) 16041 return true; 16042 InitExpr = InitExpr->IgnoreImpCasts(); 16043 16044 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16045 if (!BO->isAdditiveOp()) 16046 return true; 16047 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16048 if (!IL) 16049 return true; 16050 if (IL->getValue() != 1) 16051 return true; 16052 16053 InitExpr = BO->getLHS(); 16054 } 16055 16056 // This checks if the elements are from the same enum. 16057 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16058 if (!DRE) 16059 return true; 16060 16061 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16062 if (!EnumConstant) 16063 return true; 16064 16065 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16066 Enum) 16067 return true; 16068 16069 return false; 16070 } 16071 16072 // Emits a warning when an element is implicitly set a value that 16073 // a previous element has already been set to. 16074 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16075 EnumDecl *Enum, QualType EnumType) { 16076 // Avoid anonymous enums 16077 if (!Enum->getIdentifier()) 16078 return; 16079 16080 // Only check for small enums. 16081 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16082 return; 16083 16084 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16085 return; 16086 16087 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16088 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16089 16090 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16091 typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap; 16092 16093 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16094 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16095 llvm::APSInt Val = D->getInitVal(); 16096 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16097 }; 16098 16099 DuplicatesVector DupVector; 16100 ValueToVectorMap EnumMap; 16101 16102 // Populate the EnumMap with all values represented by enum constants without 16103 // an initializer. 16104 for (auto *Element : Elements) { 16105 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16106 16107 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16108 // this constant. Skip this enum since it may be ill-formed. 16109 if (!ECD) { 16110 return; 16111 } 16112 16113 // Constants with initalizers are handled in the next loop. 16114 if (ECD->getInitExpr()) 16115 continue; 16116 16117 // Duplicate values are handled in the next loop. 16118 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16119 } 16120 16121 if (EnumMap.size() == 0) 16122 return; 16123 16124 // Create vectors for any values that has duplicates. 16125 for (auto *Element : Elements) { 16126 // The last loop returned if any constant was null. 16127 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16128 if (!ValidDuplicateEnum(ECD, Enum)) 16129 continue; 16130 16131 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16132 if (Iter == EnumMap.end()) 16133 continue; 16134 16135 DeclOrVector& Entry = Iter->second; 16136 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16137 // Ensure constants are different. 16138 if (D == ECD) 16139 continue; 16140 16141 // Create new vector and push values onto it. 16142 auto Vec = llvm::make_unique<ECDVector>(); 16143 Vec->push_back(D); 16144 Vec->push_back(ECD); 16145 16146 // Update entry to point to the duplicates vector. 16147 Entry = Vec.get(); 16148 16149 // Store the vector somewhere we can consult later for quick emission of 16150 // diagnostics. 16151 DupVector.emplace_back(std::move(Vec)); 16152 continue; 16153 } 16154 16155 ECDVector *Vec = Entry.get<ECDVector*>(); 16156 // Make sure constants are not added more than once. 16157 if (*Vec->begin() == ECD) 16158 continue; 16159 16160 Vec->push_back(ECD); 16161 } 16162 16163 // Emit diagnostics. 16164 for (const auto &Vec : DupVector) { 16165 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16166 16167 // Emit warning for one enum constant. 16168 auto *FirstECD = Vec->front(); 16169 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16170 << FirstECD << FirstECD->getInitVal().toString(10) 16171 << FirstECD->getSourceRange(); 16172 16173 // Emit one note for each of the remaining enum constants with 16174 // the same value. 16175 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16176 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16177 << ECD << ECD->getInitVal().toString(10) 16178 << ECD->getSourceRange(); 16179 } 16180 } 16181 16182 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16183 bool AllowMask) const { 16184 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16185 assert(ED->isCompleteDefinition() && "expected enum definition"); 16186 16187 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16188 llvm::APInt &FlagBits = R.first->second; 16189 16190 if (R.second) { 16191 for (auto *E : ED->enumerators()) { 16192 const auto &EVal = E->getInitVal(); 16193 // Only single-bit enumerators introduce new flag values. 16194 if (EVal.isPowerOf2()) 16195 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16196 } 16197 } 16198 16199 // A value is in a flag enum if either its bits are a subset of the enum's 16200 // flag bits (the first condition) or we are allowing masks and the same is 16201 // true of its complement (the second condition). When masks are allowed, we 16202 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16203 // 16204 // While it's true that any value could be used as a mask, the assumption is 16205 // that a mask will have all of the insignificant bits set. Anything else is 16206 // likely a logic error. 16207 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16208 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16209 } 16210 16211 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16212 Decl *EnumDeclX, 16213 ArrayRef<Decl *> Elements, 16214 Scope *S, AttributeList *Attr) { 16215 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16216 QualType EnumType = Context.getTypeDeclType(Enum); 16217 16218 if (Attr) 16219 ProcessDeclAttributeList(S, Enum, Attr); 16220 16221 if (Enum->isDependentType()) { 16222 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16223 EnumConstantDecl *ECD = 16224 cast_or_null<EnumConstantDecl>(Elements[i]); 16225 if (!ECD) continue; 16226 16227 ECD->setType(EnumType); 16228 } 16229 16230 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16231 return; 16232 } 16233 16234 // TODO: If the result value doesn't fit in an int, it must be a long or long 16235 // long value. ISO C does not support this, but GCC does as an extension, 16236 // emit a warning. 16237 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16238 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16239 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16240 16241 // Verify that all the values are okay, compute the size of the values, and 16242 // reverse the list. 16243 unsigned NumNegativeBits = 0; 16244 unsigned NumPositiveBits = 0; 16245 16246 // Keep track of whether all elements have type int. 16247 bool AllElementsInt = true; 16248 16249 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16250 EnumConstantDecl *ECD = 16251 cast_or_null<EnumConstantDecl>(Elements[i]); 16252 if (!ECD) continue; // Already issued a diagnostic. 16253 16254 const llvm::APSInt &InitVal = ECD->getInitVal(); 16255 16256 // Keep track of the size of positive and negative values. 16257 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16258 NumPositiveBits = std::max(NumPositiveBits, 16259 (unsigned)InitVal.getActiveBits()); 16260 else 16261 NumNegativeBits = std::max(NumNegativeBits, 16262 (unsigned)InitVal.getMinSignedBits()); 16263 16264 // Keep track of whether every enum element has type int (very commmon). 16265 if (AllElementsInt) 16266 AllElementsInt = ECD->getType() == Context.IntTy; 16267 } 16268 16269 // Figure out the type that should be used for this enum. 16270 QualType BestType; 16271 unsigned BestWidth; 16272 16273 // C++0x N3000 [conv.prom]p3: 16274 // An rvalue of an unscoped enumeration type whose underlying 16275 // type is not fixed can be converted to an rvalue of the first 16276 // of the following types that can represent all the values of 16277 // the enumeration: int, unsigned int, long int, unsigned long 16278 // int, long long int, or unsigned long long int. 16279 // C99 6.4.4.3p2: 16280 // An identifier declared as an enumeration constant has type int. 16281 // The C99 rule is modified by a gcc extension 16282 QualType BestPromotionType; 16283 16284 bool Packed = Enum->hasAttr<PackedAttr>(); 16285 // -fshort-enums is the equivalent to specifying the packed attribute on all 16286 // enum definitions. 16287 if (LangOpts.ShortEnums) 16288 Packed = true; 16289 16290 // If the enum already has a type because it is fixed or dictated by the 16291 // target, promote that type instead of analyzing the enumerators. 16292 if (Enum->isComplete()) { 16293 BestType = Enum->getIntegerType(); 16294 if (BestType->isPromotableIntegerType()) 16295 BestPromotionType = Context.getPromotedIntegerType(BestType); 16296 else 16297 BestPromotionType = BestType; 16298 16299 BestWidth = Context.getIntWidth(BestType); 16300 } 16301 else if (NumNegativeBits) { 16302 // If there is a negative value, figure out the smallest integer type (of 16303 // int/long/longlong) that fits. 16304 // If it's packed, check also if it fits a char or a short. 16305 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16306 BestType = Context.SignedCharTy; 16307 BestWidth = CharWidth; 16308 } else if (Packed && NumNegativeBits <= ShortWidth && 16309 NumPositiveBits < ShortWidth) { 16310 BestType = Context.ShortTy; 16311 BestWidth = ShortWidth; 16312 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16313 BestType = Context.IntTy; 16314 BestWidth = IntWidth; 16315 } else { 16316 BestWidth = Context.getTargetInfo().getLongWidth(); 16317 16318 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16319 BestType = Context.LongTy; 16320 } else { 16321 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16322 16323 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16324 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16325 BestType = Context.LongLongTy; 16326 } 16327 } 16328 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16329 } else { 16330 // If there is no negative value, figure out the smallest type that fits 16331 // all of the enumerator values. 16332 // If it's packed, check also if it fits a char or a short. 16333 if (Packed && NumPositiveBits <= CharWidth) { 16334 BestType = Context.UnsignedCharTy; 16335 BestPromotionType = Context.IntTy; 16336 BestWidth = CharWidth; 16337 } else if (Packed && NumPositiveBits <= ShortWidth) { 16338 BestType = Context.UnsignedShortTy; 16339 BestPromotionType = Context.IntTy; 16340 BestWidth = ShortWidth; 16341 } else if (NumPositiveBits <= IntWidth) { 16342 BestType = Context.UnsignedIntTy; 16343 BestWidth = IntWidth; 16344 BestPromotionType 16345 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16346 ? Context.UnsignedIntTy : Context.IntTy; 16347 } else if (NumPositiveBits <= 16348 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16349 BestType = Context.UnsignedLongTy; 16350 BestPromotionType 16351 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16352 ? Context.UnsignedLongTy : Context.LongTy; 16353 } else { 16354 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16355 assert(NumPositiveBits <= BestWidth && 16356 "How could an initializer get larger than ULL?"); 16357 BestType = Context.UnsignedLongLongTy; 16358 BestPromotionType 16359 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16360 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16361 } 16362 } 16363 16364 // Loop over all of the enumerator constants, changing their types to match 16365 // the type of the enum if needed. 16366 for (auto *D : Elements) { 16367 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16368 if (!ECD) continue; // Already issued a diagnostic. 16369 16370 // Standard C says the enumerators have int type, but we allow, as an 16371 // extension, the enumerators to be larger than int size. If each 16372 // enumerator value fits in an int, type it as an int, otherwise type it the 16373 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16374 // that X has type 'int', not 'unsigned'. 16375 16376 // Determine whether the value fits into an int. 16377 llvm::APSInt InitVal = ECD->getInitVal(); 16378 16379 // If it fits into an integer type, force it. Otherwise force it to match 16380 // the enum decl type. 16381 QualType NewTy; 16382 unsigned NewWidth; 16383 bool NewSign; 16384 if (!getLangOpts().CPlusPlus && 16385 !Enum->isFixed() && 16386 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16387 NewTy = Context.IntTy; 16388 NewWidth = IntWidth; 16389 NewSign = true; 16390 } else if (ECD->getType() == BestType) { 16391 // Already the right type! 16392 if (getLangOpts().CPlusPlus) 16393 // C++ [dcl.enum]p4: Following the closing brace of an 16394 // enum-specifier, each enumerator has the type of its 16395 // enumeration. 16396 ECD->setType(EnumType); 16397 continue; 16398 } else { 16399 NewTy = BestType; 16400 NewWidth = BestWidth; 16401 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16402 } 16403 16404 // Adjust the APSInt value. 16405 InitVal = InitVal.extOrTrunc(NewWidth); 16406 InitVal.setIsSigned(NewSign); 16407 ECD->setInitVal(InitVal); 16408 16409 // Adjust the Expr initializer and type. 16410 if (ECD->getInitExpr() && 16411 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16412 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16413 CK_IntegralCast, 16414 ECD->getInitExpr(), 16415 /*base paths*/ nullptr, 16416 VK_RValue)); 16417 if (getLangOpts().CPlusPlus) 16418 // C++ [dcl.enum]p4: Following the closing brace of an 16419 // enum-specifier, each enumerator has the type of its 16420 // enumeration. 16421 ECD->setType(EnumType); 16422 else 16423 ECD->setType(NewTy); 16424 } 16425 16426 Enum->completeDefinition(BestType, BestPromotionType, 16427 NumPositiveBits, NumNegativeBits); 16428 16429 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16430 16431 if (Enum->isClosedFlag()) { 16432 for (Decl *D : Elements) { 16433 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16434 if (!ECD) continue; // Already issued a diagnostic. 16435 16436 llvm::APSInt InitVal = ECD->getInitVal(); 16437 if (InitVal != 0 && !InitVal.isPowerOf2() && 16438 !IsValueInFlagEnum(Enum, InitVal, true)) 16439 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16440 << ECD << Enum; 16441 } 16442 } 16443 16444 // Now that the enum type is defined, ensure it's not been underaligned. 16445 if (Enum->hasAttrs()) 16446 CheckAlignasUnderalignment(Enum); 16447 } 16448 16449 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16450 SourceLocation StartLoc, 16451 SourceLocation EndLoc) { 16452 StringLiteral *AsmString = cast<StringLiteral>(expr); 16453 16454 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16455 AsmString, StartLoc, 16456 EndLoc); 16457 CurContext->addDecl(New); 16458 return New; 16459 } 16460 16461 static void checkModuleImportContext(Sema &S, Module *M, 16462 SourceLocation ImportLoc, DeclContext *DC, 16463 bool FromInclude = false) { 16464 SourceLocation ExternCLoc; 16465 16466 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16467 switch (LSD->getLanguage()) { 16468 case LinkageSpecDecl::lang_c: 16469 if (ExternCLoc.isInvalid()) 16470 ExternCLoc = LSD->getLocStart(); 16471 break; 16472 case LinkageSpecDecl::lang_cxx: 16473 break; 16474 } 16475 DC = LSD->getParent(); 16476 } 16477 16478 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 16479 DC = DC->getParent(); 16480 16481 if (!isa<TranslationUnitDecl>(DC)) { 16482 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16483 ? diag::ext_module_import_not_at_top_level_noop 16484 : diag::err_module_import_not_at_top_level_fatal) 16485 << M->getFullModuleName() << DC; 16486 S.Diag(cast<Decl>(DC)->getLocStart(), 16487 diag::note_module_import_not_at_top_level) << DC; 16488 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16489 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16490 << M->getFullModuleName(); 16491 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16492 } 16493 } 16494 16495 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16496 SourceLocation ModuleLoc, 16497 ModuleDeclKind MDK, 16498 ModuleIdPath Path) { 16499 assert(getLangOpts().ModulesTS && 16500 "should only have module decl in modules TS"); 16501 16502 // A module implementation unit requires that we are not compiling a module 16503 // of any kind. A module interface unit requires that we are not compiling a 16504 // module map. 16505 switch (getLangOpts().getCompilingModule()) { 16506 case LangOptions::CMK_None: 16507 // It's OK to compile a module interface as a normal translation unit. 16508 break; 16509 16510 case LangOptions::CMK_ModuleInterface: 16511 if (MDK != ModuleDeclKind::Implementation) 16512 break; 16513 16514 // We were asked to compile a module interface unit but this is a module 16515 // implementation unit. That indicates the 'export' is missing. 16516 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16517 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16518 MDK = ModuleDeclKind::Interface; 16519 break; 16520 16521 case LangOptions::CMK_ModuleMap: 16522 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16523 return nullptr; 16524 } 16525 16526 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16527 16528 // FIXME: Most of this work should be done by the preprocessor rather than 16529 // here, in order to support macro import. 16530 16531 // Only one module-declaration is permitted per source file. 16532 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16533 Diag(ModuleLoc, diag::err_module_redeclaration); 16534 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16535 diag::note_prev_module_declaration); 16536 return nullptr; 16537 } 16538 16539 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16540 // modules, the dots here are just another character that can appear in a 16541 // module name. 16542 std::string ModuleName; 16543 for (auto &Piece : Path) { 16544 if (!ModuleName.empty()) 16545 ModuleName += "."; 16546 ModuleName += Piece.first->getName(); 16547 } 16548 16549 // If a module name was explicitly specified on the command line, it must be 16550 // correct. 16551 if (!getLangOpts().CurrentModule.empty() && 16552 getLangOpts().CurrentModule != ModuleName) { 16553 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16554 << SourceRange(Path.front().second, Path.back().second) 16555 << getLangOpts().CurrentModule; 16556 return nullptr; 16557 } 16558 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16559 16560 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16561 Module *Mod; 16562 16563 switch (MDK) { 16564 case ModuleDeclKind::Interface: { 16565 // We can't have parsed or imported a definition of this module or parsed a 16566 // module map defining it already. 16567 if (auto *M = Map.findModule(ModuleName)) { 16568 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16569 if (M->DefinitionLoc.isValid()) 16570 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16571 else if (const auto *FE = M->getASTFile()) 16572 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16573 << FE->getName(); 16574 Mod = M; 16575 break; 16576 } 16577 16578 // Create a Module for the module that we're defining. 16579 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16580 ModuleScopes.front().Module); 16581 assert(Mod && "module creation should not fail"); 16582 break; 16583 } 16584 16585 case ModuleDeclKind::Partition: 16586 // FIXME: Check we are in a submodule of the named module. 16587 return nullptr; 16588 16589 case ModuleDeclKind::Implementation: 16590 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16591 PP.getIdentifierInfo(ModuleName), Path[0].second); 16592 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16593 /*IsIncludeDirective=*/false); 16594 if (!Mod) { 16595 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 16596 // Create an empty module interface unit for error recovery. 16597 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16598 ModuleScopes.front().Module); 16599 } 16600 break; 16601 } 16602 16603 // Switch from the global module to the named module. 16604 ModuleScopes.back().Module = Mod; 16605 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 16606 VisibleModules.setVisible(Mod, ModuleLoc); 16607 16608 // From now on, we have an owning module for all declarations we see. 16609 // However, those declarations are module-private unless explicitly 16610 // exported. 16611 auto *TU = Context.getTranslationUnitDecl(); 16612 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16613 TU->setLocalOwningModule(Mod); 16614 16615 // FIXME: Create a ModuleDecl. 16616 return nullptr; 16617 } 16618 16619 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16620 SourceLocation ImportLoc, 16621 ModuleIdPath Path) { 16622 Module *Mod = 16623 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16624 /*IsIncludeDirective=*/false); 16625 if (!Mod) 16626 return true; 16627 16628 VisibleModules.setVisible(Mod, ImportLoc); 16629 16630 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16631 16632 // FIXME: we should support importing a submodule within a different submodule 16633 // of the same top-level module. Until we do, make it an error rather than 16634 // silently ignoring the import. 16635 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16636 // warn on a redundant import of the current module? 16637 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16638 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16639 Diag(ImportLoc, getLangOpts().isCompilingModule() 16640 ? diag::err_module_self_import 16641 : diag::err_module_import_in_implementation) 16642 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16643 16644 SmallVector<SourceLocation, 2> IdentifierLocs; 16645 Module *ModCheck = Mod; 16646 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16647 // If we've run out of module parents, just drop the remaining identifiers. 16648 // We need the length to be consistent. 16649 if (!ModCheck) 16650 break; 16651 ModCheck = ModCheck->Parent; 16652 16653 IdentifierLocs.push_back(Path[I].second); 16654 } 16655 16656 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 16657 Mod, IdentifierLocs); 16658 if (!ModuleScopes.empty()) 16659 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16660 CurContext->addDecl(Import); 16661 16662 // Re-export the module if needed. 16663 if (Import->isExported() && 16664 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) 16665 getCurrentModule()->Exports.emplace_back(Mod, false); 16666 16667 return Import; 16668 } 16669 16670 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16671 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16672 BuildModuleInclude(DirectiveLoc, Mod); 16673 } 16674 16675 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16676 // Determine whether we're in the #include buffer for a module. The #includes 16677 // in that buffer do not qualify as module imports; they're just an 16678 // implementation detail of us building the module. 16679 // 16680 // FIXME: Should we even get ActOnModuleInclude calls for those? 16681 bool IsInModuleIncludes = 16682 TUKind == TU_Module && 16683 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16684 16685 bool ShouldAddImport = !IsInModuleIncludes; 16686 16687 // If this module import was due to an inclusion directive, create an 16688 // implicit import declaration to capture it in the AST. 16689 if (ShouldAddImport) { 16690 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16691 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16692 DirectiveLoc, Mod, 16693 DirectiveLoc); 16694 if (!ModuleScopes.empty()) 16695 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16696 TU->addDecl(ImportD); 16697 Consumer.HandleImplicitImportDecl(ImportD); 16698 } 16699 16700 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16701 VisibleModules.setVisible(Mod, DirectiveLoc); 16702 } 16703 16704 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16705 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16706 16707 ModuleScopes.push_back({}); 16708 ModuleScopes.back().Module = Mod; 16709 if (getLangOpts().ModulesLocalVisibility) 16710 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16711 16712 VisibleModules.setVisible(Mod, DirectiveLoc); 16713 16714 // The enclosing context is now part of this module. 16715 // FIXME: Consider creating a child DeclContext to hold the entities 16716 // lexically within the module. 16717 if (getLangOpts().trackLocalOwningModule()) { 16718 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16719 cast<Decl>(DC)->setModuleOwnershipKind( 16720 getLangOpts().ModulesLocalVisibility 16721 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16722 : Decl::ModuleOwnershipKind::Visible); 16723 cast<Decl>(DC)->setLocalOwningModule(Mod); 16724 } 16725 } 16726 } 16727 16728 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16729 if (getLangOpts().ModulesLocalVisibility) { 16730 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16731 // Leaving a module hides namespace names, so our visible namespace cache 16732 // is now out of date. 16733 VisibleNamespaceCache.clear(); 16734 } 16735 16736 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16737 "left the wrong module scope"); 16738 ModuleScopes.pop_back(); 16739 16740 // We got to the end of processing a local module. Create an 16741 // ImportDecl as we would for an imported module. 16742 FileID File = getSourceManager().getFileID(EomLoc); 16743 SourceLocation DirectiveLoc; 16744 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16745 // We reached the end of a #included module header. Use the #include loc. 16746 assert(File != getSourceManager().getMainFileID() && 16747 "end of submodule in main source file"); 16748 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16749 } else { 16750 // We reached an EOM pragma. Use the pragma location. 16751 DirectiveLoc = EomLoc; 16752 } 16753 BuildModuleInclude(DirectiveLoc, Mod); 16754 16755 // Any further declarations are in whatever module we returned to. 16756 if (getLangOpts().trackLocalOwningModule()) { 16757 // The parser guarantees that this is the same context that we entered 16758 // the module within. 16759 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16760 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16761 if (!getCurrentModule()) 16762 cast<Decl>(DC)->setModuleOwnershipKind( 16763 Decl::ModuleOwnershipKind::Unowned); 16764 } 16765 } 16766 } 16767 16768 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16769 Module *Mod) { 16770 // Bail if we're not allowed to implicitly import a module here. 16771 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16772 VisibleModules.isVisible(Mod)) 16773 return; 16774 16775 // Create the implicit import declaration. 16776 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16777 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16778 Loc, Mod, Loc); 16779 TU->addDecl(ImportD); 16780 Consumer.HandleImplicitImportDecl(ImportD); 16781 16782 // Make the module visible. 16783 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16784 VisibleModules.setVisible(Mod, Loc); 16785 } 16786 16787 /// We have parsed the start of an export declaration, including the '{' 16788 /// (if present). 16789 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16790 SourceLocation LBraceLoc) { 16791 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16792 16793 // C++ Modules TS draft: 16794 // An export-declaration shall appear in the purview of a module other than 16795 // the global module. 16796 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 16797 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16798 16799 // An export-declaration [...] shall not contain more than one 16800 // export keyword. 16801 // 16802 // The intent here is that an export-declaration cannot appear within another 16803 // export-declaration. 16804 if (D->isExported()) 16805 Diag(ExportLoc, diag::err_export_within_export); 16806 16807 CurContext->addDecl(D); 16808 PushDeclContext(S, D); 16809 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16810 return D; 16811 } 16812 16813 /// Complete the definition of an export declaration. 16814 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16815 auto *ED = cast<ExportDecl>(D); 16816 if (RBraceLoc.isValid()) 16817 ED->setRBraceLoc(RBraceLoc); 16818 16819 // FIXME: Diagnose export of internal-linkage declaration (including 16820 // anonymous namespace). 16821 16822 PopDeclContext(); 16823 return D; 16824 } 16825 16826 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16827 IdentifierInfo* AliasName, 16828 SourceLocation PragmaLoc, 16829 SourceLocation NameLoc, 16830 SourceLocation AliasNameLoc) { 16831 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16832 LookupOrdinaryName); 16833 AsmLabelAttr *Attr = 16834 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16835 16836 // If a declaration that: 16837 // 1) declares a function or a variable 16838 // 2) has external linkage 16839 // already exists, add a label attribute to it. 16840 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16841 if (isDeclExternC(PrevDecl)) 16842 PrevDecl->addAttr(Attr); 16843 else 16844 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16845 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16846 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16847 } else 16848 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16849 } 16850 16851 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16852 SourceLocation PragmaLoc, 16853 SourceLocation NameLoc) { 16854 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16855 16856 if (PrevDecl) { 16857 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16858 } else { 16859 (void)WeakUndeclaredIdentifiers.insert( 16860 std::pair<IdentifierInfo*,WeakInfo> 16861 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16862 } 16863 } 16864 16865 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16866 IdentifierInfo* AliasName, 16867 SourceLocation PragmaLoc, 16868 SourceLocation NameLoc, 16869 SourceLocation AliasNameLoc) { 16870 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16871 LookupOrdinaryName); 16872 WeakInfo W = WeakInfo(Name, NameLoc); 16873 16874 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16875 if (!PrevDecl->hasAttr<AliasAttr>()) 16876 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16877 DeclApplyPragmaWeak(TUScope, ND, W); 16878 } else { 16879 (void)WeakUndeclaredIdentifiers.insert( 16880 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16881 } 16882 } 16883 16884 Decl *Sema::getObjCDeclContext() const { 16885 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16886 } 16887