1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "TypeLocBuilder.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTLambda.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/CharUnits.h" 20 #include "clang/AST/CommentDiagnostic.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/Basic/Builtins.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 35 #include "clang/Sema/CXXFieldCollector.h" 36 #include "clang/Sema/DeclSpec.h" 37 #include "clang/Sema/DelayedDiagnostic.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/Lookup.h" 40 #include "clang/Sema/ParsedTemplate.h" 41 #include "clang/Sema/Scope.h" 42 #include "clang/Sema/ScopeInfo.h" 43 #include "clang/Sema/SemaInternal.h" 44 #include "clang/Sema/Template.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/Triple.h" 47 #include <algorithm> 48 #include <cstring> 49 #include <functional> 50 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 68 bool AllowTemplates = false, 69 bool AllowNonTemplates = true) 70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 72 WantExpressionKeywords = false; 73 WantCXXNamedCasts = false; 74 WantRemainingKeywords = false; 75 } 76 77 bool ValidateCandidate(const TypoCorrection &candidate) override { 78 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 79 if (!AllowInvalidDecl && ND->isInvalidDecl()) 80 return false; 81 82 if (getAsTypeTemplateDecl(ND)) 83 return AllowTemplates; 84 85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 86 if (!IsType) 87 return false; 88 89 if (AllowNonTemplates) 90 return true; 91 92 // An injected-class-name of a class template (specialization) is valid 93 // as a template or as a non-template. 94 if (AllowTemplates) { 95 auto *RD = dyn_cast<CXXRecordDecl>(ND); 96 if (!RD || !RD->isInjectedClassName()) 97 return false; 98 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 99 return RD->getDescribedClassTemplate() || 100 isa<ClassTemplateSpecializationDecl>(RD); 101 } 102 103 return false; 104 } 105 106 return !WantClassName && candidate.isKeyword(); 107 } 108 109 private: 110 bool AllowInvalidDecl; 111 bool WantClassName; 112 bool AllowTemplates; 113 bool AllowNonTemplates; 114 }; 115 116 } // end anonymous namespace 117 118 /// \brief Determine whether the token kind starts a simple-type-specifier. 119 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 120 switch (Kind) { 121 // FIXME: Take into account the current language when deciding whether a 122 // token kind is a valid type specifier 123 case tok::kw_short: 124 case tok::kw_long: 125 case tok::kw___int64: 126 case tok::kw___int128: 127 case tok::kw_signed: 128 case tok::kw_unsigned: 129 case tok::kw_void: 130 case tok::kw_char: 131 case tok::kw_int: 132 case tok::kw_half: 133 case tok::kw_float: 134 case tok::kw_double: 135 case tok::kw__Float16: 136 case tok::kw___float128: 137 case tok::kw_wchar_t: 138 case tok::kw_bool: 139 case tok::kw___underlying_type: 140 case tok::kw___auto_type: 141 return true; 142 143 case tok::annot_typename: 144 case tok::kw_char16_t: 145 case tok::kw_char32_t: 146 case tok::kw_typeof: 147 case tok::annot_decltype: 148 case tok::kw_decltype: 149 return getLangOpts().CPlusPlus; 150 151 default: 152 break; 153 } 154 155 return false; 156 } 157 158 namespace { 159 enum class UnqualifiedTypeNameLookupResult { 160 NotFound, 161 FoundNonType, 162 FoundType 163 }; 164 } // end anonymous namespace 165 166 /// \brief Tries to perform unqualified lookup of the type decls in bases for 167 /// dependent class. 168 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 169 /// type decl, \a FoundType if only type decls are found. 170 static UnqualifiedTypeNameLookupResult 171 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 172 SourceLocation NameLoc, 173 const CXXRecordDecl *RD) { 174 if (!RD->hasDefinition()) 175 return UnqualifiedTypeNameLookupResult::NotFound; 176 // Look for type decls in base classes. 177 UnqualifiedTypeNameLookupResult FoundTypeDecl = 178 UnqualifiedTypeNameLookupResult::NotFound; 179 for (const auto &Base : RD->bases()) { 180 const CXXRecordDecl *BaseRD = nullptr; 181 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 182 BaseRD = BaseTT->getAsCXXRecordDecl(); 183 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 184 // Look for type decls in dependent base classes that have known primary 185 // templates. 186 if (!TST || !TST->isDependentType()) 187 continue; 188 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 189 if (!TD) 190 continue; 191 if (auto *BasePrimaryTemplate = 192 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 193 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 194 BaseRD = BasePrimaryTemplate; 195 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 196 if (const ClassTemplatePartialSpecializationDecl *PS = 197 CTD->findPartialSpecialization(Base.getType())) 198 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 199 BaseRD = PS; 200 } 201 } 202 } 203 if (BaseRD) { 204 for (NamedDecl *ND : BaseRD->lookup(&II)) { 205 if (!isa<TypeDecl>(ND)) 206 return UnqualifiedTypeNameLookupResult::FoundNonType; 207 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 208 } 209 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 210 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 211 case UnqualifiedTypeNameLookupResult::FoundNonType: 212 return UnqualifiedTypeNameLookupResult::FoundNonType; 213 case UnqualifiedTypeNameLookupResult::FoundType: 214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 215 break; 216 case UnqualifiedTypeNameLookupResult::NotFound: 217 break; 218 } 219 } 220 } 221 } 222 223 return FoundTypeDecl; 224 } 225 226 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 227 const IdentifierInfo &II, 228 SourceLocation NameLoc) { 229 // Lookup in the parent class template context, if any. 230 const CXXRecordDecl *RD = nullptr; 231 UnqualifiedTypeNameLookupResult FoundTypeDecl = 232 UnqualifiedTypeNameLookupResult::NotFound; 233 for (DeclContext *DC = S.CurContext; 234 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 235 DC = DC->getParent()) { 236 // Look for type decls in dependent base classes that have known primary 237 // templates. 238 RD = dyn_cast<CXXRecordDecl>(DC); 239 if (RD && RD->getDescribedClassTemplate()) 240 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 241 } 242 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 243 return nullptr; 244 245 // We found some types in dependent base classes. Recover as if the user 246 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 247 // lookup during template instantiation. 248 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 249 250 ASTContext &Context = S.Context; 251 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 252 cast<Type>(Context.getRecordType(RD))); 253 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 254 255 CXXScopeSpec SS; 256 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 257 258 TypeLocBuilder Builder; 259 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 260 DepTL.setNameLoc(NameLoc); 261 DepTL.setElaboratedKeywordLoc(SourceLocation()); 262 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 263 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 264 } 265 266 /// \brief If the identifier refers to a type name within this scope, 267 /// return the declaration of that type. 268 /// 269 /// This routine performs ordinary name lookup of the identifier II 270 /// within the given scope, with optional C++ scope specifier SS, to 271 /// determine whether the name refers to a type. If so, returns an 272 /// opaque pointer (actually a QualType) corresponding to that 273 /// type. Otherwise, returns NULL. 274 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 275 Scope *S, CXXScopeSpec *SS, 276 bool isClassName, bool HasTrailingDot, 277 ParsedType ObjectTypePtr, 278 bool IsCtorOrDtorName, 279 bool WantNontrivialTypeSourceInfo, 280 bool IsClassTemplateDeductionContext, 281 IdentifierInfo **CorrectedII) { 282 // FIXME: Consider allowing this outside C++1z mode as an extension. 283 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 284 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 285 !isClassName && !HasTrailingDot; 286 287 // Determine where we will perform name lookup. 288 DeclContext *LookupCtx = nullptr; 289 if (ObjectTypePtr) { 290 QualType ObjectType = ObjectTypePtr.get(); 291 if (ObjectType->isRecordType()) 292 LookupCtx = computeDeclContext(ObjectType); 293 } else if (SS && SS->isNotEmpty()) { 294 LookupCtx = computeDeclContext(*SS, false); 295 296 if (!LookupCtx) { 297 if (isDependentScopeSpecifier(*SS)) { 298 // C++ [temp.res]p3: 299 // A qualified-id that refers to a type and in which the 300 // nested-name-specifier depends on a template-parameter (14.6.2) 301 // shall be prefixed by the keyword typename to indicate that the 302 // qualified-id denotes a type, forming an 303 // elaborated-type-specifier (7.1.5.3). 304 // 305 // We therefore do not perform any name lookup if the result would 306 // refer to a member of an unknown specialization. 307 if (!isClassName && !IsCtorOrDtorName) 308 return nullptr; 309 310 // We know from the grammar that this name refers to a type, 311 // so build a dependent node to describe the type. 312 if (WantNontrivialTypeSourceInfo) 313 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 314 315 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 316 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 317 II, NameLoc); 318 return ParsedType::make(T); 319 } 320 321 return nullptr; 322 } 323 324 if (!LookupCtx->isDependentContext() && 325 RequireCompleteDeclContext(*SS, LookupCtx)) 326 return nullptr; 327 } 328 329 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 330 // lookup for class-names. 331 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 332 LookupOrdinaryName; 333 LookupResult Result(*this, &II, NameLoc, Kind); 334 if (LookupCtx) { 335 // Perform "qualified" name lookup into the declaration context we 336 // computed, which is either the type of the base of a member access 337 // expression or the declaration context associated with a prior 338 // nested-name-specifier. 339 LookupQualifiedName(Result, LookupCtx); 340 341 if (ObjectTypePtr && Result.empty()) { 342 // C++ [basic.lookup.classref]p3: 343 // If the unqualified-id is ~type-name, the type-name is looked up 344 // in the context of the entire postfix-expression. If the type T of 345 // the object expression is of a class type C, the type-name is also 346 // looked up in the scope of class C. At least one of the lookups shall 347 // find a name that refers to (possibly cv-qualified) T. 348 LookupName(Result, S); 349 } 350 } else { 351 // Perform unqualified name lookup. 352 LookupName(Result, S); 353 354 // For unqualified lookup in a class template in MSVC mode, look into 355 // dependent base classes where the primary class template is known. 356 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 357 if (ParsedType TypeInBase = 358 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 359 return TypeInBase; 360 } 361 } 362 363 NamedDecl *IIDecl = nullptr; 364 switch (Result.getResultKind()) { 365 case LookupResult::NotFound: 366 case LookupResult::NotFoundInCurrentInstantiation: 367 if (CorrectedII) { 368 TypoCorrection Correction = 369 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS, 370 llvm::make_unique<TypeNameValidatorCCC>( 371 true, isClassName, AllowDeducedTemplate), 372 CTK_ErrorRecovery); 373 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 374 TemplateTy Template; 375 bool MemberOfUnknownSpecialization; 376 UnqualifiedId TemplateName; 377 TemplateName.setIdentifier(NewII, NameLoc); 378 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 379 CXXScopeSpec NewSS, *NewSSPtr = SS; 380 if (SS && NNS) { 381 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 382 NewSSPtr = &NewSS; 383 } 384 if (Correction && (NNS || NewII != &II) && 385 // Ignore a correction to a template type as the to-be-corrected 386 // identifier is not a template (typo correction for template names 387 // is handled elsewhere). 388 !(getLangOpts().CPlusPlus && NewSSPtr && 389 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 390 Template, MemberOfUnknownSpecialization))) { 391 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 392 isClassName, HasTrailingDot, ObjectTypePtr, 393 IsCtorOrDtorName, 394 WantNontrivialTypeSourceInfo, 395 IsClassTemplateDeductionContext); 396 if (Ty) { 397 diagnoseTypo(Correction, 398 PDiag(diag::err_unknown_type_or_class_name_suggest) 399 << Result.getLookupName() << isClassName); 400 if (SS && NNS) 401 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 402 *CorrectedII = NewII; 403 return Ty; 404 } 405 } 406 } 407 // If typo correction failed or was not performed, fall through 408 LLVM_FALLTHROUGH; 409 case LookupResult::FoundOverloaded: 410 case LookupResult::FoundUnresolvedValue: 411 Result.suppressDiagnostics(); 412 return nullptr; 413 414 case LookupResult::Ambiguous: 415 // Recover from type-hiding ambiguities by hiding the type. We'll 416 // do the lookup again when looking for an object, and we can 417 // diagnose the error then. If we don't do this, then the error 418 // about hiding the type will be immediately followed by an error 419 // that only makes sense if the identifier was treated like a type. 420 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 421 Result.suppressDiagnostics(); 422 return nullptr; 423 } 424 425 // Look to see if we have a type anywhere in the list of results. 426 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 427 Res != ResEnd; ++Res) { 428 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 429 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 430 if (!IIDecl || 431 (*Res)->getLocation().getRawEncoding() < 432 IIDecl->getLocation().getRawEncoding()) 433 IIDecl = *Res; 434 } 435 } 436 437 if (!IIDecl) { 438 // None of the entities we found is a type, so there is no way 439 // to even assume that the result is a type. In this case, don't 440 // complain about the ambiguity. The parser will either try to 441 // perform this lookup again (e.g., as an object name), which 442 // will produce the ambiguity, or will complain that it expected 443 // a type name. 444 Result.suppressDiagnostics(); 445 return nullptr; 446 } 447 448 // We found a type within the ambiguous lookup; diagnose the 449 // ambiguity and then return that type. This might be the right 450 // answer, or it might not be, but it suppresses any attempt to 451 // perform the name lookup again. 452 break; 453 454 case LookupResult::Found: 455 IIDecl = Result.getFoundDecl(); 456 break; 457 } 458 459 assert(IIDecl && "Didn't find decl"); 460 461 QualType T; 462 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 463 // C++ [class.qual]p2: A lookup that would find the injected-class-name 464 // instead names the constructors of the class, except when naming a class. 465 // This is ill-formed when we're not actually forming a ctor or dtor name. 466 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 467 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 468 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 469 FoundRD->isInjectedClassName() && 470 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 471 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 472 << &II << /*Type*/1; 473 474 DiagnoseUseOfDecl(IIDecl, NameLoc); 475 476 T = Context.getTypeDeclType(TD); 477 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 478 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 479 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 480 if (!HasTrailingDot) 481 T = Context.getObjCInterfaceType(IDecl); 482 } else if (AllowDeducedTemplate) { 483 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 484 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 485 QualType(), false); 486 } 487 488 if (T.isNull()) { 489 // If it's not plausibly a type, suppress diagnostics. 490 Result.suppressDiagnostics(); 491 return nullptr; 492 } 493 494 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 495 // constructor or destructor name (in such a case, the scope specifier 496 // will be attached to the enclosing Expr or Decl node). 497 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 498 !isa<ObjCInterfaceDecl>(IIDecl)) { 499 if (WantNontrivialTypeSourceInfo) { 500 // Construct a type with type-source information. 501 TypeLocBuilder Builder; 502 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 503 504 T = getElaboratedType(ETK_None, *SS, T); 505 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 506 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 507 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 508 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 509 } else { 510 T = getElaboratedType(ETK_None, *SS, T); 511 } 512 } 513 514 return ParsedType::make(T); 515 } 516 517 // Builds a fake NNS for the given decl context. 518 static NestedNameSpecifier * 519 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 520 for (;; DC = DC->getLookupParent()) { 521 DC = DC->getPrimaryContext(); 522 auto *ND = dyn_cast<NamespaceDecl>(DC); 523 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 524 return NestedNameSpecifier::Create(Context, nullptr, ND); 525 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 526 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 527 RD->getTypeForDecl()); 528 else if (isa<TranslationUnitDecl>(DC)) 529 return NestedNameSpecifier::GlobalSpecifier(Context); 530 } 531 llvm_unreachable("something isn't in TU scope?"); 532 } 533 534 /// Find the parent class with dependent bases of the innermost enclosing method 535 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 536 /// up allowing unqualified dependent type names at class-level, which MSVC 537 /// correctly rejects. 538 static const CXXRecordDecl * 539 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 540 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 541 DC = DC->getPrimaryContext(); 542 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 543 if (MD->getParent()->hasAnyDependentBases()) 544 return MD->getParent(); 545 } 546 return nullptr; 547 } 548 549 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 550 SourceLocation NameLoc, 551 bool IsTemplateTypeArg) { 552 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 553 554 NestedNameSpecifier *NNS = nullptr; 555 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 556 // If we weren't able to parse a default template argument, delay lookup 557 // until instantiation time by making a non-dependent DependentTypeName. We 558 // pretend we saw a NestedNameSpecifier referring to the current scope, and 559 // lookup is retried. 560 // FIXME: This hurts our diagnostic quality, since we get errors like "no 561 // type named 'Foo' in 'current_namespace'" when the user didn't write any 562 // name specifiers. 563 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 564 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 565 } else if (const CXXRecordDecl *RD = 566 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 567 // Build a DependentNameType that will perform lookup into RD at 568 // instantiation time. 569 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 570 RD->getTypeForDecl()); 571 572 // Diagnose that this identifier was undeclared, and retry the lookup during 573 // template instantiation. 574 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 575 << RD; 576 } else { 577 // This is not a situation that we should recover from. 578 return ParsedType(); 579 } 580 581 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 582 583 // Build type location information. We synthesized the qualifier, so we have 584 // to build a fake NestedNameSpecifierLoc. 585 NestedNameSpecifierLocBuilder NNSLocBuilder; 586 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 587 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 588 589 TypeLocBuilder Builder; 590 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 591 DepTL.setNameLoc(NameLoc); 592 DepTL.setElaboratedKeywordLoc(SourceLocation()); 593 DepTL.setQualifierLoc(QualifierLoc); 594 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 595 } 596 597 /// isTagName() - This method is called *for error recovery purposes only* 598 /// to determine if the specified name is a valid tag name ("struct foo"). If 599 /// so, this returns the TST for the tag corresponding to it (TST_enum, 600 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 601 /// cases in C where the user forgot to specify the tag. 602 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 603 // Do a tag name lookup in this scope. 604 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 605 LookupName(R, S, false); 606 R.suppressDiagnostics(); 607 if (R.getResultKind() == LookupResult::Found) 608 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 609 switch (TD->getTagKind()) { 610 case TTK_Struct: return DeclSpec::TST_struct; 611 case TTK_Interface: return DeclSpec::TST_interface; 612 case TTK_Union: return DeclSpec::TST_union; 613 case TTK_Class: return DeclSpec::TST_class; 614 case TTK_Enum: return DeclSpec::TST_enum; 615 } 616 } 617 618 return DeclSpec::TST_unspecified; 619 } 620 621 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 622 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 623 /// then downgrade the missing typename error to a warning. 624 /// This is needed for MSVC compatibility; Example: 625 /// @code 626 /// template<class T> class A { 627 /// public: 628 /// typedef int TYPE; 629 /// }; 630 /// template<class T> class B : public A<T> { 631 /// public: 632 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 633 /// }; 634 /// @endcode 635 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 636 if (CurContext->isRecord()) { 637 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 638 return true; 639 640 const Type *Ty = SS->getScopeRep()->getAsType(); 641 642 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 643 for (const auto &Base : RD->bases()) 644 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 645 return true; 646 return S->isFunctionPrototypeScope(); 647 } 648 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 649 } 650 651 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 652 SourceLocation IILoc, 653 Scope *S, 654 CXXScopeSpec *SS, 655 ParsedType &SuggestedType, 656 bool IsTemplateName) { 657 // Don't report typename errors for editor placeholders. 658 if (II->isEditorPlaceholder()) 659 return; 660 // We don't have anything to suggest (yet). 661 SuggestedType = nullptr; 662 663 // There may have been a typo in the name of the type. Look up typo 664 // results, in case we have something that we can suggest. 665 if (TypoCorrection Corrected = 666 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 667 llvm::make_unique<TypeNameValidatorCCC>( 668 false, false, IsTemplateName, !IsTemplateName), 669 CTK_ErrorRecovery)) { 670 // FIXME: Support error recovery for the template-name case. 671 bool CanRecover = !IsTemplateName; 672 if (Corrected.isKeyword()) { 673 // We corrected to a keyword. 674 diagnoseTypo(Corrected, 675 PDiag(IsTemplateName ? diag::err_no_template_suggest 676 : diag::err_unknown_typename_suggest) 677 << II); 678 II = Corrected.getCorrectionAsIdentifierInfo(); 679 } else { 680 // We found a similarly-named type or interface; suggest that. 681 if (!SS || !SS->isSet()) { 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II, CanRecover); 686 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 687 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 688 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 689 II->getName().equals(CorrectedStr); 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName 692 ? diag::err_no_member_template_suggest 693 : diag::err_unknown_nested_typename_suggest) 694 << II << DC << DroppedSpecifier << SS->getRange(), 695 CanRecover); 696 } else { 697 llvm_unreachable("could not have corrected a typo here"); 698 } 699 700 if (!CanRecover) 701 return; 702 703 CXXScopeSpec tmpSS; 704 if (Corrected.getCorrectionSpecifier()) 705 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 706 SourceRange(IILoc)); 707 // FIXME: Support class template argument deduction here. 708 SuggestedType = 709 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 710 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 711 /*IsCtorOrDtorName=*/false, 712 /*NonTrivialTypeSourceInfo=*/true); 713 } 714 return; 715 } 716 717 if (getLangOpts().CPlusPlus && !IsTemplateName) { 718 // See if II is a class template that the user forgot to pass arguments to. 719 UnqualifiedId Name; 720 Name.setIdentifier(II, IILoc); 721 CXXScopeSpec EmptySS; 722 TemplateTy TemplateResult; 723 bool MemberOfUnknownSpecialization; 724 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 725 Name, nullptr, true, TemplateResult, 726 MemberOfUnknownSpecialization) == TNK_Type_template) { 727 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 728 return; 729 } 730 } 731 732 // FIXME: Should we move the logic that tries to recover from a missing tag 733 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 734 735 if (!SS || (!SS->isSet() && !SS->isInvalid())) 736 Diag(IILoc, IsTemplateName ? diag::err_no_template 737 : diag::err_unknown_typename) 738 << II; 739 else if (DeclContext *DC = computeDeclContext(*SS, false)) 740 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 741 : diag::err_typename_nested_not_found) 742 << II << DC << SS->getRange(); 743 else if (isDependentScopeSpecifier(*SS)) { 744 unsigned DiagID = diag::err_typename_missing; 745 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 746 DiagID = diag::ext_typename_missing; 747 748 Diag(SS->getRange().getBegin(), DiagID) 749 << SS->getScopeRep() << II->getName() 750 << SourceRange(SS->getRange().getBegin(), IILoc) 751 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 752 SuggestedType = ActOnTypenameType(S, SourceLocation(), 753 *SS, *II, IILoc).get(); 754 } else { 755 assert(SS && SS->isInvalid() && 756 "Invalid scope specifier has already been diagnosed"); 757 } 758 } 759 760 /// \brief Determine whether the given result set contains either a type name 761 /// or 762 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 763 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 764 NextToken.is(tok::less); 765 766 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 767 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 768 return true; 769 770 if (CheckTemplate && isa<TemplateDecl>(*I)) 771 return true; 772 } 773 774 return false; 775 } 776 777 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 778 Scope *S, CXXScopeSpec &SS, 779 IdentifierInfo *&Name, 780 SourceLocation NameLoc) { 781 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 782 SemaRef.LookupParsedName(R, S, &SS); 783 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 784 StringRef FixItTagName; 785 switch (Tag->getTagKind()) { 786 case TTK_Class: 787 FixItTagName = "class "; 788 break; 789 790 case TTK_Enum: 791 FixItTagName = "enum "; 792 break; 793 794 case TTK_Struct: 795 FixItTagName = "struct "; 796 break; 797 798 case TTK_Interface: 799 FixItTagName = "__interface "; 800 break; 801 802 case TTK_Union: 803 FixItTagName = "union "; 804 break; 805 } 806 807 StringRef TagName = FixItTagName.drop_back(); 808 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 809 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 810 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 811 812 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 813 I != IEnd; ++I) 814 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 815 << Name << TagName; 816 817 // Replace lookup results with just the tag decl. 818 Result.clear(Sema::LookupTagName); 819 SemaRef.LookupParsedName(Result, S, &SS); 820 return true; 821 } 822 823 return false; 824 } 825 826 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 827 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 828 QualType T, SourceLocation NameLoc) { 829 ASTContext &Context = S.Context; 830 831 TypeLocBuilder Builder; 832 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 833 834 T = S.getElaboratedType(ETK_None, SS, T); 835 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 836 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 837 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 838 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 839 } 840 841 Sema::NameClassification 842 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 843 SourceLocation NameLoc, const Token &NextToken, 844 bool IsAddressOfOperand, 845 std::unique_ptr<CorrectionCandidateCallback> CCC) { 846 DeclarationNameInfo NameInfo(Name, NameLoc); 847 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 848 849 if (NextToken.is(tok::coloncolon)) { 850 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation()); 851 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false); 852 } else if (getLangOpts().CPlusPlus && SS.isSet() && 853 isCurrentClassName(*Name, S, &SS)) { 854 // Per [class.qual]p2, this names the constructors of SS, not the 855 // injected-class-name. We don't have a classification for that. 856 // There's not much point caching this result, since the parser 857 // will reject it later. 858 return NameClassification::Unknown(); 859 } 860 861 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 862 LookupParsedName(Result, S, &SS, !CurMethod); 863 864 // For unqualified lookup in a class template in MSVC mode, look into 865 // dependent base classes where the primary class template is known. 866 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 867 if (ParsedType TypeInBase = 868 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 869 return TypeInBase; 870 } 871 872 // Perform lookup for Objective-C instance variables (including automatically 873 // synthesized instance variables), if we're in an Objective-C method. 874 // FIXME: This lookup really, really needs to be folded in to the normal 875 // unqualified lookup mechanism. 876 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 877 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 878 if (E.get() || E.isInvalid()) 879 return E; 880 } 881 882 bool SecondTry = false; 883 bool IsFilteredTemplateName = false; 884 885 Corrected: 886 switch (Result.getResultKind()) { 887 case LookupResult::NotFound: 888 // If an unqualified-id is followed by a '(', then we have a function 889 // call. 890 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 891 // In C++, this is an ADL-only call. 892 // FIXME: Reference? 893 if (getLangOpts().CPlusPlus) 894 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 895 896 // C90 6.3.2.2: 897 // If the expression that precedes the parenthesized argument list in a 898 // function call consists solely of an identifier, and if no 899 // declaration is visible for this identifier, the identifier is 900 // implicitly declared exactly as if, in the innermost block containing 901 // the function call, the declaration 902 // 903 // extern int identifier (); 904 // 905 // appeared. 906 // 907 // We also allow this in C99 as an extension. 908 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 909 Result.addDecl(D); 910 Result.resolveKind(); 911 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 912 } 913 } 914 915 // In C, we first see whether there is a tag type by the same name, in 916 // which case it's likely that the user just forgot to write "enum", 917 // "struct", or "union". 918 if (!getLangOpts().CPlusPlus && !SecondTry && 919 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 920 break; 921 } 922 923 // Perform typo correction to determine if there is another name that is 924 // close to this name. 925 if (!SecondTry && CCC) { 926 SecondTry = true; 927 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 928 Result.getLookupKind(), S, 929 &SS, std::move(CCC), 930 CTK_ErrorRecovery)) { 931 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 932 unsigned QualifiedDiag = diag::err_no_member_suggest; 933 934 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 935 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 936 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 937 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 938 UnqualifiedDiag = diag::err_no_template_suggest; 939 QualifiedDiag = diag::err_no_member_template_suggest; 940 } else if (UnderlyingFirstDecl && 941 (isa<TypeDecl>(UnderlyingFirstDecl) || 942 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 943 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 944 UnqualifiedDiag = diag::err_unknown_typename_suggest; 945 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 946 } 947 948 if (SS.isEmpty()) { 949 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 950 } else {// FIXME: is this even reachable? Test it. 951 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 952 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 953 Name->getName().equals(CorrectedStr); 954 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 955 << Name << computeDeclContext(SS, false) 956 << DroppedSpecifier << SS.getRange()); 957 } 958 959 // Update the name, so that the caller has the new name. 960 Name = Corrected.getCorrectionAsIdentifierInfo(); 961 962 // Typo correction corrected to a keyword. 963 if (Corrected.isKeyword()) 964 return Name; 965 966 // Also update the LookupResult... 967 // FIXME: This should probably go away at some point 968 Result.clear(); 969 Result.setLookupName(Corrected.getCorrection()); 970 if (FirstDecl) 971 Result.addDecl(FirstDecl); 972 973 // If we found an Objective-C instance variable, let 974 // LookupInObjCMethod build the appropriate expression to 975 // reference the ivar. 976 // FIXME: This is a gross hack. 977 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 978 Result.clear(); 979 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 980 return E; 981 } 982 983 goto Corrected; 984 } 985 } 986 987 // We failed to correct; just fall through and let the parser deal with it. 988 Result.suppressDiagnostics(); 989 return NameClassification::Unknown(); 990 991 case LookupResult::NotFoundInCurrentInstantiation: { 992 // We performed name lookup into the current instantiation, and there were 993 // dependent bases, so we treat this result the same way as any other 994 // dependent nested-name-specifier. 995 996 // C++ [temp.res]p2: 997 // A name used in a template declaration or definition and that is 998 // dependent on a template-parameter is assumed not to name a type 999 // unless the applicable name lookup finds a type name or the name is 1000 // qualified by the keyword typename. 1001 // 1002 // FIXME: If the next token is '<', we might want to ask the parser to 1003 // perform some heroics to see if we actually have a 1004 // template-argument-list, which would indicate a missing 'template' 1005 // keyword here. 1006 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1007 NameInfo, IsAddressOfOperand, 1008 /*TemplateArgs=*/nullptr); 1009 } 1010 1011 case LookupResult::Found: 1012 case LookupResult::FoundOverloaded: 1013 case LookupResult::FoundUnresolvedValue: 1014 break; 1015 1016 case LookupResult::Ambiguous: 1017 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1018 hasAnyAcceptableTemplateNames(Result)) { 1019 // C++ [temp.local]p3: 1020 // A lookup that finds an injected-class-name (10.2) can result in an 1021 // ambiguity in certain cases (for example, if it is found in more than 1022 // one base class). If all of the injected-class-names that are found 1023 // refer to specializations of the same class template, and if the name 1024 // is followed by a template-argument-list, the reference refers to the 1025 // class template itself and not a specialization thereof, and is not 1026 // ambiguous. 1027 // 1028 // This filtering can make an ambiguous result into an unambiguous one, 1029 // so try again after filtering out template names. 1030 FilterAcceptableTemplateNames(Result); 1031 if (!Result.isAmbiguous()) { 1032 IsFilteredTemplateName = true; 1033 break; 1034 } 1035 } 1036 1037 // Diagnose the ambiguity and return an error. 1038 return NameClassification::Error(); 1039 } 1040 1041 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1042 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 1043 // C++ [temp.names]p3: 1044 // After name lookup (3.4) finds that a name is a template-name or that 1045 // an operator-function-id or a literal- operator-id refers to a set of 1046 // overloaded functions any member of which is a function template if 1047 // this is followed by a <, the < is always taken as the delimiter of a 1048 // template-argument-list and never as the less-than operator. 1049 if (!IsFilteredTemplateName) 1050 FilterAcceptableTemplateNames(Result); 1051 1052 if (!Result.empty()) { 1053 bool IsFunctionTemplate; 1054 bool IsVarTemplate; 1055 TemplateName Template; 1056 if (Result.end() - Result.begin() > 1) { 1057 IsFunctionTemplate = true; 1058 Template = Context.getOverloadedTemplateName(Result.begin(), 1059 Result.end()); 1060 } else { 1061 TemplateDecl *TD 1062 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 1063 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1064 IsVarTemplate = isa<VarTemplateDecl>(TD); 1065 1066 if (SS.isSet() && !SS.isInvalid()) 1067 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 1068 /*TemplateKeyword=*/false, 1069 TD); 1070 else 1071 Template = TemplateName(TD); 1072 } 1073 1074 if (IsFunctionTemplate) { 1075 // Function templates always go through overload resolution, at which 1076 // point we'll perform the various checks (e.g., accessibility) we need 1077 // to based on which function we selected. 1078 Result.suppressDiagnostics(); 1079 1080 return NameClassification::FunctionTemplate(Template); 1081 } 1082 1083 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1084 : NameClassification::TypeTemplate(Template); 1085 } 1086 } 1087 1088 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1089 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1090 DiagnoseUseOfDecl(Type, NameLoc); 1091 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1092 QualType T = Context.getTypeDeclType(Type); 1093 if (SS.isNotEmpty()) 1094 return buildNestedType(*this, SS, T, NameLoc); 1095 return ParsedType::make(T); 1096 } 1097 1098 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1099 if (!Class) { 1100 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1101 if (ObjCCompatibleAliasDecl *Alias = 1102 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1103 Class = Alias->getClassInterface(); 1104 } 1105 1106 if (Class) { 1107 DiagnoseUseOfDecl(Class, NameLoc); 1108 1109 if (NextToken.is(tok::period)) { 1110 // Interface. <something> is parsed as a property reference expression. 1111 // Just return "unknown" as a fall-through for now. 1112 Result.suppressDiagnostics(); 1113 return NameClassification::Unknown(); 1114 } 1115 1116 QualType T = Context.getObjCInterfaceType(Class); 1117 return ParsedType::make(T); 1118 } 1119 1120 // We can have a type template here if we're classifying a template argument. 1121 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1122 !isa<VarTemplateDecl>(FirstDecl)) 1123 return NameClassification::TypeTemplate( 1124 TemplateName(cast<TemplateDecl>(FirstDecl))); 1125 1126 // Check for a tag type hidden by a non-type decl in a few cases where it 1127 // seems likely a type is wanted instead of the non-type that was found. 1128 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1129 if ((NextToken.is(tok::identifier) || 1130 (NextIsOp && 1131 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1132 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1133 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1134 DiagnoseUseOfDecl(Type, NameLoc); 1135 QualType T = Context.getTypeDeclType(Type); 1136 if (SS.isNotEmpty()) 1137 return buildNestedType(*this, SS, T, NameLoc); 1138 return ParsedType::make(T); 1139 } 1140 1141 if (FirstDecl->isCXXClassMember()) 1142 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1143 nullptr, S); 1144 1145 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1146 return BuildDeclarationNameExpr(SS, Result, ADL); 1147 } 1148 1149 Sema::TemplateNameKindForDiagnostics 1150 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1151 auto *TD = Name.getAsTemplateDecl(); 1152 if (!TD) 1153 return TemplateNameKindForDiagnostics::DependentTemplate; 1154 if (isa<ClassTemplateDecl>(TD)) 1155 return TemplateNameKindForDiagnostics::ClassTemplate; 1156 if (isa<FunctionTemplateDecl>(TD)) 1157 return TemplateNameKindForDiagnostics::FunctionTemplate; 1158 if (isa<VarTemplateDecl>(TD)) 1159 return TemplateNameKindForDiagnostics::VarTemplate; 1160 if (isa<TypeAliasTemplateDecl>(TD)) 1161 return TemplateNameKindForDiagnostics::AliasTemplate; 1162 if (isa<TemplateTemplateParmDecl>(TD)) 1163 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1164 return TemplateNameKindForDiagnostics::DependentTemplate; 1165 } 1166 1167 // Determines the context to return to after temporarily entering a 1168 // context. This depends in an unnecessarily complicated way on the 1169 // exact ordering of callbacks from the parser. 1170 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1171 1172 // Functions defined inline within classes aren't parsed until we've 1173 // finished parsing the top-level class, so the top-level class is 1174 // the context we'll need to return to. 1175 // A Lambda call operator whose parent is a class must not be treated 1176 // as an inline member function. A Lambda can be used legally 1177 // either as an in-class member initializer or a default argument. These 1178 // are parsed once the class has been marked complete and so the containing 1179 // context would be the nested class (when the lambda is defined in one); 1180 // If the class is not complete, then the lambda is being used in an 1181 // ill-formed fashion (such as to specify the width of a bit-field, or 1182 // in an array-bound) - in which case we still want to return the 1183 // lexically containing DC (which could be a nested class). 1184 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1185 DC = DC->getLexicalParent(); 1186 1187 // A function not defined within a class will always return to its 1188 // lexical context. 1189 if (!isa<CXXRecordDecl>(DC)) 1190 return DC; 1191 1192 // A C++ inline method/friend is parsed *after* the topmost class 1193 // it was declared in is fully parsed ("complete"); the topmost 1194 // class is the context we need to return to. 1195 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1196 DC = RD; 1197 1198 // Return the declaration context of the topmost class the inline method is 1199 // declared in. 1200 return DC; 1201 } 1202 1203 return DC->getLexicalParent(); 1204 } 1205 1206 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1207 assert(getContainingDC(DC) == CurContext && 1208 "The next DeclContext should be lexically contained in the current one."); 1209 CurContext = DC; 1210 S->setEntity(DC); 1211 } 1212 1213 void Sema::PopDeclContext() { 1214 assert(CurContext && "DeclContext imbalance!"); 1215 1216 CurContext = getContainingDC(CurContext); 1217 assert(CurContext && "Popped translation unit!"); 1218 } 1219 1220 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1221 Decl *D) { 1222 // Unlike PushDeclContext, the context to which we return is not necessarily 1223 // the containing DC of TD, because the new context will be some pre-existing 1224 // TagDecl definition instead of a fresh one. 1225 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1226 CurContext = cast<TagDecl>(D)->getDefinition(); 1227 assert(CurContext && "skipping definition of undefined tag"); 1228 // Start lookups from the parent of the current context; we don't want to look 1229 // into the pre-existing complete definition. 1230 S->setEntity(CurContext->getLookupParent()); 1231 return Result; 1232 } 1233 1234 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1235 CurContext = static_cast<decltype(CurContext)>(Context); 1236 } 1237 1238 /// EnterDeclaratorContext - Used when we must lookup names in the context 1239 /// of a declarator's nested name specifier. 1240 /// 1241 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1242 // C++0x [basic.lookup.unqual]p13: 1243 // A name used in the definition of a static data member of class 1244 // X (after the qualified-id of the static member) is looked up as 1245 // if the name was used in a member function of X. 1246 // C++0x [basic.lookup.unqual]p14: 1247 // If a variable member of a namespace is defined outside of the 1248 // scope of its namespace then any name used in the definition of 1249 // the variable member (after the declarator-id) is looked up as 1250 // if the definition of the variable member occurred in its 1251 // namespace. 1252 // Both of these imply that we should push a scope whose context 1253 // is the semantic context of the declaration. We can't use 1254 // PushDeclContext here because that context is not necessarily 1255 // lexically contained in the current context. Fortunately, 1256 // the containing scope should have the appropriate information. 1257 1258 assert(!S->getEntity() && "scope already has entity"); 1259 1260 #ifndef NDEBUG 1261 Scope *Ancestor = S->getParent(); 1262 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1263 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1264 #endif 1265 1266 CurContext = DC; 1267 S->setEntity(DC); 1268 } 1269 1270 void Sema::ExitDeclaratorContext(Scope *S) { 1271 assert(S->getEntity() == CurContext && "Context imbalance!"); 1272 1273 // Switch back to the lexical context. The safety of this is 1274 // enforced by an assert in EnterDeclaratorContext. 1275 Scope *Ancestor = S->getParent(); 1276 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1277 CurContext = Ancestor->getEntity(); 1278 1279 // We don't need to do anything with the scope, which is going to 1280 // disappear. 1281 } 1282 1283 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1284 // We assume that the caller has already called 1285 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1286 FunctionDecl *FD = D->getAsFunction(); 1287 if (!FD) 1288 return; 1289 1290 // Same implementation as PushDeclContext, but enters the context 1291 // from the lexical parent, rather than the top-level class. 1292 assert(CurContext == FD->getLexicalParent() && 1293 "The next DeclContext should be lexically contained in the current one."); 1294 CurContext = FD; 1295 S->setEntity(CurContext); 1296 1297 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1298 ParmVarDecl *Param = FD->getParamDecl(P); 1299 // If the parameter has an identifier, then add it to the scope 1300 if (Param->getIdentifier()) { 1301 S->AddDecl(Param); 1302 IdResolver.AddDecl(Param); 1303 } 1304 } 1305 } 1306 1307 void Sema::ActOnExitFunctionContext() { 1308 // Same implementation as PopDeclContext, but returns to the lexical parent, 1309 // rather than the top-level class. 1310 assert(CurContext && "DeclContext imbalance!"); 1311 CurContext = CurContext->getLexicalParent(); 1312 assert(CurContext && "Popped translation unit!"); 1313 } 1314 1315 /// \brief Determine whether we allow overloading of the function 1316 /// PrevDecl with another declaration. 1317 /// 1318 /// This routine determines whether overloading is possible, not 1319 /// whether some new function is actually an overload. It will return 1320 /// true in C++ (where we can always provide overloads) or, as an 1321 /// extension, in C when the previous function is already an 1322 /// overloaded function declaration or has the "overloadable" 1323 /// attribute. 1324 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1325 ASTContext &Context, 1326 const FunctionDecl *New) { 1327 if (Context.getLangOpts().CPlusPlus) 1328 return true; 1329 1330 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1331 return true; 1332 1333 return Previous.getResultKind() == LookupResult::Found && 1334 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1335 New->hasAttr<OverloadableAttr>()); 1336 } 1337 1338 /// Add this decl to the scope shadowed decl chains. 1339 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1340 // Move up the scope chain until we find the nearest enclosing 1341 // non-transparent context. The declaration will be introduced into this 1342 // scope. 1343 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1344 S = S->getParent(); 1345 1346 // Add scoped declarations into their context, so that they can be 1347 // found later. Declarations without a context won't be inserted 1348 // into any context. 1349 if (AddToContext) 1350 CurContext->addDecl(D); 1351 1352 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1353 // are function-local declarations. 1354 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1355 !D->getDeclContext()->getRedeclContext()->Equals( 1356 D->getLexicalDeclContext()->getRedeclContext()) && 1357 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1358 return; 1359 1360 // Template instantiations should also not be pushed into scope. 1361 if (isa<FunctionDecl>(D) && 1362 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1363 return; 1364 1365 // If this replaces anything in the current scope, 1366 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1367 IEnd = IdResolver.end(); 1368 for (; I != IEnd; ++I) { 1369 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1370 S->RemoveDecl(*I); 1371 IdResolver.RemoveDecl(*I); 1372 1373 // Should only need to replace one decl. 1374 break; 1375 } 1376 } 1377 1378 S->AddDecl(D); 1379 1380 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1381 // Implicitly-generated labels may end up getting generated in an order that 1382 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1383 // the label at the appropriate place in the identifier chain. 1384 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1385 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1386 if (IDC == CurContext) { 1387 if (!S->isDeclScope(*I)) 1388 continue; 1389 } else if (IDC->Encloses(CurContext)) 1390 break; 1391 } 1392 1393 IdResolver.InsertDeclAfter(I, D); 1394 } else { 1395 IdResolver.AddDecl(D); 1396 } 1397 } 1398 1399 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1400 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1401 TUScope->AddDecl(D); 1402 } 1403 1404 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1405 bool AllowInlineNamespace) { 1406 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1407 } 1408 1409 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1410 DeclContext *TargetDC = DC->getPrimaryContext(); 1411 do { 1412 if (DeclContext *ScopeDC = S->getEntity()) 1413 if (ScopeDC->getPrimaryContext() == TargetDC) 1414 return S; 1415 } while ((S = S->getParent())); 1416 1417 return nullptr; 1418 } 1419 1420 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1421 DeclContext*, 1422 ASTContext&); 1423 1424 /// Filters out lookup results that don't fall within the given scope 1425 /// as determined by isDeclInScope. 1426 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1427 bool ConsiderLinkage, 1428 bool AllowInlineNamespace) { 1429 LookupResult::Filter F = R.makeFilter(); 1430 while (F.hasNext()) { 1431 NamedDecl *D = F.next(); 1432 1433 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1434 continue; 1435 1436 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1437 continue; 1438 1439 F.erase(); 1440 } 1441 1442 F.done(); 1443 } 1444 1445 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1446 /// have compatible owning modules. 1447 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1448 // FIXME: The Modules TS is not clear about how friend declarations are 1449 // to be treated. It's not meaningful to have different owning modules for 1450 // linkage in redeclarations of the same entity, so for now allow the 1451 // redeclaration and change the owning modules to match. 1452 if (New->getFriendObjectKind() && 1453 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1454 New->setLocalOwningModule(Old->getOwningModule()); 1455 makeMergedDefinitionVisible(New); 1456 return false; 1457 } 1458 1459 Module *NewM = New->getOwningModule(); 1460 Module *OldM = Old->getOwningModule(); 1461 if (NewM == OldM) 1462 return false; 1463 1464 // FIXME: Check proclaimed-ownership-declarations here too. 1465 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit; 1466 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit; 1467 if (NewIsModuleInterface || OldIsModuleInterface) { 1468 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1469 // if a declaration of D [...] appears in the purview of a module, all 1470 // other such declarations shall appear in the purview of the same module 1471 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1472 << New 1473 << NewIsModuleInterface 1474 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1475 << OldIsModuleInterface 1476 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1477 Diag(Old->getLocation(), diag::note_previous_declaration); 1478 New->setInvalidDecl(); 1479 return true; 1480 } 1481 1482 return false; 1483 } 1484 1485 static bool isUsingDecl(NamedDecl *D) { 1486 return isa<UsingShadowDecl>(D) || 1487 isa<UnresolvedUsingTypenameDecl>(D) || 1488 isa<UnresolvedUsingValueDecl>(D); 1489 } 1490 1491 /// Removes using shadow declarations from the lookup results. 1492 static void RemoveUsingDecls(LookupResult &R) { 1493 LookupResult::Filter F = R.makeFilter(); 1494 while (F.hasNext()) 1495 if (isUsingDecl(F.next())) 1496 F.erase(); 1497 1498 F.done(); 1499 } 1500 1501 /// \brief Check for this common pattern: 1502 /// @code 1503 /// class S { 1504 /// S(const S&); // DO NOT IMPLEMENT 1505 /// void operator=(const S&); // DO NOT IMPLEMENT 1506 /// }; 1507 /// @endcode 1508 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1509 // FIXME: Should check for private access too but access is set after we get 1510 // the decl here. 1511 if (D->doesThisDeclarationHaveABody()) 1512 return false; 1513 1514 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1515 return CD->isCopyConstructor(); 1516 return D->isCopyAssignmentOperator(); 1517 } 1518 1519 // We need this to handle 1520 // 1521 // typedef struct { 1522 // void *foo() { return 0; } 1523 // } A; 1524 // 1525 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1526 // for example. If 'A', foo will have external linkage. If we have '*A', 1527 // foo will have no linkage. Since we can't know until we get to the end 1528 // of the typedef, this function finds out if D might have non-external linkage. 1529 // Callers should verify at the end of the TU if it D has external linkage or 1530 // not. 1531 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1532 const DeclContext *DC = D->getDeclContext(); 1533 while (!DC->isTranslationUnit()) { 1534 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1535 if (!RD->hasNameForLinkage()) 1536 return true; 1537 } 1538 DC = DC->getParent(); 1539 } 1540 1541 return !D->isExternallyVisible(); 1542 } 1543 1544 // FIXME: This needs to be refactored; some other isInMainFile users want 1545 // these semantics. 1546 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1547 if (S.TUKind != TU_Complete) 1548 return false; 1549 return S.SourceMgr.isInMainFile(Loc); 1550 } 1551 1552 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1553 assert(D); 1554 1555 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1556 return false; 1557 1558 // Ignore all entities declared within templates, and out-of-line definitions 1559 // of members of class templates. 1560 if (D->getDeclContext()->isDependentContext() || 1561 D->getLexicalDeclContext()->isDependentContext()) 1562 return false; 1563 1564 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1565 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1566 return false; 1567 // A non-out-of-line declaration of a member specialization was implicitly 1568 // instantiated; it's the out-of-line declaration that we're interested in. 1569 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1570 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1571 return false; 1572 1573 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1574 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1575 return false; 1576 } else { 1577 // 'static inline' functions are defined in headers; don't warn. 1578 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1579 return false; 1580 } 1581 1582 if (FD->doesThisDeclarationHaveABody() && 1583 Context.DeclMustBeEmitted(FD)) 1584 return false; 1585 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1586 // Constants and utility variables are defined in headers with internal 1587 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1588 // like "inline".) 1589 if (!isMainFileLoc(*this, VD->getLocation())) 1590 return false; 1591 1592 if (Context.DeclMustBeEmitted(VD)) 1593 return false; 1594 1595 if (VD->isStaticDataMember() && 1596 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1597 return false; 1598 if (VD->isStaticDataMember() && 1599 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1600 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1601 return false; 1602 1603 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1604 return false; 1605 } else { 1606 return false; 1607 } 1608 1609 // Only warn for unused decls internal to the translation unit. 1610 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1611 // for inline functions defined in the main source file, for instance. 1612 return mightHaveNonExternalLinkage(D); 1613 } 1614 1615 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1616 if (!D) 1617 return; 1618 1619 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1620 const FunctionDecl *First = FD->getFirstDecl(); 1621 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1622 return; // First should already be in the vector. 1623 } 1624 1625 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1626 const VarDecl *First = VD->getFirstDecl(); 1627 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1628 return; // First should already be in the vector. 1629 } 1630 1631 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1632 UnusedFileScopedDecls.push_back(D); 1633 } 1634 1635 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1636 if (D->isInvalidDecl()) 1637 return false; 1638 1639 bool Referenced = false; 1640 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1641 // For a decomposition declaration, warn if none of the bindings are 1642 // referenced, instead of if the variable itself is referenced (which 1643 // it is, by the bindings' expressions). 1644 for (auto *BD : DD->bindings()) { 1645 if (BD->isReferenced()) { 1646 Referenced = true; 1647 break; 1648 } 1649 } 1650 } else if (!D->getDeclName()) { 1651 return false; 1652 } else if (D->isReferenced() || D->isUsed()) { 1653 Referenced = true; 1654 } 1655 1656 if (Referenced || D->hasAttr<UnusedAttr>() || 1657 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1658 return false; 1659 1660 if (isa<LabelDecl>(D)) 1661 return true; 1662 1663 // Except for labels, we only care about unused decls that are local to 1664 // functions. 1665 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1666 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1667 // For dependent types, the diagnostic is deferred. 1668 WithinFunction = 1669 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1670 if (!WithinFunction) 1671 return false; 1672 1673 if (isa<TypedefNameDecl>(D)) 1674 return true; 1675 1676 // White-list anything that isn't a local variable. 1677 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1678 return false; 1679 1680 // Types of valid local variables should be complete, so this should succeed. 1681 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1682 1683 // White-list anything with an __attribute__((unused)) type. 1684 const auto *Ty = VD->getType().getTypePtr(); 1685 1686 // Only look at the outermost level of typedef. 1687 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1688 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1689 return false; 1690 } 1691 1692 // If we failed to complete the type for some reason, or if the type is 1693 // dependent, don't diagnose the variable. 1694 if (Ty->isIncompleteType() || Ty->isDependentType()) 1695 return false; 1696 1697 // Look at the element type to ensure that the warning behaviour is 1698 // consistent for both scalars and arrays. 1699 Ty = Ty->getBaseElementTypeUnsafe(); 1700 1701 if (const TagType *TT = Ty->getAs<TagType>()) { 1702 const TagDecl *Tag = TT->getDecl(); 1703 if (Tag->hasAttr<UnusedAttr>()) 1704 return false; 1705 1706 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1707 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1708 return false; 1709 1710 if (const Expr *Init = VD->getInit()) { 1711 if (const ExprWithCleanups *Cleanups = 1712 dyn_cast<ExprWithCleanups>(Init)) 1713 Init = Cleanups->getSubExpr(); 1714 const CXXConstructExpr *Construct = 1715 dyn_cast<CXXConstructExpr>(Init); 1716 if (Construct && !Construct->isElidable()) { 1717 CXXConstructorDecl *CD = Construct->getConstructor(); 1718 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1719 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1720 return false; 1721 } 1722 } 1723 } 1724 } 1725 1726 // TODO: __attribute__((unused)) templates? 1727 } 1728 1729 return true; 1730 } 1731 1732 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1733 FixItHint &Hint) { 1734 if (isa<LabelDecl>(D)) { 1735 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1736 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1737 if (AfterColon.isInvalid()) 1738 return; 1739 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1740 getCharRange(D->getLocStart(), AfterColon)); 1741 } 1742 } 1743 1744 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1745 if (D->getTypeForDecl()->isDependentType()) 1746 return; 1747 1748 for (auto *TmpD : D->decls()) { 1749 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1750 DiagnoseUnusedDecl(T); 1751 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1752 DiagnoseUnusedNestedTypedefs(R); 1753 } 1754 } 1755 1756 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1757 /// unless they are marked attr(unused). 1758 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1759 if (!ShouldDiagnoseUnusedDecl(D)) 1760 return; 1761 1762 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1763 // typedefs can be referenced later on, so the diagnostics are emitted 1764 // at end-of-translation-unit. 1765 UnusedLocalTypedefNameCandidates.insert(TD); 1766 return; 1767 } 1768 1769 FixItHint Hint; 1770 GenerateFixForUnusedDecl(D, Context, Hint); 1771 1772 unsigned DiagID; 1773 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1774 DiagID = diag::warn_unused_exception_param; 1775 else if (isa<LabelDecl>(D)) 1776 DiagID = diag::warn_unused_label; 1777 else 1778 DiagID = diag::warn_unused_variable; 1779 1780 Diag(D->getLocation(), DiagID) << D << Hint; 1781 } 1782 1783 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1784 // Verify that we have no forward references left. If so, there was a goto 1785 // or address of a label taken, but no definition of it. Label fwd 1786 // definitions are indicated with a null substmt which is also not a resolved 1787 // MS inline assembly label name. 1788 bool Diagnose = false; 1789 if (L->isMSAsmLabel()) 1790 Diagnose = !L->isResolvedMSAsmLabel(); 1791 else 1792 Diagnose = L->getStmt() == nullptr; 1793 if (Diagnose) 1794 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1795 } 1796 1797 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1798 S->mergeNRVOIntoParent(); 1799 1800 if (S->decl_empty()) return; 1801 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1802 "Scope shouldn't contain decls!"); 1803 1804 for (auto *TmpD : S->decls()) { 1805 assert(TmpD && "This decl didn't get pushed??"); 1806 1807 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1808 NamedDecl *D = cast<NamedDecl>(TmpD); 1809 1810 // Diagnose unused variables in this scope. 1811 if (!S->hasUnrecoverableErrorOccurred()) { 1812 DiagnoseUnusedDecl(D); 1813 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1814 DiagnoseUnusedNestedTypedefs(RD); 1815 } 1816 1817 if (!D->getDeclName()) continue; 1818 1819 // If this was a forward reference to a label, verify it was defined. 1820 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1821 CheckPoppedLabel(LD, *this); 1822 1823 // Remove this name from our lexical scope, and warn on it if we haven't 1824 // already. 1825 IdResolver.RemoveDecl(D); 1826 auto ShadowI = ShadowingDecls.find(D); 1827 if (ShadowI != ShadowingDecls.end()) { 1828 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1829 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1830 << D << FD << FD->getParent(); 1831 Diag(FD->getLocation(), diag::note_previous_declaration); 1832 } 1833 ShadowingDecls.erase(ShadowI); 1834 } 1835 } 1836 } 1837 1838 /// \brief Look for an Objective-C class in the translation unit. 1839 /// 1840 /// \param Id The name of the Objective-C class we're looking for. If 1841 /// typo-correction fixes this name, the Id will be updated 1842 /// to the fixed name. 1843 /// 1844 /// \param IdLoc The location of the name in the translation unit. 1845 /// 1846 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1847 /// if there is no class with the given name. 1848 /// 1849 /// \returns The declaration of the named Objective-C class, or NULL if the 1850 /// class could not be found. 1851 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1852 SourceLocation IdLoc, 1853 bool DoTypoCorrection) { 1854 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1855 // creation from this context. 1856 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1857 1858 if (!IDecl && DoTypoCorrection) { 1859 // Perform typo correction at the given location, but only if we 1860 // find an Objective-C class name. 1861 if (TypoCorrection C = CorrectTypo( 1862 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1863 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1864 CTK_ErrorRecovery)) { 1865 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1866 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1867 Id = IDecl->getIdentifier(); 1868 } 1869 } 1870 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1871 // This routine must always return a class definition, if any. 1872 if (Def && Def->getDefinition()) 1873 Def = Def->getDefinition(); 1874 return Def; 1875 } 1876 1877 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1878 /// from S, where a non-field would be declared. This routine copes 1879 /// with the difference between C and C++ scoping rules in structs and 1880 /// unions. For example, the following code is well-formed in C but 1881 /// ill-formed in C++: 1882 /// @code 1883 /// struct S6 { 1884 /// enum { BAR } e; 1885 /// }; 1886 /// 1887 /// void test_S6() { 1888 /// struct S6 a; 1889 /// a.e = BAR; 1890 /// } 1891 /// @endcode 1892 /// For the declaration of BAR, this routine will return a different 1893 /// scope. The scope S will be the scope of the unnamed enumeration 1894 /// within S6. In C++, this routine will return the scope associated 1895 /// with S6, because the enumeration's scope is a transparent 1896 /// context but structures can contain non-field names. In C, this 1897 /// routine will return the translation unit scope, since the 1898 /// enumeration's scope is a transparent context and structures cannot 1899 /// contain non-field names. 1900 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1901 while (((S->getFlags() & Scope::DeclScope) == 0) || 1902 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1903 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1904 S = S->getParent(); 1905 return S; 1906 } 1907 1908 /// \brief Looks up the declaration of "struct objc_super" and 1909 /// saves it for later use in building builtin declaration of 1910 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1911 /// pre-existing declaration exists no action takes place. 1912 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1913 IdentifierInfo *II) { 1914 if (!II->isStr("objc_msgSendSuper")) 1915 return; 1916 ASTContext &Context = ThisSema.Context; 1917 1918 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1919 SourceLocation(), Sema::LookupTagName); 1920 ThisSema.LookupName(Result, S); 1921 if (Result.getResultKind() == LookupResult::Found) 1922 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1923 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1924 } 1925 1926 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1927 switch (Error) { 1928 case ASTContext::GE_None: 1929 return ""; 1930 case ASTContext::GE_Missing_stdio: 1931 return "stdio.h"; 1932 case ASTContext::GE_Missing_setjmp: 1933 return "setjmp.h"; 1934 case ASTContext::GE_Missing_ucontext: 1935 return "ucontext.h"; 1936 } 1937 llvm_unreachable("unhandled error kind"); 1938 } 1939 1940 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1941 /// file scope. lazily create a decl for it. ForRedeclaration is true 1942 /// if we're creating this built-in in anticipation of redeclaring the 1943 /// built-in. 1944 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1945 Scope *S, bool ForRedeclaration, 1946 SourceLocation Loc) { 1947 LookupPredefedObjCSuperType(*this, S, II); 1948 1949 ASTContext::GetBuiltinTypeError Error; 1950 QualType R = Context.GetBuiltinType(ID, Error); 1951 if (Error) { 1952 if (ForRedeclaration) 1953 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1954 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1955 return nullptr; 1956 } 1957 1958 if (!ForRedeclaration && 1959 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 1960 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 1961 Diag(Loc, diag::ext_implicit_lib_function_decl) 1962 << Context.BuiltinInfo.getName(ID) << R; 1963 if (Context.BuiltinInfo.getHeaderName(ID) && 1964 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1965 Diag(Loc, diag::note_include_header_or_declare) 1966 << Context.BuiltinInfo.getHeaderName(ID) 1967 << Context.BuiltinInfo.getName(ID); 1968 } 1969 1970 if (R.isNull()) 1971 return nullptr; 1972 1973 DeclContext *Parent = Context.getTranslationUnitDecl(); 1974 if (getLangOpts().CPlusPlus) { 1975 LinkageSpecDecl *CLinkageDecl = 1976 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1977 LinkageSpecDecl::lang_c, false); 1978 CLinkageDecl->setImplicit(); 1979 Parent->addDecl(CLinkageDecl); 1980 Parent = CLinkageDecl; 1981 } 1982 1983 FunctionDecl *New = FunctionDecl::Create(Context, 1984 Parent, 1985 Loc, Loc, II, R, /*TInfo=*/nullptr, 1986 SC_Extern, 1987 false, 1988 R->isFunctionProtoType()); 1989 New->setImplicit(); 1990 1991 // Create Decl objects for each parameter, adding them to the 1992 // FunctionDecl. 1993 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1994 SmallVector<ParmVarDecl*, 16> Params; 1995 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1996 ParmVarDecl *parm = 1997 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1998 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1999 SC_None, nullptr); 2000 parm->setScopeInfo(0, i); 2001 Params.push_back(parm); 2002 } 2003 New->setParams(Params); 2004 } 2005 2006 AddKnownFunctionAttributes(New); 2007 RegisterLocallyScopedExternCDecl(New, S); 2008 2009 // TUScope is the translation-unit scope to insert this function into. 2010 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2011 // relate Scopes to DeclContexts, and probably eliminate CurContext 2012 // entirely, but we're not there yet. 2013 DeclContext *SavedContext = CurContext; 2014 CurContext = Parent; 2015 PushOnScopeChains(New, TUScope); 2016 CurContext = SavedContext; 2017 return New; 2018 } 2019 2020 /// Typedef declarations don't have linkage, but they still denote the same 2021 /// entity if their types are the same. 2022 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2023 /// isSameEntity. 2024 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2025 TypedefNameDecl *Decl, 2026 LookupResult &Previous) { 2027 // This is only interesting when modules are enabled. 2028 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2029 return; 2030 2031 // Empty sets are uninteresting. 2032 if (Previous.empty()) 2033 return; 2034 2035 LookupResult::Filter Filter = Previous.makeFilter(); 2036 while (Filter.hasNext()) { 2037 NamedDecl *Old = Filter.next(); 2038 2039 // Non-hidden declarations are never ignored. 2040 if (S.isVisible(Old)) 2041 continue; 2042 2043 // Declarations of the same entity are not ignored, even if they have 2044 // different linkages. 2045 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2046 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2047 Decl->getUnderlyingType())) 2048 continue; 2049 2050 // If both declarations give a tag declaration a typedef name for linkage 2051 // purposes, then they declare the same entity. 2052 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2053 Decl->getAnonDeclWithTypedefName()) 2054 continue; 2055 } 2056 2057 Filter.erase(); 2058 } 2059 2060 Filter.done(); 2061 } 2062 2063 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2064 QualType OldType; 2065 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2066 OldType = OldTypedef->getUnderlyingType(); 2067 else 2068 OldType = Context.getTypeDeclType(Old); 2069 QualType NewType = New->getUnderlyingType(); 2070 2071 if (NewType->isVariablyModifiedType()) { 2072 // Must not redefine a typedef with a variably-modified type. 2073 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2074 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2075 << Kind << NewType; 2076 if (Old->getLocation().isValid()) 2077 notePreviousDefinition(Old, New->getLocation()); 2078 New->setInvalidDecl(); 2079 return true; 2080 } 2081 2082 if (OldType != NewType && 2083 !OldType->isDependentType() && 2084 !NewType->isDependentType() && 2085 !Context.hasSameType(OldType, NewType)) { 2086 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2087 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2088 << Kind << NewType << OldType; 2089 if (Old->getLocation().isValid()) 2090 notePreviousDefinition(Old, New->getLocation()); 2091 New->setInvalidDecl(); 2092 return true; 2093 } 2094 return false; 2095 } 2096 2097 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2098 /// same name and scope as a previous declaration 'Old'. Figure out 2099 /// how to resolve this situation, merging decls or emitting 2100 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2101 /// 2102 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2103 LookupResult &OldDecls) { 2104 // If the new decl is known invalid already, don't bother doing any 2105 // merging checks. 2106 if (New->isInvalidDecl()) return; 2107 2108 // Allow multiple definitions for ObjC built-in typedefs. 2109 // FIXME: Verify the underlying types are equivalent! 2110 if (getLangOpts().ObjC1) { 2111 const IdentifierInfo *TypeID = New->getIdentifier(); 2112 switch (TypeID->getLength()) { 2113 default: break; 2114 case 2: 2115 { 2116 if (!TypeID->isStr("id")) 2117 break; 2118 QualType T = New->getUnderlyingType(); 2119 if (!T->isPointerType()) 2120 break; 2121 if (!T->isVoidPointerType()) { 2122 QualType PT = T->getAs<PointerType>()->getPointeeType(); 2123 if (!PT->isStructureType()) 2124 break; 2125 } 2126 Context.setObjCIdRedefinitionType(T); 2127 // Install the built-in type for 'id', ignoring the current definition. 2128 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2129 return; 2130 } 2131 case 5: 2132 if (!TypeID->isStr("Class")) 2133 break; 2134 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2135 // Install the built-in type for 'Class', ignoring the current definition. 2136 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2137 return; 2138 case 3: 2139 if (!TypeID->isStr("SEL")) 2140 break; 2141 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2142 // Install the built-in type for 'SEL', ignoring the current definition. 2143 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2144 return; 2145 } 2146 // Fall through - the typedef name was not a builtin type. 2147 } 2148 2149 // Verify the old decl was also a type. 2150 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2151 if (!Old) { 2152 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2153 << New->getDeclName(); 2154 2155 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2156 if (OldD->getLocation().isValid()) 2157 notePreviousDefinition(OldD, New->getLocation()); 2158 2159 return New->setInvalidDecl(); 2160 } 2161 2162 // If the old declaration is invalid, just give up here. 2163 if (Old->isInvalidDecl()) 2164 return New->setInvalidDecl(); 2165 2166 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2167 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2168 auto *NewTag = New->getAnonDeclWithTypedefName(); 2169 NamedDecl *Hidden = nullptr; 2170 if (OldTag && NewTag && 2171 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2172 !hasVisibleDefinition(OldTag, &Hidden)) { 2173 // There is a definition of this tag, but it is not visible. Use it 2174 // instead of our tag. 2175 New->setTypeForDecl(OldTD->getTypeForDecl()); 2176 if (OldTD->isModed()) 2177 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2178 OldTD->getUnderlyingType()); 2179 else 2180 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2181 2182 // Make the old tag definition visible. 2183 makeMergedDefinitionVisible(Hidden); 2184 2185 // If this was an unscoped enumeration, yank all of its enumerators 2186 // out of the scope. 2187 if (isa<EnumDecl>(NewTag)) { 2188 Scope *EnumScope = getNonFieldDeclScope(S); 2189 for (auto *D : NewTag->decls()) { 2190 auto *ED = cast<EnumConstantDecl>(D); 2191 assert(EnumScope->isDeclScope(ED)); 2192 EnumScope->RemoveDecl(ED); 2193 IdResolver.RemoveDecl(ED); 2194 ED->getLexicalDeclContext()->removeDecl(ED); 2195 } 2196 } 2197 } 2198 } 2199 2200 // If the typedef types are not identical, reject them in all languages and 2201 // with any extensions enabled. 2202 if (isIncompatibleTypedef(Old, New)) 2203 return; 2204 2205 // The types match. Link up the redeclaration chain and merge attributes if 2206 // the old declaration was a typedef. 2207 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2208 New->setPreviousDecl(Typedef); 2209 mergeDeclAttributes(New, Old); 2210 } 2211 2212 if (getLangOpts().MicrosoftExt) 2213 return; 2214 2215 if (getLangOpts().CPlusPlus) { 2216 // C++ [dcl.typedef]p2: 2217 // In a given non-class scope, a typedef specifier can be used to 2218 // redefine the name of any type declared in that scope to refer 2219 // to the type to which it already refers. 2220 if (!isa<CXXRecordDecl>(CurContext)) 2221 return; 2222 2223 // C++0x [dcl.typedef]p4: 2224 // In a given class scope, a typedef specifier can be used to redefine 2225 // any class-name declared in that scope that is not also a typedef-name 2226 // to refer to the type to which it already refers. 2227 // 2228 // This wording came in via DR424, which was a correction to the 2229 // wording in DR56, which accidentally banned code like: 2230 // 2231 // struct S { 2232 // typedef struct A { } A; 2233 // }; 2234 // 2235 // in the C++03 standard. We implement the C++0x semantics, which 2236 // allow the above but disallow 2237 // 2238 // struct S { 2239 // typedef int I; 2240 // typedef int I; 2241 // }; 2242 // 2243 // since that was the intent of DR56. 2244 if (!isa<TypedefNameDecl>(Old)) 2245 return; 2246 2247 Diag(New->getLocation(), diag::err_redefinition) 2248 << New->getDeclName(); 2249 notePreviousDefinition(Old, New->getLocation()); 2250 return New->setInvalidDecl(); 2251 } 2252 2253 // Modules always permit redefinition of typedefs, as does C11. 2254 if (getLangOpts().Modules || getLangOpts().C11) 2255 return; 2256 2257 // If we have a redefinition of a typedef in C, emit a warning. This warning 2258 // is normally mapped to an error, but can be controlled with 2259 // -Wtypedef-redefinition. If either the original or the redefinition is 2260 // in a system header, don't emit this for compatibility with GCC. 2261 if (getDiagnostics().getSuppressSystemWarnings() && 2262 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2263 (Old->isImplicit() || 2264 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2265 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2266 return; 2267 2268 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2269 << New->getDeclName(); 2270 notePreviousDefinition(Old, New->getLocation()); 2271 } 2272 2273 /// DeclhasAttr - returns true if decl Declaration already has the target 2274 /// attribute. 2275 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2276 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2277 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2278 for (const auto *i : D->attrs()) 2279 if (i->getKind() == A->getKind()) { 2280 if (Ann) { 2281 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2282 return true; 2283 continue; 2284 } 2285 // FIXME: Don't hardcode this check 2286 if (OA && isa<OwnershipAttr>(i)) 2287 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2288 return true; 2289 } 2290 2291 return false; 2292 } 2293 2294 static bool isAttributeTargetADefinition(Decl *D) { 2295 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2296 return VD->isThisDeclarationADefinition(); 2297 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2298 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2299 return true; 2300 } 2301 2302 /// Merge alignment attributes from \p Old to \p New, taking into account the 2303 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2304 /// 2305 /// \return \c true if any attributes were added to \p New. 2306 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2307 // Look for alignas attributes on Old, and pick out whichever attribute 2308 // specifies the strictest alignment requirement. 2309 AlignedAttr *OldAlignasAttr = nullptr; 2310 AlignedAttr *OldStrictestAlignAttr = nullptr; 2311 unsigned OldAlign = 0; 2312 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2313 // FIXME: We have no way of representing inherited dependent alignments 2314 // in a case like: 2315 // template<int A, int B> struct alignas(A) X; 2316 // template<int A, int B> struct alignas(B) X {}; 2317 // For now, we just ignore any alignas attributes which are not on the 2318 // definition in such a case. 2319 if (I->isAlignmentDependent()) 2320 return false; 2321 2322 if (I->isAlignas()) 2323 OldAlignasAttr = I; 2324 2325 unsigned Align = I->getAlignment(S.Context); 2326 if (Align > OldAlign) { 2327 OldAlign = Align; 2328 OldStrictestAlignAttr = I; 2329 } 2330 } 2331 2332 // Look for alignas attributes on New. 2333 AlignedAttr *NewAlignasAttr = nullptr; 2334 unsigned NewAlign = 0; 2335 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2336 if (I->isAlignmentDependent()) 2337 return false; 2338 2339 if (I->isAlignas()) 2340 NewAlignasAttr = I; 2341 2342 unsigned Align = I->getAlignment(S.Context); 2343 if (Align > NewAlign) 2344 NewAlign = Align; 2345 } 2346 2347 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2348 // Both declarations have 'alignas' attributes. We require them to match. 2349 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2350 // fall short. (If two declarations both have alignas, they must both match 2351 // every definition, and so must match each other if there is a definition.) 2352 2353 // If either declaration only contains 'alignas(0)' specifiers, then it 2354 // specifies the natural alignment for the type. 2355 if (OldAlign == 0 || NewAlign == 0) { 2356 QualType Ty; 2357 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2358 Ty = VD->getType(); 2359 else 2360 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2361 2362 if (OldAlign == 0) 2363 OldAlign = S.Context.getTypeAlign(Ty); 2364 if (NewAlign == 0) 2365 NewAlign = S.Context.getTypeAlign(Ty); 2366 } 2367 2368 if (OldAlign != NewAlign) { 2369 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2370 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2371 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2372 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2373 } 2374 } 2375 2376 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2377 // C++11 [dcl.align]p6: 2378 // if any declaration of an entity has an alignment-specifier, 2379 // every defining declaration of that entity shall specify an 2380 // equivalent alignment. 2381 // C11 6.7.5/7: 2382 // If the definition of an object does not have an alignment 2383 // specifier, any other declaration of that object shall also 2384 // have no alignment specifier. 2385 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2386 << OldAlignasAttr; 2387 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2388 << OldAlignasAttr; 2389 } 2390 2391 bool AnyAdded = false; 2392 2393 // Ensure we have an attribute representing the strictest alignment. 2394 if (OldAlign > NewAlign) { 2395 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2396 Clone->setInherited(true); 2397 New->addAttr(Clone); 2398 AnyAdded = true; 2399 } 2400 2401 // Ensure we have an alignas attribute if the old declaration had one. 2402 if (OldAlignasAttr && !NewAlignasAttr && 2403 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2404 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2405 Clone->setInherited(true); 2406 New->addAttr(Clone); 2407 AnyAdded = true; 2408 } 2409 2410 return AnyAdded; 2411 } 2412 2413 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2414 const InheritableAttr *Attr, 2415 Sema::AvailabilityMergeKind AMK) { 2416 // This function copies an attribute Attr from a previous declaration to the 2417 // new declaration D if the new declaration doesn't itself have that attribute 2418 // yet or if that attribute allows duplicates. 2419 // If you're adding a new attribute that requires logic different from 2420 // "use explicit attribute on decl if present, else use attribute from 2421 // previous decl", for example if the attribute needs to be consistent 2422 // between redeclarations, you need to call a custom merge function here. 2423 InheritableAttr *NewAttr = nullptr; 2424 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2425 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2426 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2427 AA->isImplicit(), AA->getIntroduced(), 2428 AA->getDeprecated(), 2429 AA->getObsoleted(), AA->getUnavailable(), 2430 AA->getMessage(), AA->getStrict(), 2431 AA->getReplacement(), AMK, 2432 AttrSpellingListIndex); 2433 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2434 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2435 AttrSpellingListIndex); 2436 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2437 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2438 AttrSpellingListIndex); 2439 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2440 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2441 AttrSpellingListIndex); 2442 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2443 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2444 AttrSpellingListIndex); 2445 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2446 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2447 FA->getFormatIdx(), FA->getFirstArg(), 2448 AttrSpellingListIndex); 2449 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2450 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2451 AttrSpellingListIndex); 2452 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2453 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2454 AttrSpellingListIndex, 2455 IA->getSemanticSpelling()); 2456 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2457 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2458 &S.Context.Idents.get(AA->getSpelling()), 2459 AttrSpellingListIndex); 2460 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2461 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2462 isa<CUDAGlobalAttr>(Attr))) { 2463 // CUDA target attributes are part of function signature for 2464 // overloading purposes and must not be merged. 2465 return false; 2466 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2467 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2468 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2469 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2470 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2471 NewAttr = S.mergeInternalLinkageAttr( 2472 D, InternalLinkageA->getRange(), 2473 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2474 AttrSpellingListIndex); 2475 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2476 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2477 &S.Context.Idents.get(CommonA->getSpelling()), 2478 AttrSpellingListIndex); 2479 else if (isa<AlignedAttr>(Attr)) 2480 // AlignedAttrs are handled separately, because we need to handle all 2481 // such attributes on a declaration at the same time. 2482 NewAttr = nullptr; 2483 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2484 (AMK == Sema::AMK_Override || 2485 AMK == Sema::AMK_ProtocolImplementation)) 2486 NewAttr = nullptr; 2487 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2488 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex, 2489 UA->getGuid()); 2490 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2491 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2492 2493 if (NewAttr) { 2494 NewAttr->setInherited(true); 2495 D->addAttr(NewAttr); 2496 if (isa<MSInheritanceAttr>(NewAttr)) 2497 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2498 return true; 2499 } 2500 2501 return false; 2502 } 2503 2504 static const NamedDecl *getDefinition(const Decl *D) { 2505 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2506 return TD->getDefinition(); 2507 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2508 const VarDecl *Def = VD->getDefinition(); 2509 if (Def) 2510 return Def; 2511 return VD->getActingDefinition(); 2512 } 2513 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2514 return FD->getDefinition(); 2515 return nullptr; 2516 } 2517 2518 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2519 for (const auto *Attribute : D->attrs()) 2520 if (Attribute->getKind() == Kind) 2521 return true; 2522 return false; 2523 } 2524 2525 /// checkNewAttributesAfterDef - If we already have a definition, check that 2526 /// there are no new attributes in this declaration. 2527 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2528 if (!New->hasAttrs()) 2529 return; 2530 2531 const NamedDecl *Def = getDefinition(Old); 2532 if (!Def || Def == New) 2533 return; 2534 2535 AttrVec &NewAttributes = New->getAttrs(); 2536 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2537 const Attr *NewAttribute = NewAttributes[I]; 2538 2539 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2540 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2541 Sema::SkipBodyInfo SkipBody; 2542 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2543 2544 // If we're skipping this definition, drop the "alias" attribute. 2545 if (SkipBody.ShouldSkip) { 2546 NewAttributes.erase(NewAttributes.begin() + I); 2547 --E; 2548 continue; 2549 } 2550 } else { 2551 VarDecl *VD = cast<VarDecl>(New); 2552 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2553 VarDecl::TentativeDefinition 2554 ? diag::err_alias_after_tentative 2555 : diag::err_redefinition; 2556 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2557 if (Diag == diag::err_redefinition) 2558 S.notePreviousDefinition(Def, VD->getLocation()); 2559 else 2560 S.Diag(Def->getLocation(), diag::note_previous_definition); 2561 VD->setInvalidDecl(); 2562 } 2563 ++I; 2564 continue; 2565 } 2566 2567 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2568 // Tentative definitions are only interesting for the alias check above. 2569 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2570 ++I; 2571 continue; 2572 } 2573 } 2574 2575 if (hasAttribute(Def, NewAttribute->getKind())) { 2576 ++I; 2577 continue; // regular attr merging will take care of validating this. 2578 } 2579 2580 if (isa<C11NoReturnAttr>(NewAttribute)) { 2581 // C's _Noreturn is allowed to be added to a function after it is defined. 2582 ++I; 2583 continue; 2584 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2585 if (AA->isAlignas()) { 2586 // C++11 [dcl.align]p6: 2587 // if any declaration of an entity has an alignment-specifier, 2588 // every defining declaration of that entity shall specify an 2589 // equivalent alignment. 2590 // C11 6.7.5/7: 2591 // If the definition of an object does not have an alignment 2592 // specifier, any other declaration of that object shall also 2593 // have no alignment specifier. 2594 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2595 << AA; 2596 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2597 << AA; 2598 NewAttributes.erase(NewAttributes.begin() + I); 2599 --E; 2600 continue; 2601 } 2602 } 2603 2604 S.Diag(NewAttribute->getLocation(), 2605 diag::warn_attribute_precede_definition); 2606 S.Diag(Def->getLocation(), diag::note_previous_definition); 2607 NewAttributes.erase(NewAttributes.begin() + I); 2608 --E; 2609 } 2610 } 2611 2612 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2613 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2614 AvailabilityMergeKind AMK) { 2615 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2616 UsedAttr *NewAttr = OldAttr->clone(Context); 2617 NewAttr->setInherited(true); 2618 New->addAttr(NewAttr); 2619 } 2620 2621 if (!Old->hasAttrs() && !New->hasAttrs()) 2622 return; 2623 2624 // Attributes declared post-definition are currently ignored. 2625 checkNewAttributesAfterDef(*this, New, Old); 2626 2627 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2628 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2629 if (OldA->getLabel() != NewA->getLabel()) { 2630 // This redeclaration changes __asm__ label. 2631 Diag(New->getLocation(), diag::err_different_asm_label); 2632 Diag(OldA->getLocation(), diag::note_previous_declaration); 2633 } 2634 } else if (Old->isUsed()) { 2635 // This redeclaration adds an __asm__ label to a declaration that has 2636 // already been ODR-used. 2637 Diag(New->getLocation(), diag::err_late_asm_label_name) 2638 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2639 } 2640 } 2641 2642 // Re-declaration cannot add abi_tag's. 2643 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2644 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2645 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2646 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2647 NewTag) == OldAbiTagAttr->tags_end()) { 2648 Diag(NewAbiTagAttr->getLocation(), 2649 diag::err_new_abi_tag_on_redeclaration) 2650 << NewTag; 2651 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2652 } 2653 } 2654 } else { 2655 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2656 Diag(Old->getLocation(), diag::note_previous_declaration); 2657 } 2658 } 2659 2660 // This redeclaration adds a section attribute. 2661 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2662 if (auto *VD = dyn_cast<VarDecl>(New)) { 2663 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2664 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2665 Diag(Old->getLocation(), diag::note_previous_declaration); 2666 } 2667 } 2668 } 2669 2670 if (!Old->hasAttrs()) 2671 return; 2672 2673 bool foundAny = New->hasAttrs(); 2674 2675 // Ensure that any moving of objects within the allocated map is done before 2676 // we process them. 2677 if (!foundAny) New->setAttrs(AttrVec()); 2678 2679 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2680 // Ignore deprecated/unavailable/availability attributes if requested. 2681 AvailabilityMergeKind LocalAMK = AMK_None; 2682 if (isa<DeprecatedAttr>(I) || 2683 isa<UnavailableAttr>(I) || 2684 isa<AvailabilityAttr>(I)) { 2685 switch (AMK) { 2686 case AMK_None: 2687 continue; 2688 2689 case AMK_Redeclaration: 2690 case AMK_Override: 2691 case AMK_ProtocolImplementation: 2692 LocalAMK = AMK; 2693 break; 2694 } 2695 } 2696 2697 // Already handled. 2698 if (isa<UsedAttr>(I)) 2699 continue; 2700 2701 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2702 foundAny = true; 2703 } 2704 2705 if (mergeAlignedAttrs(*this, New, Old)) 2706 foundAny = true; 2707 2708 if (!foundAny) New->dropAttrs(); 2709 } 2710 2711 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2712 /// to the new one. 2713 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2714 const ParmVarDecl *oldDecl, 2715 Sema &S) { 2716 // C++11 [dcl.attr.depend]p2: 2717 // The first declaration of a function shall specify the 2718 // carries_dependency attribute for its declarator-id if any declaration 2719 // of the function specifies the carries_dependency attribute. 2720 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2721 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2722 S.Diag(CDA->getLocation(), 2723 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2724 // Find the first declaration of the parameter. 2725 // FIXME: Should we build redeclaration chains for function parameters? 2726 const FunctionDecl *FirstFD = 2727 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2728 const ParmVarDecl *FirstVD = 2729 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2730 S.Diag(FirstVD->getLocation(), 2731 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2732 } 2733 2734 if (!oldDecl->hasAttrs()) 2735 return; 2736 2737 bool foundAny = newDecl->hasAttrs(); 2738 2739 // Ensure that any moving of objects within the allocated map is 2740 // done before we process them. 2741 if (!foundAny) newDecl->setAttrs(AttrVec()); 2742 2743 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2744 if (!DeclHasAttr(newDecl, I)) { 2745 InheritableAttr *newAttr = 2746 cast<InheritableParamAttr>(I->clone(S.Context)); 2747 newAttr->setInherited(true); 2748 newDecl->addAttr(newAttr); 2749 foundAny = true; 2750 } 2751 } 2752 2753 if (!foundAny) newDecl->dropAttrs(); 2754 } 2755 2756 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2757 const ParmVarDecl *OldParam, 2758 Sema &S) { 2759 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2760 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2761 if (*Oldnullability != *Newnullability) { 2762 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2763 << DiagNullabilityKind( 2764 *Newnullability, 2765 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2766 != 0)) 2767 << DiagNullabilityKind( 2768 *Oldnullability, 2769 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2770 != 0)); 2771 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2772 } 2773 } else { 2774 QualType NewT = NewParam->getType(); 2775 NewT = S.Context.getAttributedType( 2776 AttributedType::getNullabilityAttrKind(*Oldnullability), 2777 NewT, NewT); 2778 NewParam->setType(NewT); 2779 } 2780 } 2781 } 2782 2783 namespace { 2784 2785 /// Used in MergeFunctionDecl to keep track of function parameters in 2786 /// C. 2787 struct GNUCompatibleParamWarning { 2788 ParmVarDecl *OldParm; 2789 ParmVarDecl *NewParm; 2790 QualType PromotedType; 2791 }; 2792 2793 } // end anonymous namespace 2794 2795 /// getSpecialMember - get the special member enum for a method. 2796 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2797 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2798 if (Ctor->isDefaultConstructor()) 2799 return Sema::CXXDefaultConstructor; 2800 2801 if (Ctor->isCopyConstructor()) 2802 return Sema::CXXCopyConstructor; 2803 2804 if (Ctor->isMoveConstructor()) 2805 return Sema::CXXMoveConstructor; 2806 } else if (isa<CXXDestructorDecl>(MD)) { 2807 return Sema::CXXDestructor; 2808 } else if (MD->isCopyAssignmentOperator()) { 2809 return Sema::CXXCopyAssignment; 2810 } else if (MD->isMoveAssignmentOperator()) { 2811 return Sema::CXXMoveAssignment; 2812 } 2813 2814 return Sema::CXXInvalid; 2815 } 2816 2817 // Determine whether the previous declaration was a definition, implicit 2818 // declaration, or a declaration. 2819 template <typename T> 2820 static std::pair<diag::kind, SourceLocation> 2821 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2822 diag::kind PrevDiag; 2823 SourceLocation OldLocation = Old->getLocation(); 2824 if (Old->isThisDeclarationADefinition()) 2825 PrevDiag = diag::note_previous_definition; 2826 else if (Old->isImplicit()) { 2827 PrevDiag = diag::note_previous_implicit_declaration; 2828 if (OldLocation.isInvalid()) 2829 OldLocation = New->getLocation(); 2830 } else 2831 PrevDiag = diag::note_previous_declaration; 2832 return std::make_pair(PrevDiag, OldLocation); 2833 } 2834 2835 /// canRedefineFunction - checks if a function can be redefined. Currently, 2836 /// only extern inline functions can be redefined, and even then only in 2837 /// GNU89 mode. 2838 static bool canRedefineFunction(const FunctionDecl *FD, 2839 const LangOptions& LangOpts) { 2840 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2841 !LangOpts.CPlusPlus && 2842 FD->isInlineSpecified() && 2843 FD->getStorageClass() == SC_Extern); 2844 } 2845 2846 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2847 const AttributedType *AT = T->getAs<AttributedType>(); 2848 while (AT && !AT->isCallingConv()) 2849 AT = AT->getModifiedType()->getAs<AttributedType>(); 2850 return AT; 2851 } 2852 2853 template <typename T> 2854 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2855 const DeclContext *DC = Old->getDeclContext(); 2856 if (DC->isRecord()) 2857 return false; 2858 2859 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2860 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2861 return true; 2862 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2863 return true; 2864 return false; 2865 } 2866 2867 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2868 static bool isExternC(VarTemplateDecl *) { return false; } 2869 2870 /// \brief Check whether a redeclaration of an entity introduced by a 2871 /// using-declaration is valid, given that we know it's not an overload 2872 /// (nor a hidden tag declaration). 2873 template<typename ExpectedDecl> 2874 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2875 ExpectedDecl *New) { 2876 // C++11 [basic.scope.declarative]p4: 2877 // Given a set of declarations in a single declarative region, each of 2878 // which specifies the same unqualified name, 2879 // -- they shall all refer to the same entity, or all refer to functions 2880 // and function templates; or 2881 // -- exactly one declaration shall declare a class name or enumeration 2882 // name that is not a typedef name and the other declarations shall all 2883 // refer to the same variable or enumerator, or all refer to functions 2884 // and function templates; in this case the class name or enumeration 2885 // name is hidden (3.3.10). 2886 2887 // C++11 [namespace.udecl]p14: 2888 // If a function declaration in namespace scope or block scope has the 2889 // same name and the same parameter-type-list as a function introduced 2890 // by a using-declaration, and the declarations do not declare the same 2891 // function, the program is ill-formed. 2892 2893 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2894 if (Old && 2895 !Old->getDeclContext()->getRedeclContext()->Equals( 2896 New->getDeclContext()->getRedeclContext()) && 2897 !(isExternC(Old) && isExternC(New))) 2898 Old = nullptr; 2899 2900 if (!Old) { 2901 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2902 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2903 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2904 return true; 2905 } 2906 return false; 2907 } 2908 2909 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 2910 const FunctionDecl *B) { 2911 assert(A->getNumParams() == B->getNumParams()); 2912 2913 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 2914 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 2915 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 2916 if (AttrA == AttrB) 2917 return true; 2918 return AttrA && AttrB && AttrA->getType() == AttrB->getType(); 2919 }; 2920 2921 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 2922 } 2923 2924 /// If necessary, adjust the semantic declaration context for a qualified 2925 /// declaration to name the correct inline namespace within the qualifier. 2926 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 2927 DeclaratorDecl *OldD) { 2928 // The only case where we need to update the DeclContext is when 2929 // redeclaration lookup for a qualified name finds a declaration 2930 // in an inline namespace within the context named by the qualifier: 2931 // 2932 // inline namespace N { int f(); } 2933 // int ::f(); // Sema DC needs adjusting from :: to N::. 2934 // 2935 // For unqualified declarations, the semantic context *can* change 2936 // along the redeclaration chain (for local extern declarations, 2937 // extern "C" declarations, and friend declarations in particular). 2938 if (!NewD->getQualifier()) 2939 return; 2940 2941 // NewD is probably already in the right context. 2942 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 2943 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 2944 if (NamedDC->Equals(SemaDC)) 2945 return; 2946 2947 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 2948 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 2949 "unexpected context for redeclaration"); 2950 2951 auto *LexDC = NewD->getLexicalDeclContext(); 2952 auto FixSemaDC = [=](NamedDecl *D) { 2953 if (!D) 2954 return; 2955 D->setDeclContext(SemaDC); 2956 D->setLexicalDeclContext(LexDC); 2957 }; 2958 2959 FixSemaDC(NewD); 2960 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 2961 FixSemaDC(FD->getDescribedFunctionTemplate()); 2962 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 2963 FixSemaDC(VD->getDescribedVarTemplate()); 2964 } 2965 2966 /// MergeFunctionDecl - We just parsed a function 'New' from 2967 /// declarator D which has the same name and scope as a previous 2968 /// declaration 'Old'. Figure out how to resolve this situation, 2969 /// merging decls or emitting diagnostics as appropriate. 2970 /// 2971 /// In C++, New and Old must be declarations that are not 2972 /// overloaded. Use IsOverload to determine whether New and Old are 2973 /// overloaded, and to select the Old declaration that New should be 2974 /// merged with. 2975 /// 2976 /// Returns true if there was an error, false otherwise. 2977 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2978 Scope *S, bool MergeTypeWithOld) { 2979 // Verify the old decl was also a function. 2980 FunctionDecl *Old = OldD->getAsFunction(); 2981 if (!Old) { 2982 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2983 if (New->getFriendObjectKind()) { 2984 Diag(New->getLocation(), diag::err_using_decl_friend); 2985 Diag(Shadow->getTargetDecl()->getLocation(), 2986 diag::note_using_decl_target); 2987 Diag(Shadow->getUsingDecl()->getLocation(), 2988 diag::note_using_decl) << 0; 2989 return true; 2990 } 2991 2992 // Check whether the two declarations might declare the same function. 2993 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2994 return true; 2995 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2996 } else { 2997 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2998 << New->getDeclName(); 2999 notePreviousDefinition(OldD, New->getLocation()); 3000 return true; 3001 } 3002 } 3003 3004 // If the old declaration is invalid, just give up here. 3005 if (Old->isInvalidDecl()) 3006 return true; 3007 3008 // Disallow redeclaration of some builtins. 3009 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3010 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3011 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3012 << Old << Old->getType(); 3013 return true; 3014 } 3015 3016 diag::kind PrevDiag; 3017 SourceLocation OldLocation; 3018 std::tie(PrevDiag, OldLocation) = 3019 getNoteDiagForInvalidRedeclaration(Old, New); 3020 3021 // Don't complain about this if we're in GNU89 mode and the old function 3022 // is an extern inline function. 3023 // Don't complain about specializations. They are not supposed to have 3024 // storage classes. 3025 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3026 New->getStorageClass() == SC_Static && 3027 Old->hasExternalFormalLinkage() && 3028 !New->getTemplateSpecializationInfo() && 3029 !canRedefineFunction(Old, getLangOpts())) { 3030 if (getLangOpts().MicrosoftExt) { 3031 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3032 Diag(OldLocation, PrevDiag); 3033 } else { 3034 Diag(New->getLocation(), diag::err_static_non_static) << New; 3035 Diag(OldLocation, PrevDiag); 3036 return true; 3037 } 3038 } 3039 3040 if (New->hasAttr<InternalLinkageAttr>() && 3041 !Old->hasAttr<InternalLinkageAttr>()) { 3042 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3043 << New->getDeclName(); 3044 notePreviousDefinition(Old, New->getLocation()); 3045 New->dropAttr<InternalLinkageAttr>(); 3046 } 3047 3048 if (CheckRedeclarationModuleOwnership(New, Old)) 3049 return true; 3050 3051 if (!getLangOpts().CPlusPlus) { 3052 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3053 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3054 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3055 << New << OldOvl; 3056 3057 // Try our best to find a decl that actually has the overloadable 3058 // attribute for the note. In most cases (e.g. programs with only one 3059 // broken declaration/definition), this won't matter. 3060 // 3061 // FIXME: We could do this if we juggled some extra state in 3062 // OverloadableAttr, rather than just removing it. 3063 const Decl *DiagOld = Old; 3064 if (OldOvl) { 3065 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3066 const auto *A = D->getAttr<OverloadableAttr>(); 3067 return A && !A->isImplicit(); 3068 }); 3069 // If we've implicitly added *all* of the overloadable attrs to this 3070 // chain, emitting a "previous redecl" note is pointless. 3071 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3072 } 3073 3074 if (DiagOld) 3075 Diag(DiagOld->getLocation(), 3076 diag::note_attribute_overloadable_prev_overload) 3077 << OldOvl; 3078 3079 if (OldOvl) 3080 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3081 else 3082 New->dropAttr<OverloadableAttr>(); 3083 } 3084 } 3085 3086 // If a function is first declared with a calling convention, but is later 3087 // declared or defined without one, all following decls assume the calling 3088 // convention of the first. 3089 // 3090 // It's OK if a function is first declared without a calling convention, 3091 // but is later declared or defined with the default calling convention. 3092 // 3093 // To test if either decl has an explicit calling convention, we look for 3094 // AttributedType sugar nodes on the type as written. If they are missing or 3095 // were canonicalized away, we assume the calling convention was implicit. 3096 // 3097 // Note also that we DO NOT return at this point, because we still have 3098 // other tests to run. 3099 QualType OldQType = Context.getCanonicalType(Old->getType()); 3100 QualType NewQType = Context.getCanonicalType(New->getType()); 3101 const FunctionType *OldType = cast<FunctionType>(OldQType); 3102 const FunctionType *NewType = cast<FunctionType>(NewQType); 3103 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3104 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3105 bool RequiresAdjustment = false; 3106 3107 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3108 FunctionDecl *First = Old->getFirstDecl(); 3109 const FunctionType *FT = 3110 First->getType().getCanonicalType()->castAs<FunctionType>(); 3111 FunctionType::ExtInfo FI = FT->getExtInfo(); 3112 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3113 if (!NewCCExplicit) { 3114 // Inherit the CC from the previous declaration if it was specified 3115 // there but not here. 3116 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3117 RequiresAdjustment = true; 3118 } else { 3119 // Calling conventions aren't compatible, so complain. 3120 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3121 Diag(New->getLocation(), diag::err_cconv_change) 3122 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3123 << !FirstCCExplicit 3124 << (!FirstCCExplicit ? "" : 3125 FunctionType::getNameForCallConv(FI.getCC())); 3126 3127 // Put the note on the first decl, since it is the one that matters. 3128 Diag(First->getLocation(), diag::note_previous_declaration); 3129 return true; 3130 } 3131 } 3132 3133 // FIXME: diagnose the other way around? 3134 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3135 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3136 RequiresAdjustment = true; 3137 } 3138 3139 // Merge regparm attribute. 3140 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3141 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3142 if (NewTypeInfo.getHasRegParm()) { 3143 Diag(New->getLocation(), diag::err_regparm_mismatch) 3144 << NewType->getRegParmType() 3145 << OldType->getRegParmType(); 3146 Diag(OldLocation, diag::note_previous_declaration); 3147 return true; 3148 } 3149 3150 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3151 RequiresAdjustment = true; 3152 } 3153 3154 // Merge ns_returns_retained attribute. 3155 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3156 if (NewTypeInfo.getProducesResult()) { 3157 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3158 << "'ns_returns_retained'"; 3159 Diag(OldLocation, diag::note_previous_declaration); 3160 return true; 3161 } 3162 3163 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3164 RequiresAdjustment = true; 3165 } 3166 3167 if (OldTypeInfo.getNoCallerSavedRegs() != 3168 NewTypeInfo.getNoCallerSavedRegs()) { 3169 if (NewTypeInfo.getNoCallerSavedRegs()) { 3170 AnyX86NoCallerSavedRegistersAttr *Attr = 3171 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3172 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3173 Diag(OldLocation, diag::note_previous_declaration); 3174 return true; 3175 } 3176 3177 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3178 RequiresAdjustment = true; 3179 } 3180 3181 if (RequiresAdjustment) { 3182 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3183 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3184 New->setType(QualType(AdjustedType, 0)); 3185 NewQType = Context.getCanonicalType(New->getType()); 3186 NewType = cast<FunctionType>(NewQType); 3187 } 3188 3189 // If this redeclaration makes the function inline, we may need to add it to 3190 // UndefinedButUsed. 3191 if (!Old->isInlined() && New->isInlined() && 3192 !New->hasAttr<GNUInlineAttr>() && 3193 !getLangOpts().GNUInline && 3194 Old->isUsed(false) && 3195 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3196 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3197 SourceLocation())); 3198 3199 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3200 // about it. 3201 if (New->hasAttr<GNUInlineAttr>() && 3202 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3203 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3204 } 3205 3206 // If pass_object_size params don't match up perfectly, this isn't a valid 3207 // redeclaration. 3208 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3209 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3210 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3211 << New->getDeclName(); 3212 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3213 return true; 3214 } 3215 3216 if (getLangOpts().CPlusPlus) { 3217 // C++1z [over.load]p2 3218 // Certain function declarations cannot be overloaded: 3219 // -- Function declarations that differ only in the return type, 3220 // the exception specification, or both cannot be overloaded. 3221 3222 // Check the exception specifications match. This may recompute the type of 3223 // both Old and New if it resolved exception specifications, so grab the 3224 // types again after this. Because this updates the type, we do this before 3225 // any of the other checks below, which may update the "de facto" NewQType 3226 // but do not necessarily update the type of New. 3227 if (CheckEquivalentExceptionSpec(Old, New)) 3228 return true; 3229 OldQType = Context.getCanonicalType(Old->getType()); 3230 NewQType = Context.getCanonicalType(New->getType()); 3231 3232 // Go back to the type source info to compare the declared return types, 3233 // per C++1y [dcl.type.auto]p13: 3234 // Redeclarations or specializations of a function or function template 3235 // with a declared return type that uses a placeholder type shall also 3236 // use that placeholder, not a deduced type. 3237 QualType OldDeclaredReturnType = 3238 (Old->getTypeSourceInfo() 3239 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3240 : OldType)->getReturnType(); 3241 QualType NewDeclaredReturnType = 3242 (New->getTypeSourceInfo() 3243 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 3244 : NewType)->getReturnType(); 3245 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3246 !((NewQType->isDependentType() || OldQType->isDependentType()) && 3247 New->isLocalExternDecl())) { 3248 QualType ResQT; 3249 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3250 OldDeclaredReturnType->isObjCObjectPointerType()) 3251 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3252 if (ResQT.isNull()) { 3253 if (New->isCXXClassMember() && New->isOutOfLine()) 3254 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3255 << New << New->getReturnTypeSourceRange(); 3256 else 3257 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3258 << New->getReturnTypeSourceRange(); 3259 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3260 << Old->getReturnTypeSourceRange(); 3261 return true; 3262 } 3263 else 3264 NewQType = ResQT; 3265 } 3266 3267 QualType OldReturnType = OldType->getReturnType(); 3268 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3269 if (OldReturnType != NewReturnType) { 3270 // If this function has a deduced return type and has already been 3271 // defined, copy the deduced value from the old declaration. 3272 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3273 if (OldAT && OldAT->isDeduced()) { 3274 New->setType( 3275 SubstAutoType(New->getType(), 3276 OldAT->isDependentType() ? Context.DependentTy 3277 : OldAT->getDeducedType())); 3278 NewQType = Context.getCanonicalType( 3279 SubstAutoType(NewQType, 3280 OldAT->isDependentType() ? Context.DependentTy 3281 : OldAT->getDeducedType())); 3282 } 3283 } 3284 3285 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3286 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3287 if (OldMethod && NewMethod) { 3288 // Preserve triviality. 3289 NewMethod->setTrivial(OldMethod->isTrivial()); 3290 3291 // MSVC allows explicit template specialization at class scope: 3292 // 2 CXXMethodDecls referring to the same function will be injected. 3293 // We don't want a redeclaration error. 3294 bool IsClassScopeExplicitSpecialization = 3295 OldMethod->isFunctionTemplateSpecialization() && 3296 NewMethod->isFunctionTemplateSpecialization(); 3297 bool isFriend = NewMethod->getFriendObjectKind(); 3298 3299 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3300 !IsClassScopeExplicitSpecialization) { 3301 // -- Member function declarations with the same name and the 3302 // same parameter types cannot be overloaded if any of them 3303 // is a static member function declaration. 3304 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3305 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3306 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3307 return true; 3308 } 3309 3310 // C++ [class.mem]p1: 3311 // [...] A member shall not be declared twice in the 3312 // member-specification, except that a nested class or member 3313 // class template can be declared and then later defined. 3314 if (!inTemplateInstantiation()) { 3315 unsigned NewDiag; 3316 if (isa<CXXConstructorDecl>(OldMethod)) 3317 NewDiag = diag::err_constructor_redeclared; 3318 else if (isa<CXXDestructorDecl>(NewMethod)) 3319 NewDiag = diag::err_destructor_redeclared; 3320 else if (isa<CXXConversionDecl>(NewMethod)) 3321 NewDiag = diag::err_conv_function_redeclared; 3322 else 3323 NewDiag = diag::err_member_redeclared; 3324 3325 Diag(New->getLocation(), NewDiag); 3326 } else { 3327 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3328 << New << New->getType(); 3329 } 3330 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3331 return true; 3332 3333 // Complain if this is an explicit declaration of a special 3334 // member that was initially declared implicitly. 3335 // 3336 // As an exception, it's okay to befriend such methods in order 3337 // to permit the implicit constructor/destructor/operator calls. 3338 } else if (OldMethod->isImplicit()) { 3339 if (isFriend) { 3340 NewMethod->setImplicit(); 3341 } else { 3342 Diag(NewMethod->getLocation(), 3343 diag::err_definition_of_implicitly_declared_member) 3344 << New << getSpecialMember(OldMethod); 3345 return true; 3346 } 3347 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3348 Diag(NewMethod->getLocation(), 3349 diag::err_definition_of_explicitly_defaulted_member) 3350 << getSpecialMember(OldMethod); 3351 return true; 3352 } 3353 } 3354 3355 // C++11 [dcl.attr.noreturn]p1: 3356 // The first declaration of a function shall specify the noreturn 3357 // attribute if any declaration of that function specifies the noreturn 3358 // attribute. 3359 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3360 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3361 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3362 Diag(Old->getFirstDecl()->getLocation(), 3363 diag::note_noreturn_missing_first_decl); 3364 } 3365 3366 // C++11 [dcl.attr.depend]p2: 3367 // The first declaration of a function shall specify the 3368 // carries_dependency attribute for its declarator-id if any declaration 3369 // of the function specifies the carries_dependency attribute. 3370 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3371 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3372 Diag(CDA->getLocation(), 3373 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3374 Diag(Old->getFirstDecl()->getLocation(), 3375 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3376 } 3377 3378 // (C++98 8.3.5p3): 3379 // All declarations for a function shall agree exactly in both the 3380 // return type and the parameter-type-list. 3381 // We also want to respect all the extended bits except noreturn. 3382 3383 // noreturn should now match unless the old type info didn't have it. 3384 QualType OldQTypeForComparison = OldQType; 3385 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3386 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3387 const FunctionType *OldTypeForComparison 3388 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3389 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3390 assert(OldQTypeForComparison.isCanonical()); 3391 } 3392 3393 if (haveIncompatibleLanguageLinkages(Old, New)) { 3394 // As a special case, retain the language linkage from previous 3395 // declarations of a friend function as an extension. 3396 // 3397 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3398 // and is useful because there's otherwise no way to specify language 3399 // linkage within class scope. 3400 // 3401 // Check cautiously as the friend object kind isn't yet complete. 3402 if (New->getFriendObjectKind() != Decl::FOK_None) { 3403 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3404 Diag(OldLocation, PrevDiag); 3405 } else { 3406 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3407 Diag(OldLocation, PrevDiag); 3408 return true; 3409 } 3410 } 3411 3412 if (OldQTypeForComparison == NewQType) 3413 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3414 3415 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 3416 New->isLocalExternDecl()) { 3417 // It's OK if we couldn't merge types for a local function declaraton 3418 // if either the old or new type is dependent. We'll merge the types 3419 // when we instantiate the function. 3420 return false; 3421 } 3422 3423 // Fall through for conflicting redeclarations and redefinitions. 3424 } 3425 3426 // C: Function types need to be compatible, not identical. This handles 3427 // duplicate function decls like "void f(int); void f(enum X);" properly. 3428 if (!getLangOpts().CPlusPlus && 3429 Context.typesAreCompatible(OldQType, NewQType)) { 3430 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3431 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3432 const FunctionProtoType *OldProto = nullptr; 3433 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3434 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3435 // The old declaration provided a function prototype, but the 3436 // new declaration does not. Merge in the prototype. 3437 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3438 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3439 NewQType = 3440 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3441 OldProto->getExtProtoInfo()); 3442 New->setType(NewQType); 3443 New->setHasInheritedPrototype(); 3444 3445 // Synthesize parameters with the same types. 3446 SmallVector<ParmVarDecl*, 16> Params; 3447 for (const auto &ParamType : OldProto->param_types()) { 3448 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3449 SourceLocation(), nullptr, 3450 ParamType, /*TInfo=*/nullptr, 3451 SC_None, nullptr); 3452 Param->setScopeInfo(0, Params.size()); 3453 Param->setImplicit(); 3454 Params.push_back(Param); 3455 } 3456 3457 New->setParams(Params); 3458 } 3459 3460 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3461 } 3462 3463 // GNU C permits a K&R definition to follow a prototype declaration 3464 // if the declared types of the parameters in the K&R definition 3465 // match the types in the prototype declaration, even when the 3466 // promoted types of the parameters from the K&R definition differ 3467 // from the types in the prototype. GCC then keeps the types from 3468 // the prototype. 3469 // 3470 // If a variadic prototype is followed by a non-variadic K&R definition, 3471 // the K&R definition becomes variadic. This is sort of an edge case, but 3472 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3473 // C99 6.9.1p8. 3474 if (!getLangOpts().CPlusPlus && 3475 Old->hasPrototype() && !New->hasPrototype() && 3476 New->getType()->getAs<FunctionProtoType>() && 3477 Old->getNumParams() == New->getNumParams()) { 3478 SmallVector<QualType, 16> ArgTypes; 3479 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3480 const FunctionProtoType *OldProto 3481 = Old->getType()->getAs<FunctionProtoType>(); 3482 const FunctionProtoType *NewProto 3483 = New->getType()->getAs<FunctionProtoType>(); 3484 3485 // Determine whether this is the GNU C extension. 3486 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3487 NewProto->getReturnType()); 3488 bool LooseCompatible = !MergedReturn.isNull(); 3489 for (unsigned Idx = 0, End = Old->getNumParams(); 3490 LooseCompatible && Idx != End; ++Idx) { 3491 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3492 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3493 if (Context.typesAreCompatible(OldParm->getType(), 3494 NewProto->getParamType(Idx))) { 3495 ArgTypes.push_back(NewParm->getType()); 3496 } else if (Context.typesAreCompatible(OldParm->getType(), 3497 NewParm->getType(), 3498 /*CompareUnqualified=*/true)) { 3499 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3500 NewProto->getParamType(Idx) }; 3501 Warnings.push_back(Warn); 3502 ArgTypes.push_back(NewParm->getType()); 3503 } else 3504 LooseCompatible = false; 3505 } 3506 3507 if (LooseCompatible) { 3508 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3509 Diag(Warnings[Warn].NewParm->getLocation(), 3510 diag::ext_param_promoted_not_compatible_with_prototype) 3511 << Warnings[Warn].PromotedType 3512 << Warnings[Warn].OldParm->getType(); 3513 if (Warnings[Warn].OldParm->getLocation().isValid()) 3514 Diag(Warnings[Warn].OldParm->getLocation(), 3515 diag::note_previous_declaration); 3516 } 3517 3518 if (MergeTypeWithOld) 3519 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3520 OldProto->getExtProtoInfo())); 3521 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3522 } 3523 3524 // Fall through to diagnose conflicting types. 3525 } 3526 3527 // A function that has already been declared has been redeclared or 3528 // defined with a different type; show an appropriate diagnostic. 3529 3530 // If the previous declaration was an implicitly-generated builtin 3531 // declaration, then at the very least we should use a specialized note. 3532 unsigned BuiltinID; 3533 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3534 // If it's actually a library-defined builtin function like 'malloc' 3535 // or 'printf', just warn about the incompatible redeclaration. 3536 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3537 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3538 Diag(OldLocation, diag::note_previous_builtin_declaration) 3539 << Old << Old->getType(); 3540 3541 // If this is a global redeclaration, just forget hereafter 3542 // about the "builtin-ness" of the function. 3543 // 3544 // Doing this for local extern declarations is problematic. If 3545 // the builtin declaration remains visible, a second invalid 3546 // local declaration will produce a hard error; if it doesn't 3547 // remain visible, a single bogus local redeclaration (which is 3548 // actually only a warning) could break all the downstream code. 3549 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3550 New->getIdentifier()->revertBuiltin(); 3551 3552 return false; 3553 } 3554 3555 PrevDiag = diag::note_previous_builtin_declaration; 3556 } 3557 3558 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3559 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3560 return true; 3561 } 3562 3563 /// \brief Completes the merge of two function declarations that are 3564 /// known to be compatible. 3565 /// 3566 /// This routine handles the merging of attributes and other 3567 /// properties of function declarations from the old declaration to 3568 /// the new declaration, once we know that New is in fact a 3569 /// redeclaration of Old. 3570 /// 3571 /// \returns false 3572 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3573 Scope *S, bool MergeTypeWithOld) { 3574 // Merge the attributes 3575 mergeDeclAttributes(New, Old); 3576 3577 // Merge "pure" flag. 3578 if (Old->isPure()) 3579 New->setPure(); 3580 3581 // Merge "used" flag. 3582 if (Old->getMostRecentDecl()->isUsed(false)) 3583 New->setIsUsed(); 3584 3585 // Merge attributes from the parameters. These can mismatch with K&R 3586 // declarations. 3587 if (New->getNumParams() == Old->getNumParams()) 3588 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3589 ParmVarDecl *NewParam = New->getParamDecl(i); 3590 ParmVarDecl *OldParam = Old->getParamDecl(i); 3591 mergeParamDeclAttributes(NewParam, OldParam, *this); 3592 mergeParamDeclTypes(NewParam, OldParam, *this); 3593 } 3594 3595 if (getLangOpts().CPlusPlus) 3596 return MergeCXXFunctionDecl(New, Old, S); 3597 3598 // Merge the function types so the we get the composite types for the return 3599 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3600 // was visible. 3601 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3602 if (!Merged.isNull() && MergeTypeWithOld) 3603 New->setType(Merged); 3604 3605 return false; 3606 } 3607 3608 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3609 ObjCMethodDecl *oldMethod) { 3610 // Merge the attributes, including deprecated/unavailable 3611 AvailabilityMergeKind MergeKind = 3612 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3613 ? AMK_ProtocolImplementation 3614 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3615 : AMK_Override; 3616 3617 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3618 3619 // Merge attributes from the parameters. 3620 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3621 oe = oldMethod->param_end(); 3622 for (ObjCMethodDecl::param_iterator 3623 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3624 ni != ne && oi != oe; ++ni, ++oi) 3625 mergeParamDeclAttributes(*ni, *oi, *this); 3626 3627 CheckObjCMethodOverride(newMethod, oldMethod); 3628 } 3629 3630 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3631 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3632 3633 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3634 ? diag::err_redefinition_different_type 3635 : diag::err_redeclaration_different_type) 3636 << New->getDeclName() << New->getType() << Old->getType(); 3637 3638 diag::kind PrevDiag; 3639 SourceLocation OldLocation; 3640 std::tie(PrevDiag, OldLocation) 3641 = getNoteDiagForInvalidRedeclaration(Old, New); 3642 S.Diag(OldLocation, PrevDiag); 3643 New->setInvalidDecl(); 3644 } 3645 3646 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3647 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3648 /// emitting diagnostics as appropriate. 3649 /// 3650 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3651 /// to here in AddInitializerToDecl. We can't check them before the initializer 3652 /// is attached. 3653 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3654 bool MergeTypeWithOld) { 3655 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3656 return; 3657 3658 QualType MergedT; 3659 if (getLangOpts().CPlusPlus) { 3660 if (New->getType()->isUndeducedType()) { 3661 // We don't know what the new type is until the initializer is attached. 3662 return; 3663 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3664 // These could still be something that needs exception specs checked. 3665 return MergeVarDeclExceptionSpecs(New, Old); 3666 } 3667 // C++ [basic.link]p10: 3668 // [...] the types specified by all declarations referring to a given 3669 // object or function shall be identical, except that declarations for an 3670 // array object can specify array types that differ by the presence or 3671 // absence of a major array bound (8.3.4). 3672 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3673 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3674 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3675 3676 // We are merging a variable declaration New into Old. If it has an array 3677 // bound, and that bound differs from Old's bound, we should diagnose the 3678 // mismatch. 3679 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3680 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3681 PrevVD = PrevVD->getPreviousDecl()) { 3682 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3683 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3684 continue; 3685 3686 if (!Context.hasSameType(NewArray, PrevVDTy)) 3687 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3688 } 3689 } 3690 3691 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3692 if (Context.hasSameType(OldArray->getElementType(), 3693 NewArray->getElementType())) 3694 MergedT = New->getType(); 3695 } 3696 // FIXME: Check visibility. New is hidden but has a complete type. If New 3697 // has no array bound, it should not inherit one from Old, if Old is not 3698 // visible. 3699 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3700 if (Context.hasSameType(OldArray->getElementType(), 3701 NewArray->getElementType())) 3702 MergedT = Old->getType(); 3703 } 3704 } 3705 else if (New->getType()->isObjCObjectPointerType() && 3706 Old->getType()->isObjCObjectPointerType()) { 3707 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3708 Old->getType()); 3709 } 3710 } else { 3711 // C 6.2.7p2: 3712 // All declarations that refer to the same object or function shall have 3713 // compatible type. 3714 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3715 } 3716 if (MergedT.isNull()) { 3717 // It's OK if we couldn't merge types if either type is dependent, for a 3718 // block-scope variable. In other cases (static data members of class 3719 // templates, variable templates, ...), we require the types to be 3720 // equivalent. 3721 // FIXME: The C++ standard doesn't say anything about this. 3722 if ((New->getType()->isDependentType() || 3723 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3724 // If the old type was dependent, we can't merge with it, so the new type 3725 // becomes dependent for now. We'll reproduce the original type when we 3726 // instantiate the TypeSourceInfo for the variable. 3727 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3728 New->setType(Context.DependentTy); 3729 return; 3730 } 3731 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3732 } 3733 3734 // Don't actually update the type on the new declaration if the old 3735 // declaration was an extern declaration in a different scope. 3736 if (MergeTypeWithOld) 3737 New->setType(MergedT); 3738 } 3739 3740 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3741 LookupResult &Previous) { 3742 // C11 6.2.7p4: 3743 // For an identifier with internal or external linkage declared 3744 // in a scope in which a prior declaration of that identifier is 3745 // visible, if the prior declaration specifies internal or 3746 // external linkage, the type of the identifier at the later 3747 // declaration becomes the composite type. 3748 // 3749 // If the variable isn't visible, we do not merge with its type. 3750 if (Previous.isShadowed()) 3751 return false; 3752 3753 if (S.getLangOpts().CPlusPlus) { 3754 // C++11 [dcl.array]p3: 3755 // If there is a preceding declaration of the entity in the same 3756 // scope in which the bound was specified, an omitted array bound 3757 // is taken to be the same as in that earlier declaration. 3758 return NewVD->isPreviousDeclInSameBlockScope() || 3759 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3760 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3761 } else { 3762 // If the old declaration was function-local, don't merge with its 3763 // type unless we're in the same function. 3764 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3765 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3766 } 3767 } 3768 3769 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3770 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3771 /// situation, merging decls or emitting diagnostics as appropriate. 3772 /// 3773 /// Tentative definition rules (C99 6.9.2p2) are checked by 3774 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3775 /// definitions here, since the initializer hasn't been attached. 3776 /// 3777 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3778 // If the new decl is already invalid, don't do any other checking. 3779 if (New->isInvalidDecl()) 3780 return; 3781 3782 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3783 return; 3784 3785 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3786 3787 // Verify the old decl was also a variable or variable template. 3788 VarDecl *Old = nullptr; 3789 VarTemplateDecl *OldTemplate = nullptr; 3790 if (Previous.isSingleResult()) { 3791 if (NewTemplate) { 3792 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3793 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3794 3795 if (auto *Shadow = 3796 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3797 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3798 return New->setInvalidDecl(); 3799 } else { 3800 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3801 3802 if (auto *Shadow = 3803 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3804 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3805 return New->setInvalidDecl(); 3806 } 3807 } 3808 if (!Old) { 3809 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3810 << New->getDeclName(); 3811 notePreviousDefinition(Previous.getRepresentativeDecl(), 3812 New->getLocation()); 3813 return New->setInvalidDecl(); 3814 } 3815 3816 // Ensure the template parameters are compatible. 3817 if (NewTemplate && 3818 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3819 OldTemplate->getTemplateParameters(), 3820 /*Complain=*/true, TPL_TemplateMatch)) 3821 return New->setInvalidDecl(); 3822 3823 // C++ [class.mem]p1: 3824 // A member shall not be declared twice in the member-specification [...] 3825 // 3826 // Here, we need only consider static data members. 3827 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3828 Diag(New->getLocation(), diag::err_duplicate_member) 3829 << New->getIdentifier(); 3830 Diag(Old->getLocation(), diag::note_previous_declaration); 3831 New->setInvalidDecl(); 3832 } 3833 3834 mergeDeclAttributes(New, Old); 3835 // Warn if an already-declared variable is made a weak_import in a subsequent 3836 // declaration 3837 if (New->hasAttr<WeakImportAttr>() && 3838 Old->getStorageClass() == SC_None && 3839 !Old->hasAttr<WeakImportAttr>()) { 3840 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3841 notePreviousDefinition(Old, New->getLocation()); 3842 // Remove weak_import attribute on new declaration. 3843 New->dropAttr<WeakImportAttr>(); 3844 } 3845 3846 if (New->hasAttr<InternalLinkageAttr>() && 3847 !Old->hasAttr<InternalLinkageAttr>()) { 3848 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3849 << New->getDeclName(); 3850 notePreviousDefinition(Old, New->getLocation()); 3851 New->dropAttr<InternalLinkageAttr>(); 3852 } 3853 3854 // Merge the types. 3855 VarDecl *MostRecent = Old->getMostRecentDecl(); 3856 if (MostRecent != Old) { 3857 MergeVarDeclTypes(New, MostRecent, 3858 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3859 if (New->isInvalidDecl()) 3860 return; 3861 } 3862 3863 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3864 if (New->isInvalidDecl()) 3865 return; 3866 3867 diag::kind PrevDiag; 3868 SourceLocation OldLocation; 3869 std::tie(PrevDiag, OldLocation) = 3870 getNoteDiagForInvalidRedeclaration(Old, New); 3871 3872 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3873 if (New->getStorageClass() == SC_Static && 3874 !New->isStaticDataMember() && 3875 Old->hasExternalFormalLinkage()) { 3876 if (getLangOpts().MicrosoftExt) { 3877 Diag(New->getLocation(), diag::ext_static_non_static) 3878 << New->getDeclName(); 3879 Diag(OldLocation, PrevDiag); 3880 } else { 3881 Diag(New->getLocation(), diag::err_static_non_static) 3882 << New->getDeclName(); 3883 Diag(OldLocation, PrevDiag); 3884 return New->setInvalidDecl(); 3885 } 3886 } 3887 // C99 6.2.2p4: 3888 // For an identifier declared with the storage-class specifier 3889 // extern in a scope in which a prior declaration of that 3890 // identifier is visible,23) if the prior declaration specifies 3891 // internal or external linkage, the linkage of the identifier at 3892 // the later declaration is the same as the linkage specified at 3893 // the prior declaration. If no prior declaration is visible, or 3894 // if the prior declaration specifies no linkage, then the 3895 // identifier has external linkage. 3896 if (New->hasExternalStorage() && Old->hasLinkage()) 3897 /* Okay */; 3898 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3899 !New->isStaticDataMember() && 3900 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3901 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3902 Diag(OldLocation, PrevDiag); 3903 return New->setInvalidDecl(); 3904 } 3905 3906 // Check if extern is followed by non-extern and vice-versa. 3907 if (New->hasExternalStorage() && 3908 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3909 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3910 Diag(OldLocation, PrevDiag); 3911 return New->setInvalidDecl(); 3912 } 3913 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3914 !New->hasExternalStorage()) { 3915 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3916 Diag(OldLocation, PrevDiag); 3917 return New->setInvalidDecl(); 3918 } 3919 3920 if (CheckRedeclarationModuleOwnership(New, Old)) 3921 return; 3922 3923 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3924 3925 // FIXME: The test for external storage here seems wrong? We still 3926 // need to check for mismatches. 3927 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3928 // Don't complain about out-of-line definitions of static members. 3929 !(Old->getLexicalDeclContext()->isRecord() && 3930 !New->getLexicalDeclContext()->isRecord())) { 3931 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3932 Diag(OldLocation, PrevDiag); 3933 return New->setInvalidDecl(); 3934 } 3935 3936 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 3937 if (VarDecl *Def = Old->getDefinition()) { 3938 // C++1z [dcl.fcn.spec]p4: 3939 // If the definition of a variable appears in a translation unit before 3940 // its first declaration as inline, the program is ill-formed. 3941 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 3942 Diag(Def->getLocation(), diag::note_previous_definition); 3943 } 3944 } 3945 3946 // If this redeclaration makes the variable inline, we may need to add it to 3947 // UndefinedButUsed. 3948 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 3949 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 3950 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3951 SourceLocation())); 3952 3953 if (New->getTLSKind() != Old->getTLSKind()) { 3954 if (!Old->getTLSKind()) { 3955 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3956 Diag(OldLocation, PrevDiag); 3957 } else if (!New->getTLSKind()) { 3958 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3959 Diag(OldLocation, PrevDiag); 3960 } else { 3961 // Do not allow redeclaration to change the variable between requiring 3962 // static and dynamic initialization. 3963 // FIXME: GCC allows this, but uses the TLS keyword on the first 3964 // declaration to determine the kind. Do we need to be compatible here? 3965 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3966 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3967 Diag(OldLocation, PrevDiag); 3968 } 3969 } 3970 3971 // C++ doesn't have tentative definitions, so go right ahead and check here. 3972 if (getLangOpts().CPlusPlus && 3973 New->isThisDeclarationADefinition() == VarDecl::Definition) { 3974 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 3975 Old->getCanonicalDecl()->isConstexpr()) { 3976 // This definition won't be a definition any more once it's been merged. 3977 Diag(New->getLocation(), 3978 diag::warn_deprecated_redundant_constexpr_static_def); 3979 } else if (VarDecl *Def = Old->getDefinition()) { 3980 if (checkVarDeclRedefinition(Def, New)) 3981 return; 3982 } 3983 } 3984 3985 if (haveIncompatibleLanguageLinkages(Old, New)) { 3986 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3987 Diag(OldLocation, PrevDiag); 3988 New->setInvalidDecl(); 3989 return; 3990 } 3991 3992 // Merge "used" flag. 3993 if (Old->getMostRecentDecl()->isUsed(false)) 3994 New->setIsUsed(); 3995 3996 // Keep a chain of previous declarations. 3997 New->setPreviousDecl(Old); 3998 if (NewTemplate) 3999 NewTemplate->setPreviousDecl(OldTemplate); 4000 adjustDeclContextForDeclaratorDecl(New, Old); 4001 4002 // Inherit access appropriately. 4003 New->setAccess(Old->getAccess()); 4004 if (NewTemplate) 4005 NewTemplate->setAccess(New->getAccess()); 4006 4007 if (Old->isInline()) 4008 New->setImplicitlyInline(); 4009 } 4010 4011 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4012 SourceManager &SrcMgr = getSourceManager(); 4013 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4014 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4015 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4016 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4017 auto &HSI = PP.getHeaderSearchInfo(); 4018 StringRef HdrFilename = 4019 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4020 4021 auto noteFromModuleOrInclude = [&](Module *Mod, 4022 SourceLocation IncLoc) -> bool { 4023 // Redefinition errors with modules are common with non modular mapped 4024 // headers, example: a non-modular header H in module A that also gets 4025 // included directly in a TU. Pointing twice to the same header/definition 4026 // is confusing, try to get better diagnostics when modules is on. 4027 if (IncLoc.isValid()) { 4028 if (Mod) { 4029 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4030 << HdrFilename.str() << Mod->getFullModuleName(); 4031 if (!Mod->DefinitionLoc.isInvalid()) 4032 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4033 << Mod->getFullModuleName(); 4034 } else { 4035 Diag(IncLoc, diag::note_redefinition_include_same_file) 4036 << HdrFilename.str(); 4037 } 4038 return true; 4039 } 4040 4041 return false; 4042 }; 4043 4044 // Is it the same file and same offset? Provide more information on why 4045 // this leads to a redefinition error. 4046 bool EmittedDiag = false; 4047 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4048 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4049 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4050 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4051 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4052 4053 // If the header has no guards, emit a note suggesting one. 4054 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4055 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4056 4057 if (EmittedDiag) 4058 return; 4059 } 4060 4061 // Redefinition coming from different files or couldn't do better above. 4062 if (Old->getLocation().isValid()) 4063 Diag(Old->getLocation(), diag::note_previous_definition); 4064 } 4065 4066 /// We've just determined that \p Old and \p New both appear to be definitions 4067 /// of the same variable. Either diagnose or fix the problem. 4068 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4069 if (!hasVisibleDefinition(Old) && 4070 (New->getFormalLinkage() == InternalLinkage || 4071 New->isInline() || 4072 New->getDescribedVarTemplate() || 4073 New->getNumTemplateParameterLists() || 4074 New->getDeclContext()->isDependentContext())) { 4075 // The previous definition is hidden, and multiple definitions are 4076 // permitted (in separate TUs). Demote this to a declaration. 4077 New->demoteThisDefinitionToDeclaration(); 4078 4079 // Make the canonical definition visible. 4080 if (auto *OldTD = Old->getDescribedVarTemplate()) 4081 makeMergedDefinitionVisible(OldTD); 4082 makeMergedDefinitionVisible(Old); 4083 return false; 4084 } else { 4085 Diag(New->getLocation(), diag::err_redefinition) << New; 4086 notePreviousDefinition(Old, New->getLocation()); 4087 New->setInvalidDecl(); 4088 return true; 4089 } 4090 } 4091 4092 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4093 /// no declarator (e.g. "struct foo;") is parsed. 4094 Decl * 4095 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4096 RecordDecl *&AnonRecord) { 4097 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4098 AnonRecord); 4099 } 4100 4101 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4102 // disambiguate entities defined in different scopes. 4103 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4104 // compatibility. 4105 // We will pick our mangling number depending on which version of MSVC is being 4106 // targeted. 4107 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4108 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4109 ? S->getMSCurManglingNumber() 4110 : S->getMSLastManglingNumber(); 4111 } 4112 4113 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4114 if (!Context.getLangOpts().CPlusPlus) 4115 return; 4116 4117 if (isa<CXXRecordDecl>(Tag->getParent())) { 4118 // If this tag is the direct child of a class, number it if 4119 // it is anonymous. 4120 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4121 return; 4122 MangleNumberingContext &MCtx = 4123 Context.getManglingNumberContext(Tag->getParent()); 4124 Context.setManglingNumber( 4125 Tag, MCtx.getManglingNumber( 4126 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4127 return; 4128 } 4129 4130 // If this tag isn't a direct child of a class, number it if it is local. 4131 Decl *ManglingContextDecl; 4132 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4133 Tag->getDeclContext(), ManglingContextDecl)) { 4134 Context.setManglingNumber( 4135 Tag, MCtx->getManglingNumber( 4136 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4137 } 4138 } 4139 4140 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4141 TypedefNameDecl *NewTD) { 4142 if (TagFromDeclSpec->isInvalidDecl()) 4143 return; 4144 4145 // Do nothing if the tag already has a name for linkage purposes. 4146 if (TagFromDeclSpec->hasNameForLinkage()) 4147 return; 4148 4149 // A well-formed anonymous tag must always be a TUK_Definition. 4150 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4151 4152 // The type must match the tag exactly; no qualifiers allowed. 4153 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4154 Context.getTagDeclType(TagFromDeclSpec))) { 4155 if (getLangOpts().CPlusPlus) 4156 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4157 return; 4158 } 4159 4160 // If we've already computed linkage for the anonymous tag, then 4161 // adding a typedef name for the anonymous decl can change that 4162 // linkage, which might be a serious problem. Diagnose this as 4163 // unsupported and ignore the typedef name. TODO: we should 4164 // pursue this as a language defect and establish a formal rule 4165 // for how to handle it. 4166 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 4167 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 4168 4169 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 4170 tagLoc = getLocForEndOfToken(tagLoc); 4171 4172 llvm::SmallString<40> textToInsert; 4173 textToInsert += ' '; 4174 textToInsert += NewTD->getIdentifier()->getName(); 4175 Diag(tagLoc, diag::note_typedef_changes_linkage) 4176 << FixItHint::CreateInsertion(tagLoc, textToInsert); 4177 return; 4178 } 4179 4180 // Otherwise, set this is the anon-decl typedef for the tag. 4181 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4182 } 4183 4184 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4185 switch (T) { 4186 case DeclSpec::TST_class: 4187 return 0; 4188 case DeclSpec::TST_struct: 4189 return 1; 4190 case DeclSpec::TST_interface: 4191 return 2; 4192 case DeclSpec::TST_union: 4193 return 3; 4194 case DeclSpec::TST_enum: 4195 return 4; 4196 default: 4197 llvm_unreachable("unexpected type specifier"); 4198 } 4199 } 4200 4201 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4202 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4203 /// parameters to cope with template friend declarations. 4204 Decl * 4205 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4206 MultiTemplateParamsArg TemplateParams, 4207 bool IsExplicitInstantiation, 4208 RecordDecl *&AnonRecord) { 4209 Decl *TagD = nullptr; 4210 TagDecl *Tag = nullptr; 4211 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4212 DS.getTypeSpecType() == DeclSpec::TST_struct || 4213 DS.getTypeSpecType() == DeclSpec::TST_interface || 4214 DS.getTypeSpecType() == DeclSpec::TST_union || 4215 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4216 TagD = DS.getRepAsDecl(); 4217 4218 if (!TagD) // We probably had an error 4219 return nullptr; 4220 4221 // Note that the above type specs guarantee that the 4222 // type rep is a Decl, whereas in many of the others 4223 // it's a Type. 4224 if (isa<TagDecl>(TagD)) 4225 Tag = cast<TagDecl>(TagD); 4226 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4227 Tag = CTD->getTemplatedDecl(); 4228 } 4229 4230 if (Tag) { 4231 handleTagNumbering(Tag, S); 4232 Tag->setFreeStanding(); 4233 if (Tag->isInvalidDecl()) 4234 return Tag; 4235 } 4236 4237 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4238 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4239 // or incomplete types shall not be restrict-qualified." 4240 if (TypeQuals & DeclSpec::TQ_restrict) 4241 Diag(DS.getRestrictSpecLoc(), 4242 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4243 << DS.getSourceRange(); 4244 } 4245 4246 if (DS.isInlineSpecified()) 4247 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4248 << getLangOpts().CPlusPlus17; 4249 4250 if (DS.isConstexprSpecified()) { 4251 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4252 // and definitions of functions and variables. 4253 if (Tag) 4254 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4255 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 4256 else 4257 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 4258 // Don't emit warnings after this error. 4259 return TagD; 4260 } 4261 4262 DiagnoseFunctionSpecifiers(DS); 4263 4264 if (DS.isFriendSpecified()) { 4265 // If we're dealing with a decl but not a TagDecl, assume that 4266 // whatever routines created it handled the friendship aspect. 4267 if (TagD && !Tag) 4268 return nullptr; 4269 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4270 } 4271 4272 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4273 bool IsExplicitSpecialization = 4274 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4275 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4276 !IsExplicitInstantiation && !IsExplicitSpecialization && 4277 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4278 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4279 // nested-name-specifier unless it is an explicit instantiation 4280 // or an explicit specialization. 4281 // 4282 // FIXME: We allow class template partial specializations here too, per the 4283 // obvious intent of DR1819. 4284 // 4285 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4286 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4287 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4288 return nullptr; 4289 } 4290 4291 // Track whether this decl-specifier declares anything. 4292 bool DeclaresAnything = true; 4293 4294 // Handle anonymous struct definitions. 4295 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4296 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4297 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4298 if (getLangOpts().CPlusPlus || 4299 Record->getDeclContext()->isRecord()) { 4300 // If CurContext is a DeclContext that can contain statements, 4301 // RecursiveASTVisitor won't visit the decls that 4302 // BuildAnonymousStructOrUnion() will put into CurContext. 4303 // Also store them here so that they can be part of the 4304 // DeclStmt that gets created in this case. 4305 // FIXME: Also return the IndirectFieldDecls created by 4306 // BuildAnonymousStructOr union, for the same reason? 4307 if (CurContext->isFunctionOrMethod()) 4308 AnonRecord = Record; 4309 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4310 Context.getPrintingPolicy()); 4311 } 4312 4313 DeclaresAnything = false; 4314 } 4315 } 4316 4317 // C11 6.7.2.1p2: 4318 // A struct-declaration that does not declare an anonymous structure or 4319 // anonymous union shall contain a struct-declarator-list. 4320 // 4321 // This rule also existed in C89 and C99; the grammar for struct-declaration 4322 // did not permit a struct-declaration without a struct-declarator-list. 4323 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4324 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4325 // Check for Microsoft C extension: anonymous struct/union member. 4326 // Handle 2 kinds of anonymous struct/union: 4327 // struct STRUCT; 4328 // union UNION; 4329 // and 4330 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4331 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4332 if ((Tag && Tag->getDeclName()) || 4333 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4334 RecordDecl *Record = nullptr; 4335 if (Tag) 4336 Record = dyn_cast<RecordDecl>(Tag); 4337 else if (const RecordType *RT = 4338 DS.getRepAsType().get()->getAsStructureType()) 4339 Record = RT->getDecl(); 4340 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4341 Record = UT->getDecl(); 4342 4343 if (Record && getLangOpts().MicrosoftExt) { 4344 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 4345 << Record->isUnion() << DS.getSourceRange(); 4346 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4347 } 4348 4349 DeclaresAnything = false; 4350 } 4351 } 4352 4353 // Skip all the checks below if we have a type error. 4354 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4355 (TagD && TagD->isInvalidDecl())) 4356 return TagD; 4357 4358 if (getLangOpts().CPlusPlus && 4359 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4360 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4361 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4362 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4363 DeclaresAnything = false; 4364 4365 if (!DS.isMissingDeclaratorOk()) { 4366 // Customize diagnostic for a typedef missing a name. 4367 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4368 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 4369 << DS.getSourceRange(); 4370 else 4371 DeclaresAnything = false; 4372 } 4373 4374 if (DS.isModulePrivateSpecified() && 4375 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4376 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4377 << Tag->getTagKind() 4378 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4379 4380 ActOnDocumentableDecl(TagD); 4381 4382 // C 6.7/2: 4383 // A declaration [...] shall declare at least a declarator [...], a tag, 4384 // or the members of an enumeration. 4385 // C++ [dcl.dcl]p3: 4386 // [If there are no declarators], and except for the declaration of an 4387 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4388 // names into the program, or shall redeclare a name introduced by a 4389 // previous declaration. 4390 if (!DeclaresAnything) { 4391 // In C, we allow this as a (popular) extension / bug. Don't bother 4392 // producing further diagnostics for redundant qualifiers after this. 4393 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 4394 return TagD; 4395 } 4396 4397 // C++ [dcl.stc]p1: 4398 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4399 // init-declarator-list of the declaration shall not be empty. 4400 // C++ [dcl.fct.spec]p1: 4401 // If a cv-qualifier appears in a decl-specifier-seq, the 4402 // init-declarator-list of the declaration shall not be empty. 4403 // 4404 // Spurious qualifiers here appear to be valid in C. 4405 unsigned DiagID = diag::warn_standalone_specifier; 4406 if (getLangOpts().CPlusPlus) 4407 DiagID = diag::ext_standalone_specifier; 4408 4409 // Note that a linkage-specification sets a storage class, but 4410 // 'extern "C" struct foo;' is actually valid and not theoretically 4411 // useless. 4412 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4413 if (SCS == DeclSpec::SCS_mutable) 4414 // Since mutable is not a viable storage class specifier in C, there is 4415 // no reason to treat it as an extension. Instead, diagnose as an error. 4416 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4417 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4418 Diag(DS.getStorageClassSpecLoc(), DiagID) 4419 << DeclSpec::getSpecifierName(SCS); 4420 } 4421 4422 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4423 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4424 << DeclSpec::getSpecifierName(TSCS); 4425 if (DS.getTypeQualifiers()) { 4426 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4427 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4428 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4429 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4430 // Restrict is covered above. 4431 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4432 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4433 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4434 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4435 } 4436 4437 // Warn about ignored type attributes, for example: 4438 // __attribute__((aligned)) struct A; 4439 // Attributes should be placed after tag to apply to type declaration. 4440 if (!DS.getAttributes().empty()) { 4441 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4442 if (TypeSpecType == DeclSpec::TST_class || 4443 TypeSpecType == DeclSpec::TST_struct || 4444 TypeSpecType == DeclSpec::TST_interface || 4445 TypeSpecType == DeclSpec::TST_union || 4446 TypeSpecType == DeclSpec::TST_enum) { 4447 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 4448 attrs = attrs->getNext()) 4449 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 4450 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 4451 } 4452 } 4453 4454 return TagD; 4455 } 4456 4457 /// We are trying to inject an anonymous member into the given scope; 4458 /// check if there's an existing declaration that can't be overloaded. 4459 /// 4460 /// \return true if this is a forbidden redeclaration 4461 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4462 Scope *S, 4463 DeclContext *Owner, 4464 DeclarationName Name, 4465 SourceLocation NameLoc, 4466 bool IsUnion) { 4467 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4468 Sema::ForVisibleRedeclaration); 4469 if (!SemaRef.LookupName(R, S)) return false; 4470 4471 // Pick a representative declaration. 4472 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4473 assert(PrevDecl && "Expected a non-null Decl"); 4474 4475 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4476 return false; 4477 4478 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4479 << IsUnion << Name; 4480 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4481 4482 return true; 4483 } 4484 4485 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4486 /// anonymous struct or union AnonRecord into the owning context Owner 4487 /// and scope S. This routine will be invoked just after we realize 4488 /// that an unnamed union or struct is actually an anonymous union or 4489 /// struct, e.g., 4490 /// 4491 /// @code 4492 /// union { 4493 /// int i; 4494 /// float f; 4495 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4496 /// // f into the surrounding scope.x 4497 /// @endcode 4498 /// 4499 /// This routine is recursive, injecting the names of nested anonymous 4500 /// structs/unions into the owning context and scope as well. 4501 static bool 4502 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4503 RecordDecl *AnonRecord, AccessSpecifier AS, 4504 SmallVectorImpl<NamedDecl *> &Chaining) { 4505 bool Invalid = false; 4506 4507 // Look every FieldDecl and IndirectFieldDecl with a name. 4508 for (auto *D : AnonRecord->decls()) { 4509 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4510 cast<NamedDecl>(D)->getDeclName()) { 4511 ValueDecl *VD = cast<ValueDecl>(D); 4512 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4513 VD->getLocation(), 4514 AnonRecord->isUnion())) { 4515 // C++ [class.union]p2: 4516 // The names of the members of an anonymous union shall be 4517 // distinct from the names of any other entity in the 4518 // scope in which the anonymous union is declared. 4519 Invalid = true; 4520 } else { 4521 // C++ [class.union]p2: 4522 // For the purpose of name lookup, after the anonymous union 4523 // definition, the members of the anonymous union are 4524 // considered to have been defined in the scope in which the 4525 // anonymous union is declared. 4526 unsigned OldChainingSize = Chaining.size(); 4527 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4528 Chaining.append(IF->chain_begin(), IF->chain_end()); 4529 else 4530 Chaining.push_back(VD); 4531 4532 assert(Chaining.size() >= 2); 4533 NamedDecl **NamedChain = 4534 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4535 for (unsigned i = 0; i < Chaining.size(); i++) 4536 NamedChain[i] = Chaining[i]; 4537 4538 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4539 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4540 VD->getType(), {NamedChain, Chaining.size()}); 4541 4542 for (const auto *Attr : VD->attrs()) 4543 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4544 4545 IndirectField->setAccess(AS); 4546 IndirectField->setImplicit(); 4547 SemaRef.PushOnScopeChains(IndirectField, S); 4548 4549 // That includes picking up the appropriate access specifier. 4550 if (AS != AS_none) IndirectField->setAccess(AS); 4551 4552 Chaining.resize(OldChainingSize); 4553 } 4554 } 4555 } 4556 4557 return Invalid; 4558 } 4559 4560 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4561 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4562 /// illegal input values are mapped to SC_None. 4563 static StorageClass 4564 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4565 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4566 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4567 "Parser allowed 'typedef' as storage class VarDecl."); 4568 switch (StorageClassSpec) { 4569 case DeclSpec::SCS_unspecified: return SC_None; 4570 case DeclSpec::SCS_extern: 4571 if (DS.isExternInLinkageSpec()) 4572 return SC_None; 4573 return SC_Extern; 4574 case DeclSpec::SCS_static: return SC_Static; 4575 case DeclSpec::SCS_auto: return SC_Auto; 4576 case DeclSpec::SCS_register: return SC_Register; 4577 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4578 // Illegal SCSs map to None: error reporting is up to the caller. 4579 case DeclSpec::SCS_mutable: // Fall through. 4580 case DeclSpec::SCS_typedef: return SC_None; 4581 } 4582 llvm_unreachable("unknown storage class specifier"); 4583 } 4584 4585 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4586 assert(Record->hasInClassInitializer()); 4587 4588 for (const auto *I : Record->decls()) { 4589 const auto *FD = dyn_cast<FieldDecl>(I); 4590 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4591 FD = IFD->getAnonField(); 4592 if (FD && FD->hasInClassInitializer()) 4593 return FD->getLocation(); 4594 } 4595 4596 llvm_unreachable("couldn't find in-class initializer"); 4597 } 4598 4599 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4600 SourceLocation DefaultInitLoc) { 4601 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4602 return; 4603 4604 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4605 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4606 } 4607 4608 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4609 CXXRecordDecl *AnonUnion) { 4610 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4611 return; 4612 4613 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4614 } 4615 4616 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4617 /// anonymous structure or union. Anonymous unions are a C++ feature 4618 /// (C++ [class.union]) and a C11 feature; anonymous structures 4619 /// are a C11 feature and GNU C++ extension. 4620 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4621 AccessSpecifier AS, 4622 RecordDecl *Record, 4623 const PrintingPolicy &Policy) { 4624 DeclContext *Owner = Record->getDeclContext(); 4625 4626 // Diagnose whether this anonymous struct/union is an extension. 4627 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4628 Diag(Record->getLocation(), diag::ext_anonymous_union); 4629 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4630 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4631 else if (!Record->isUnion() && !getLangOpts().C11) 4632 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4633 4634 // C and C++ require different kinds of checks for anonymous 4635 // structs/unions. 4636 bool Invalid = false; 4637 if (getLangOpts().CPlusPlus) { 4638 const char *PrevSpec = nullptr; 4639 unsigned DiagID; 4640 if (Record->isUnion()) { 4641 // C++ [class.union]p6: 4642 // Anonymous unions declared in a named namespace or in the 4643 // global namespace shall be declared static. 4644 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4645 (isa<TranslationUnitDecl>(Owner) || 4646 (isa<NamespaceDecl>(Owner) && 4647 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4648 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4649 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4650 4651 // Recover by adding 'static'. 4652 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4653 PrevSpec, DiagID, Policy); 4654 } 4655 // C++ [class.union]p6: 4656 // A storage class is not allowed in a declaration of an 4657 // anonymous union in a class scope. 4658 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4659 isa<RecordDecl>(Owner)) { 4660 Diag(DS.getStorageClassSpecLoc(), 4661 diag::err_anonymous_union_with_storage_spec) 4662 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4663 4664 // Recover by removing the storage specifier. 4665 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4666 SourceLocation(), 4667 PrevSpec, DiagID, Context.getPrintingPolicy()); 4668 } 4669 } 4670 4671 // Ignore const/volatile/restrict qualifiers. 4672 if (DS.getTypeQualifiers()) { 4673 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4674 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4675 << Record->isUnion() << "const" 4676 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4677 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4678 Diag(DS.getVolatileSpecLoc(), 4679 diag::ext_anonymous_struct_union_qualified) 4680 << Record->isUnion() << "volatile" 4681 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4682 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4683 Diag(DS.getRestrictSpecLoc(), 4684 diag::ext_anonymous_struct_union_qualified) 4685 << Record->isUnion() << "restrict" 4686 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4687 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4688 Diag(DS.getAtomicSpecLoc(), 4689 diag::ext_anonymous_struct_union_qualified) 4690 << Record->isUnion() << "_Atomic" 4691 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4692 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4693 Diag(DS.getUnalignedSpecLoc(), 4694 diag::ext_anonymous_struct_union_qualified) 4695 << Record->isUnion() << "__unaligned" 4696 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 4697 4698 DS.ClearTypeQualifiers(); 4699 } 4700 4701 // C++ [class.union]p2: 4702 // The member-specification of an anonymous union shall only 4703 // define non-static data members. [Note: nested types and 4704 // functions cannot be declared within an anonymous union. ] 4705 for (auto *Mem : Record->decls()) { 4706 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4707 // C++ [class.union]p3: 4708 // An anonymous union shall not have private or protected 4709 // members (clause 11). 4710 assert(FD->getAccess() != AS_none); 4711 if (FD->getAccess() != AS_public) { 4712 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4713 << Record->isUnion() << (FD->getAccess() == AS_protected); 4714 Invalid = true; 4715 } 4716 4717 // C++ [class.union]p1 4718 // An object of a class with a non-trivial constructor, a non-trivial 4719 // copy constructor, a non-trivial destructor, or a non-trivial copy 4720 // assignment operator cannot be a member of a union, nor can an 4721 // array of such objects. 4722 if (CheckNontrivialField(FD)) 4723 Invalid = true; 4724 } else if (Mem->isImplicit()) { 4725 // Any implicit members are fine. 4726 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4727 // This is a type that showed up in an 4728 // elaborated-type-specifier inside the anonymous struct or 4729 // union, but which actually declares a type outside of the 4730 // anonymous struct or union. It's okay. 4731 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4732 if (!MemRecord->isAnonymousStructOrUnion() && 4733 MemRecord->getDeclName()) { 4734 // Visual C++ allows type definition in anonymous struct or union. 4735 if (getLangOpts().MicrosoftExt) 4736 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4737 << Record->isUnion(); 4738 else { 4739 // This is a nested type declaration. 4740 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4741 << Record->isUnion(); 4742 Invalid = true; 4743 } 4744 } else { 4745 // This is an anonymous type definition within another anonymous type. 4746 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4747 // not part of standard C++. 4748 Diag(MemRecord->getLocation(), 4749 diag::ext_anonymous_record_with_anonymous_type) 4750 << Record->isUnion(); 4751 } 4752 } else if (isa<AccessSpecDecl>(Mem)) { 4753 // Any access specifier is fine. 4754 } else if (isa<StaticAssertDecl>(Mem)) { 4755 // In C++1z, static_assert declarations are also fine. 4756 } else { 4757 // We have something that isn't a non-static data 4758 // member. Complain about it. 4759 unsigned DK = diag::err_anonymous_record_bad_member; 4760 if (isa<TypeDecl>(Mem)) 4761 DK = diag::err_anonymous_record_with_type; 4762 else if (isa<FunctionDecl>(Mem)) 4763 DK = diag::err_anonymous_record_with_function; 4764 else if (isa<VarDecl>(Mem)) 4765 DK = diag::err_anonymous_record_with_static; 4766 4767 // Visual C++ allows type definition in anonymous struct or union. 4768 if (getLangOpts().MicrosoftExt && 4769 DK == diag::err_anonymous_record_with_type) 4770 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4771 << Record->isUnion(); 4772 else { 4773 Diag(Mem->getLocation(), DK) << Record->isUnion(); 4774 Invalid = true; 4775 } 4776 } 4777 } 4778 4779 // C++11 [class.union]p8 (DR1460): 4780 // At most one variant member of a union may have a 4781 // brace-or-equal-initializer. 4782 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4783 Owner->isRecord()) 4784 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4785 cast<CXXRecordDecl>(Record)); 4786 } 4787 4788 if (!Record->isUnion() && !Owner->isRecord()) { 4789 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4790 << getLangOpts().CPlusPlus; 4791 Invalid = true; 4792 } 4793 4794 // Mock up a declarator. 4795 Declarator Dc(DS, DeclaratorContext::MemberContext); 4796 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4797 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4798 4799 // Create a declaration for this anonymous struct/union. 4800 NamedDecl *Anon = nullptr; 4801 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4802 Anon = FieldDecl::Create(Context, OwningClass, 4803 DS.getLocStart(), 4804 Record->getLocation(), 4805 /*IdentifierInfo=*/nullptr, 4806 Context.getTypeDeclType(Record), 4807 TInfo, 4808 /*BitWidth=*/nullptr, /*Mutable=*/false, 4809 /*InitStyle=*/ICIS_NoInit); 4810 Anon->setAccess(AS); 4811 if (getLangOpts().CPlusPlus) 4812 FieldCollector->Add(cast<FieldDecl>(Anon)); 4813 } else { 4814 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4815 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4816 if (SCSpec == DeclSpec::SCS_mutable) { 4817 // mutable can only appear on non-static class members, so it's always 4818 // an error here 4819 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4820 Invalid = true; 4821 SC = SC_None; 4822 } 4823 4824 Anon = VarDecl::Create(Context, Owner, 4825 DS.getLocStart(), 4826 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4827 Context.getTypeDeclType(Record), 4828 TInfo, SC); 4829 4830 // Default-initialize the implicit variable. This initialization will be 4831 // trivial in almost all cases, except if a union member has an in-class 4832 // initializer: 4833 // union { int n = 0; }; 4834 ActOnUninitializedDecl(Anon); 4835 } 4836 Anon->setImplicit(); 4837 4838 // Mark this as an anonymous struct/union type. 4839 Record->setAnonymousStructOrUnion(true); 4840 4841 // Add the anonymous struct/union object to the current 4842 // context. We'll be referencing this object when we refer to one of 4843 // its members. 4844 Owner->addDecl(Anon); 4845 4846 // Inject the members of the anonymous struct/union into the owning 4847 // context and into the identifier resolver chain for name lookup 4848 // purposes. 4849 SmallVector<NamedDecl*, 2> Chain; 4850 Chain.push_back(Anon); 4851 4852 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 4853 Invalid = true; 4854 4855 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4856 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4857 Decl *ManglingContextDecl; 4858 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4859 NewVD->getDeclContext(), ManglingContextDecl)) { 4860 Context.setManglingNumber( 4861 NewVD, MCtx->getManglingNumber( 4862 NewVD, getMSManglingNumber(getLangOpts(), S))); 4863 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4864 } 4865 } 4866 } 4867 4868 if (Invalid) 4869 Anon->setInvalidDecl(); 4870 4871 return Anon; 4872 } 4873 4874 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4875 /// Microsoft C anonymous structure. 4876 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4877 /// Example: 4878 /// 4879 /// struct A { int a; }; 4880 /// struct B { struct A; int b; }; 4881 /// 4882 /// void foo() { 4883 /// B var; 4884 /// var.a = 3; 4885 /// } 4886 /// 4887 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4888 RecordDecl *Record) { 4889 assert(Record && "expected a record!"); 4890 4891 // Mock up a declarator. 4892 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 4893 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4894 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4895 4896 auto *ParentDecl = cast<RecordDecl>(CurContext); 4897 QualType RecTy = Context.getTypeDeclType(Record); 4898 4899 // Create a declaration for this anonymous struct. 4900 NamedDecl *Anon = FieldDecl::Create(Context, 4901 ParentDecl, 4902 DS.getLocStart(), 4903 DS.getLocStart(), 4904 /*IdentifierInfo=*/nullptr, 4905 RecTy, 4906 TInfo, 4907 /*BitWidth=*/nullptr, /*Mutable=*/false, 4908 /*InitStyle=*/ICIS_NoInit); 4909 Anon->setImplicit(); 4910 4911 // Add the anonymous struct object to the current context. 4912 CurContext->addDecl(Anon); 4913 4914 // Inject the members of the anonymous struct into the current 4915 // context and into the identifier resolver chain for name lookup 4916 // purposes. 4917 SmallVector<NamedDecl*, 2> Chain; 4918 Chain.push_back(Anon); 4919 4920 RecordDecl *RecordDef = Record->getDefinition(); 4921 if (RequireCompleteType(Anon->getLocation(), RecTy, 4922 diag::err_field_incomplete) || 4923 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4924 AS_none, Chain)) { 4925 Anon->setInvalidDecl(); 4926 ParentDecl->setInvalidDecl(); 4927 } 4928 4929 return Anon; 4930 } 4931 4932 /// GetNameForDeclarator - Determine the full declaration name for the 4933 /// given Declarator. 4934 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4935 return GetNameFromUnqualifiedId(D.getName()); 4936 } 4937 4938 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4939 DeclarationNameInfo 4940 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4941 DeclarationNameInfo NameInfo; 4942 NameInfo.setLoc(Name.StartLocation); 4943 4944 switch (Name.getKind()) { 4945 4946 case UnqualifiedIdKind::IK_ImplicitSelfParam: 4947 case UnqualifiedIdKind::IK_Identifier: 4948 NameInfo.setName(Name.Identifier); 4949 NameInfo.setLoc(Name.StartLocation); 4950 return NameInfo; 4951 4952 case UnqualifiedIdKind::IK_DeductionGuideName: { 4953 // C++ [temp.deduct.guide]p3: 4954 // The simple-template-id shall name a class template specialization. 4955 // The template-name shall be the same identifier as the template-name 4956 // of the simple-template-id. 4957 // These together intend to imply that the template-name shall name a 4958 // class template. 4959 // FIXME: template<typename T> struct X {}; 4960 // template<typename T> using Y = X<T>; 4961 // Y(int) -> Y<int>; 4962 // satisfies these rules but does not name a class template. 4963 TemplateName TN = Name.TemplateName.get().get(); 4964 auto *Template = TN.getAsTemplateDecl(); 4965 if (!Template || !isa<ClassTemplateDecl>(Template)) { 4966 Diag(Name.StartLocation, 4967 diag::err_deduction_guide_name_not_class_template) 4968 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 4969 if (Template) 4970 Diag(Template->getLocation(), diag::note_template_decl_here); 4971 return DeclarationNameInfo(); 4972 } 4973 4974 NameInfo.setName( 4975 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 4976 NameInfo.setLoc(Name.StartLocation); 4977 return NameInfo; 4978 } 4979 4980 case UnqualifiedIdKind::IK_OperatorFunctionId: 4981 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4982 Name.OperatorFunctionId.Operator)); 4983 NameInfo.setLoc(Name.StartLocation); 4984 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4985 = Name.OperatorFunctionId.SymbolLocations[0]; 4986 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4987 = Name.EndLocation.getRawEncoding(); 4988 return NameInfo; 4989 4990 case UnqualifiedIdKind::IK_LiteralOperatorId: 4991 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4992 Name.Identifier)); 4993 NameInfo.setLoc(Name.StartLocation); 4994 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4995 return NameInfo; 4996 4997 case UnqualifiedIdKind::IK_ConversionFunctionId: { 4998 TypeSourceInfo *TInfo; 4999 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5000 if (Ty.isNull()) 5001 return DeclarationNameInfo(); 5002 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5003 Context.getCanonicalType(Ty))); 5004 NameInfo.setLoc(Name.StartLocation); 5005 NameInfo.setNamedTypeInfo(TInfo); 5006 return NameInfo; 5007 } 5008 5009 case UnqualifiedIdKind::IK_ConstructorName: { 5010 TypeSourceInfo *TInfo; 5011 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5012 if (Ty.isNull()) 5013 return DeclarationNameInfo(); 5014 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5015 Context.getCanonicalType(Ty))); 5016 NameInfo.setLoc(Name.StartLocation); 5017 NameInfo.setNamedTypeInfo(TInfo); 5018 return NameInfo; 5019 } 5020 5021 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5022 // In well-formed code, we can only have a constructor 5023 // template-id that refers to the current context, so go there 5024 // to find the actual type being constructed. 5025 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5026 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5027 return DeclarationNameInfo(); 5028 5029 // Determine the type of the class being constructed. 5030 QualType CurClassType = Context.getTypeDeclType(CurClass); 5031 5032 // FIXME: Check two things: that the template-id names the same type as 5033 // CurClassType, and that the template-id does not occur when the name 5034 // was qualified. 5035 5036 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5037 Context.getCanonicalType(CurClassType))); 5038 NameInfo.setLoc(Name.StartLocation); 5039 // FIXME: should we retrieve TypeSourceInfo? 5040 NameInfo.setNamedTypeInfo(nullptr); 5041 return NameInfo; 5042 } 5043 5044 case UnqualifiedIdKind::IK_DestructorName: { 5045 TypeSourceInfo *TInfo; 5046 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5047 if (Ty.isNull()) 5048 return DeclarationNameInfo(); 5049 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5050 Context.getCanonicalType(Ty))); 5051 NameInfo.setLoc(Name.StartLocation); 5052 NameInfo.setNamedTypeInfo(TInfo); 5053 return NameInfo; 5054 } 5055 5056 case UnqualifiedIdKind::IK_TemplateId: { 5057 TemplateName TName = Name.TemplateId->Template.get(); 5058 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5059 return Context.getNameForTemplate(TName, TNameLoc); 5060 } 5061 5062 } // switch (Name.getKind()) 5063 5064 llvm_unreachable("Unknown name kind"); 5065 } 5066 5067 static QualType getCoreType(QualType Ty) { 5068 do { 5069 if (Ty->isPointerType() || Ty->isReferenceType()) 5070 Ty = Ty->getPointeeType(); 5071 else if (Ty->isArrayType()) 5072 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5073 else 5074 return Ty.withoutLocalFastQualifiers(); 5075 } while (true); 5076 } 5077 5078 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5079 /// and Definition have "nearly" matching parameters. This heuristic is 5080 /// used to improve diagnostics in the case where an out-of-line function 5081 /// definition doesn't match any declaration within the class or namespace. 5082 /// Also sets Params to the list of indices to the parameters that differ 5083 /// between the declaration and the definition. If hasSimilarParameters 5084 /// returns true and Params is empty, then all of the parameters match. 5085 static bool hasSimilarParameters(ASTContext &Context, 5086 FunctionDecl *Declaration, 5087 FunctionDecl *Definition, 5088 SmallVectorImpl<unsigned> &Params) { 5089 Params.clear(); 5090 if (Declaration->param_size() != Definition->param_size()) 5091 return false; 5092 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5093 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5094 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5095 5096 // The parameter types are identical 5097 if (Context.hasSameType(DefParamTy, DeclParamTy)) 5098 continue; 5099 5100 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5101 QualType DefParamBaseTy = getCoreType(DefParamTy); 5102 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5103 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5104 5105 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5106 (DeclTyName && DeclTyName == DefTyName)) 5107 Params.push_back(Idx); 5108 else // The two parameters aren't even close 5109 return false; 5110 } 5111 5112 return true; 5113 } 5114 5115 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5116 /// declarator needs to be rebuilt in the current instantiation. 5117 /// Any bits of declarator which appear before the name are valid for 5118 /// consideration here. That's specifically the type in the decl spec 5119 /// and the base type in any member-pointer chunks. 5120 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5121 DeclarationName Name) { 5122 // The types we specifically need to rebuild are: 5123 // - typenames, typeofs, and decltypes 5124 // - types which will become injected class names 5125 // Of course, we also need to rebuild any type referencing such a 5126 // type. It's safest to just say "dependent", but we call out a 5127 // few cases here. 5128 5129 DeclSpec &DS = D.getMutableDeclSpec(); 5130 switch (DS.getTypeSpecType()) { 5131 case DeclSpec::TST_typename: 5132 case DeclSpec::TST_typeofType: 5133 case DeclSpec::TST_underlyingType: 5134 case DeclSpec::TST_atomic: { 5135 // Grab the type from the parser. 5136 TypeSourceInfo *TSI = nullptr; 5137 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5138 if (T.isNull() || !T->isDependentType()) break; 5139 5140 // Make sure there's a type source info. This isn't really much 5141 // of a waste; most dependent types should have type source info 5142 // attached already. 5143 if (!TSI) 5144 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5145 5146 // Rebuild the type in the current instantiation. 5147 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5148 if (!TSI) return true; 5149 5150 // Store the new type back in the decl spec. 5151 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5152 DS.UpdateTypeRep(LocType); 5153 break; 5154 } 5155 5156 case DeclSpec::TST_decltype: 5157 case DeclSpec::TST_typeofExpr: { 5158 Expr *E = DS.getRepAsExpr(); 5159 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5160 if (Result.isInvalid()) return true; 5161 DS.UpdateExprRep(Result.get()); 5162 break; 5163 } 5164 5165 default: 5166 // Nothing to do for these decl specs. 5167 break; 5168 } 5169 5170 // It doesn't matter what order we do this in. 5171 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5172 DeclaratorChunk &Chunk = D.getTypeObject(I); 5173 5174 // The only type information in the declarator which can come 5175 // before the declaration name is the base type of a member 5176 // pointer. 5177 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5178 continue; 5179 5180 // Rebuild the scope specifier in-place. 5181 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5182 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5183 return true; 5184 } 5185 5186 return false; 5187 } 5188 5189 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5190 D.setFunctionDefinitionKind(FDK_Declaration); 5191 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5192 5193 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5194 Dcl && Dcl->getDeclContext()->isFileContext()) 5195 Dcl->setTopLevelDeclInObjCContainer(); 5196 5197 if (getLangOpts().OpenCL) 5198 setCurrentOpenCLExtensionForDecl(Dcl); 5199 5200 return Dcl; 5201 } 5202 5203 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5204 /// If T is the name of a class, then each of the following shall have a 5205 /// name different from T: 5206 /// - every static data member of class T; 5207 /// - every member function of class T 5208 /// - every member of class T that is itself a type; 5209 /// \returns true if the declaration name violates these rules. 5210 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5211 DeclarationNameInfo NameInfo) { 5212 DeclarationName Name = NameInfo.getName(); 5213 5214 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5215 while (Record && Record->isAnonymousStructOrUnion()) 5216 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5217 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5218 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5219 return true; 5220 } 5221 5222 return false; 5223 } 5224 5225 /// \brief Diagnose a declaration whose declarator-id has the given 5226 /// nested-name-specifier. 5227 /// 5228 /// \param SS The nested-name-specifier of the declarator-id. 5229 /// 5230 /// \param DC The declaration context to which the nested-name-specifier 5231 /// resolves. 5232 /// 5233 /// \param Name The name of the entity being declared. 5234 /// 5235 /// \param Loc The location of the name of the entity being declared. 5236 /// 5237 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5238 /// we're declaring an explicit / partial specialization / instantiation. 5239 /// 5240 /// \returns true if we cannot safely recover from this error, false otherwise. 5241 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5242 DeclarationName Name, 5243 SourceLocation Loc, bool IsTemplateId) { 5244 DeclContext *Cur = CurContext; 5245 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5246 Cur = Cur->getParent(); 5247 5248 // If the user provided a superfluous scope specifier that refers back to the 5249 // class in which the entity is already declared, diagnose and ignore it. 5250 // 5251 // class X { 5252 // void X::f(); 5253 // }; 5254 // 5255 // Note, it was once ill-formed to give redundant qualification in all 5256 // contexts, but that rule was removed by DR482. 5257 if (Cur->Equals(DC)) { 5258 if (Cur->isRecord()) { 5259 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5260 : diag::err_member_extra_qualification) 5261 << Name << FixItHint::CreateRemoval(SS.getRange()); 5262 SS.clear(); 5263 } else { 5264 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5265 } 5266 return false; 5267 } 5268 5269 // Check whether the qualifying scope encloses the scope of the original 5270 // declaration. For a template-id, we perform the checks in 5271 // CheckTemplateSpecializationScope. 5272 if (!Cur->Encloses(DC) && !IsTemplateId) { 5273 if (Cur->isRecord()) 5274 Diag(Loc, diag::err_member_qualification) 5275 << Name << SS.getRange(); 5276 else if (isa<TranslationUnitDecl>(DC)) 5277 Diag(Loc, diag::err_invalid_declarator_global_scope) 5278 << Name << SS.getRange(); 5279 else if (isa<FunctionDecl>(Cur)) 5280 Diag(Loc, diag::err_invalid_declarator_in_function) 5281 << Name << SS.getRange(); 5282 else if (isa<BlockDecl>(Cur)) 5283 Diag(Loc, diag::err_invalid_declarator_in_block) 5284 << Name << SS.getRange(); 5285 else 5286 Diag(Loc, diag::err_invalid_declarator_scope) 5287 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5288 5289 return true; 5290 } 5291 5292 if (Cur->isRecord()) { 5293 // Cannot qualify members within a class. 5294 Diag(Loc, diag::err_member_qualification) 5295 << Name << SS.getRange(); 5296 SS.clear(); 5297 5298 // C++ constructors and destructors with incorrect scopes can break 5299 // our AST invariants by having the wrong underlying types. If 5300 // that's the case, then drop this declaration entirely. 5301 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5302 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5303 !Context.hasSameType(Name.getCXXNameType(), 5304 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5305 return true; 5306 5307 return false; 5308 } 5309 5310 // C++11 [dcl.meaning]p1: 5311 // [...] "The nested-name-specifier of the qualified declarator-id shall 5312 // not begin with a decltype-specifer" 5313 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5314 while (SpecLoc.getPrefix()) 5315 SpecLoc = SpecLoc.getPrefix(); 5316 if (dyn_cast_or_null<DecltypeType>( 5317 SpecLoc.getNestedNameSpecifier()->getAsType())) 5318 Diag(Loc, diag::err_decltype_in_declarator) 5319 << SpecLoc.getTypeLoc().getSourceRange(); 5320 5321 return false; 5322 } 5323 5324 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5325 MultiTemplateParamsArg TemplateParamLists) { 5326 // TODO: consider using NameInfo for diagnostic. 5327 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5328 DeclarationName Name = NameInfo.getName(); 5329 5330 // All of these full declarators require an identifier. If it doesn't have 5331 // one, the ParsedFreeStandingDeclSpec action should be used. 5332 if (D.isDecompositionDeclarator()) { 5333 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5334 } else if (!Name) { 5335 if (!D.isInvalidType()) // Reject this if we think it is valid. 5336 Diag(D.getDeclSpec().getLocStart(), 5337 diag::err_declarator_need_ident) 5338 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5339 return nullptr; 5340 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5341 return nullptr; 5342 5343 // The scope passed in may not be a decl scope. Zip up the scope tree until 5344 // we find one that is. 5345 while ((S->getFlags() & Scope::DeclScope) == 0 || 5346 (S->getFlags() & Scope::TemplateParamScope) != 0) 5347 S = S->getParent(); 5348 5349 DeclContext *DC = CurContext; 5350 if (D.getCXXScopeSpec().isInvalid()) 5351 D.setInvalidType(); 5352 else if (D.getCXXScopeSpec().isSet()) { 5353 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5354 UPPC_DeclarationQualifier)) 5355 return nullptr; 5356 5357 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5358 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5359 if (!DC || isa<EnumDecl>(DC)) { 5360 // If we could not compute the declaration context, it's because the 5361 // declaration context is dependent but does not refer to a class, 5362 // class template, or class template partial specialization. Complain 5363 // and return early, to avoid the coming semantic disaster. 5364 Diag(D.getIdentifierLoc(), 5365 diag::err_template_qualified_declarator_no_match) 5366 << D.getCXXScopeSpec().getScopeRep() 5367 << D.getCXXScopeSpec().getRange(); 5368 return nullptr; 5369 } 5370 bool IsDependentContext = DC->isDependentContext(); 5371 5372 if (!IsDependentContext && 5373 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5374 return nullptr; 5375 5376 // If a class is incomplete, do not parse entities inside it. 5377 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5378 Diag(D.getIdentifierLoc(), 5379 diag::err_member_def_undefined_record) 5380 << Name << DC << D.getCXXScopeSpec().getRange(); 5381 return nullptr; 5382 } 5383 if (!D.getDeclSpec().isFriendSpecified()) { 5384 if (diagnoseQualifiedDeclaration( 5385 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5386 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5387 if (DC->isRecord()) 5388 return nullptr; 5389 5390 D.setInvalidType(); 5391 } 5392 } 5393 5394 // Check whether we need to rebuild the type of the given 5395 // declaration in the current instantiation. 5396 if (EnteringContext && IsDependentContext && 5397 TemplateParamLists.size() != 0) { 5398 ContextRAII SavedContext(*this, DC); 5399 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5400 D.setInvalidType(); 5401 } 5402 } 5403 5404 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5405 QualType R = TInfo->getType(); 5406 5407 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5408 UPPC_DeclarationType)) 5409 D.setInvalidType(); 5410 5411 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5412 forRedeclarationInCurContext()); 5413 5414 // See if this is a redefinition of a variable in the same scope. 5415 if (!D.getCXXScopeSpec().isSet()) { 5416 bool IsLinkageLookup = false; 5417 bool CreateBuiltins = false; 5418 5419 // If the declaration we're planning to build will be a function 5420 // or object with linkage, then look for another declaration with 5421 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5422 // 5423 // If the declaration we're planning to build will be declared with 5424 // external linkage in the translation unit, create any builtin with 5425 // the same name. 5426 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5427 /* Do nothing*/; 5428 else if (CurContext->isFunctionOrMethod() && 5429 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5430 R->isFunctionType())) { 5431 IsLinkageLookup = true; 5432 CreateBuiltins = 5433 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5434 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5435 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5436 CreateBuiltins = true; 5437 5438 if (IsLinkageLookup) { 5439 Previous.clear(LookupRedeclarationWithLinkage); 5440 Previous.setRedeclarationKind(ForExternalRedeclaration); 5441 } 5442 5443 LookupName(Previous, S, CreateBuiltins); 5444 } else { // Something like "int foo::x;" 5445 LookupQualifiedName(Previous, DC); 5446 5447 // C++ [dcl.meaning]p1: 5448 // When the declarator-id is qualified, the declaration shall refer to a 5449 // previously declared member of the class or namespace to which the 5450 // qualifier refers (or, in the case of a namespace, of an element of the 5451 // inline namespace set of that namespace (7.3.1)) or to a specialization 5452 // thereof; [...] 5453 // 5454 // Note that we already checked the context above, and that we do not have 5455 // enough information to make sure that Previous contains the declaration 5456 // we want to match. For example, given: 5457 // 5458 // class X { 5459 // void f(); 5460 // void f(float); 5461 // }; 5462 // 5463 // void X::f(int) { } // ill-formed 5464 // 5465 // In this case, Previous will point to the overload set 5466 // containing the two f's declared in X, but neither of them 5467 // matches. 5468 5469 // C++ [dcl.meaning]p1: 5470 // [...] the member shall not merely have been introduced by a 5471 // using-declaration in the scope of the class or namespace nominated by 5472 // the nested-name-specifier of the declarator-id. 5473 RemoveUsingDecls(Previous); 5474 } 5475 5476 if (Previous.isSingleResult() && 5477 Previous.getFoundDecl()->isTemplateParameter()) { 5478 // Maybe we will complain about the shadowed template parameter. 5479 if (!D.isInvalidType()) 5480 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5481 Previous.getFoundDecl()); 5482 5483 // Just pretend that we didn't see the previous declaration. 5484 Previous.clear(); 5485 } 5486 5487 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5488 // Forget that the previous declaration is the injected-class-name. 5489 Previous.clear(); 5490 5491 // In C++, the previous declaration we find might be a tag type 5492 // (class or enum). In this case, the new declaration will hide the 5493 // tag type. Note that this applies to functions, function templates, and 5494 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5495 if (Previous.isSingleTagDecl() && 5496 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5497 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5498 Previous.clear(); 5499 5500 // Check that there are no default arguments other than in the parameters 5501 // of a function declaration (C++ only). 5502 if (getLangOpts().CPlusPlus) 5503 CheckExtraCXXDefaultArguments(D); 5504 5505 NamedDecl *New; 5506 5507 bool AddToScope = true; 5508 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5509 if (TemplateParamLists.size()) { 5510 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5511 return nullptr; 5512 } 5513 5514 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5515 } else if (R->isFunctionType()) { 5516 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5517 TemplateParamLists, 5518 AddToScope); 5519 } else { 5520 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5521 AddToScope); 5522 } 5523 5524 if (!New) 5525 return nullptr; 5526 5527 // If this has an identifier and is not a function template specialization, 5528 // add it to the scope stack. 5529 if (New->getDeclName() && AddToScope) { 5530 // Only make a locally-scoped extern declaration visible if it is the first 5531 // declaration of this entity. Qualified lookup for such an entity should 5532 // only find this declaration if there is no visible declaration of it. 5533 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 5534 PushOnScopeChains(New, S, AddToContext); 5535 if (!AddToContext) 5536 CurContext->addHiddenDecl(New); 5537 } 5538 5539 if (isInOpenMPDeclareTargetContext()) 5540 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5541 5542 return New; 5543 } 5544 5545 /// Helper method to turn variable array types into constant array 5546 /// types in certain situations which would otherwise be errors (for 5547 /// GCC compatibility). 5548 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5549 ASTContext &Context, 5550 bool &SizeIsNegative, 5551 llvm::APSInt &Oversized) { 5552 // This method tries to turn a variable array into a constant 5553 // array even when the size isn't an ICE. This is necessary 5554 // for compatibility with code that depends on gcc's buggy 5555 // constant expression folding, like struct {char x[(int)(char*)2];} 5556 SizeIsNegative = false; 5557 Oversized = 0; 5558 5559 if (T->isDependentType()) 5560 return QualType(); 5561 5562 QualifierCollector Qs; 5563 const Type *Ty = Qs.strip(T); 5564 5565 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5566 QualType Pointee = PTy->getPointeeType(); 5567 QualType FixedType = 5568 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5569 Oversized); 5570 if (FixedType.isNull()) return FixedType; 5571 FixedType = Context.getPointerType(FixedType); 5572 return Qs.apply(Context, FixedType); 5573 } 5574 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5575 QualType Inner = PTy->getInnerType(); 5576 QualType FixedType = 5577 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5578 Oversized); 5579 if (FixedType.isNull()) return FixedType; 5580 FixedType = Context.getParenType(FixedType); 5581 return Qs.apply(Context, FixedType); 5582 } 5583 5584 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5585 if (!VLATy) 5586 return QualType(); 5587 // FIXME: We should probably handle this case 5588 if (VLATy->getElementType()->isVariablyModifiedType()) 5589 return QualType(); 5590 5591 llvm::APSInt Res; 5592 if (!VLATy->getSizeExpr() || 5593 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5594 return QualType(); 5595 5596 // Check whether the array size is negative. 5597 if (Res.isSigned() && Res.isNegative()) { 5598 SizeIsNegative = true; 5599 return QualType(); 5600 } 5601 5602 // Check whether the array is too large to be addressed. 5603 unsigned ActiveSizeBits 5604 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5605 Res); 5606 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5607 Oversized = Res; 5608 return QualType(); 5609 } 5610 5611 return Context.getConstantArrayType(VLATy->getElementType(), 5612 Res, ArrayType::Normal, 0); 5613 } 5614 5615 static void 5616 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5617 SrcTL = SrcTL.getUnqualifiedLoc(); 5618 DstTL = DstTL.getUnqualifiedLoc(); 5619 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5620 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5621 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5622 DstPTL.getPointeeLoc()); 5623 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5624 return; 5625 } 5626 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5627 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5628 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5629 DstPTL.getInnerLoc()); 5630 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5631 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5632 return; 5633 } 5634 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5635 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5636 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5637 TypeLoc DstElemTL = DstATL.getElementLoc(); 5638 DstElemTL.initializeFullCopy(SrcElemTL); 5639 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5640 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5641 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5642 } 5643 5644 /// Helper method to turn variable array types into constant array 5645 /// types in certain situations which would otherwise be errors (for 5646 /// GCC compatibility). 5647 static TypeSourceInfo* 5648 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5649 ASTContext &Context, 5650 bool &SizeIsNegative, 5651 llvm::APSInt &Oversized) { 5652 QualType FixedTy 5653 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5654 SizeIsNegative, Oversized); 5655 if (FixedTy.isNull()) 5656 return nullptr; 5657 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5658 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5659 FixedTInfo->getTypeLoc()); 5660 return FixedTInfo; 5661 } 5662 5663 /// \brief Register the given locally-scoped extern "C" declaration so 5664 /// that it can be found later for redeclarations. We include any extern "C" 5665 /// declaration that is not visible in the translation unit here, not just 5666 /// function-scope declarations. 5667 void 5668 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5669 if (!getLangOpts().CPlusPlus && 5670 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5671 // Don't need to track declarations in the TU in C. 5672 return; 5673 5674 // Note that we have a locally-scoped external with this name. 5675 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5676 } 5677 5678 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5679 // FIXME: We can have multiple results via __attribute__((overloadable)). 5680 auto Result = Context.getExternCContextDecl()->lookup(Name); 5681 return Result.empty() ? nullptr : *Result.begin(); 5682 } 5683 5684 /// \brief Diagnose function specifiers on a declaration of an identifier that 5685 /// does not identify a function. 5686 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5687 // FIXME: We should probably indicate the identifier in question to avoid 5688 // confusion for constructs like "virtual int a(), b;" 5689 if (DS.isVirtualSpecified()) 5690 Diag(DS.getVirtualSpecLoc(), 5691 diag::err_virtual_non_function); 5692 5693 if (DS.isExplicitSpecified()) 5694 Diag(DS.getExplicitSpecLoc(), 5695 diag::err_explicit_non_function); 5696 5697 if (DS.isNoreturnSpecified()) 5698 Diag(DS.getNoreturnSpecLoc(), 5699 diag::err_noreturn_non_function); 5700 } 5701 5702 NamedDecl* 5703 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5704 TypeSourceInfo *TInfo, LookupResult &Previous) { 5705 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5706 if (D.getCXXScopeSpec().isSet()) { 5707 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5708 << D.getCXXScopeSpec().getRange(); 5709 D.setInvalidType(); 5710 // Pretend we didn't see the scope specifier. 5711 DC = CurContext; 5712 Previous.clear(); 5713 } 5714 5715 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5716 5717 if (D.getDeclSpec().isInlineSpecified()) 5718 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 5719 << getLangOpts().CPlusPlus17; 5720 if (D.getDeclSpec().isConstexprSpecified()) 5721 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5722 << 1; 5723 5724 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 5725 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 5726 Diag(D.getName().StartLocation, 5727 diag::err_deduction_guide_invalid_specifier) 5728 << "typedef"; 5729 else 5730 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5731 << D.getName().getSourceRange(); 5732 return nullptr; 5733 } 5734 5735 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5736 if (!NewTD) return nullptr; 5737 5738 // Handle attributes prior to checking for duplicates in MergeVarDecl 5739 ProcessDeclAttributes(S, NewTD, D); 5740 5741 CheckTypedefForVariablyModifiedType(S, NewTD); 5742 5743 bool Redeclaration = D.isRedeclaration(); 5744 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5745 D.setRedeclaration(Redeclaration); 5746 return ND; 5747 } 5748 5749 void 5750 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5751 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5752 // then it shall have block scope. 5753 // Note that variably modified types must be fixed before merging the decl so 5754 // that redeclarations will match. 5755 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5756 QualType T = TInfo->getType(); 5757 if (T->isVariablyModifiedType()) { 5758 setFunctionHasBranchProtectedScope(); 5759 5760 if (S->getFnParent() == nullptr) { 5761 bool SizeIsNegative; 5762 llvm::APSInt Oversized; 5763 TypeSourceInfo *FixedTInfo = 5764 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5765 SizeIsNegative, 5766 Oversized); 5767 if (FixedTInfo) { 5768 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5769 NewTD->setTypeSourceInfo(FixedTInfo); 5770 } else { 5771 if (SizeIsNegative) 5772 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5773 else if (T->isVariableArrayType()) 5774 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5775 else if (Oversized.getBoolValue()) 5776 Diag(NewTD->getLocation(), diag::err_array_too_large) 5777 << Oversized.toString(10); 5778 else 5779 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5780 NewTD->setInvalidDecl(); 5781 } 5782 } 5783 } 5784 } 5785 5786 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5787 /// declares a typedef-name, either using the 'typedef' type specifier or via 5788 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5789 NamedDecl* 5790 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5791 LookupResult &Previous, bool &Redeclaration) { 5792 5793 // Find the shadowed declaration before filtering for scope. 5794 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 5795 5796 // Merge the decl with the existing one if appropriate. If the decl is 5797 // in an outer scope, it isn't the same thing. 5798 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5799 /*AllowInlineNamespace*/false); 5800 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5801 if (!Previous.empty()) { 5802 Redeclaration = true; 5803 MergeTypedefNameDecl(S, NewTD, Previous); 5804 } 5805 5806 if (ShadowedDecl && !Redeclaration) 5807 CheckShadow(NewTD, ShadowedDecl, Previous); 5808 5809 // If this is the C FILE type, notify the AST context. 5810 if (IdentifierInfo *II = NewTD->getIdentifier()) 5811 if (!NewTD->isInvalidDecl() && 5812 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5813 if (II->isStr("FILE")) 5814 Context.setFILEDecl(NewTD); 5815 else if (II->isStr("jmp_buf")) 5816 Context.setjmp_bufDecl(NewTD); 5817 else if (II->isStr("sigjmp_buf")) 5818 Context.setsigjmp_bufDecl(NewTD); 5819 else if (II->isStr("ucontext_t")) 5820 Context.setucontext_tDecl(NewTD); 5821 } 5822 5823 return NewTD; 5824 } 5825 5826 /// \brief Determines whether the given declaration is an out-of-scope 5827 /// previous declaration. 5828 /// 5829 /// This routine should be invoked when name lookup has found a 5830 /// previous declaration (PrevDecl) that is not in the scope where a 5831 /// new declaration by the same name is being introduced. If the new 5832 /// declaration occurs in a local scope, previous declarations with 5833 /// linkage may still be considered previous declarations (C99 5834 /// 6.2.2p4-5, C++ [basic.link]p6). 5835 /// 5836 /// \param PrevDecl the previous declaration found by name 5837 /// lookup 5838 /// 5839 /// \param DC the context in which the new declaration is being 5840 /// declared. 5841 /// 5842 /// \returns true if PrevDecl is an out-of-scope previous declaration 5843 /// for a new delcaration with the same name. 5844 static bool 5845 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5846 ASTContext &Context) { 5847 if (!PrevDecl) 5848 return false; 5849 5850 if (!PrevDecl->hasLinkage()) 5851 return false; 5852 5853 if (Context.getLangOpts().CPlusPlus) { 5854 // C++ [basic.link]p6: 5855 // If there is a visible declaration of an entity with linkage 5856 // having the same name and type, ignoring entities declared 5857 // outside the innermost enclosing namespace scope, the block 5858 // scope declaration declares that same entity and receives the 5859 // linkage of the previous declaration. 5860 DeclContext *OuterContext = DC->getRedeclContext(); 5861 if (!OuterContext->isFunctionOrMethod()) 5862 // This rule only applies to block-scope declarations. 5863 return false; 5864 5865 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5866 if (PrevOuterContext->isRecord()) 5867 // We found a member function: ignore it. 5868 return false; 5869 5870 // Find the innermost enclosing namespace for the new and 5871 // previous declarations. 5872 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5873 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5874 5875 // The previous declaration is in a different namespace, so it 5876 // isn't the same function. 5877 if (!OuterContext->Equals(PrevOuterContext)) 5878 return false; 5879 } 5880 5881 return true; 5882 } 5883 5884 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5885 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5886 if (!SS.isSet()) return; 5887 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5888 } 5889 5890 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5891 QualType type = decl->getType(); 5892 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5893 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5894 // Various kinds of declaration aren't allowed to be __autoreleasing. 5895 unsigned kind = -1U; 5896 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5897 if (var->hasAttr<BlocksAttr>()) 5898 kind = 0; // __block 5899 else if (!var->hasLocalStorage()) 5900 kind = 1; // global 5901 } else if (isa<ObjCIvarDecl>(decl)) { 5902 kind = 3; // ivar 5903 } else if (isa<FieldDecl>(decl)) { 5904 kind = 2; // field 5905 } 5906 5907 if (kind != -1U) { 5908 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5909 << kind; 5910 } 5911 } else if (lifetime == Qualifiers::OCL_None) { 5912 // Try to infer lifetime. 5913 if (!type->isObjCLifetimeType()) 5914 return false; 5915 5916 lifetime = type->getObjCARCImplicitLifetime(); 5917 type = Context.getLifetimeQualifiedType(type, lifetime); 5918 decl->setType(type); 5919 } 5920 5921 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5922 // Thread-local variables cannot have lifetime. 5923 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5924 var->getTLSKind()) { 5925 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5926 << var->getType(); 5927 return true; 5928 } 5929 } 5930 5931 return false; 5932 } 5933 5934 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5935 // Ensure that an auto decl is deduced otherwise the checks below might cache 5936 // the wrong linkage. 5937 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5938 5939 // 'weak' only applies to declarations with external linkage. 5940 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5941 if (!ND.isExternallyVisible()) { 5942 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5943 ND.dropAttr<WeakAttr>(); 5944 } 5945 } 5946 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5947 if (ND.isExternallyVisible()) { 5948 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5949 ND.dropAttr<WeakRefAttr>(); 5950 ND.dropAttr<AliasAttr>(); 5951 } 5952 } 5953 5954 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5955 if (VD->hasInit()) { 5956 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5957 assert(VD->isThisDeclarationADefinition() && 5958 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5959 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 5960 VD->dropAttr<AliasAttr>(); 5961 } 5962 } 5963 } 5964 5965 // 'selectany' only applies to externally visible variable declarations. 5966 // It does not apply to functions. 5967 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5968 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5969 S.Diag(Attr->getLocation(), 5970 diag::err_attribute_selectany_non_extern_data); 5971 ND.dropAttr<SelectAnyAttr>(); 5972 } 5973 } 5974 5975 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5976 // dll attributes require external linkage. Static locals may have external 5977 // linkage but still cannot be explicitly imported or exported. 5978 auto *VD = dyn_cast<VarDecl>(&ND); 5979 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5980 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5981 << &ND << Attr; 5982 ND.setInvalidDecl(); 5983 } 5984 } 5985 5986 // Virtual functions cannot be marked as 'notail'. 5987 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5988 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5989 if (MD->isVirtual()) { 5990 S.Diag(ND.getLocation(), 5991 diag::err_invalid_attribute_on_virtual_function) 5992 << Attr; 5993 ND.dropAttr<NotTailCalledAttr>(); 5994 } 5995 } 5996 5997 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5998 NamedDecl *NewDecl, 5999 bool IsSpecialization, 6000 bool IsDefinition) { 6001 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6002 return; 6003 6004 bool IsTemplate = false; 6005 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6006 OldDecl = OldTD->getTemplatedDecl(); 6007 IsTemplate = true; 6008 if (!IsSpecialization) 6009 IsDefinition = false; 6010 } 6011 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6012 NewDecl = NewTD->getTemplatedDecl(); 6013 IsTemplate = true; 6014 } 6015 6016 if (!OldDecl || !NewDecl) 6017 return; 6018 6019 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6020 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6021 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6022 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6023 6024 // dllimport and dllexport are inheritable attributes so we have to exclude 6025 // inherited attribute instances. 6026 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6027 (NewExportAttr && !NewExportAttr->isInherited()); 6028 6029 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6030 // the only exception being explicit specializations. 6031 // Implicitly generated declarations are also excluded for now because there 6032 // is no other way to switch these to use dllimport or dllexport. 6033 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6034 6035 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6036 // Allow with a warning for free functions and global variables. 6037 bool JustWarn = false; 6038 if (!OldDecl->isCXXClassMember()) { 6039 auto *VD = dyn_cast<VarDecl>(OldDecl); 6040 if (VD && !VD->getDescribedVarTemplate()) 6041 JustWarn = true; 6042 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6043 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6044 JustWarn = true; 6045 } 6046 6047 // We cannot change a declaration that's been used because IR has already 6048 // been emitted. Dllimported functions will still work though (modulo 6049 // address equality) as they can use the thunk. 6050 if (OldDecl->isUsed()) 6051 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6052 JustWarn = false; 6053 6054 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6055 : diag::err_attribute_dll_redeclaration; 6056 S.Diag(NewDecl->getLocation(), DiagID) 6057 << NewDecl 6058 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6059 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6060 if (!JustWarn) { 6061 NewDecl->setInvalidDecl(); 6062 return; 6063 } 6064 } 6065 6066 // A redeclaration is not allowed to drop a dllimport attribute, the only 6067 // exceptions being inline function definitions (except for function 6068 // templates), local extern declarations, qualified friend declarations or 6069 // special MSVC extension: in the last case, the declaration is treated as if 6070 // it were marked dllexport. 6071 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6072 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6073 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6074 // Ignore static data because out-of-line definitions are diagnosed 6075 // separately. 6076 IsStaticDataMember = VD->isStaticDataMember(); 6077 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6078 VarDecl::DeclarationOnly; 6079 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6080 IsInline = FD->isInlined(); 6081 IsQualifiedFriend = FD->getQualifier() && 6082 FD->getFriendObjectKind() == Decl::FOK_Declared; 6083 } 6084 6085 if (OldImportAttr && !HasNewAttr && 6086 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6087 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6088 if (IsMicrosoft && IsDefinition) { 6089 S.Diag(NewDecl->getLocation(), 6090 diag::warn_redeclaration_without_import_attribute) 6091 << NewDecl; 6092 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6093 NewDecl->dropAttr<DLLImportAttr>(); 6094 NewDecl->addAttr(::new (S.Context) DLLExportAttr( 6095 NewImportAttr->getRange(), S.Context, 6096 NewImportAttr->getSpellingListIndex())); 6097 } else { 6098 S.Diag(NewDecl->getLocation(), 6099 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6100 << NewDecl << OldImportAttr; 6101 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6102 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6103 OldDecl->dropAttr<DLLImportAttr>(); 6104 NewDecl->dropAttr<DLLImportAttr>(); 6105 } 6106 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6107 // In MinGW, seeing a function declared inline drops the dllimport 6108 // attribute. 6109 OldDecl->dropAttr<DLLImportAttr>(); 6110 NewDecl->dropAttr<DLLImportAttr>(); 6111 S.Diag(NewDecl->getLocation(), 6112 diag::warn_dllimport_dropped_from_inline_function) 6113 << NewDecl << OldImportAttr; 6114 } 6115 6116 // A specialization of a class template member function is processed here 6117 // since it's a redeclaration. If the parent class is dllexport, the 6118 // specialization inherits that attribute. This doesn't happen automatically 6119 // since the parent class isn't instantiated until later. 6120 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6121 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6122 !NewImportAttr && !NewExportAttr) { 6123 if (const DLLExportAttr *ParentExportAttr = 6124 MD->getParent()->getAttr<DLLExportAttr>()) { 6125 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6126 NewAttr->setInherited(true); 6127 NewDecl->addAttr(NewAttr); 6128 } 6129 } 6130 } 6131 } 6132 6133 /// Given that we are within the definition of the given function, 6134 /// will that definition behave like C99's 'inline', where the 6135 /// definition is discarded except for optimization purposes? 6136 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6137 // Try to avoid calling GetGVALinkageForFunction. 6138 6139 // All cases of this require the 'inline' keyword. 6140 if (!FD->isInlined()) return false; 6141 6142 // This is only possible in C++ with the gnu_inline attribute. 6143 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6144 return false; 6145 6146 // Okay, go ahead and call the relatively-more-expensive function. 6147 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6148 } 6149 6150 /// Determine whether a variable is extern "C" prior to attaching 6151 /// an initializer. We can't just call isExternC() here, because that 6152 /// will also compute and cache whether the declaration is externally 6153 /// visible, which might change when we attach the initializer. 6154 /// 6155 /// This can only be used if the declaration is known to not be a 6156 /// redeclaration of an internal linkage declaration. 6157 /// 6158 /// For instance: 6159 /// 6160 /// auto x = []{}; 6161 /// 6162 /// Attaching the initializer here makes this declaration not externally 6163 /// visible, because its type has internal linkage. 6164 /// 6165 /// FIXME: This is a hack. 6166 template<typename T> 6167 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6168 if (S.getLangOpts().CPlusPlus) { 6169 // In C++, the overloadable attribute negates the effects of extern "C". 6170 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6171 return false; 6172 6173 // So do CUDA's host/device attributes. 6174 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6175 D->template hasAttr<CUDAHostAttr>())) 6176 return false; 6177 } 6178 return D->isExternC(); 6179 } 6180 6181 static bool shouldConsiderLinkage(const VarDecl *VD) { 6182 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6183 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC)) 6184 return VD->hasExternalStorage(); 6185 if (DC->isFileContext()) 6186 return true; 6187 if (DC->isRecord()) 6188 return false; 6189 llvm_unreachable("Unexpected context"); 6190 } 6191 6192 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6193 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6194 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6195 isa<OMPDeclareReductionDecl>(DC)) 6196 return true; 6197 if (DC->isRecord()) 6198 return false; 6199 llvm_unreachable("Unexpected context"); 6200 } 6201 6202 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 6203 AttributeList::Kind Kind) { 6204 for (const AttributeList *L = AttrList; L; L = L->getNext()) 6205 if (L->getKind() == Kind) 6206 return true; 6207 return false; 6208 } 6209 6210 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6211 AttributeList::Kind Kind) { 6212 // Check decl attributes on the DeclSpec. 6213 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 6214 return true; 6215 6216 // Walk the declarator structure, checking decl attributes that were in a type 6217 // position to the decl itself. 6218 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6219 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 6220 return true; 6221 } 6222 6223 // Finally, check attributes on the decl itself. 6224 return hasParsedAttr(S, PD.getAttributes(), Kind); 6225 } 6226 6227 /// Adjust the \c DeclContext for a function or variable that might be a 6228 /// function-local external declaration. 6229 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6230 if (!DC->isFunctionOrMethod()) 6231 return false; 6232 6233 // If this is a local extern function or variable declared within a function 6234 // template, don't add it into the enclosing namespace scope until it is 6235 // instantiated; it might have a dependent type right now. 6236 if (DC->isDependentContext()) 6237 return true; 6238 6239 // C++11 [basic.link]p7: 6240 // When a block scope declaration of an entity with linkage is not found to 6241 // refer to some other declaration, then that entity is a member of the 6242 // innermost enclosing namespace. 6243 // 6244 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6245 // semantically-enclosing namespace, not a lexically-enclosing one. 6246 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6247 DC = DC->getParent(); 6248 return true; 6249 } 6250 6251 /// \brief Returns true if given declaration has external C language linkage. 6252 static bool isDeclExternC(const Decl *D) { 6253 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6254 return FD->isExternC(); 6255 if (const auto *VD = dyn_cast<VarDecl>(D)) 6256 return VD->isExternC(); 6257 6258 llvm_unreachable("Unknown type of decl!"); 6259 } 6260 6261 NamedDecl *Sema::ActOnVariableDeclarator( 6262 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6263 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6264 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6265 QualType R = TInfo->getType(); 6266 DeclarationName Name = GetNameForDeclarator(D).getName(); 6267 6268 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6269 6270 if (D.isDecompositionDeclarator()) { 6271 // Take the name of the first declarator as our name for diagnostic 6272 // purposes. 6273 auto &Decomp = D.getDecompositionDeclarator(); 6274 if (!Decomp.bindings().empty()) { 6275 II = Decomp.bindings()[0].Name; 6276 Name = II; 6277 } 6278 } else if (!II) { 6279 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6280 return nullptr; 6281 } 6282 6283 if (getLangOpts().OpenCL) { 6284 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6285 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6286 // argument. 6287 if (R->isImageType() || R->isPipeType()) { 6288 Diag(D.getIdentifierLoc(), 6289 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6290 << R; 6291 D.setInvalidType(); 6292 return nullptr; 6293 } 6294 6295 // OpenCL v1.2 s6.9.r: 6296 // The event type cannot be used to declare a program scope variable. 6297 // OpenCL v2.0 s6.9.q: 6298 // The clk_event_t and reserve_id_t types cannot be declared in program scope. 6299 if (NULL == S->getParent()) { 6300 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6301 Diag(D.getIdentifierLoc(), 6302 diag::err_invalid_type_for_program_scope_var) << R; 6303 D.setInvalidType(); 6304 return nullptr; 6305 } 6306 } 6307 6308 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6309 QualType NR = R; 6310 while (NR->isPointerType()) { 6311 if (NR->isFunctionPointerType()) { 6312 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6313 D.setInvalidType(); 6314 break; 6315 } 6316 NR = NR->getPointeeType(); 6317 } 6318 6319 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6320 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6321 // half array type (unless the cl_khr_fp16 extension is enabled). 6322 if (Context.getBaseElementType(R)->isHalfType()) { 6323 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6324 D.setInvalidType(); 6325 } 6326 } 6327 6328 if (R->isSamplerT()) { 6329 // OpenCL v1.2 s6.9.b p4: 6330 // The sampler type cannot be used with the __local and __global address 6331 // space qualifiers. 6332 if (R.getAddressSpace() == LangAS::opencl_local || 6333 R.getAddressSpace() == LangAS::opencl_global) { 6334 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6335 } 6336 6337 // OpenCL v1.2 s6.12.14.1: 6338 // A global sampler must be declared with either the constant address 6339 // space qualifier or with the const qualifier. 6340 if (DC->isTranslationUnit() && 6341 !(R.getAddressSpace() == LangAS::opencl_constant || 6342 R.isConstQualified())) { 6343 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6344 D.setInvalidType(); 6345 } 6346 } 6347 6348 // OpenCL v1.2 s6.9.r: 6349 // The event type cannot be used with the __local, __constant and __global 6350 // address space qualifiers. 6351 if (R->isEventT()) { 6352 if (R.getAddressSpace() != LangAS::opencl_private) { 6353 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 6354 D.setInvalidType(); 6355 } 6356 } 6357 } 6358 6359 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6360 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6361 6362 // dllimport globals without explicit storage class are treated as extern. We 6363 // have to change the storage class this early to get the right DeclContext. 6364 if (SC == SC_None && !DC->isRecord() && 6365 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 6366 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 6367 SC = SC_Extern; 6368 6369 DeclContext *OriginalDC = DC; 6370 bool IsLocalExternDecl = SC == SC_Extern && 6371 adjustContextForLocalExternDecl(DC); 6372 6373 if (SCSpec == DeclSpec::SCS_mutable) { 6374 // mutable can only appear on non-static class members, so it's always 6375 // an error here 6376 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6377 D.setInvalidType(); 6378 SC = SC_None; 6379 } 6380 6381 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6382 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6383 D.getDeclSpec().getStorageClassSpecLoc())) { 6384 // In C++11, the 'register' storage class specifier is deprecated. 6385 // Suppress the warning in system macros, it's used in macros in some 6386 // popular C system headers, such as in glibc's htonl() macro. 6387 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6388 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6389 : diag::warn_deprecated_register) 6390 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6391 } 6392 6393 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6394 6395 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6396 // C99 6.9p2: The storage-class specifiers auto and register shall not 6397 // appear in the declaration specifiers in an external declaration. 6398 // Global Register+Asm is a GNU extension we support. 6399 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6400 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6401 D.setInvalidType(); 6402 } 6403 } 6404 6405 bool IsMemberSpecialization = false; 6406 bool IsVariableTemplateSpecialization = false; 6407 bool IsPartialSpecialization = false; 6408 bool IsVariableTemplate = false; 6409 VarDecl *NewVD = nullptr; 6410 VarTemplateDecl *NewTemplate = nullptr; 6411 TemplateParameterList *TemplateParams = nullptr; 6412 if (!getLangOpts().CPlusPlus) { 6413 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6414 D.getIdentifierLoc(), II, 6415 R, TInfo, SC); 6416 6417 if (R->getContainedDeducedType()) 6418 ParsingInitForAutoVars.insert(NewVD); 6419 6420 if (D.isInvalidType()) 6421 NewVD->setInvalidDecl(); 6422 } else { 6423 bool Invalid = false; 6424 6425 if (DC->isRecord() && !CurContext->isRecord()) { 6426 // This is an out-of-line definition of a static data member. 6427 switch (SC) { 6428 case SC_None: 6429 break; 6430 case SC_Static: 6431 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6432 diag::err_static_out_of_line) 6433 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6434 break; 6435 case SC_Auto: 6436 case SC_Register: 6437 case SC_Extern: 6438 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6439 // to names of variables declared in a block or to function parameters. 6440 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6441 // of class members 6442 6443 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6444 diag::err_storage_class_for_static_member) 6445 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6446 break; 6447 case SC_PrivateExtern: 6448 llvm_unreachable("C storage class in c++!"); 6449 } 6450 } 6451 6452 if (SC == SC_Static && CurContext->isRecord()) { 6453 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6454 if (RD->isLocalClass()) 6455 Diag(D.getIdentifierLoc(), 6456 diag::err_static_data_member_not_allowed_in_local_class) 6457 << Name << RD->getDeclName(); 6458 6459 // C++98 [class.union]p1: If a union contains a static data member, 6460 // the program is ill-formed. C++11 drops this restriction. 6461 if (RD->isUnion()) 6462 Diag(D.getIdentifierLoc(), 6463 getLangOpts().CPlusPlus11 6464 ? diag::warn_cxx98_compat_static_data_member_in_union 6465 : diag::ext_static_data_member_in_union) << Name; 6466 // We conservatively disallow static data members in anonymous structs. 6467 else if (!RD->getDeclName()) 6468 Diag(D.getIdentifierLoc(), 6469 diag::err_static_data_member_not_allowed_in_anon_struct) 6470 << Name << RD->isUnion(); 6471 } 6472 } 6473 6474 // Match up the template parameter lists with the scope specifier, then 6475 // determine whether we have a template or a template specialization. 6476 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6477 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6478 D.getCXXScopeSpec(), 6479 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6480 ? D.getName().TemplateId 6481 : nullptr, 6482 TemplateParamLists, 6483 /*never a friend*/ false, IsMemberSpecialization, Invalid); 6484 6485 if (TemplateParams) { 6486 if (!TemplateParams->size() && 6487 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6488 // There is an extraneous 'template<>' for this variable. Complain 6489 // about it, but allow the declaration of the variable. 6490 Diag(TemplateParams->getTemplateLoc(), 6491 diag::err_template_variable_noparams) 6492 << II 6493 << SourceRange(TemplateParams->getTemplateLoc(), 6494 TemplateParams->getRAngleLoc()); 6495 TemplateParams = nullptr; 6496 } else { 6497 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6498 // This is an explicit specialization or a partial specialization. 6499 // FIXME: Check that we can declare a specialization here. 6500 IsVariableTemplateSpecialization = true; 6501 IsPartialSpecialization = TemplateParams->size() > 0; 6502 } else { // if (TemplateParams->size() > 0) 6503 // This is a template declaration. 6504 IsVariableTemplate = true; 6505 6506 // Check that we can declare a template here. 6507 if (CheckTemplateDeclScope(S, TemplateParams)) 6508 return nullptr; 6509 6510 // Only C++1y supports variable templates (N3651). 6511 Diag(D.getIdentifierLoc(), 6512 getLangOpts().CPlusPlus14 6513 ? diag::warn_cxx11_compat_variable_template 6514 : diag::ext_variable_template); 6515 } 6516 } 6517 } else { 6518 assert((Invalid || 6519 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6520 "should have a 'template<>' for this decl"); 6521 } 6522 6523 if (IsVariableTemplateSpecialization) { 6524 SourceLocation TemplateKWLoc = 6525 TemplateParamLists.size() > 0 6526 ? TemplateParamLists[0]->getTemplateLoc() 6527 : SourceLocation(); 6528 DeclResult Res = ActOnVarTemplateSpecialization( 6529 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6530 IsPartialSpecialization); 6531 if (Res.isInvalid()) 6532 return nullptr; 6533 NewVD = cast<VarDecl>(Res.get()); 6534 AddToScope = false; 6535 } else if (D.isDecompositionDeclarator()) { 6536 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(), 6537 D.getIdentifierLoc(), R, TInfo, SC, 6538 Bindings); 6539 } else 6540 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 6541 D.getIdentifierLoc(), II, R, TInfo, SC); 6542 6543 // If this is supposed to be a variable template, create it as such. 6544 if (IsVariableTemplate) { 6545 NewTemplate = 6546 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6547 TemplateParams, NewVD); 6548 NewVD->setDescribedVarTemplate(NewTemplate); 6549 } 6550 6551 // If this decl has an auto type in need of deduction, make a note of the 6552 // Decl so we can diagnose uses of it in its own initializer. 6553 if (R->getContainedDeducedType()) 6554 ParsingInitForAutoVars.insert(NewVD); 6555 6556 if (D.isInvalidType() || Invalid) { 6557 NewVD->setInvalidDecl(); 6558 if (NewTemplate) 6559 NewTemplate->setInvalidDecl(); 6560 } 6561 6562 SetNestedNameSpecifier(NewVD, D); 6563 6564 // If we have any template parameter lists that don't directly belong to 6565 // the variable (matching the scope specifier), store them. 6566 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6567 if (TemplateParamLists.size() > VDTemplateParamLists) 6568 NewVD->setTemplateParameterListsInfo( 6569 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6570 6571 if (D.getDeclSpec().isConstexprSpecified()) { 6572 NewVD->setConstexpr(true); 6573 // C++1z [dcl.spec.constexpr]p1: 6574 // A static data member declared with the constexpr specifier is 6575 // implicitly an inline variable. 6576 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17) 6577 NewVD->setImplicitlyInline(); 6578 } 6579 } 6580 6581 if (D.getDeclSpec().isInlineSpecified()) { 6582 if (!getLangOpts().CPlusPlus) { 6583 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6584 << 0; 6585 } else if (CurContext->isFunctionOrMethod()) { 6586 // 'inline' is not allowed on block scope variable declaration. 6587 Diag(D.getDeclSpec().getInlineSpecLoc(), 6588 diag::err_inline_declaration_block_scope) << Name 6589 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 6590 } else { 6591 Diag(D.getDeclSpec().getInlineSpecLoc(), 6592 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 6593 : diag::ext_inline_variable); 6594 NewVD->setInlineSpecified(); 6595 } 6596 } 6597 6598 // Set the lexical context. If the declarator has a C++ scope specifier, the 6599 // lexical context will be different from the semantic context. 6600 NewVD->setLexicalDeclContext(CurContext); 6601 if (NewTemplate) 6602 NewTemplate->setLexicalDeclContext(CurContext); 6603 6604 if (IsLocalExternDecl) { 6605 if (D.isDecompositionDeclarator()) 6606 for (auto *B : Bindings) 6607 B->setLocalExternDecl(); 6608 else 6609 NewVD->setLocalExternDecl(); 6610 } 6611 6612 bool EmitTLSUnsupportedError = false; 6613 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 6614 // C++11 [dcl.stc]p4: 6615 // When thread_local is applied to a variable of block scope the 6616 // storage-class-specifier static is implied if it does not appear 6617 // explicitly. 6618 // Core issue: 'static' is not implied if the variable is declared 6619 // 'extern'. 6620 if (NewVD->hasLocalStorage() && 6621 (SCSpec != DeclSpec::SCS_unspecified || 6622 TSCS != DeclSpec::TSCS_thread_local || 6623 !DC->isFunctionOrMethod())) 6624 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6625 diag::err_thread_non_global) 6626 << DeclSpec::getSpecifierName(TSCS); 6627 else if (!Context.getTargetInfo().isTLSSupported()) { 6628 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6629 // Postpone error emission until we've collected attributes required to 6630 // figure out whether it's a host or device variable and whether the 6631 // error should be ignored. 6632 EmitTLSUnsupportedError = true; 6633 // We still need to mark the variable as TLS so it shows up in AST with 6634 // proper storage class for other tools to use even if we're not going 6635 // to emit any code for it. 6636 NewVD->setTSCSpec(TSCS); 6637 } else 6638 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6639 diag::err_thread_unsupported); 6640 } else 6641 NewVD->setTSCSpec(TSCS); 6642 } 6643 6644 // C99 6.7.4p3 6645 // An inline definition of a function with external linkage shall 6646 // not contain a definition of a modifiable object with static or 6647 // thread storage duration... 6648 // We only apply this when the function is required to be defined 6649 // elsewhere, i.e. when the function is not 'extern inline'. Note 6650 // that a local variable with thread storage duration still has to 6651 // be marked 'static'. Also note that it's possible to get these 6652 // semantics in C++ using __attribute__((gnu_inline)). 6653 if (SC == SC_Static && S->getFnParent() != nullptr && 6654 !NewVD->getType().isConstQualified()) { 6655 FunctionDecl *CurFD = getCurFunctionDecl(); 6656 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 6657 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6658 diag::warn_static_local_in_extern_inline); 6659 MaybeSuggestAddingStaticToDecl(CurFD); 6660 } 6661 } 6662 6663 if (D.getDeclSpec().isModulePrivateSpecified()) { 6664 if (IsVariableTemplateSpecialization) 6665 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6666 << (IsPartialSpecialization ? 1 : 0) 6667 << FixItHint::CreateRemoval( 6668 D.getDeclSpec().getModulePrivateSpecLoc()); 6669 else if (IsMemberSpecialization) 6670 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6671 << 2 6672 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6673 else if (NewVD->hasLocalStorage()) 6674 Diag(NewVD->getLocation(), diag::err_module_private_local) 6675 << 0 << NewVD->getDeclName() 6676 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6677 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6678 else { 6679 NewVD->setModulePrivate(); 6680 if (NewTemplate) 6681 NewTemplate->setModulePrivate(); 6682 for (auto *B : Bindings) 6683 B->setModulePrivate(); 6684 } 6685 } 6686 6687 // Handle attributes prior to checking for duplicates in MergeVarDecl 6688 ProcessDeclAttributes(S, NewVD, D); 6689 6690 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 6691 if (EmitTLSUnsupportedError && 6692 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 6693 (getLangOpts().OpenMPIsDevice && 6694 NewVD->hasAttr<OMPDeclareTargetDeclAttr>()))) 6695 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6696 diag::err_thread_unsupported); 6697 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6698 // storage [duration]." 6699 if (SC == SC_None && S->getFnParent() != nullptr && 6700 (NewVD->hasAttr<CUDASharedAttr>() || 6701 NewVD->hasAttr<CUDAConstantAttr>())) { 6702 NewVD->setStorageClass(SC_Static); 6703 } 6704 } 6705 6706 // Ensure that dllimport globals without explicit storage class are treated as 6707 // extern. The storage class is set above using parsed attributes. Now we can 6708 // check the VarDecl itself. 6709 assert(!NewVD->hasAttr<DLLImportAttr>() || 6710 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6711 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6712 6713 // In auto-retain/release, infer strong retension for variables of 6714 // retainable type. 6715 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6716 NewVD->setInvalidDecl(); 6717 6718 // Handle GNU asm-label extension (encoded as an attribute). 6719 if (Expr *E = (Expr*)D.getAsmLabel()) { 6720 // The parser guarantees this is a string. 6721 StringLiteral *SE = cast<StringLiteral>(E); 6722 StringRef Label = SE->getString(); 6723 if (S->getFnParent() != nullptr) { 6724 switch (SC) { 6725 case SC_None: 6726 case SC_Auto: 6727 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6728 break; 6729 case SC_Register: 6730 // Local Named register 6731 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6732 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6733 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6734 break; 6735 case SC_Static: 6736 case SC_Extern: 6737 case SC_PrivateExtern: 6738 break; 6739 } 6740 } else if (SC == SC_Register) { 6741 // Global Named register 6742 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 6743 const auto &TI = Context.getTargetInfo(); 6744 bool HasSizeMismatch; 6745 6746 if (!TI.isValidGCCRegisterName(Label)) 6747 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6748 else if (!TI.validateGlobalRegisterVariable(Label, 6749 Context.getTypeSize(R), 6750 HasSizeMismatch)) 6751 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 6752 else if (HasSizeMismatch) 6753 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 6754 } 6755 6756 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6757 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6758 NewVD->setInvalidDecl(true); 6759 } 6760 } 6761 6762 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6763 Context, Label, 0)); 6764 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6765 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6766 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6767 if (I != ExtnameUndeclaredIdentifiers.end()) { 6768 if (isDeclExternC(NewVD)) { 6769 NewVD->addAttr(I->second); 6770 ExtnameUndeclaredIdentifiers.erase(I); 6771 } else 6772 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6773 << /*Variable*/1 << NewVD; 6774 } 6775 } 6776 6777 // Find the shadowed declaration before filtering for scope. 6778 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 6779 ? getShadowedDeclaration(NewVD, Previous) 6780 : nullptr; 6781 6782 // Don't consider existing declarations that are in a different 6783 // scope and are out-of-semantic-context declarations (if the new 6784 // declaration has linkage). 6785 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6786 D.getCXXScopeSpec().isNotEmpty() || 6787 IsMemberSpecialization || 6788 IsVariableTemplateSpecialization); 6789 6790 // Check whether the previous declaration is in the same block scope. This 6791 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6792 if (getLangOpts().CPlusPlus && 6793 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6794 NewVD->setPreviousDeclInSameBlockScope( 6795 Previous.isSingleResult() && !Previous.isShadowed() && 6796 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6797 6798 if (!getLangOpts().CPlusPlus) { 6799 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6800 } else { 6801 // If this is an explicit specialization of a static data member, check it. 6802 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 6803 CheckMemberSpecialization(NewVD, Previous)) 6804 NewVD->setInvalidDecl(); 6805 6806 // Merge the decl with the existing one if appropriate. 6807 if (!Previous.empty()) { 6808 if (Previous.isSingleResult() && 6809 isa<FieldDecl>(Previous.getFoundDecl()) && 6810 D.getCXXScopeSpec().isSet()) { 6811 // The user tried to define a non-static data member 6812 // out-of-line (C++ [dcl.meaning]p1). 6813 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6814 << D.getCXXScopeSpec().getRange(); 6815 Previous.clear(); 6816 NewVD->setInvalidDecl(); 6817 } 6818 } else if (D.getCXXScopeSpec().isSet()) { 6819 // No previous declaration in the qualifying scope. 6820 Diag(D.getIdentifierLoc(), diag::err_no_member) 6821 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6822 << D.getCXXScopeSpec().getRange(); 6823 NewVD->setInvalidDecl(); 6824 } 6825 6826 if (!IsVariableTemplateSpecialization) 6827 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6828 6829 if (NewTemplate) { 6830 VarTemplateDecl *PrevVarTemplate = 6831 NewVD->getPreviousDecl() 6832 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6833 : nullptr; 6834 6835 // Check the template parameter list of this declaration, possibly 6836 // merging in the template parameter list from the previous variable 6837 // template declaration. 6838 if (CheckTemplateParameterList( 6839 TemplateParams, 6840 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6841 : nullptr, 6842 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6843 DC->isDependentContext()) 6844 ? TPC_ClassTemplateMember 6845 : TPC_VarTemplate)) 6846 NewVD->setInvalidDecl(); 6847 6848 // If we are providing an explicit specialization of a static variable 6849 // template, make a note of that. 6850 if (PrevVarTemplate && 6851 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6852 PrevVarTemplate->setMemberSpecialization(); 6853 } 6854 } 6855 6856 // Diagnose shadowed variables iff this isn't a redeclaration. 6857 if (ShadowedDecl && !D.isRedeclaration()) 6858 CheckShadow(NewVD, ShadowedDecl, Previous); 6859 6860 ProcessPragmaWeak(S, NewVD); 6861 6862 // If this is the first declaration of an extern C variable, update 6863 // the map of such variables. 6864 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6865 isIncompleteDeclExternC(*this, NewVD)) 6866 RegisterLocallyScopedExternCDecl(NewVD, S); 6867 6868 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6869 Decl *ManglingContextDecl; 6870 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6871 NewVD->getDeclContext(), ManglingContextDecl)) { 6872 Context.setManglingNumber( 6873 NewVD, MCtx->getManglingNumber( 6874 NewVD, getMSManglingNumber(getLangOpts(), S))); 6875 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6876 } 6877 } 6878 6879 // Special handling of variable named 'main'. 6880 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 6881 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6882 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6883 6884 // C++ [basic.start.main]p3 6885 // A program that declares a variable main at global scope is ill-formed. 6886 if (getLangOpts().CPlusPlus) 6887 Diag(D.getLocStart(), diag::err_main_global_variable); 6888 6889 // In C, and external-linkage variable named main results in undefined 6890 // behavior. 6891 else if (NewVD->hasExternalFormalLinkage()) 6892 Diag(D.getLocStart(), diag::warn_main_redefined); 6893 } 6894 6895 if (D.isRedeclaration() && !Previous.empty()) { 6896 NamedDecl *Prev = Previous.getRepresentativeDecl(); 6897 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 6898 D.isFunctionDefinition()); 6899 } 6900 6901 if (NewTemplate) { 6902 if (NewVD->isInvalidDecl()) 6903 NewTemplate->setInvalidDecl(); 6904 ActOnDocumentableDecl(NewTemplate); 6905 return NewTemplate; 6906 } 6907 6908 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 6909 CompleteMemberSpecialization(NewVD, Previous); 6910 6911 return NewVD; 6912 } 6913 6914 /// Enum describing the %select options in diag::warn_decl_shadow. 6915 enum ShadowedDeclKind { 6916 SDK_Local, 6917 SDK_Global, 6918 SDK_StaticMember, 6919 SDK_Field, 6920 SDK_Typedef, 6921 SDK_Using 6922 }; 6923 6924 /// Determine what kind of declaration we're shadowing. 6925 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 6926 const DeclContext *OldDC) { 6927 if (isa<TypeAliasDecl>(ShadowedDecl)) 6928 return SDK_Using; 6929 else if (isa<TypedefDecl>(ShadowedDecl)) 6930 return SDK_Typedef; 6931 else if (isa<RecordDecl>(OldDC)) 6932 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 6933 6934 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 6935 } 6936 6937 /// Return the location of the capture if the given lambda captures the given 6938 /// variable \p VD, or an invalid source location otherwise. 6939 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 6940 const VarDecl *VD) { 6941 for (const Capture &Capture : LSI->Captures) { 6942 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 6943 return Capture.getLocation(); 6944 } 6945 return SourceLocation(); 6946 } 6947 6948 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 6949 const LookupResult &R) { 6950 // Only diagnose if we're shadowing an unambiguous field or variable. 6951 if (R.getResultKind() != LookupResult::Found) 6952 return false; 6953 6954 // Return false if warning is ignored. 6955 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 6956 } 6957 6958 /// \brief Return the declaration shadowed by the given variable \p D, or null 6959 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6960 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 6961 const LookupResult &R) { 6962 if (!shouldWarnIfShadowedDecl(Diags, R)) 6963 return nullptr; 6964 6965 // Don't diagnose declarations at file scope. 6966 if (D->hasGlobalStorage()) 6967 return nullptr; 6968 6969 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6970 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 6971 ? ShadowedDecl 6972 : nullptr; 6973 } 6974 6975 /// \brief Return the declaration shadowed by the given typedef \p D, or null 6976 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 6977 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 6978 const LookupResult &R) { 6979 // Don't warn if typedef declaration is part of a class 6980 if (D->getDeclContext()->isRecord()) 6981 return nullptr; 6982 6983 if (!shouldWarnIfShadowedDecl(Diags, R)) 6984 return nullptr; 6985 6986 NamedDecl *ShadowedDecl = R.getFoundDecl(); 6987 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 6988 } 6989 6990 /// \brief Diagnose variable or built-in function shadowing. Implements 6991 /// -Wshadow. 6992 /// 6993 /// This method is called whenever a VarDecl is added to a "useful" 6994 /// scope. 6995 /// 6996 /// \param ShadowedDecl the declaration that is shadowed by the given variable 6997 /// \param R the lookup of the name 6998 /// 6999 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7000 const LookupResult &R) { 7001 DeclContext *NewDC = D->getDeclContext(); 7002 7003 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7004 // Fields are not shadowed by variables in C++ static methods. 7005 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7006 if (MD->isStatic()) 7007 return; 7008 7009 // Fields shadowed by constructor parameters are a special case. Usually 7010 // the constructor initializes the field with the parameter. 7011 if (isa<CXXConstructorDecl>(NewDC)) 7012 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7013 // Remember that this was shadowed so we can either warn about its 7014 // modification or its existence depending on warning settings. 7015 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7016 return; 7017 } 7018 } 7019 7020 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7021 if (shadowedVar->isExternC()) { 7022 // For shadowing external vars, make sure that we point to the global 7023 // declaration, not a locally scoped extern declaration. 7024 for (auto I : shadowedVar->redecls()) 7025 if (I->isFileVarDecl()) { 7026 ShadowedDecl = I; 7027 break; 7028 } 7029 } 7030 7031 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7032 7033 unsigned WarningDiag = diag::warn_decl_shadow; 7034 SourceLocation CaptureLoc; 7035 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7036 isa<CXXMethodDecl>(NewDC)) { 7037 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7038 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7039 if (RD->getLambdaCaptureDefault() == LCD_None) { 7040 // Try to avoid warnings for lambdas with an explicit capture list. 7041 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7042 // Warn only when the lambda captures the shadowed decl explicitly. 7043 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7044 if (CaptureLoc.isInvalid()) 7045 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7046 } else { 7047 // Remember that this was shadowed so we can avoid the warning if the 7048 // shadowed decl isn't captured and the warning settings allow it. 7049 cast<LambdaScopeInfo>(getCurFunction()) 7050 ->ShadowingDecls.push_back( 7051 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7052 return; 7053 } 7054 } 7055 7056 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7057 // A variable can't shadow a local variable in an enclosing scope, if 7058 // they are separated by a non-capturing declaration context. 7059 for (DeclContext *ParentDC = NewDC; 7060 ParentDC && !ParentDC->Equals(OldDC); 7061 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7062 // Only block literals, captured statements, and lambda expressions 7063 // can capture; other scopes don't. 7064 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7065 !isLambdaCallOperator(ParentDC)) { 7066 return; 7067 } 7068 } 7069 } 7070 } 7071 } 7072 7073 // Only warn about certain kinds of shadowing for class members. 7074 if (NewDC && NewDC->isRecord()) { 7075 // In particular, don't warn about shadowing non-class members. 7076 if (!OldDC->isRecord()) 7077 return; 7078 7079 // TODO: should we warn about static data members shadowing 7080 // static data members from base classes? 7081 7082 // TODO: don't diagnose for inaccessible shadowed members. 7083 // This is hard to do perfectly because we might friend the 7084 // shadowing context, but that's just a false negative. 7085 } 7086 7087 7088 DeclarationName Name = R.getLookupName(); 7089 7090 // Emit warning and note. 7091 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7092 return; 7093 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7094 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7095 if (!CaptureLoc.isInvalid()) 7096 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7097 << Name << /*explicitly*/ 1; 7098 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7099 } 7100 7101 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7102 /// when these variables are captured by the lambda. 7103 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7104 for (const auto &Shadow : LSI->ShadowingDecls) { 7105 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7106 // Try to avoid the warning when the shadowed decl isn't captured. 7107 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7108 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7109 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7110 ? diag::warn_decl_shadow_uncaptured_local 7111 : diag::warn_decl_shadow) 7112 << Shadow.VD->getDeclName() 7113 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7114 if (!CaptureLoc.isInvalid()) 7115 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7116 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7117 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7118 } 7119 } 7120 7121 /// \brief Check -Wshadow without the advantage of a previous lookup. 7122 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7123 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7124 return; 7125 7126 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7127 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7128 LookupName(R, S); 7129 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7130 CheckShadow(D, ShadowedDecl, R); 7131 } 7132 7133 /// Check if 'E', which is an expression that is about to be modified, refers 7134 /// to a constructor parameter that shadows a field. 7135 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7136 // Quickly ignore expressions that can't be shadowing ctor parameters. 7137 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7138 return; 7139 E = E->IgnoreParenImpCasts(); 7140 auto *DRE = dyn_cast<DeclRefExpr>(E); 7141 if (!DRE) 7142 return; 7143 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7144 auto I = ShadowingDecls.find(D); 7145 if (I == ShadowingDecls.end()) 7146 return; 7147 const NamedDecl *ShadowedDecl = I->second; 7148 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7149 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7150 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7151 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7152 7153 // Avoid issuing multiple warnings about the same decl. 7154 ShadowingDecls.erase(I); 7155 } 7156 7157 /// Check for conflict between this global or extern "C" declaration and 7158 /// previous global or extern "C" declarations. This is only used in C++. 7159 template<typename T> 7160 static bool checkGlobalOrExternCConflict( 7161 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7162 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7163 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7164 7165 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7166 // The common case: this global doesn't conflict with any extern "C" 7167 // declaration. 7168 return false; 7169 } 7170 7171 if (Prev) { 7172 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7173 // Both the old and new declarations have C language linkage. This is a 7174 // redeclaration. 7175 Previous.clear(); 7176 Previous.addDecl(Prev); 7177 return true; 7178 } 7179 7180 // This is a global, non-extern "C" declaration, and there is a previous 7181 // non-global extern "C" declaration. Diagnose if this is a variable 7182 // declaration. 7183 if (!isa<VarDecl>(ND)) 7184 return false; 7185 } else { 7186 // The declaration is extern "C". Check for any declaration in the 7187 // translation unit which might conflict. 7188 if (IsGlobal) { 7189 // We have already performed the lookup into the translation unit. 7190 IsGlobal = false; 7191 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7192 I != E; ++I) { 7193 if (isa<VarDecl>(*I)) { 7194 Prev = *I; 7195 break; 7196 } 7197 } 7198 } else { 7199 DeclContext::lookup_result R = 7200 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7201 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7202 I != E; ++I) { 7203 if (isa<VarDecl>(*I)) { 7204 Prev = *I; 7205 break; 7206 } 7207 // FIXME: If we have any other entity with this name in global scope, 7208 // the declaration is ill-formed, but that is a defect: it breaks the 7209 // 'stat' hack, for instance. Only variables can have mangled name 7210 // clashes with extern "C" declarations, so only they deserve a 7211 // diagnostic. 7212 } 7213 } 7214 7215 if (!Prev) 7216 return false; 7217 } 7218 7219 // Use the first declaration's location to ensure we point at something which 7220 // is lexically inside an extern "C" linkage-spec. 7221 assert(Prev && "should have found a previous declaration to diagnose"); 7222 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7223 Prev = FD->getFirstDecl(); 7224 else 7225 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7226 7227 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7228 << IsGlobal << ND; 7229 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7230 << IsGlobal; 7231 return false; 7232 } 7233 7234 /// Apply special rules for handling extern "C" declarations. Returns \c true 7235 /// if we have found that this is a redeclaration of some prior entity. 7236 /// 7237 /// Per C++ [dcl.link]p6: 7238 /// Two declarations [for a function or variable] with C language linkage 7239 /// with the same name that appear in different scopes refer to the same 7240 /// [entity]. An entity with C language linkage shall not be declared with 7241 /// the same name as an entity in global scope. 7242 template<typename T> 7243 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7244 LookupResult &Previous) { 7245 if (!S.getLangOpts().CPlusPlus) { 7246 // In C, when declaring a global variable, look for a corresponding 'extern' 7247 // variable declared in function scope. We don't need this in C++, because 7248 // we find local extern decls in the surrounding file-scope DeclContext. 7249 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7250 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7251 Previous.clear(); 7252 Previous.addDecl(Prev); 7253 return true; 7254 } 7255 } 7256 return false; 7257 } 7258 7259 // A declaration in the translation unit can conflict with an extern "C" 7260 // declaration. 7261 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7262 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7263 7264 // An extern "C" declaration can conflict with a declaration in the 7265 // translation unit or can be a redeclaration of an extern "C" declaration 7266 // in another scope. 7267 if (isIncompleteDeclExternC(S,ND)) 7268 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7269 7270 // Neither global nor extern "C": nothing to do. 7271 return false; 7272 } 7273 7274 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7275 // If the decl is already known invalid, don't check it. 7276 if (NewVD->isInvalidDecl()) 7277 return; 7278 7279 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 7280 QualType T = TInfo->getType(); 7281 7282 // Defer checking an 'auto' type until its initializer is attached. 7283 if (T->isUndeducedType()) 7284 return; 7285 7286 if (NewVD->hasAttrs()) 7287 CheckAlignasUnderalignment(NewVD); 7288 7289 if (T->isObjCObjectType()) { 7290 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7291 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7292 T = Context.getObjCObjectPointerType(T); 7293 NewVD->setType(T); 7294 } 7295 7296 // Emit an error if an address space was applied to decl with local storage. 7297 // This includes arrays of objects with address space qualifiers, but not 7298 // automatic variables that point to other address spaces. 7299 // ISO/IEC TR 18037 S5.1.2 7300 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7301 T.getAddressSpace() != LangAS::Default) { 7302 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7303 NewVD->setInvalidDecl(); 7304 return; 7305 } 7306 7307 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7308 // scope. 7309 if (getLangOpts().OpenCLVersion == 120 && 7310 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7311 NewVD->isStaticLocal()) { 7312 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7313 NewVD->setInvalidDecl(); 7314 return; 7315 } 7316 7317 if (getLangOpts().OpenCL) { 7318 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7319 if (NewVD->hasAttr<BlocksAttr>()) { 7320 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7321 return; 7322 } 7323 7324 if (T->isBlockPointerType()) { 7325 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7326 // can't use 'extern' storage class. 7327 if (!T.isConstQualified()) { 7328 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7329 << 0 /*const*/; 7330 NewVD->setInvalidDecl(); 7331 return; 7332 } 7333 if (NewVD->hasExternalStorage()) { 7334 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7335 NewVD->setInvalidDecl(); 7336 return; 7337 } 7338 } 7339 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 7340 // __constant address space. 7341 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 7342 // variables inside a function can also be declared in the global 7343 // address space. 7344 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7345 NewVD->hasExternalStorage()) { 7346 if (!T->isSamplerT() && 7347 !(T.getAddressSpace() == LangAS::opencl_constant || 7348 (T.getAddressSpace() == LangAS::opencl_global && 7349 getLangOpts().OpenCLVersion == 200))) { 7350 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7351 if (getLangOpts().OpenCLVersion == 200) 7352 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7353 << Scope << "global or constant"; 7354 else 7355 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7356 << Scope << "constant"; 7357 NewVD->setInvalidDecl(); 7358 return; 7359 } 7360 } else { 7361 if (T.getAddressSpace() == LangAS::opencl_global) { 7362 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7363 << 1 /*is any function*/ << "global"; 7364 NewVD->setInvalidDecl(); 7365 return; 7366 } 7367 if (T.getAddressSpace() == LangAS::opencl_constant || 7368 T.getAddressSpace() == LangAS::opencl_local) { 7369 FunctionDecl *FD = getCurFunctionDecl(); 7370 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7371 // in functions. 7372 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7373 if (T.getAddressSpace() == LangAS::opencl_constant) 7374 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7375 << 0 /*non-kernel only*/ << "constant"; 7376 else 7377 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7378 << 0 /*non-kernel only*/ << "local"; 7379 NewVD->setInvalidDecl(); 7380 return; 7381 } 7382 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7383 // in the outermost scope of a kernel function. 7384 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7385 if (!getCurScope()->isFunctionScope()) { 7386 if (T.getAddressSpace() == LangAS::opencl_constant) 7387 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7388 << "constant"; 7389 else 7390 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7391 << "local"; 7392 NewVD->setInvalidDecl(); 7393 return; 7394 } 7395 } 7396 } else if (T.getAddressSpace() != LangAS::opencl_private) { 7397 // Do not allow other address spaces on automatic variable. 7398 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7399 NewVD->setInvalidDecl(); 7400 return; 7401 } 7402 } 7403 } 7404 7405 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7406 && !NewVD->hasAttr<BlocksAttr>()) { 7407 if (getLangOpts().getGC() != LangOptions::NonGC) 7408 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7409 else { 7410 assert(!getLangOpts().ObjCAutoRefCount); 7411 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7412 } 7413 } 7414 7415 bool isVM = T->isVariablyModifiedType(); 7416 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7417 NewVD->hasAttr<BlocksAttr>()) 7418 setFunctionHasBranchProtectedScope(); 7419 7420 if ((isVM && NewVD->hasLinkage()) || 7421 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7422 bool SizeIsNegative; 7423 llvm::APSInt Oversized; 7424 TypeSourceInfo *FixedTInfo = 7425 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 7426 SizeIsNegative, Oversized); 7427 if (!FixedTInfo && T->isVariableArrayType()) { 7428 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7429 // FIXME: This won't give the correct result for 7430 // int a[10][n]; 7431 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7432 7433 if (NewVD->isFileVarDecl()) 7434 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7435 << SizeRange; 7436 else if (NewVD->isStaticLocal()) 7437 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7438 << SizeRange; 7439 else 7440 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7441 << SizeRange; 7442 NewVD->setInvalidDecl(); 7443 return; 7444 } 7445 7446 if (!FixedTInfo) { 7447 if (NewVD->isFileVarDecl()) 7448 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7449 else 7450 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7451 NewVD->setInvalidDecl(); 7452 return; 7453 } 7454 7455 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7456 NewVD->setType(FixedTInfo->getType()); 7457 NewVD->setTypeSourceInfo(FixedTInfo); 7458 } 7459 7460 if (T->isVoidType()) { 7461 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7462 // of objects and functions. 7463 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7464 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7465 << T; 7466 NewVD->setInvalidDecl(); 7467 return; 7468 } 7469 } 7470 7471 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7472 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7473 NewVD->setInvalidDecl(); 7474 return; 7475 } 7476 7477 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7478 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7479 NewVD->setInvalidDecl(); 7480 return; 7481 } 7482 7483 if (NewVD->isConstexpr() && !T->isDependentType() && 7484 RequireLiteralType(NewVD->getLocation(), T, 7485 diag::err_constexpr_var_non_literal)) { 7486 NewVD->setInvalidDecl(); 7487 return; 7488 } 7489 } 7490 7491 /// \brief Perform semantic checking on a newly-created variable 7492 /// declaration. 7493 /// 7494 /// This routine performs all of the type-checking required for a 7495 /// variable declaration once it has been built. It is used both to 7496 /// check variables after they have been parsed and their declarators 7497 /// have been translated into a declaration, and to check variables 7498 /// that have been instantiated from a template. 7499 /// 7500 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7501 /// 7502 /// Returns true if the variable declaration is a redeclaration. 7503 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7504 CheckVariableDeclarationType(NewVD); 7505 7506 // If the decl is already known invalid, don't check it. 7507 if (NewVD->isInvalidDecl()) 7508 return false; 7509 7510 // If we did not find anything by this name, look for a non-visible 7511 // extern "C" declaration with the same name. 7512 if (Previous.empty() && 7513 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7514 Previous.setShadowed(); 7515 7516 if (!Previous.empty()) { 7517 MergeVarDecl(NewVD, Previous); 7518 return true; 7519 } 7520 return false; 7521 } 7522 7523 namespace { 7524 struct FindOverriddenMethod { 7525 Sema *S; 7526 CXXMethodDecl *Method; 7527 7528 /// Member lookup function that determines whether a given C++ 7529 /// method overrides a method in a base class, to be used with 7530 /// CXXRecordDecl::lookupInBases(). 7531 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7532 RecordDecl *BaseRecord = 7533 Specifier->getType()->getAs<RecordType>()->getDecl(); 7534 7535 DeclarationName Name = Method->getDeclName(); 7536 7537 // FIXME: Do we care about other names here too? 7538 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7539 // We really want to find the base class destructor here. 7540 QualType T = S->Context.getTypeDeclType(BaseRecord); 7541 CanQualType CT = S->Context.getCanonicalType(T); 7542 7543 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 7544 } 7545 7546 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 7547 Path.Decls = Path.Decls.slice(1)) { 7548 NamedDecl *D = Path.Decls.front(); 7549 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 7550 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 7551 return true; 7552 } 7553 } 7554 7555 return false; 7556 } 7557 }; 7558 7559 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 7560 } // end anonymous namespace 7561 7562 /// \brief Report an error regarding overriding, along with any relevant 7563 /// overridden methods. 7564 /// 7565 /// \param DiagID the primary error to report. 7566 /// \param MD the overriding method. 7567 /// \param OEK which overrides to include as notes. 7568 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 7569 OverrideErrorKind OEK = OEK_All) { 7570 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 7571 for (const CXXMethodDecl *O : MD->overridden_methods()) { 7572 // This check (& the OEK parameter) could be replaced by a predicate, but 7573 // without lambdas that would be overkill. This is still nicer than writing 7574 // out the diag loop 3 times. 7575 if ((OEK == OEK_All) || 7576 (OEK == OEK_NonDeleted && !O->isDeleted()) || 7577 (OEK == OEK_Deleted && O->isDeleted())) 7578 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 7579 } 7580 } 7581 7582 /// AddOverriddenMethods - See if a method overrides any in the base classes, 7583 /// and if so, check that it's a valid override and remember it. 7584 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 7585 // Look for methods in base classes that this method might override. 7586 CXXBasePaths Paths; 7587 FindOverriddenMethod FOM; 7588 FOM.Method = MD; 7589 FOM.S = this; 7590 bool hasDeletedOverridenMethods = false; 7591 bool hasNonDeletedOverridenMethods = false; 7592 bool AddedAny = false; 7593 if (DC->lookupInBases(FOM, Paths)) { 7594 for (auto *I : Paths.found_decls()) { 7595 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 7596 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 7597 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 7598 !CheckOverridingFunctionAttributes(MD, OldMD) && 7599 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 7600 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 7601 hasDeletedOverridenMethods |= OldMD->isDeleted(); 7602 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 7603 AddedAny = true; 7604 } 7605 } 7606 } 7607 } 7608 7609 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 7610 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 7611 } 7612 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 7613 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 7614 } 7615 7616 return AddedAny; 7617 } 7618 7619 namespace { 7620 // Struct for holding all of the extra arguments needed by 7621 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 7622 struct ActOnFDArgs { 7623 Scope *S; 7624 Declarator &D; 7625 MultiTemplateParamsArg TemplateParamLists; 7626 bool AddToScope; 7627 }; 7628 } // end anonymous namespace 7629 7630 namespace { 7631 7632 // Callback to only accept typo corrections that have a non-zero edit distance. 7633 // Also only accept corrections that have the same parent decl. 7634 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 7635 public: 7636 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 7637 CXXRecordDecl *Parent) 7638 : Context(Context), OriginalFD(TypoFD), 7639 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 7640 7641 bool ValidateCandidate(const TypoCorrection &candidate) override { 7642 if (candidate.getEditDistance() == 0) 7643 return false; 7644 7645 SmallVector<unsigned, 1> MismatchedParams; 7646 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 7647 CDeclEnd = candidate.end(); 7648 CDecl != CDeclEnd; ++CDecl) { 7649 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7650 7651 if (FD && !FD->hasBody() && 7652 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 7653 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7654 CXXRecordDecl *Parent = MD->getParent(); 7655 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 7656 return true; 7657 } else if (!ExpectedParent) { 7658 return true; 7659 } 7660 } 7661 } 7662 7663 return false; 7664 } 7665 7666 private: 7667 ASTContext &Context; 7668 FunctionDecl *OriginalFD; 7669 CXXRecordDecl *ExpectedParent; 7670 }; 7671 7672 } // end anonymous namespace 7673 7674 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 7675 TypoCorrectedFunctionDefinitions.insert(F); 7676 } 7677 7678 /// \brief Generate diagnostics for an invalid function redeclaration. 7679 /// 7680 /// This routine handles generating the diagnostic messages for an invalid 7681 /// function redeclaration, including finding possible similar declarations 7682 /// or performing typo correction if there are no previous declarations with 7683 /// the same name. 7684 /// 7685 /// Returns a NamedDecl iff typo correction was performed and substituting in 7686 /// the new declaration name does not cause new errors. 7687 static NamedDecl *DiagnoseInvalidRedeclaration( 7688 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 7689 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 7690 DeclarationName Name = NewFD->getDeclName(); 7691 DeclContext *NewDC = NewFD->getDeclContext(); 7692 SmallVector<unsigned, 1> MismatchedParams; 7693 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 7694 TypoCorrection Correction; 7695 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 7696 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 7697 : diag::err_member_decl_does_not_match; 7698 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 7699 IsLocalFriend ? Sema::LookupLocalFriendName 7700 : Sema::LookupOrdinaryName, 7701 Sema::ForVisibleRedeclaration); 7702 7703 NewFD->setInvalidDecl(); 7704 if (IsLocalFriend) 7705 SemaRef.LookupName(Prev, S); 7706 else 7707 SemaRef.LookupQualifiedName(Prev, NewDC); 7708 assert(!Prev.isAmbiguous() && 7709 "Cannot have an ambiguity in previous-declaration lookup"); 7710 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7711 if (!Prev.empty()) { 7712 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 7713 Func != FuncEnd; ++Func) { 7714 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 7715 if (FD && 7716 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7717 // Add 1 to the index so that 0 can mean the mismatch didn't 7718 // involve a parameter 7719 unsigned ParamNum = 7720 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 7721 NearMatches.push_back(std::make_pair(FD, ParamNum)); 7722 } 7723 } 7724 // If the qualified name lookup yielded nothing, try typo correction 7725 } else if ((Correction = SemaRef.CorrectTypo( 7726 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 7727 &ExtraArgs.D.getCXXScopeSpec(), 7728 llvm::make_unique<DifferentNameValidatorCCC>( 7729 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 7730 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 7731 // Set up everything for the call to ActOnFunctionDeclarator 7732 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 7733 ExtraArgs.D.getIdentifierLoc()); 7734 Previous.clear(); 7735 Previous.setLookupName(Correction.getCorrection()); 7736 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 7737 CDeclEnd = Correction.end(); 7738 CDecl != CDeclEnd; ++CDecl) { 7739 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 7740 if (FD && !FD->hasBody() && 7741 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 7742 Previous.addDecl(FD); 7743 } 7744 } 7745 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 7746 7747 NamedDecl *Result; 7748 // Retry building the function declaration with the new previous 7749 // declarations, and with errors suppressed. 7750 { 7751 // Trap errors. 7752 Sema::SFINAETrap Trap(SemaRef); 7753 7754 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 7755 // pieces need to verify the typo-corrected C++ declaration and hopefully 7756 // eliminate the need for the parameter pack ExtraArgs. 7757 Result = SemaRef.ActOnFunctionDeclarator( 7758 ExtraArgs.S, ExtraArgs.D, 7759 Correction.getCorrectionDecl()->getDeclContext(), 7760 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 7761 ExtraArgs.AddToScope); 7762 7763 if (Trap.hasErrorOccurred()) 7764 Result = nullptr; 7765 } 7766 7767 if (Result) { 7768 // Determine which correction we picked. 7769 Decl *Canonical = Result->getCanonicalDecl(); 7770 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7771 I != E; ++I) 7772 if ((*I)->getCanonicalDecl() == Canonical) 7773 Correction.setCorrectionDecl(*I); 7774 7775 // Let Sema know about the correction. 7776 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 7777 SemaRef.diagnoseTypo( 7778 Correction, 7779 SemaRef.PDiag(IsLocalFriend 7780 ? diag::err_no_matching_local_friend_suggest 7781 : diag::err_member_decl_does_not_match_suggest) 7782 << Name << NewDC << IsDefinition); 7783 return Result; 7784 } 7785 7786 // Pretend the typo correction never occurred 7787 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 7788 ExtraArgs.D.getIdentifierLoc()); 7789 ExtraArgs.D.setRedeclaration(wasRedeclaration); 7790 Previous.clear(); 7791 Previous.setLookupName(Name); 7792 } 7793 7794 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 7795 << Name << NewDC << IsDefinition << NewFD->getLocation(); 7796 7797 bool NewFDisConst = false; 7798 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 7799 NewFDisConst = NewMD->isConst(); 7800 7801 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 7802 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 7803 NearMatch != NearMatchEnd; ++NearMatch) { 7804 FunctionDecl *FD = NearMatch->first; 7805 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 7806 bool FDisConst = MD && MD->isConst(); 7807 bool IsMember = MD || !IsLocalFriend; 7808 7809 // FIXME: These notes are poorly worded for the local friend case. 7810 if (unsigned Idx = NearMatch->second) { 7811 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 7812 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 7813 if (Loc.isInvalid()) Loc = FD->getLocation(); 7814 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 7815 : diag::note_local_decl_close_param_match) 7816 << Idx << FDParam->getType() 7817 << NewFD->getParamDecl(Idx - 1)->getType(); 7818 } else if (FDisConst != NewFDisConst) { 7819 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 7820 << NewFDisConst << FD->getSourceRange().getEnd(); 7821 } else 7822 SemaRef.Diag(FD->getLocation(), 7823 IsMember ? diag::note_member_def_close_match 7824 : diag::note_local_decl_close_match); 7825 } 7826 return nullptr; 7827 } 7828 7829 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 7830 switch (D.getDeclSpec().getStorageClassSpec()) { 7831 default: llvm_unreachable("Unknown storage class!"); 7832 case DeclSpec::SCS_auto: 7833 case DeclSpec::SCS_register: 7834 case DeclSpec::SCS_mutable: 7835 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7836 diag::err_typecheck_sclass_func); 7837 D.getMutableDeclSpec().ClearStorageClassSpecs(); 7838 D.setInvalidType(); 7839 break; 7840 case DeclSpec::SCS_unspecified: break; 7841 case DeclSpec::SCS_extern: 7842 if (D.getDeclSpec().isExternInLinkageSpec()) 7843 return SC_None; 7844 return SC_Extern; 7845 case DeclSpec::SCS_static: { 7846 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 7847 // C99 6.7.1p5: 7848 // The declaration of an identifier for a function that has 7849 // block scope shall have no explicit storage-class specifier 7850 // other than extern 7851 // See also (C++ [dcl.stc]p4). 7852 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7853 diag::err_static_block_func); 7854 break; 7855 } else 7856 return SC_Static; 7857 } 7858 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 7859 } 7860 7861 // No explicit storage class has already been returned 7862 return SC_None; 7863 } 7864 7865 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 7866 DeclContext *DC, QualType &R, 7867 TypeSourceInfo *TInfo, 7868 StorageClass SC, 7869 bool &IsVirtualOkay) { 7870 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7871 DeclarationName Name = NameInfo.getName(); 7872 7873 FunctionDecl *NewFD = nullptr; 7874 bool isInline = D.getDeclSpec().isInlineSpecified(); 7875 7876 if (!SemaRef.getLangOpts().CPlusPlus) { 7877 // Determine whether the function was written with a 7878 // prototype. This true when: 7879 // - there is a prototype in the declarator, or 7880 // - the type R of the function is some kind of typedef or other non- 7881 // attributed reference to a type name (which eventually refers to a 7882 // function type). 7883 bool HasPrototype = 7884 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7885 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 7886 7887 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7888 D.getLocStart(), NameInfo, R, 7889 TInfo, SC, isInline, 7890 HasPrototype, false); 7891 if (D.isInvalidType()) 7892 NewFD->setInvalidDecl(); 7893 7894 return NewFD; 7895 } 7896 7897 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7898 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7899 7900 // Check that the return type is not an abstract class type. 7901 // For record types, this is done by the AbstractClassUsageDiagnoser once 7902 // the class has been completely parsed. 7903 if (!DC->isRecord() && 7904 SemaRef.RequireNonAbstractType( 7905 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7906 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7907 D.setInvalidType(); 7908 7909 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7910 // This is a C++ constructor declaration. 7911 assert(DC->isRecord() && 7912 "Constructors can only be declared in a member context"); 7913 7914 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7915 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7916 D.getLocStart(), NameInfo, 7917 R, TInfo, isExplicit, isInline, 7918 /*isImplicitlyDeclared=*/false, 7919 isConstexpr); 7920 7921 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7922 // This is a C++ destructor declaration. 7923 if (DC->isRecord()) { 7924 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7925 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7926 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7927 SemaRef.Context, Record, 7928 D.getLocStart(), 7929 NameInfo, R, TInfo, isInline, 7930 /*isImplicitlyDeclared=*/false); 7931 7932 // If the class is complete, then we now create the implicit exception 7933 // specification. If the class is incomplete or dependent, we can't do 7934 // it yet. 7935 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7936 Record->getDefinition() && !Record->isBeingDefined() && 7937 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7938 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7939 } 7940 7941 IsVirtualOkay = true; 7942 return NewDD; 7943 7944 } else { 7945 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7946 D.setInvalidType(); 7947 7948 // Create a FunctionDecl to satisfy the function definition parsing 7949 // code path. 7950 return FunctionDecl::Create(SemaRef.Context, DC, 7951 D.getLocStart(), 7952 D.getIdentifierLoc(), Name, R, TInfo, 7953 SC, isInline, 7954 /*hasPrototype=*/true, isConstexpr); 7955 } 7956 7957 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7958 if (!DC->isRecord()) { 7959 SemaRef.Diag(D.getIdentifierLoc(), 7960 diag::err_conv_function_not_member); 7961 return nullptr; 7962 } 7963 7964 SemaRef.CheckConversionDeclarator(D, R, SC); 7965 IsVirtualOkay = true; 7966 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7967 D.getLocStart(), NameInfo, 7968 R, TInfo, isInline, isExplicit, 7969 isConstexpr, SourceLocation()); 7970 7971 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 7972 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 7973 7974 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(), 7975 isExplicit, NameInfo, R, TInfo, 7976 D.getLocEnd()); 7977 } else if (DC->isRecord()) { 7978 // If the name of the function is the same as the name of the record, 7979 // then this must be an invalid constructor that has a return type. 7980 // (The parser checks for a return type and makes the declarator a 7981 // constructor if it has no return type). 7982 if (Name.getAsIdentifierInfo() && 7983 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7984 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7985 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7986 << SourceRange(D.getIdentifierLoc()); 7987 return nullptr; 7988 } 7989 7990 // This is a C++ method declaration. 7991 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7992 cast<CXXRecordDecl>(DC), 7993 D.getLocStart(), NameInfo, R, 7994 TInfo, SC, isInline, 7995 isConstexpr, SourceLocation()); 7996 IsVirtualOkay = !Ret->isStatic(); 7997 return Ret; 7998 } else { 7999 bool isFriend = 8000 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8001 if (!isFriend && SemaRef.CurContext->isRecord()) 8002 return nullptr; 8003 8004 // Determine whether the function was written with a 8005 // prototype. This true when: 8006 // - we're in C++ (where every function has a prototype), 8007 return FunctionDecl::Create(SemaRef.Context, DC, 8008 D.getLocStart(), 8009 NameInfo, R, TInfo, SC, isInline, 8010 true/*HasPrototype*/, isConstexpr); 8011 } 8012 } 8013 8014 enum OpenCLParamType { 8015 ValidKernelParam, 8016 PtrPtrKernelParam, 8017 PtrKernelParam, 8018 InvalidAddrSpacePtrKernelParam, 8019 InvalidKernelParam, 8020 RecordKernelParam 8021 }; 8022 8023 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8024 if (PT->isPointerType()) { 8025 QualType PointeeType = PT->getPointeeType(); 8026 if (PointeeType->isPointerType()) 8027 return PtrPtrKernelParam; 8028 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8029 PointeeType.getAddressSpace() == LangAS::opencl_private || 8030 PointeeType.getAddressSpace() == LangAS::Default) 8031 return InvalidAddrSpacePtrKernelParam; 8032 return PtrKernelParam; 8033 } 8034 8035 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 8036 // be used as builtin types. 8037 8038 if (PT->isImageType()) 8039 return PtrKernelParam; 8040 8041 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8042 return InvalidKernelParam; 8043 8044 // OpenCL extension spec v1.2 s9.5: 8045 // This extension adds support for half scalar and vector types as built-in 8046 // types that can be used for arithmetic operations, conversions etc. 8047 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8048 return InvalidKernelParam; 8049 8050 if (PT->isRecordType()) 8051 return RecordKernelParam; 8052 8053 return ValidKernelParam; 8054 } 8055 8056 static void checkIsValidOpenCLKernelParameter( 8057 Sema &S, 8058 Declarator &D, 8059 ParmVarDecl *Param, 8060 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8061 QualType PT = Param->getType(); 8062 8063 // Cache the valid types we encounter to avoid rechecking structs that are 8064 // used again 8065 if (ValidTypes.count(PT.getTypePtr())) 8066 return; 8067 8068 switch (getOpenCLKernelParameterType(S, PT)) { 8069 case PtrPtrKernelParam: 8070 // OpenCL v1.2 s6.9.a: 8071 // A kernel function argument cannot be declared as a 8072 // pointer to a pointer type. 8073 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8074 D.setInvalidType(); 8075 return; 8076 8077 case InvalidAddrSpacePtrKernelParam: 8078 // OpenCL v1.0 s6.5: 8079 // __kernel function arguments declared to be a pointer of a type can point 8080 // to one of the following address spaces only : __global, __local or 8081 // __constant. 8082 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8083 D.setInvalidType(); 8084 return; 8085 8086 // OpenCL v1.2 s6.9.k: 8087 // Arguments to kernel functions in a program cannot be declared with the 8088 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8089 // uintptr_t or a struct and/or union that contain fields declared to be 8090 // one of these built-in scalar types. 8091 8092 case InvalidKernelParam: 8093 // OpenCL v1.2 s6.8 n: 8094 // A kernel function argument cannot be declared 8095 // of event_t type. 8096 // Do not diagnose half type since it is diagnosed as invalid argument 8097 // type for any function elsewhere. 8098 if (!PT->isHalfType()) 8099 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8100 D.setInvalidType(); 8101 return; 8102 8103 case PtrKernelParam: 8104 case ValidKernelParam: 8105 ValidTypes.insert(PT.getTypePtr()); 8106 return; 8107 8108 case RecordKernelParam: 8109 break; 8110 } 8111 8112 // Track nested structs we will inspect 8113 SmallVector<const Decl *, 4> VisitStack; 8114 8115 // Track where we are in the nested structs. Items will migrate from 8116 // VisitStack to HistoryStack as we do the DFS for bad field. 8117 SmallVector<const FieldDecl *, 4> HistoryStack; 8118 HistoryStack.push_back(nullptr); 8119 8120 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 8121 VisitStack.push_back(PD); 8122 8123 assert(VisitStack.back() && "First decl null?"); 8124 8125 do { 8126 const Decl *Next = VisitStack.pop_back_val(); 8127 if (!Next) { 8128 assert(!HistoryStack.empty()); 8129 // Found a marker, we have gone up a level 8130 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8131 ValidTypes.insert(Hist->getType().getTypePtr()); 8132 8133 continue; 8134 } 8135 8136 // Adds everything except the original parameter declaration (which is not a 8137 // field itself) to the history stack. 8138 const RecordDecl *RD; 8139 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8140 HistoryStack.push_back(Field); 8141 RD = Field->getType()->castAs<RecordType>()->getDecl(); 8142 } else { 8143 RD = cast<RecordDecl>(Next); 8144 } 8145 8146 // Add a null marker so we know when we've gone back up a level 8147 VisitStack.push_back(nullptr); 8148 8149 for (const auto *FD : RD->fields()) { 8150 QualType QT = FD->getType(); 8151 8152 if (ValidTypes.count(QT.getTypePtr())) 8153 continue; 8154 8155 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8156 if (ParamType == ValidKernelParam) 8157 continue; 8158 8159 if (ParamType == RecordKernelParam) { 8160 VisitStack.push_back(FD); 8161 continue; 8162 } 8163 8164 // OpenCL v1.2 s6.9.p: 8165 // Arguments to kernel functions that are declared to be a struct or union 8166 // do not allow OpenCL objects to be passed as elements of the struct or 8167 // union. 8168 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8169 ParamType == InvalidAddrSpacePtrKernelParam) { 8170 S.Diag(Param->getLocation(), 8171 diag::err_record_with_pointers_kernel_param) 8172 << PT->isUnionType() 8173 << PT; 8174 } else { 8175 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8176 } 8177 8178 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 8179 << PD->getDeclName(); 8180 8181 // We have an error, now let's go back up through history and show where 8182 // the offending field came from 8183 for (ArrayRef<const FieldDecl *>::const_iterator 8184 I = HistoryStack.begin() + 1, 8185 E = HistoryStack.end(); 8186 I != E; ++I) { 8187 const FieldDecl *OuterField = *I; 8188 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8189 << OuterField->getType(); 8190 } 8191 8192 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8193 << QT->isPointerType() 8194 << QT; 8195 D.setInvalidType(); 8196 return; 8197 } 8198 } while (!VisitStack.empty()); 8199 } 8200 8201 /// Find the DeclContext in which a tag is implicitly declared if we see an 8202 /// elaborated type specifier in the specified context, and lookup finds 8203 /// nothing. 8204 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8205 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8206 DC = DC->getParent(); 8207 return DC; 8208 } 8209 8210 /// Find the Scope in which a tag is implicitly declared if we see an 8211 /// elaborated type specifier in the specified context, and lookup finds 8212 /// nothing. 8213 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8214 while (S->isClassScope() || 8215 (LangOpts.CPlusPlus && 8216 S->isFunctionPrototypeScope()) || 8217 ((S->getFlags() & Scope::DeclScope) == 0) || 8218 (S->getEntity() && S->getEntity()->isTransparentContext())) 8219 S = S->getParent(); 8220 return S; 8221 } 8222 8223 NamedDecl* 8224 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8225 TypeSourceInfo *TInfo, LookupResult &Previous, 8226 MultiTemplateParamsArg TemplateParamLists, 8227 bool &AddToScope) { 8228 QualType R = TInfo->getType(); 8229 8230 assert(R.getTypePtr()->isFunctionType()); 8231 8232 // TODO: consider using NameInfo for diagnostic. 8233 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8234 DeclarationName Name = NameInfo.getName(); 8235 StorageClass SC = getFunctionStorageClass(*this, D); 8236 8237 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8238 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8239 diag::err_invalid_thread) 8240 << DeclSpec::getSpecifierName(TSCS); 8241 8242 if (D.isFirstDeclarationOfMember()) 8243 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8244 D.getIdentifierLoc()); 8245 8246 bool isFriend = false; 8247 FunctionTemplateDecl *FunctionTemplate = nullptr; 8248 bool isMemberSpecialization = false; 8249 bool isFunctionTemplateSpecialization = false; 8250 8251 bool isDependentClassScopeExplicitSpecialization = false; 8252 bool HasExplicitTemplateArgs = false; 8253 TemplateArgumentListInfo TemplateArgs; 8254 8255 bool isVirtualOkay = false; 8256 8257 DeclContext *OriginalDC = DC; 8258 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8259 8260 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8261 isVirtualOkay); 8262 if (!NewFD) return nullptr; 8263 8264 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8265 NewFD->setTopLevelDeclInObjCContainer(); 8266 8267 // Set the lexical context. If this is a function-scope declaration, or has a 8268 // C++ scope specifier, or is the object of a friend declaration, the lexical 8269 // context will be different from the semantic context. 8270 NewFD->setLexicalDeclContext(CurContext); 8271 8272 if (IsLocalExternDecl) 8273 NewFD->setLocalExternDecl(); 8274 8275 if (getLangOpts().CPlusPlus) { 8276 bool isInline = D.getDeclSpec().isInlineSpecified(); 8277 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8278 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 8279 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 8280 isFriend = D.getDeclSpec().isFriendSpecified(); 8281 if (isFriend && !isInline && D.isFunctionDefinition()) { 8282 // C++ [class.friend]p5 8283 // A function can be defined in a friend declaration of a 8284 // class . . . . Such a function is implicitly inline. 8285 NewFD->setImplicitlyInline(); 8286 } 8287 8288 // If this is a method defined in an __interface, and is not a constructor 8289 // or an overloaded operator, then set the pure flag (isVirtual will already 8290 // return true). 8291 if (const CXXRecordDecl *Parent = 8292 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8293 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8294 NewFD->setPure(true); 8295 8296 // C++ [class.union]p2 8297 // A union can have member functions, but not virtual functions. 8298 if (isVirtual && Parent->isUnion()) 8299 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8300 } 8301 8302 SetNestedNameSpecifier(NewFD, D); 8303 isMemberSpecialization = false; 8304 isFunctionTemplateSpecialization = false; 8305 if (D.isInvalidType()) 8306 NewFD->setInvalidDecl(); 8307 8308 // Match up the template parameter lists with the scope specifier, then 8309 // determine whether we have a template or a template specialization. 8310 bool Invalid = false; 8311 if (TemplateParameterList *TemplateParams = 8312 MatchTemplateParametersToScopeSpecifier( 8313 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 8314 D.getCXXScopeSpec(), 8315 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8316 ? D.getName().TemplateId 8317 : nullptr, 8318 TemplateParamLists, isFriend, isMemberSpecialization, 8319 Invalid)) { 8320 if (TemplateParams->size() > 0) { 8321 // This is a function template 8322 8323 // Check that we can declare a template here. 8324 if (CheckTemplateDeclScope(S, TemplateParams)) 8325 NewFD->setInvalidDecl(); 8326 8327 // A destructor cannot be a template. 8328 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8329 Diag(NewFD->getLocation(), diag::err_destructor_template); 8330 NewFD->setInvalidDecl(); 8331 } 8332 8333 // If we're adding a template to a dependent context, we may need to 8334 // rebuilding some of the types used within the template parameter list, 8335 // now that we know what the current instantiation is. 8336 if (DC->isDependentContext()) { 8337 ContextRAII SavedContext(*this, DC); 8338 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8339 Invalid = true; 8340 } 8341 8342 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8343 NewFD->getLocation(), 8344 Name, TemplateParams, 8345 NewFD); 8346 FunctionTemplate->setLexicalDeclContext(CurContext); 8347 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8348 8349 // For source fidelity, store the other template param lists. 8350 if (TemplateParamLists.size() > 1) { 8351 NewFD->setTemplateParameterListsInfo(Context, 8352 TemplateParamLists.drop_back(1)); 8353 } 8354 } else { 8355 // This is a function template specialization. 8356 isFunctionTemplateSpecialization = true; 8357 // For source fidelity, store all the template param lists. 8358 if (TemplateParamLists.size() > 0) 8359 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8360 8361 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8362 if (isFriend) { 8363 // We want to remove the "template<>", found here. 8364 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8365 8366 // If we remove the template<> and the name is not a 8367 // template-id, we're actually silently creating a problem: 8368 // the friend declaration will refer to an untemplated decl, 8369 // and clearly the user wants a template specialization. So 8370 // we need to insert '<>' after the name. 8371 SourceLocation InsertLoc; 8372 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8373 InsertLoc = D.getName().getSourceRange().getEnd(); 8374 InsertLoc = getLocForEndOfToken(InsertLoc); 8375 } 8376 8377 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8378 << Name << RemoveRange 8379 << FixItHint::CreateRemoval(RemoveRange) 8380 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8381 } 8382 } 8383 } 8384 else { 8385 // All template param lists were matched against the scope specifier: 8386 // this is NOT (an explicit specialization of) a template. 8387 if (TemplateParamLists.size() > 0) 8388 // For source fidelity, store all the template param lists. 8389 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8390 } 8391 8392 if (Invalid) { 8393 NewFD->setInvalidDecl(); 8394 if (FunctionTemplate) 8395 FunctionTemplate->setInvalidDecl(); 8396 } 8397 8398 // C++ [dcl.fct.spec]p5: 8399 // The virtual specifier shall only be used in declarations of 8400 // nonstatic class member functions that appear within a 8401 // member-specification of a class declaration; see 10.3. 8402 // 8403 if (isVirtual && !NewFD->isInvalidDecl()) { 8404 if (!isVirtualOkay) { 8405 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8406 diag::err_virtual_non_function); 8407 } else if (!CurContext->isRecord()) { 8408 // 'virtual' was specified outside of the class. 8409 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8410 diag::err_virtual_out_of_class) 8411 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8412 } else if (NewFD->getDescribedFunctionTemplate()) { 8413 // C++ [temp.mem]p3: 8414 // A member function template shall not be virtual. 8415 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8416 diag::err_virtual_member_function_template) 8417 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8418 } else { 8419 // Okay: Add virtual to the method. 8420 NewFD->setVirtualAsWritten(true); 8421 } 8422 8423 if (getLangOpts().CPlusPlus14 && 8424 NewFD->getReturnType()->isUndeducedType()) 8425 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8426 } 8427 8428 if (getLangOpts().CPlusPlus14 && 8429 (NewFD->isDependentContext() || 8430 (isFriend && CurContext->isDependentContext())) && 8431 NewFD->getReturnType()->isUndeducedType()) { 8432 // If the function template is referenced directly (for instance, as a 8433 // member of the current instantiation), pretend it has a dependent type. 8434 // This is not really justified by the standard, but is the only sane 8435 // thing to do. 8436 // FIXME: For a friend function, we have not marked the function as being 8437 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8438 const FunctionProtoType *FPT = 8439 NewFD->getType()->castAs<FunctionProtoType>(); 8440 QualType Result = 8441 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 8442 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 8443 FPT->getExtProtoInfo())); 8444 } 8445 8446 // C++ [dcl.fct.spec]p3: 8447 // The inline specifier shall not appear on a block scope function 8448 // declaration. 8449 if (isInline && !NewFD->isInvalidDecl()) { 8450 if (CurContext->isFunctionOrMethod()) { 8451 // 'inline' is not allowed on block scope function declaration. 8452 Diag(D.getDeclSpec().getInlineSpecLoc(), 8453 diag::err_inline_declaration_block_scope) << Name 8454 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 8455 } 8456 } 8457 8458 // C++ [dcl.fct.spec]p6: 8459 // The explicit specifier shall be used only in the declaration of a 8460 // constructor or conversion function within its class definition; 8461 // see 12.3.1 and 12.3.2. 8462 if (isExplicit && !NewFD->isInvalidDecl() && 8463 !isa<CXXDeductionGuideDecl>(NewFD)) { 8464 if (!CurContext->isRecord()) { 8465 // 'explicit' was specified outside of the class. 8466 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8467 diag::err_explicit_out_of_class) 8468 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8469 } else if (!isa<CXXConstructorDecl>(NewFD) && 8470 !isa<CXXConversionDecl>(NewFD)) { 8471 // 'explicit' was specified on a function that wasn't a constructor 8472 // or conversion function. 8473 Diag(D.getDeclSpec().getExplicitSpecLoc(), 8474 diag::err_explicit_non_ctor_or_conv_function) 8475 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 8476 } 8477 } 8478 8479 if (isConstexpr) { 8480 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 8481 // are implicitly inline. 8482 NewFD->setImplicitlyInline(); 8483 8484 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 8485 // be either constructors or to return a literal type. Therefore, 8486 // destructors cannot be declared constexpr. 8487 if (isa<CXXDestructorDecl>(NewFD)) 8488 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 8489 } 8490 8491 // If __module_private__ was specified, mark the function accordingly. 8492 if (D.getDeclSpec().isModulePrivateSpecified()) { 8493 if (isFunctionTemplateSpecialization) { 8494 SourceLocation ModulePrivateLoc 8495 = D.getDeclSpec().getModulePrivateSpecLoc(); 8496 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 8497 << 0 8498 << FixItHint::CreateRemoval(ModulePrivateLoc); 8499 } else { 8500 NewFD->setModulePrivate(); 8501 if (FunctionTemplate) 8502 FunctionTemplate->setModulePrivate(); 8503 } 8504 } 8505 8506 if (isFriend) { 8507 if (FunctionTemplate) { 8508 FunctionTemplate->setObjectOfFriendDecl(); 8509 FunctionTemplate->setAccess(AS_public); 8510 } 8511 NewFD->setObjectOfFriendDecl(); 8512 NewFD->setAccess(AS_public); 8513 } 8514 8515 // If a function is defined as defaulted or deleted, mark it as such now. 8516 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 8517 // definition kind to FDK_Definition. 8518 switch (D.getFunctionDefinitionKind()) { 8519 case FDK_Declaration: 8520 case FDK_Definition: 8521 break; 8522 8523 case FDK_Defaulted: 8524 NewFD->setDefaulted(); 8525 break; 8526 8527 case FDK_Deleted: 8528 NewFD->setDeletedAsWritten(); 8529 break; 8530 } 8531 8532 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 8533 D.isFunctionDefinition()) { 8534 // C++ [class.mfct]p2: 8535 // A member function may be defined (8.4) in its class definition, in 8536 // which case it is an inline member function (7.1.2) 8537 NewFD->setImplicitlyInline(); 8538 } 8539 8540 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 8541 !CurContext->isRecord()) { 8542 // C++ [class.static]p1: 8543 // A data or function member of a class may be declared static 8544 // in a class definition, in which case it is a static member of 8545 // the class. 8546 8547 // Complain about the 'static' specifier if it's on an out-of-line 8548 // member function definition. 8549 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8550 diag::err_static_out_of_line) 8551 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 8552 } 8553 8554 // C++11 [except.spec]p15: 8555 // A deallocation function with no exception-specification is treated 8556 // as if it were specified with noexcept(true). 8557 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 8558 if ((Name.getCXXOverloadedOperator() == OO_Delete || 8559 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 8560 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 8561 NewFD->setType(Context.getFunctionType( 8562 FPT->getReturnType(), FPT->getParamTypes(), 8563 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 8564 } 8565 8566 // Filter out previous declarations that don't match the scope. 8567 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 8568 D.getCXXScopeSpec().isNotEmpty() || 8569 isMemberSpecialization || 8570 isFunctionTemplateSpecialization); 8571 8572 // Handle GNU asm-label extension (encoded as an attribute). 8573 if (Expr *E = (Expr*) D.getAsmLabel()) { 8574 // The parser guarantees this is a string. 8575 StringLiteral *SE = cast<StringLiteral>(E); 8576 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 8577 SE->getString(), 0)); 8578 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 8579 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 8580 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 8581 if (I != ExtnameUndeclaredIdentifiers.end()) { 8582 if (isDeclExternC(NewFD)) { 8583 NewFD->addAttr(I->second); 8584 ExtnameUndeclaredIdentifiers.erase(I); 8585 } else 8586 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 8587 << /*Variable*/0 << NewFD; 8588 } 8589 } 8590 8591 // Copy the parameter declarations from the declarator D to the function 8592 // declaration NewFD, if they are available. First scavenge them into Params. 8593 SmallVector<ParmVarDecl*, 16> Params; 8594 unsigned FTIIdx; 8595 if (D.isFunctionDeclarator(FTIIdx)) { 8596 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 8597 8598 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 8599 // function that takes no arguments, not a function that takes a 8600 // single void argument. 8601 // We let through "const void" here because Sema::GetTypeForDeclarator 8602 // already checks for that case. 8603 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 8604 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 8605 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 8606 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 8607 Param->setDeclContext(NewFD); 8608 Params.push_back(Param); 8609 8610 if (Param->isInvalidDecl()) 8611 NewFD->setInvalidDecl(); 8612 } 8613 } 8614 8615 if (!getLangOpts().CPlusPlus) { 8616 // In C, find all the tag declarations from the prototype and move them 8617 // into the function DeclContext. Remove them from the surrounding tag 8618 // injection context of the function, which is typically but not always 8619 // the TU. 8620 DeclContext *PrototypeTagContext = 8621 getTagInjectionContext(NewFD->getLexicalDeclContext()); 8622 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 8623 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 8624 8625 // We don't want to reparent enumerators. Look at their parent enum 8626 // instead. 8627 if (!TD) { 8628 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 8629 TD = cast<EnumDecl>(ECD->getDeclContext()); 8630 } 8631 if (!TD) 8632 continue; 8633 DeclContext *TagDC = TD->getLexicalDeclContext(); 8634 if (!TagDC->containsDecl(TD)) 8635 continue; 8636 TagDC->removeDecl(TD); 8637 TD->setDeclContext(NewFD); 8638 NewFD->addDecl(TD); 8639 8640 // Preserve the lexical DeclContext if it is not the surrounding tag 8641 // injection context of the FD. In this example, the semantic context of 8642 // E will be f and the lexical context will be S, while both the 8643 // semantic and lexical contexts of S will be f: 8644 // void f(struct S { enum E { a } f; } s); 8645 if (TagDC != PrototypeTagContext) 8646 TD->setLexicalDeclContext(TagDC); 8647 } 8648 } 8649 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 8650 // When we're declaring a function with a typedef, typeof, etc as in the 8651 // following example, we'll need to synthesize (unnamed) 8652 // parameters for use in the declaration. 8653 // 8654 // @code 8655 // typedef void fn(int); 8656 // fn f; 8657 // @endcode 8658 8659 // Synthesize a parameter for each argument type. 8660 for (const auto &AI : FT->param_types()) { 8661 ParmVarDecl *Param = 8662 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 8663 Param->setScopeInfo(0, Params.size()); 8664 Params.push_back(Param); 8665 } 8666 } else { 8667 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 8668 "Should not need args for typedef of non-prototype fn"); 8669 } 8670 8671 // Finally, we know we have the right number of parameters, install them. 8672 NewFD->setParams(Params); 8673 8674 if (D.getDeclSpec().isNoreturnSpecified()) 8675 NewFD->addAttr( 8676 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 8677 Context, 0)); 8678 8679 // Functions returning a variably modified type violate C99 6.7.5.2p2 8680 // because all functions have linkage. 8681 if (!NewFD->isInvalidDecl() && 8682 NewFD->getReturnType()->isVariablyModifiedType()) { 8683 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 8684 NewFD->setInvalidDecl(); 8685 } 8686 8687 // Apply an implicit SectionAttr if '#pragma clang section text' is active 8688 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 8689 !NewFD->hasAttr<SectionAttr>()) { 8690 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context, 8691 PragmaClangTextSection.SectionName, 8692 PragmaClangTextSection.PragmaLocation)); 8693 } 8694 8695 // Apply an implicit SectionAttr if #pragma code_seg is active. 8696 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 8697 !NewFD->hasAttr<SectionAttr>()) { 8698 NewFD->addAttr( 8699 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 8700 CodeSegStack.CurrentValue->getString(), 8701 CodeSegStack.CurrentPragmaLocation)); 8702 if (UnifySection(CodeSegStack.CurrentValue->getString(), 8703 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 8704 ASTContext::PSF_Read, 8705 NewFD)) 8706 NewFD->dropAttr<SectionAttr>(); 8707 } 8708 8709 // Handle attributes. 8710 ProcessDeclAttributes(S, NewFD, D); 8711 8712 if (getLangOpts().OpenCL) { 8713 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 8714 // type declaration will generate a compilation error. 8715 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 8716 if (AddressSpace != LangAS::Default) { 8717 Diag(NewFD->getLocation(), 8718 diag::err_opencl_return_value_with_address_space); 8719 NewFD->setInvalidDecl(); 8720 } 8721 } 8722 8723 if (!getLangOpts().CPlusPlus) { 8724 // Perform semantic checking on the function declaration. 8725 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8726 CheckMain(NewFD, D.getDeclSpec()); 8727 8728 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8729 CheckMSVCRTEntryPoint(NewFD); 8730 8731 if (!NewFD->isInvalidDecl()) 8732 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8733 isMemberSpecialization)); 8734 else if (!Previous.empty()) 8735 // Recover gracefully from an invalid redeclaration. 8736 D.setRedeclaration(true); 8737 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8738 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8739 "previous declaration set still overloaded"); 8740 8741 // Diagnose no-prototype function declarations with calling conventions that 8742 // don't support variadic calls. Only do this in C and do it after merging 8743 // possibly prototyped redeclarations. 8744 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 8745 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 8746 CallingConv CC = FT->getExtInfo().getCC(); 8747 if (!supportsVariadicCall(CC)) { 8748 // Windows system headers sometimes accidentally use stdcall without 8749 // (void) parameters, so we relax this to a warning. 8750 int DiagID = 8751 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 8752 Diag(NewFD->getLocation(), DiagID) 8753 << FunctionType::getNameForCallConv(CC); 8754 } 8755 } 8756 } else { 8757 // C++11 [replacement.functions]p3: 8758 // The program's definitions shall not be specified as inline. 8759 // 8760 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 8761 // 8762 // Suppress the diagnostic if the function is __attribute__((used)), since 8763 // that forces an external definition to be emitted. 8764 if (D.getDeclSpec().isInlineSpecified() && 8765 NewFD->isReplaceableGlobalAllocationFunction() && 8766 !NewFD->hasAttr<UsedAttr>()) 8767 Diag(D.getDeclSpec().getInlineSpecLoc(), 8768 diag::ext_operator_new_delete_declared_inline) 8769 << NewFD->getDeclName(); 8770 8771 // If the declarator is a template-id, translate the parser's template 8772 // argument list into our AST format. 8773 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 8774 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 8775 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 8776 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 8777 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 8778 TemplateId->NumArgs); 8779 translateTemplateArguments(TemplateArgsPtr, 8780 TemplateArgs); 8781 8782 HasExplicitTemplateArgs = true; 8783 8784 if (NewFD->isInvalidDecl()) { 8785 HasExplicitTemplateArgs = false; 8786 } else if (FunctionTemplate) { 8787 // Function template with explicit template arguments. 8788 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 8789 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 8790 8791 HasExplicitTemplateArgs = false; 8792 } else { 8793 assert((isFunctionTemplateSpecialization || 8794 D.getDeclSpec().isFriendSpecified()) && 8795 "should have a 'template<>' for this decl"); 8796 // "friend void foo<>(int);" is an implicit specialization decl. 8797 isFunctionTemplateSpecialization = true; 8798 } 8799 } else if (isFriend && isFunctionTemplateSpecialization) { 8800 // This combination is only possible in a recovery case; the user 8801 // wrote something like: 8802 // template <> friend void foo(int); 8803 // which we're recovering from as if the user had written: 8804 // friend void foo<>(int); 8805 // Go ahead and fake up a template id. 8806 HasExplicitTemplateArgs = true; 8807 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 8808 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 8809 } 8810 8811 // We do not add HD attributes to specializations here because 8812 // they may have different constexpr-ness compared to their 8813 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 8814 // may end up with different effective targets. Instead, a 8815 // specialization inherits its target attributes from its template 8816 // in the CheckFunctionTemplateSpecialization() call below. 8817 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization) 8818 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 8819 8820 // If it's a friend (and only if it's a friend), it's possible 8821 // that either the specialized function type or the specialized 8822 // template is dependent, and therefore matching will fail. In 8823 // this case, don't check the specialization yet. 8824 bool InstantiationDependent = false; 8825 if (isFunctionTemplateSpecialization && isFriend && 8826 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 8827 TemplateSpecializationType::anyDependentTemplateArguments( 8828 TemplateArgs, 8829 InstantiationDependent))) { 8830 assert(HasExplicitTemplateArgs && 8831 "friend function specialization without template args"); 8832 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 8833 Previous)) 8834 NewFD->setInvalidDecl(); 8835 } else if (isFunctionTemplateSpecialization) { 8836 if (CurContext->isDependentContext() && CurContext->isRecord() 8837 && !isFriend) { 8838 isDependentClassScopeExplicitSpecialization = true; 8839 } else if (!NewFD->isInvalidDecl() && 8840 CheckFunctionTemplateSpecialization( 8841 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 8842 Previous)) 8843 NewFD->setInvalidDecl(); 8844 8845 // C++ [dcl.stc]p1: 8846 // A storage-class-specifier shall not be specified in an explicit 8847 // specialization (14.7.3) 8848 FunctionTemplateSpecializationInfo *Info = 8849 NewFD->getTemplateSpecializationInfo(); 8850 if (Info && SC != SC_None) { 8851 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 8852 Diag(NewFD->getLocation(), 8853 diag::err_explicit_specialization_inconsistent_storage_class) 8854 << SC 8855 << FixItHint::CreateRemoval( 8856 D.getDeclSpec().getStorageClassSpecLoc()); 8857 8858 else 8859 Diag(NewFD->getLocation(), 8860 diag::ext_explicit_specialization_storage_class) 8861 << FixItHint::CreateRemoval( 8862 D.getDeclSpec().getStorageClassSpecLoc()); 8863 } 8864 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 8865 if (CheckMemberSpecialization(NewFD, Previous)) 8866 NewFD->setInvalidDecl(); 8867 } 8868 8869 // Perform semantic checking on the function declaration. 8870 if (!isDependentClassScopeExplicitSpecialization) { 8871 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 8872 CheckMain(NewFD, D.getDeclSpec()); 8873 8874 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 8875 CheckMSVCRTEntryPoint(NewFD); 8876 8877 if (!NewFD->isInvalidDecl()) 8878 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8879 isMemberSpecialization)); 8880 else if (!Previous.empty()) 8881 // Recover gracefully from an invalid redeclaration. 8882 D.setRedeclaration(true); 8883 } 8884 8885 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8886 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8887 "previous declaration set still overloaded"); 8888 8889 NamedDecl *PrincipalDecl = (FunctionTemplate 8890 ? cast<NamedDecl>(FunctionTemplate) 8891 : NewFD); 8892 8893 if (isFriend && NewFD->getPreviousDecl()) { 8894 AccessSpecifier Access = AS_public; 8895 if (!NewFD->isInvalidDecl()) 8896 Access = NewFD->getPreviousDecl()->getAccess(); 8897 8898 NewFD->setAccess(Access); 8899 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8900 } 8901 8902 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8903 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8904 PrincipalDecl->setNonMemberOperator(); 8905 8906 // If we have a function template, check the template parameter 8907 // list. This will check and merge default template arguments. 8908 if (FunctionTemplate) { 8909 FunctionTemplateDecl *PrevTemplate = 8910 FunctionTemplate->getPreviousDecl(); 8911 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8912 PrevTemplate ? PrevTemplate->getTemplateParameters() 8913 : nullptr, 8914 D.getDeclSpec().isFriendSpecified() 8915 ? (D.isFunctionDefinition() 8916 ? TPC_FriendFunctionTemplateDefinition 8917 : TPC_FriendFunctionTemplate) 8918 : (D.getCXXScopeSpec().isSet() && 8919 DC && DC->isRecord() && 8920 DC->isDependentContext()) 8921 ? TPC_ClassTemplateMember 8922 : TPC_FunctionTemplate); 8923 } 8924 8925 if (NewFD->isInvalidDecl()) { 8926 // Ignore all the rest of this. 8927 } else if (!D.isRedeclaration()) { 8928 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8929 AddToScope }; 8930 // Fake up an access specifier if it's supposed to be a class member. 8931 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8932 NewFD->setAccess(AS_public); 8933 8934 // Qualified decls generally require a previous declaration. 8935 if (D.getCXXScopeSpec().isSet()) { 8936 // ...with the major exception of templated-scope or 8937 // dependent-scope friend declarations. 8938 8939 // TODO: we currently also suppress this check in dependent 8940 // contexts because (1) the parameter depth will be off when 8941 // matching friend templates and (2) we might actually be 8942 // selecting a friend based on a dependent factor. But there 8943 // are situations where these conditions don't apply and we 8944 // can actually do this check immediately. 8945 if (isFriend && 8946 (TemplateParamLists.size() || 8947 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8948 CurContext->isDependentContext())) { 8949 // ignore these 8950 } else { 8951 // The user tried to provide an out-of-line definition for a 8952 // function that is a member of a class or namespace, but there 8953 // was no such member function declared (C++ [class.mfct]p2, 8954 // C++ [namespace.memdef]p2). For example: 8955 // 8956 // class X { 8957 // void f() const; 8958 // }; 8959 // 8960 // void X::f() { } // ill-formed 8961 // 8962 // Complain about this problem, and attempt to suggest close 8963 // matches (e.g., those that differ only in cv-qualifiers and 8964 // whether the parameter types are references). 8965 8966 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8967 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8968 AddToScope = ExtraArgs.AddToScope; 8969 return Result; 8970 } 8971 } 8972 8973 // Unqualified local friend declarations are required to resolve 8974 // to something. 8975 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8976 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8977 *this, Previous, NewFD, ExtraArgs, true, S)) { 8978 AddToScope = ExtraArgs.AddToScope; 8979 return Result; 8980 } 8981 } 8982 } else if (!D.isFunctionDefinition() && 8983 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8984 !isFriend && !isFunctionTemplateSpecialization && 8985 !isMemberSpecialization) { 8986 // An out-of-line member function declaration must also be a 8987 // definition (C++ [class.mfct]p2). 8988 // Note that this is not the case for explicit specializations of 8989 // function templates or member functions of class templates, per 8990 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8991 // extension for compatibility with old SWIG code which likes to 8992 // generate them. 8993 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8994 << D.getCXXScopeSpec().getRange(); 8995 } 8996 } 8997 8998 ProcessPragmaWeak(S, NewFD); 8999 checkAttributesAfterMerging(*this, *NewFD); 9000 9001 AddKnownFunctionAttributes(NewFD); 9002 9003 if (NewFD->hasAttr<OverloadableAttr>() && 9004 !NewFD->getType()->getAs<FunctionProtoType>()) { 9005 Diag(NewFD->getLocation(), 9006 diag::err_attribute_overloadable_no_prototype) 9007 << NewFD; 9008 9009 // Turn this into a variadic function with no parameters. 9010 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9011 FunctionProtoType::ExtProtoInfo EPI( 9012 Context.getDefaultCallingConvention(true, false)); 9013 EPI.Variadic = true; 9014 EPI.ExtInfo = FT->getExtInfo(); 9015 9016 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9017 NewFD->setType(R); 9018 } 9019 9020 // If there's a #pragma GCC visibility in scope, and this isn't a class 9021 // member, set the visibility of this function. 9022 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9023 AddPushedVisibilityAttribute(NewFD); 9024 9025 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9026 // marking the function. 9027 AddCFAuditedAttribute(NewFD); 9028 9029 // If this is a function definition, check if we have to apply optnone due to 9030 // a pragma. 9031 if(D.isFunctionDefinition()) 9032 AddRangeBasedOptnone(NewFD); 9033 9034 // If this is the first declaration of an extern C variable, update 9035 // the map of such variables. 9036 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9037 isIncompleteDeclExternC(*this, NewFD)) 9038 RegisterLocallyScopedExternCDecl(NewFD, S); 9039 9040 // Set this FunctionDecl's range up to the right paren. 9041 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9042 9043 if (D.isRedeclaration() && !Previous.empty()) { 9044 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9045 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9046 isMemberSpecialization || 9047 isFunctionTemplateSpecialization, 9048 D.isFunctionDefinition()); 9049 } 9050 9051 if (getLangOpts().CUDA) { 9052 IdentifierInfo *II = NewFD->getIdentifier(); 9053 if (II && 9054 II->isStr(getLangOpts().HIP ? "hipConfigureCall" 9055 : "cudaConfigureCall") && 9056 !NewFD->isInvalidDecl() && 9057 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9058 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9059 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 9060 Context.setcudaConfigureCallDecl(NewFD); 9061 } 9062 9063 // Variadic functions, other than a *declaration* of printf, are not allowed 9064 // in device-side CUDA code, unless someone passed 9065 // -fcuda-allow-variadic-functions. 9066 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9067 (NewFD->hasAttr<CUDADeviceAttr>() || 9068 NewFD->hasAttr<CUDAGlobalAttr>()) && 9069 !(II && II->isStr("printf") && NewFD->isExternC() && 9070 !D.isFunctionDefinition())) { 9071 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9072 } 9073 } 9074 9075 MarkUnusedFileScopedDecl(NewFD); 9076 9077 if (getLangOpts().CPlusPlus) { 9078 if (FunctionTemplate) { 9079 if (NewFD->isInvalidDecl()) 9080 FunctionTemplate->setInvalidDecl(); 9081 return FunctionTemplate; 9082 } 9083 9084 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9085 CompleteMemberSpecialization(NewFD, Previous); 9086 } 9087 9088 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 9089 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9090 if ((getLangOpts().OpenCLVersion >= 120) 9091 && (SC == SC_Static)) { 9092 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9093 D.setInvalidType(); 9094 } 9095 9096 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9097 if (!NewFD->getReturnType()->isVoidType()) { 9098 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9099 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9100 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9101 : FixItHint()); 9102 D.setInvalidType(); 9103 } 9104 9105 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9106 for (auto Param : NewFD->parameters()) 9107 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9108 } 9109 for (const ParmVarDecl *Param : NewFD->parameters()) { 9110 QualType PT = Param->getType(); 9111 9112 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9113 // types. 9114 if (getLangOpts().OpenCLVersion >= 200) { 9115 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9116 QualType ElemTy = PipeTy->getElementType(); 9117 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9118 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9119 D.setInvalidType(); 9120 } 9121 } 9122 } 9123 } 9124 9125 // Here we have an function template explicit specialization at class scope. 9126 // The actual specialization will be postponed to template instatiation 9127 // time via the ClassScopeFunctionSpecializationDecl node. 9128 if (isDependentClassScopeExplicitSpecialization) { 9129 ClassScopeFunctionSpecializationDecl *NewSpec = 9130 ClassScopeFunctionSpecializationDecl::Create( 9131 Context, CurContext, NewFD->getLocation(), 9132 cast<CXXMethodDecl>(NewFD), 9133 HasExplicitTemplateArgs, TemplateArgs); 9134 CurContext->addDecl(NewSpec); 9135 AddToScope = false; 9136 } 9137 9138 // Diagnose availability attributes. Availability cannot be used on functions 9139 // that are run during load/unload. 9140 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9141 if (NewFD->hasAttr<ConstructorAttr>()) { 9142 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9143 << 1; 9144 NewFD->dropAttr<AvailabilityAttr>(); 9145 } 9146 if (NewFD->hasAttr<DestructorAttr>()) { 9147 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9148 << 2; 9149 NewFD->dropAttr<AvailabilityAttr>(); 9150 } 9151 } 9152 9153 return NewFD; 9154 } 9155 9156 /// \brief Checks if the new declaration declared in dependent context must be 9157 /// put in the same redeclaration chain as the specified declaration. 9158 /// 9159 /// \param D Declaration that is checked. 9160 /// \param PrevDecl Previous declaration found with proper lookup method for the 9161 /// same declaration name. 9162 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9163 /// belongs to. 9164 /// 9165 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9166 // Any declarations should be put into redeclaration chains except for 9167 // friend declaration in a dependent context that names a function in 9168 // namespace scope. 9169 // 9170 // This allows to compile code like: 9171 // 9172 // void func(); 9173 // template<typename T> class C1 { friend void func() { } }; 9174 // template<typename T> class C2 { friend void func() { } }; 9175 // 9176 // This code snippet is a valid code unless both templates are instantiated. 9177 return !(D->getLexicalDeclContext()->isDependentContext() && 9178 D->getDeclContext()->isFileContext() && 9179 D->getFriendObjectKind() != Decl::FOK_None); 9180 } 9181 9182 /// \brief Check the target attribute of the function for MultiVersion 9183 /// validity. 9184 /// 9185 /// Returns true if there was an error, false otherwise. 9186 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9187 const auto *TA = FD->getAttr<TargetAttr>(); 9188 assert(TA && "MultiVersion Candidate requires a target attribute"); 9189 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse(); 9190 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9191 enum ErrType { Feature = 0, Architecture = 1 }; 9192 9193 if (!ParseInfo.Architecture.empty() && 9194 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9195 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9196 << Architecture << ParseInfo.Architecture; 9197 return true; 9198 } 9199 9200 for (const auto &Feat : ParseInfo.Features) { 9201 auto BareFeat = StringRef{Feat}.substr(1); 9202 if (Feat[0] == '-') { 9203 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9204 << Feature << ("no-" + BareFeat).str(); 9205 return true; 9206 } 9207 9208 if (!TargetInfo.validateCpuSupports(BareFeat) || 9209 !TargetInfo.isValidFeatureName(BareFeat)) { 9210 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9211 << Feature << BareFeat; 9212 return true; 9213 } 9214 } 9215 return false; 9216 } 9217 9218 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 9219 const FunctionDecl *NewFD, 9220 bool CausesMV) { 9221 enum DoesntSupport { 9222 FuncTemplates = 0, 9223 VirtFuncs = 1, 9224 DeducedReturn = 2, 9225 Constructors = 3, 9226 Destructors = 4, 9227 DeletedFuncs = 5, 9228 DefaultedFuncs = 6 9229 }; 9230 enum Different { 9231 CallingConv = 0, 9232 ReturnType = 1, 9233 ConstexprSpec = 2, 9234 InlineSpec = 3, 9235 StorageClass = 4, 9236 Linkage = 5 9237 }; 9238 9239 // For now, disallow all other attributes. These should be opt-in, but 9240 // an analysis of all of them is a future FIXME. 9241 if (CausesMV && OldFD && 9242 std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) { 9243 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs); 9244 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9245 return true; 9246 } 9247 9248 if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1) 9249 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs); 9250 9251 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 9252 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9253 << FuncTemplates; 9254 9255 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 9256 if (NewCXXFD->isVirtual()) 9257 return S.Diag(NewCXXFD->getLocation(), 9258 diag::err_multiversion_doesnt_support) 9259 << VirtFuncs; 9260 9261 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD)) 9262 return S.Diag(NewCXXCtor->getLocation(), 9263 diag::err_multiversion_doesnt_support) 9264 << Constructors; 9265 9266 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD)) 9267 return S.Diag(NewCXXDtor->getLocation(), 9268 diag::err_multiversion_doesnt_support) 9269 << Destructors; 9270 } 9271 9272 if (NewFD->isDeleted()) 9273 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9274 << DeletedFuncs; 9275 9276 if (NewFD->isDefaulted()) 9277 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9278 << DefaultedFuncs; 9279 9280 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType()); 9281 const auto *NewType = cast<FunctionType>(NewQType); 9282 QualType NewReturnType = NewType->getReturnType(); 9283 9284 if (NewReturnType->isUndeducedType()) 9285 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support) 9286 << DeducedReturn; 9287 9288 // Only allow transition to MultiVersion if it hasn't been used. 9289 if (OldFD && CausesMV && OldFD->isUsed(false)) 9290 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 9291 9292 // Ensure the return type is identical. 9293 if (OldFD) { 9294 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType()); 9295 const auto *OldType = cast<FunctionType>(OldQType); 9296 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 9297 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 9298 9299 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 9300 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9301 << CallingConv; 9302 9303 QualType OldReturnType = OldType->getReturnType(); 9304 9305 if (OldReturnType != NewReturnType) 9306 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9307 << ReturnType; 9308 9309 if (OldFD->isConstexpr() != NewFD->isConstexpr()) 9310 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9311 << ConstexprSpec; 9312 9313 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 9314 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9315 << InlineSpec; 9316 9317 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 9318 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9319 << StorageClass; 9320 9321 if (OldFD->isExternC() != NewFD->isExternC()) 9322 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff) 9323 << Linkage; 9324 9325 if (S.CheckEquivalentExceptionSpec( 9326 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 9327 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 9328 return true; 9329 } 9330 return false; 9331 } 9332 9333 /// \brief Check the validity of a mulitversion function declaration. 9334 /// Also sets the multiversion'ness' of the function itself. 9335 /// 9336 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9337 /// 9338 /// Returns true if there was an error, false otherwise. 9339 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 9340 bool &Redeclaration, NamedDecl *&OldDecl, 9341 bool &MergeTypeWithPrevious, 9342 LookupResult &Previous) { 9343 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 9344 if (NewFD->isMain()) { 9345 if (NewTA && NewTA->isDefaultVersion()) { 9346 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 9347 NewFD->setInvalidDecl(); 9348 return true; 9349 } 9350 return false; 9351 } 9352 9353 // If there is no matching previous decl, only 'default' can 9354 // cause MultiVersioning. 9355 if (!OldDecl) { 9356 if (NewTA && NewTA->isDefaultVersion()) { 9357 if (!NewFD->getType()->getAs<FunctionProtoType>()) { 9358 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto); 9359 NewFD->setInvalidDecl(); 9360 return true; 9361 } 9362 if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) { 9363 NewFD->setInvalidDecl(); 9364 return true; 9365 } 9366 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9367 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9368 NewFD->setInvalidDecl(); 9369 return true; 9370 } 9371 9372 NewFD->setIsMultiVersion(); 9373 } 9374 return false; 9375 } 9376 9377 if (OldDecl->getDeclContext()->getRedeclContext() != 9378 NewFD->getDeclContext()->getRedeclContext()) 9379 return false; 9380 9381 FunctionDecl *OldFD = OldDecl->getAsFunction(); 9382 // Unresolved 'using' statements (the other way OldDecl can be not a function) 9383 // likely cannot cause a problem here. 9384 if (!OldFD) 9385 return false; 9386 9387 if (!OldFD->isMultiVersion() && !NewTA) 9388 return false; 9389 9390 if (OldFD->isMultiVersion() && !NewTA) { 9391 S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl); 9392 NewFD->setInvalidDecl(); 9393 return true; 9394 } 9395 9396 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse(); 9397 // Sort order doesn't matter, it just needs to be consistent. 9398 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end()); 9399 9400 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 9401 if (!OldFD->isMultiVersion()) { 9402 // If the old decl is NOT MultiVersioned yet, and we don't cause that 9403 // to change, this is a simple redeclaration. 9404 if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()) 9405 return false; 9406 9407 // Otherwise, this decl causes MultiVersioning. 9408 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 9409 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 9410 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9411 NewFD->setInvalidDecl(); 9412 return true; 9413 } 9414 9415 if (!OldFD->getType()->getAs<FunctionProtoType>()) { 9416 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto); 9417 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9418 NewFD->setInvalidDecl(); 9419 return true; 9420 } 9421 9422 if (CheckMultiVersionValue(S, NewFD)) { 9423 NewFD->setInvalidDecl(); 9424 return true; 9425 } 9426 9427 if (CheckMultiVersionValue(S, OldFD)) { 9428 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9429 NewFD->setInvalidDecl(); 9430 return true; 9431 } 9432 9433 TargetAttr::ParsedTargetAttr OldParsed = 9434 OldTA->parse(std::less<std::string>()); 9435 9436 if (OldParsed == NewParsed) { 9437 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9438 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 9439 NewFD->setInvalidDecl(); 9440 return true; 9441 } 9442 9443 for (const auto *FD : OldFD->redecls()) { 9444 const auto *CurTA = FD->getAttr<TargetAttr>(); 9445 if (!CurTA || CurTA->isInherited()) { 9446 S.Diag(FD->getLocation(), diag::err_target_required_in_redecl); 9447 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 9448 NewFD->setInvalidDecl(); 9449 return true; 9450 } 9451 } 9452 9453 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) { 9454 NewFD->setInvalidDecl(); 9455 return true; 9456 } 9457 9458 OldFD->setIsMultiVersion(); 9459 NewFD->setIsMultiVersion(); 9460 Redeclaration = false; 9461 MergeTypeWithPrevious = false; 9462 OldDecl = nullptr; 9463 Previous.clear(); 9464 return false; 9465 } 9466 9467 bool UseMemberUsingDeclRules = 9468 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 9469 9470 // Next, check ALL non-overloads to see if this is a redeclaration of a 9471 // previous member of the MultiVersion set. 9472 for (NamedDecl *ND : Previous) { 9473 FunctionDecl *CurFD = ND->getAsFunction(); 9474 if (!CurFD) 9475 continue; 9476 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 9477 continue; 9478 9479 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 9480 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 9481 NewFD->setIsMultiVersion(); 9482 Redeclaration = true; 9483 OldDecl = ND; 9484 return false; 9485 } 9486 9487 TargetAttr::ParsedTargetAttr CurParsed = 9488 CurTA->parse(std::less<std::string>()); 9489 9490 if (CurParsed == NewParsed) { 9491 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 9492 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 9493 NewFD->setInvalidDecl(); 9494 return true; 9495 } 9496 } 9497 9498 // Else, this is simply a non-redecl case. 9499 if (CheckMultiVersionValue(S, NewFD)) { 9500 NewFD->setInvalidDecl(); 9501 return true; 9502 } 9503 9504 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) { 9505 NewFD->setInvalidDecl(); 9506 return true; 9507 } 9508 9509 NewFD->setIsMultiVersion(); 9510 Redeclaration = false; 9511 MergeTypeWithPrevious = false; 9512 OldDecl = nullptr; 9513 Previous.clear(); 9514 return false; 9515 } 9516 9517 /// \brief Perform semantic checking of a new function declaration. 9518 /// 9519 /// Performs semantic analysis of the new function declaration 9520 /// NewFD. This routine performs all semantic checking that does not 9521 /// require the actual declarator involved in the declaration, and is 9522 /// used both for the declaration of functions as they are parsed 9523 /// (called via ActOnDeclarator) and for the declaration of functions 9524 /// that have been instantiated via C++ template instantiation (called 9525 /// via InstantiateDecl). 9526 /// 9527 /// \param IsMemberSpecialization whether this new function declaration is 9528 /// a member specialization (that replaces any definition provided by the 9529 /// previous declaration). 9530 /// 9531 /// This sets NewFD->isInvalidDecl() to true if there was an error. 9532 /// 9533 /// \returns true if the function declaration is a redeclaration. 9534 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 9535 LookupResult &Previous, 9536 bool IsMemberSpecialization) { 9537 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 9538 "Variably modified return types are not handled here"); 9539 9540 // Determine whether the type of this function should be merged with 9541 // a previous visible declaration. This never happens for functions in C++, 9542 // and always happens in C if the previous declaration was visible. 9543 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 9544 !Previous.isShadowed(); 9545 9546 bool Redeclaration = false; 9547 NamedDecl *OldDecl = nullptr; 9548 bool MayNeedOverloadableChecks = false; 9549 9550 // Merge or overload the declaration with an existing declaration of 9551 // the same name, if appropriate. 9552 if (!Previous.empty()) { 9553 // Determine whether NewFD is an overload of PrevDecl or 9554 // a declaration that requires merging. If it's an overload, 9555 // there's no more work to do here; we'll just add the new 9556 // function to the scope. 9557 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 9558 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 9559 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 9560 Redeclaration = true; 9561 OldDecl = Candidate; 9562 } 9563 } else { 9564 MayNeedOverloadableChecks = true; 9565 switch (CheckOverload(S, NewFD, Previous, OldDecl, 9566 /*NewIsUsingDecl*/ false)) { 9567 case Ovl_Match: 9568 Redeclaration = true; 9569 break; 9570 9571 case Ovl_NonFunction: 9572 Redeclaration = true; 9573 break; 9574 9575 case Ovl_Overload: 9576 Redeclaration = false; 9577 break; 9578 } 9579 } 9580 } 9581 9582 // Check for a previous extern "C" declaration with this name. 9583 if (!Redeclaration && 9584 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 9585 if (!Previous.empty()) { 9586 // This is an extern "C" declaration with the same name as a previous 9587 // declaration, and thus redeclares that entity... 9588 Redeclaration = true; 9589 OldDecl = Previous.getFoundDecl(); 9590 MergeTypeWithPrevious = false; 9591 9592 // ... except in the presence of __attribute__((overloadable)). 9593 if (OldDecl->hasAttr<OverloadableAttr>() || 9594 NewFD->hasAttr<OverloadableAttr>()) { 9595 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 9596 MayNeedOverloadableChecks = true; 9597 Redeclaration = false; 9598 OldDecl = nullptr; 9599 } 9600 } 9601 } 9602 } 9603 9604 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 9605 MergeTypeWithPrevious, Previous)) 9606 return Redeclaration; 9607 9608 // C++11 [dcl.constexpr]p8: 9609 // A constexpr specifier for a non-static member function that is not 9610 // a constructor declares that member function to be const. 9611 // 9612 // This needs to be delayed until we know whether this is an out-of-line 9613 // definition of a static member function. 9614 // 9615 // This rule is not present in C++1y, so we produce a backwards 9616 // compatibility warning whenever it happens in C++11. 9617 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 9618 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 9619 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 9620 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 9621 CXXMethodDecl *OldMD = nullptr; 9622 if (OldDecl) 9623 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 9624 if (!OldMD || !OldMD->isStatic()) { 9625 const FunctionProtoType *FPT = 9626 MD->getType()->castAs<FunctionProtoType>(); 9627 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 9628 EPI.TypeQuals |= Qualifiers::Const; 9629 MD->setType(Context.getFunctionType(FPT->getReturnType(), 9630 FPT->getParamTypes(), EPI)); 9631 9632 // Warn that we did this, if we're not performing template instantiation. 9633 // In that case, we'll have warned already when the template was defined. 9634 if (!inTemplateInstantiation()) { 9635 SourceLocation AddConstLoc; 9636 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 9637 .IgnoreParens().getAs<FunctionTypeLoc>()) 9638 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 9639 9640 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 9641 << FixItHint::CreateInsertion(AddConstLoc, " const"); 9642 } 9643 } 9644 } 9645 9646 if (Redeclaration) { 9647 // NewFD and OldDecl represent declarations that need to be 9648 // merged. 9649 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 9650 NewFD->setInvalidDecl(); 9651 return Redeclaration; 9652 } 9653 9654 Previous.clear(); 9655 Previous.addDecl(OldDecl); 9656 9657 if (FunctionTemplateDecl *OldTemplateDecl = 9658 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 9659 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 9660 NewFD->setPreviousDeclaration(OldFD); 9661 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9662 FunctionTemplateDecl *NewTemplateDecl 9663 = NewFD->getDescribedFunctionTemplate(); 9664 assert(NewTemplateDecl && "Template/non-template mismatch"); 9665 if (NewFD->isCXXClassMember()) { 9666 NewFD->setAccess(OldTemplateDecl->getAccess()); 9667 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 9668 } 9669 9670 // If this is an explicit specialization of a member that is a function 9671 // template, mark it as a member specialization. 9672 if (IsMemberSpecialization && 9673 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 9674 NewTemplateDecl->setMemberSpecialization(); 9675 assert(OldTemplateDecl->isMemberSpecialization()); 9676 // Explicit specializations of a member template do not inherit deleted 9677 // status from the parent member template that they are specializing. 9678 if (OldFD->isDeleted()) { 9679 // FIXME: This assert will not hold in the presence of modules. 9680 assert(OldFD->getCanonicalDecl() == OldFD); 9681 // FIXME: We need an update record for this AST mutation. 9682 OldFD->setDeletedAsWritten(false); 9683 } 9684 } 9685 9686 } else { 9687 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 9688 auto *OldFD = cast<FunctionDecl>(OldDecl); 9689 // This needs to happen first so that 'inline' propagates. 9690 NewFD->setPreviousDeclaration(OldFD); 9691 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 9692 if (NewFD->isCXXClassMember()) 9693 NewFD->setAccess(OldFD->getAccess()); 9694 } 9695 } 9696 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 9697 !NewFD->getAttr<OverloadableAttr>()) { 9698 assert((Previous.empty() || 9699 llvm::any_of(Previous, 9700 [](const NamedDecl *ND) { 9701 return ND->hasAttr<OverloadableAttr>(); 9702 })) && 9703 "Non-redecls shouldn't happen without overloadable present"); 9704 9705 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 9706 const auto *FD = dyn_cast<FunctionDecl>(ND); 9707 return FD && !FD->hasAttr<OverloadableAttr>(); 9708 }); 9709 9710 if (OtherUnmarkedIter != Previous.end()) { 9711 Diag(NewFD->getLocation(), 9712 diag::err_attribute_overloadable_multiple_unmarked_overloads); 9713 Diag((*OtherUnmarkedIter)->getLocation(), 9714 diag::note_attribute_overloadable_prev_overload) 9715 << false; 9716 9717 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 9718 } 9719 } 9720 9721 // Semantic checking for this function declaration (in isolation). 9722 9723 if (getLangOpts().CPlusPlus) { 9724 // C++-specific checks. 9725 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 9726 CheckConstructor(Constructor); 9727 } else if (CXXDestructorDecl *Destructor = 9728 dyn_cast<CXXDestructorDecl>(NewFD)) { 9729 CXXRecordDecl *Record = Destructor->getParent(); 9730 QualType ClassType = Context.getTypeDeclType(Record); 9731 9732 // FIXME: Shouldn't we be able to perform this check even when the class 9733 // type is dependent? Both gcc and edg can handle that. 9734 if (!ClassType->isDependentType()) { 9735 DeclarationName Name 9736 = Context.DeclarationNames.getCXXDestructorName( 9737 Context.getCanonicalType(ClassType)); 9738 if (NewFD->getDeclName() != Name) { 9739 Diag(NewFD->getLocation(), diag::err_destructor_name); 9740 NewFD->setInvalidDecl(); 9741 return Redeclaration; 9742 } 9743 } 9744 } else if (CXXConversionDecl *Conversion 9745 = dyn_cast<CXXConversionDecl>(NewFD)) { 9746 ActOnConversionDeclarator(Conversion); 9747 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 9748 if (auto *TD = Guide->getDescribedFunctionTemplate()) 9749 CheckDeductionGuideTemplate(TD); 9750 9751 // A deduction guide is not on the list of entities that can be 9752 // explicitly specialized. 9753 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 9754 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized) 9755 << /*explicit specialization*/ 1; 9756 } 9757 9758 // Find any virtual functions that this function overrides. 9759 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 9760 if (!Method->isFunctionTemplateSpecialization() && 9761 !Method->getDescribedFunctionTemplate() && 9762 Method->isCanonicalDecl()) { 9763 if (AddOverriddenMethods(Method->getParent(), Method)) { 9764 // If the function was marked as "static", we have a problem. 9765 if (NewFD->getStorageClass() == SC_Static) { 9766 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 9767 } 9768 } 9769 } 9770 9771 if (Method->isStatic()) 9772 checkThisInStaticMemberFunctionType(Method); 9773 } 9774 9775 // Extra checking for C++ overloaded operators (C++ [over.oper]). 9776 if (NewFD->isOverloadedOperator() && 9777 CheckOverloadedOperatorDeclaration(NewFD)) { 9778 NewFD->setInvalidDecl(); 9779 return Redeclaration; 9780 } 9781 9782 // Extra checking for C++0x literal operators (C++0x [over.literal]). 9783 if (NewFD->getLiteralIdentifier() && 9784 CheckLiteralOperatorDeclaration(NewFD)) { 9785 NewFD->setInvalidDecl(); 9786 return Redeclaration; 9787 } 9788 9789 // In C++, check default arguments now that we have merged decls. Unless 9790 // the lexical context is the class, because in this case this is done 9791 // during delayed parsing anyway. 9792 if (!CurContext->isRecord()) 9793 CheckCXXDefaultArguments(NewFD); 9794 9795 // If this function declares a builtin function, check the type of this 9796 // declaration against the expected type for the builtin. 9797 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 9798 ASTContext::GetBuiltinTypeError Error; 9799 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 9800 QualType T = Context.GetBuiltinType(BuiltinID, Error); 9801 // If the type of the builtin differs only in its exception 9802 // specification, that's OK. 9803 // FIXME: If the types do differ in this way, it would be better to 9804 // retain the 'noexcept' form of the type. 9805 if (!T.isNull() && 9806 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 9807 NewFD->getType())) 9808 // The type of this function differs from the type of the builtin, 9809 // so forget about the builtin entirely. 9810 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 9811 } 9812 9813 // If this function is declared as being extern "C", then check to see if 9814 // the function returns a UDT (class, struct, or union type) that is not C 9815 // compatible, and if it does, warn the user. 9816 // But, issue any diagnostic on the first declaration only. 9817 if (Previous.empty() && NewFD->isExternC()) { 9818 QualType R = NewFD->getReturnType(); 9819 if (R->isIncompleteType() && !R->isVoidType()) 9820 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 9821 << NewFD << R; 9822 else if (!R.isPODType(Context) && !R->isVoidType() && 9823 !R->isObjCObjectPointerType()) 9824 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 9825 } 9826 9827 // C++1z [dcl.fct]p6: 9828 // [...] whether the function has a non-throwing exception-specification 9829 // [is] part of the function type 9830 // 9831 // This results in an ABI break between C++14 and C++17 for functions whose 9832 // declared type includes an exception-specification in a parameter or 9833 // return type. (Exception specifications on the function itself are OK in 9834 // most cases, and exception specifications are not permitted in most other 9835 // contexts where they could make it into a mangling.) 9836 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 9837 auto HasNoexcept = [&](QualType T) -> bool { 9838 // Strip off declarator chunks that could be between us and a function 9839 // type. We don't need to look far, exception specifications are very 9840 // restricted prior to C++17. 9841 if (auto *RT = T->getAs<ReferenceType>()) 9842 T = RT->getPointeeType(); 9843 else if (T->isAnyPointerType()) 9844 T = T->getPointeeType(); 9845 else if (auto *MPT = T->getAs<MemberPointerType>()) 9846 T = MPT->getPointeeType(); 9847 if (auto *FPT = T->getAs<FunctionProtoType>()) 9848 if (FPT->isNothrow(Context)) 9849 return true; 9850 return false; 9851 }; 9852 9853 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 9854 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 9855 for (QualType T : FPT->param_types()) 9856 AnyNoexcept |= HasNoexcept(T); 9857 if (AnyNoexcept) 9858 Diag(NewFD->getLocation(), 9859 diag::warn_cxx17_compat_exception_spec_in_signature) 9860 << NewFD; 9861 } 9862 9863 if (!Redeclaration && LangOpts.CUDA) 9864 checkCUDATargetOverload(NewFD, Previous); 9865 } 9866 return Redeclaration; 9867 } 9868 9869 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 9870 // C++11 [basic.start.main]p3: 9871 // A program that [...] declares main to be inline, static or 9872 // constexpr is ill-formed. 9873 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 9874 // appear in a declaration of main. 9875 // static main is not an error under C99, but we should warn about it. 9876 // We accept _Noreturn main as an extension. 9877 if (FD->getStorageClass() == SC_Static) 9878 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 9879 ? diag::err_static_main : diag::warn_static_main) 9880 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 9881 if (FD->isInlineSpecified()) 9882 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 9883 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 9884 if (DS.isNoreturnSpecified()) { 9885 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 9886 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 9887 Diag(NoreturnLoc, diag::ext_noreturn_main); 9888 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 9889 << FixItHint::CreateRemoval(NoreturnRange); 9890 } 9891 if (FD->isConstexpr()) { 9892 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 9893 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 9894 FD->setConstexpr(false); 9895 } 9896 9897 if (getLangOpts().OpenCL) { 9898 Diag(FD->getLocation(), diag::err_opencl_no_main) 9899 << FD->hasAttr<OpenCLKernelAttr>(); 9900 FD->setInvalidDecl(); 9901 return; 9902 } 9903 9904 QualType T = FD->getType(); 9905 assert(T->isFunctionType() && "function decl is not of function type"); 9906 const FunctionType* FT = T->castAs<FunctionType>(); 9907 9908 // Set default calling convention for main() 9909 if (FT->getCallConv() != CC_C) { 9910 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 9911 FD->setType(QualType(FT, 0)); 9912 T = Context.getCanonicalType(FD->getType()); 9913 } 9914 9915 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 9916 // In C with GNU extensions we allow main() to have non-integer return 9917 // type, but we should warn about the extension, and we disable the 9918 // implicit-return-zero rule. 9919 9920 // GCC in C mode accepts qualified 'int'. 9921 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 9922 FD->setHasImplicitReturnZero(true); 9923 else { 9924 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 9925 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9926 if (RTRange.isValid()) 9927 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 9928 << FixItHint::CreateReplacement(RTRange, "int"); 9929 } 9930 } else { 9931 // In C and C++, main magically returns 0 if you fall off the end; 9932 // set the flag which tells us that. 9933 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 9934 9935 // All the standards say that main() should return 'int'. 9936 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 9937 FD->setHasImplicitReturnZero(true); 9938 else { 9939 // Otherwise, this is just a flat-out error. 9940 SourceRange RTRange = FD->getReturnTypeSourceRange(); 9941 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 9942 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 9943 : FixItHint()); 9944 FD->setInvalidDecl(true); 9945 } 9946 } 9947 9948 // Treat protoless main() as nullary. 9949 if (isa<FunctionNoProtoType>(FT)) return; 9950 9951 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 9952 unsigned nparams = FTP->getNumParams(); 9953 assert(FD->getNumParams() == nparams); 9954 9955 bool HasExtraParameters = (nparams > 3); 9956 9957 if (FTP->isVariadic()) { 9958 Diag(FD->getLocation(), diag::ext_variadic_main); 9959 // FIXME: if we had information about the location of the ellipsis, we 9960 // could add a FixIt hint to remove it as a parameter. 9961 } 9962 9963 // Darwin passes an undocumented fourth argument of type char**. If 9964 // other platforms start sprouting these, the logic below will start 9965 // getting shifty. 9966 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 9967 HasExtraParameters = false; 9968 9969 if (HasExtraParameters) { 9970 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 9971 FD->setInvalidDecl(true); 9972 nparams = 3; 9973 } 9974 9975 // FIXME: a lot of the following diagnostics would be improved 9976 // if we had some location information about types. 9977 9978 QualType CharPP = 9979 Context.getPointerType(Context.getPointerType(Context.CharTy)); 9980 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 9981 9982 for (unsigned i = 0; i < nparams; ++i) { 9983 QualType AT = FTP->getParamType(i); 9984 9985 bool mismatch = true; 9986 9987 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 9988 mismatch = false; 9989 else if (Expected[i] == CharPP) { 9990 // As an extension, the following forms are okay: 9991 // char const ** 9992 // char const * const * 9993 // char * const * 9994 9995 QualifierCollector qs; 9996 const PointerType* PT; 9997 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 9998 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 9999 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10000 Context.CharTy)) { 10001 qs.removeConst(); 10002 mismatch = !qs.empty(); 10003 } 10004 } 10005 10006 if (mismatch) { 10007 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10008 // TODO: suggest replacing given type with expected type 10009 FD->setInvalidDecl(true); 10010 } 10011 } 10012 10013 if (nparams == 1 && !FD->isInvalidDecl()) { 10014 Diag(FD->getLocation(), diag::warn_main_one_arg); 10015 } 10016 10017 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10018 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10019 FD->setInvalidDecl(); 10020 } 10021 } 10022 10023 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10024 QualType T = FD->getType(); 10025 assert(T->isFunctionType() && "function decl is not of function type"); 10026 const FunctionType *FT = T->castAs<FunctionType>(); 10027 10028 // Set an implicit return of 'zero' if the function can return some integral, 10029 // enumeration, pointer or nullptr type. 10030 if (FT->getReturnType()->isIntegralOrEnumerationType() || 10031 FT->getReturnType()->isAnyPointerType() || 10032 FT->getReturnType()->isNullPtrType()) 10033 // DllMain is exempt because a return value of zero means it failed. 10034 if (FD->getName() != "DllMain") 10035 FD->setHasImplicitReturnZero(true); 10036 10037 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10038 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10039 FD->setInvalidDecl(); 10040 } 10041 } 10042 10043 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 10044 // FIXME: Need strict checking. In C89, we need to check for 10045 // any assignment, increment, decrement, function-calls, or 10046 // commas outside of a sizeof. In C99, it's the same list, 10047 // except that the aforementioned are allowed in unevaluated 10048 // expressions. Everything else falls under the 10049 // "may accept other forms of constant expressions" exception. 10050 // (We never end up here for C++, so the constant expression 10051 // rules there don't matter.) 10052 const Expr *Culprit; 10053 if (Init->isConstantInitializer(Context, false, &Culprit)) 10054 return false; 10055 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 10056 << Culprit->getSourceRange(); 10057 return true; 10058 } 10059 10060 namespace { 10061 // Visits an initialization expression to see if OrigDecl is evaluated in 10062 // its own initialization and throws a warning if it does. 10063 class SelfReferenceChecker 10064 : public EvaluatedExprVisitor<SelfReferenceChecker> { 10065 Sema &S; 10066 Decl *OrigDecl; 10067 bool isRecordType; 10068 bool isPODType; 10069 bool isReferenceType; 10070 10071 bool isInitList; 10072 llvm::SmallVector<unsigned, 4> InitFieldIndex; 10073 10074 public: 10075 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 10076 10077 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 10078 S(S), OrigDecl(OrigDecl) { 10079 isPODType = false; 10080 isRecordType = false; 10081 isReferenceType = false; 10082 isInitList = false; 10083 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 10084 isPODType = VD->getType().isPODType(S.Context); 10085 isRecordType = VD->getType()->isRecordType(); 10086 isReferenceType = VD->getType()->isReferenceType(); 10087 } 10088 } 10089 10090 // For most expressions, just call the visitor. For initializer lists, 10091 // track the index of the field being initialized since fields are 10092 // initialized in order allowing use of previously initialized fields. 10093 void CheckExpr(Expr *E) { 10094 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 10095 if (!InitList) { 10096 Visit(E); 10097 return; 10098 } 10099 10100 // Track and increment the index here. 10101 isInitList = true; 10102 InitFieldIndex.push_back(0); 10103 for (auto Child : InitList->children()) { 10104 CheckExpr(cast<Expr>(Child)); 10105 ++InitFieldIndex.back(); 10106 } 10107 InitFieldIndex.pop_back(); 10108 } 10109 10110 // Returns true if MemberExpr is checked and no further checking is needed. 10111 // Returns false if additional checking is required. 10112 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 10113 llvm::SmallVector<FieldDecl*, 4> Fields; 10114 Expr *Base = E; 10115 bool ReferenceField = false; 10116 10117 // Get the field memebers used. 10118 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10119 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 10120 if (!FD) 10121 return false; 10122 Fields.push_back(FD); 10123 if (FD->getType()->isReferenceType()) 10124 ReferenceField = true; 10125 Base = ME->getBase()->IgnoreParenImpCasts(); 10126 } 10127 10128 // Keep checking only if the base Decl is the same. 10129 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 10130 if (!DRE || DRE->getDecl() != OrigDecl) 10131 return false; 10132 10133 // A reference field can be bound to an unininitialized field. 10134 if (CheckReference && !ReferenceField) 10135 return true; 10136 10137 // Convert FieldDecls to their index number. 10138 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 10139 for (const FieldDecl *I : llvm::reverse(Fields)) 10140 UsedFieldIndex.push_back(I->getFieldIndex()); 10141 10142 // See if a warning is needed by checking the first difference in index 10143 // numbers. If field being used has index less than the field being 10144 // initialized, then the use is safe. 10145 for (auto UsedIter = UsedFieldIndex.begin(), 10146 UsedEnd = UsedFieldIndex.end(), 10147 OrigIter = InitFieldIndex.begin(), 10148 OrigEnd = InitFieldIndex.end(); 10149 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 10150 if (*UsedIter < *OrigIter) 10151 return true; 10152 if (*UsedIter > *OrigIter) 10153 break; 10154 } 10155 10156 // TODO: Add a different warning which will print the field names. 10157 HandleDeclRefExpr(DRE); 10158 return true; 10159 } 10160 10161 // For most expressions, the cast is directly above the DeclRefExpr. 10162 // For conditional operators, the cast can be outside the conditional 10163 // operator if both expressions are DeclRefExpr's. 10164 void HandleValue(Expr *E) { 10165 E = E->IgnoreParens(); 10166 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 10167 HandleDeclRefExpr(DRE); 10168 return; 10169 } 10170 10171 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 10172 Visit(CO->getCond()); 10173 HandleValue(CO->getTrueExpr()); 10174 HandleValue(CO->getFalseExpr()); 10175 return; 10176 } 10177 10178 if (BinaryConditionalOperator *BCO = 10179 dyn_cast<BinaryConditionalOperator>(E)) { 10180 Visit(BCO->getCond()); 10181 HandleValue(BCO->getFalseExpr()); 10182 return; 10183 } 10184 10185 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 10186 HandleValue(OVE->getSourceExpr()); 10187 return; 10188 } 10189 10190 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 10191 if (BO->getOpcode() == BO_Comma) { 10192 Visit(BO->getLHS()); 10193 HandleValue(BO->getRHS()); 10194 return; 10195 } 10196 } 10197 10198 if (isa<MemberExpr>(E)) { 10199 if (isInitList) { 10200 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 10201 false /*CheckReference*/)) 10202 return; 10203 } 10204 10205 Expr *Base = E->IgnoreParenImpCasts(); 10206 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10207 // Check for static member variables and don't warn on them. 10208 if (!isa<FieldDecl>(ME->getMemberDecl())) 10209 return; 10210 Base = ME->getBase()->IgnoreParenImpCasts(); 10211 } 10212 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 10213 HandleDeclRefExpr(DRE); 10214 return; 10215 } 10216 10217 Visit(E); 10218 } 10219 10220 // Reference types not handled in HandleValue are handled here since all 10221 // uses of references are bad, not just r-value uses. 10222 void VisitDeclRefExpr(DeclRefExpr *E) { 10223 if (isReferenceType) 10224 HandleDeclRefExpr(E); 10225 } 10226 10227 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 10228 if (E->getCastKind() == CK_LValueToRValue) { 10229 HandleValue(E->getSubExpr()); 10230 return; 10231 } 10232 10233 Inherited::VisitImplicitCastExpr(E); 10234 } 10235 10236 void VisitMemberExpr(MemberExpr *E) { 10237 if (isInitList) { 10238 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 10239 return; 10240 } 10241 10242 // Don't warn on arrays since they can be treated as pointers. 10243 if (E->getType()->canDecayToPointerType()) return; 10244 10245 // Warn when a non-static method call is followed by non-static member 10246 // field accesses, which is followed by a DeclRefExpr. 10247 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 10248 bool Warn = (MD && !MD->isStatic()); 10249 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 10250 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 10251 if (!isa<FieldDecl>(ME->getMemberDecl())) 10252 Warn = false; 10253 Base = ME->getBase()->IgnoreParenImpCasts(); 10254 } 10255 10256 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 10257 if (Warn) 10258 HandleDeclRefExpr(DRE); 10259 return; 10260 } 10261 10262 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 10263 // Visit that expression. 10264 Visit(Base); 10265 } 10266 10267 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 10268 Expr *Callee = E->getCallee(); 10269 10270 if (isa<UnresolvedLookupExpr>(Callee)) 10271 return Inherited::VisitCXXOperatorCallExpr(E); 10272 10273 Visit(Callee); 10274 for (auto Arg: E->arguments()) 10275 HandleValue(Arg->IgnoreParenImpCasts()); 10276 } 10277 10278 void VisitUnaryOperator(UnaryOperator *E) { 10279 // For POD record types, addresses of its own members are well-defined. 10280 if (E->getOpcode() == UO_AddrOf && isRecordType && 10281 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 10282 if (!isPODType) 10283 HandleValue(E->getSubExpr()); 10284 return; 10285 } 10286 10287 if (E->isIncrementDecrementOp()) { 10288 HandleValue(E->getSubExpr()); 10289 return; 10290 } 10291 10292 Inherited::VisitUnaryOperator(E); 10293 } 10294 10295 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 10296 10297 void VisitCXXConstructExpr(CXXConstructExpr *E) { 10298 if (E->getConstructor()->isCopyConstructor()) { 10299 Expr *ArgExpr = E->getArg(0); 10300 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 10301 if (ILE->getNumInits() == 1) 10302 ArgExpr = ILE->getInit(0); 10303 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 10304 if (ICE->getCastKind() == CK_NoOp) 10305 ArgExpr = ICE->getSubExpr(); 10306 HandleValue(ArgExpr); 10307 return; 10308 } 10309 Inherited::VisitCXXConstructExpr(E); 10310 } 10311 10312 void VisitCallExpr(CallExpr *E) { 10313 // Treat std::move as a use. 10314 if (E->isCallToStdMove()) { 10315 HandleValue(E->getArg(0)); 10316 return; 10317 } 10318 10319 Inherited::VisitCallExpr(E); 10320 } 10321 10322 void VisitBinaryOperator(BinaryOperator *E) { 10323 if (E->isCompoundAssignmentOp()) { 10324 HandleValue(E->getLHS()); 10325 Visit(E->getRHS()); 10326 return; 10327 } 10328 10329 Inherited::VisitBinaryOperator(E); 10330 } 10331 10332 // A custom visitor for BinaryConditionalOperator is needed because the 10333 // regular visitor would check the condition and true expression separately 10334 // but both point to the same place giving duplicate diagnostics. 10335 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 10336 Visit(E->getCond()); 10337 Visit(E->getFalseExpr()); 10338 } 10339 10340 void HandleDeclRefExpr(DeclRefExpr *DRE) { 10341 Decl* ReferenceDecl = DRE->getDecl(); 10342 if (OrigDecl != ReferenceDecl) return; 10343 unsigned diag; 10344 if (isReferenceType) { 10345 diag = diag::warn_uninit_self_reference_in_reference_init; 10346 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 10347 diag = diag::warn_static_self_reference_in_init; 10348 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 10349 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 10350 DRE->getDecl()->getType()->isRecordType()) { 10351 diag = diag::warn_uninit_self_reference_in_init; 10352 } else { 10353 // Local variables will be handled by the CFG analysis. 10354 return; 10355 } 10356 10357 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 10358 S.PDiag(diag) 10359 << DRE->getDecl() 10360 << OrigDecl->getLocation() 10361 << DRE->getSourceRange()); 10362 } 10363 }; 10364 10365 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 10366 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 10367 bool DirectInit) { 10368 // Parameters arguments are occassionially constructed with itself, 10369 // for instance, in recursive functions. Skip them. 10370 if (isa<ParmVarDecl>(OrigDecl)) 10371 return; 10372 10373 E = E->IgnoreParens(); 10374 10375 // Skip checking T a = a where T is not a record or reference type. 10376 // Doing so is a way to silence uninitialized warnings. 10377 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 10378 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 10379 if (ICE->getCastKind() == CK_LValueToRValue) 10380 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 10381 if (DRE->getDecl() == OrigDecl) 10382 return; 10383 10384 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 10385 } 10386 } // end anonymous namespace 10387 10388 namespace { 10389 // Simple wrapper to add the name of a variable or (if no variable is 10390 // available) a DeclarationName into a diagnostic. 10391 struct VarDeclOrName { 10392 VarDecl *VDecl; 10393 DeclarationName Name; 10394 10395 friend const Sema::SemaDiagnosticBuilder & 10396 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 10397 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 10398 } 10399 }; 10400 } // end anonymous namespace 10401 10402 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 10403 DeclarationName Name, QualType Type, 10404 TypeSourceInfo *TSI, 10405 SourceRange Range, bool DirectInit, 10406 Expr *Init) { 10407 bool IsInitCapture = !VDecl; 10408 assert((!VDecl || !VDecl->isInitCapture()) && 10409 "init captures are expected to be deduced prior to initialization"); 10410 10411 VarDeclOrName VN{VDecl, Name}; 10412 10413 DeducedType *Deduced = Type->getContainedDeducedType(); 10414 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 10415 10416 // C++11 [dcl.spec.auto]p3 10417 if (!Init) { 10418 assert(VDecl && "no init for init capture deduction?"); 10419 10420 // Except for class argument deduction, and then for an initializing 10421 // declaration only, i.e. no static at class scope or extern. 10422 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 10423 VDecl->hasExternalStorage() || 10424 VDecl->isStaticDataMember()) { 10425 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 10426 << VDecl->getDeclName() << Type; 10427 return QualType(); 10428 } 10429 } 10430 10431 ArrayRef<Expr*> DeduceInits; 10432 if (Init) 10433 DeduceInits = Init; 10434 10435 if (DirectInit) { 10436 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 10437 DeduceInits = PL->exprs(); 10438 } 10439 10440 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 10441 assert(VDecl && "non-auto type for init capture deduction?"); 10442 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10443 InitializationKind Kind = InitializationKind::CreateForInit( 10444 VDecl->getLocation(), DirectInit, Init); 10445 // FIXME: Initialization should not be taking a mutable list of inits. 10446 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 10447 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 10448 InitsCopy); 10449 } 10450 10451 if (DirectInit) { 10452 if (auto *IL = dyn_cast<InitListExpr>(Init)) 10453 DeduceInits = IL->inits(); 10454 } 10455 10456 // Deduction only works if we have exactly one source expression. 10457 if (DeduceInits.empty()) { 10458 // It isn't possible to write this directly, but it is possible to 10459 // end up in this situation with "auto x(some_pack...);" 10460 Diag(Init->getLocStart(), IsInitCapture 10461 ? diag::err_init_capture_no_expression 10462 : diag::err_auto_var_init_no_expression) 10463 << VN << Type << Range; 10464 return QualType(); 10465 } 10466 10467 if (DeduceInits.size() > 1) { 10468 Diag(DeduceInits[1]->getLocStart(), 10469 IsInitCapture ? diag::err_init_capture_multiple_expressions 10470 : diag::err_auto_var_init_multiple_expressions) 10471 << VN << Type << Range; 10472 return QualType(); 10473 } 10474 10475 Expr *DeduceInit = DeduceInits[0]; 10476 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 10477 Diag(Init->getLocStart(), IsInitCapture 10478 ? diag::err_init_capture_paren_braces 10479 : diag::err_auto_var_init_paren_braces) 10480 << isa<InitListExpr>(Init) << VN << Type << Range; 10481 return QualType(); 10482 } 10483 10484 // Expressions default to 'id' when we're in a debugger. 10485 bool DefaultedAnyToId = false; 10486 if (getLangOpts().DebuggerCastResultToId && 10487 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 10488 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10489 if (Result.isInvalid()) { 10490 return QualType(); 10491 } 10492 Init = Result.get(); 10493 DefaultedAnyToId = true; 10494 } 10495 10496 // C++ [dcl.decomp]p1: 10497 // If the assignment-expression [...] has array type A and no ref-qualifier 10498 // is present, e has type cv A 10499 if (VDecl && isa<DecompositionDecl>(VDecl) && 10500 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 10501 DeduceInit->getType()->isConstantArrayType()) 10502 return Context.getQualifiedType(DeduceInit->getType(), 10503 Type.getQualifiers()); 10504 10505 QualType DeducedType; 10506 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 10507 if (!IsInitCapture) 10508 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 10509 else if (isa<InitListExpr>(Init)) 10510 Diag(Range.getBegin(), 10511 diag::err_init_capture_deduction_failure_from_init_list) 10512 << VN 10513 << (DeduceInit->getType().isNull() ? TSI->getType() 10514 : DeduceInit->getType()) 10515 << DeduceInit->getSourceRange(); 10516 else 10517 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 10518 << VN << TSI->getType() 10519 << (DeduceInit->getType().isNull() ? TSI->getType() 10520 : DeduceInit->getType()) 10521 << DeduceInit->getSourceRange(); 10522 } 10523 10524 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 10525 // 'id' instead of a specific object type prevents most of our usual 10526 // checks. 10527 // We only want to warn outside of template instantiations, though: 10528 // inside a template, the 'id' could have come from a parameter. 10529 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 10530 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 10531 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 10532 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 10533 } 10534 10535 return DeducedType; 10536 } 10537 10538 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 10539 Expr *Init) { 10540 QualType DeducedType = deduceVarTypeFromInitializer( 10541 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 10542 VDecl->getSourceRange(), DirectInit, Init); 10543 if (DeducedType.isNull()) { 10544 VDecl->setInvalidDecl(); 10545 return true; 10546 } 10547 10548 VDecl->setType(DeducedType); 10549 assert(VDecl->isLinkageValid()); 10550 10551 // In ARC, infer lifetime. 10552 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 10553 VDecl->setInvalidDecl(); 10554 10555 // If this is a redeclaration, check that the type we just deduced matches 10556 // the previously declared type. 10557 if (VarDecl *Old = VDecl->getPreviousDecl()) { 10558 // We never need to merge the type, because we cannot form an incomplete 10559 // array of auto, nor deduce such a type. 10560 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 10561 } 10562 10563 // Check the deduced type is valid for a variable declaration. 10564 CheckVariableDeclarationType(VDecl); 10565 return VDecl->isInvalidDecl(); 10566 } 10567 10568 /// AddInitializerToDecl - Adds the initializer Init to the 10569 /// declaration dcl. If DirectInit is true, this is C++ direct 10570 /// initialization rather than copy initialization. 10571 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 10572 // If there is no declaration, there was an error parsing it. Just ignore 10573 // the initializer. 10574 if (!RealDecl || RealDecl->isInvalidDecl()) { 10575 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 10576 return; 10577 } 10578 10579 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 10580 // Pure-specifiers are handled in ActOnPureSpecifier. 10581 Diag(Method->getLocation(), diag::err_member_function_initialization) 10582 << Method->getDeclName() << Init->getSourceRange(); 10583 Method->setInvalidDecl(); 10584 return; 10585 } 10586 10587 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 10588 if (!VDecl) { 10589 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 10590 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 10591 RealDecl->setInvalidDecl(); 10592 return; 10593 } 10594 10595 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 10596 if (VDecl->getType()->isUndeducedType()) { 10597 // Attempt typo correction early so that the type of the init expression can 10598 // be deduced based on the chosen correction if the original init contains a 10599 // TypoExpr. 10600 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 10601 if (!Res.isUsable()) { 10602 RealDecl->setInvalidDecl(); 10603 return; 10604 } 10605 Init = Res.get(); 10606 10607 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 10608 return; 10609 } 10610 10611 // dllimport cannot be used on variable definitions. 10612 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 10613 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 10614 VDecl->setInvalidDecl(); 10615 return; 10616 } 10617 10618 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 10619 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 10620 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 10621 VDecl->setInvalidDecl(); 10622 return; 10623 } 10624 10625 if (!VDecl->getType()->isDependentType()) { 10626 // A definition must end up with a complete type, which means it must be 10627 // complete with the restriction that an array type might be completed by 10628 // the initializer; note that later code assumes this restriction. 10629 QualType BaseDeclType = VDecl->getType(); 10630 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 10631 BaseDeclType = Array->getElementType(); 10632 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 10633 diag::err_typecheck_decl_incomplete_type)) { 10634 RealDecl->setInvalidDecl(); 10635 return; 10636 } 10637 10638 // The variable can not have an abstract class type. 10639 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 10640 diag::err_abstract_type_in_decl, 10641 AbstractVariableType)) 10642 VDecl->setInvalidDecl(); 10643 } 10644 10645 // If adding the initializer will turn this declaration into a definition, 10646 // and we already have a definition for this variable, diagnose or otherwise 10647 // handle the situation. 10648 VarDecl *Def; 10649 if ((Def = VDecl->getDefinition()) && Def != VDecl && 10650 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 10651 !VDecl->isThisDeclarationADemotedDefinition() && 10652 checkVarDeclRedefinition(Def, VDecl)) 10653 return; 10654 10655 if (getLangOpts().CPlusPlus) { 10656 // C++ [class.static.data]p4 10657 // If a static data member is of const integral or const 10658 // enumeration type, its declaration in the class definition can 10659 // specify a constant-initializer which shall be an integral 10660 // constant expression (5.19). In that case, the member can appear 10661 // in integral constant expressions. The member shall still be 10662 // defined in a namespace scope if it is used in the program and the 10663 // namespace scope definition shall not contain an initializer. 10664 // 10665 // We already performed a redefinition check above, but for static 10666 // data members we also need to check whether there was an in-class 10667 // declaration with an initializer. 10668 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 10669 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 10670 << VDecl->getDeclName(); 10671 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 10672 diag::note_previous_initializer) 10673 << 0; 10674 return; 10675 } 10676 10677 if (VDecl->hasLocalStorage()) 10678 setFunctionHasBranchProtectedScope(); 10679 10680 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 10681 VDecl->setInvalidDecl(); 10682 return; 10683 } 10684 } 10685 10686 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 10687 // a kernel function cannot be initialized." 10688 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 10689 Diag(VDecl->getLocation(), diag::err_local_cant_init); 10690 VDecl->setInvalidDecl(); 10691 return; 10692 } 10693 10694 // Get the decls type and save a reference for later, since 10695 // CheckInitializerTypes may change it. 10696 QualType DclT = VDecl->getType(), SavT = DclT; 10697 10698 // Expressions default to 'id' when we're in a debugger 10699 // and we are assigning it to a variable of Objective-C pointer type. 10700 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 10701 Init->getType() == Context.UnknownAnyTy) { 10702 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 10703 if (Result.isInvalid()) { 10704 VDecl->setInvalidDecl(); 10705 return; 10706 } 10707 Init = Result.get(); 10708 } 10709 10710 // Perform the initialization. 10711 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 10712 if (!VDecl->isInvalidDecl()) { 10713 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 10714 InitializationKind Kind = InitializationKind::CreateForInit( 10715 VDecl->getLocation(), DirectInit, Init); 10716 10717 MultiExprArg Args = Init; 10718 if (CXXDirectInit) 10719 Args = MultiExprArg(CXXDirectInit->getExprs(), 10720 CXXDirectInit->getNumExprs()); 10721 10722 // Try to correct any TypoExprs in the initialization arguments. 10723 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 10724 ExprResult Res = CorrectDelayedTyposInExpr( 10725 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 10726 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 10727 return Init.Failed() ? ExprError() : E; 10728 }); 10729 if (Res.isInvalid()) { 10730 VDecl->setInvalidDecl(); 10731 } else if (Res.get() != Args[Idx]) { 10732 Args[Idx] = Res.get(); 10733 } 10734 } 10735 if (VDecl->isInvalidDecl()) 10736 return; 10737 10738 InitializationSequence InitSeq(*this, Entity, Kind, Args, 10739 /*TopLevelOfInitList=*/false, 10740 /*TreatUnavailableAsInvalid=*/false); 10741 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 10742 if (Result.isInvalid()) { 10743 VDecl->setInvalidDecl(); 10744 return; 10745 } 10746 10747 Init = Result.getAs<Expr>(); 10748 } 10749 10750 // Check for self-references within variable initializers. 10751 // Variables declared within a function/method body (except for references) 10752 // are handled by a dataflow analysis. 10753 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 10754 VDecl->getType()->isReferenceType()) { 10755 CheckSelfReference(*this, RealDecl, Init, DirectInit); 10756 } 10757 10758 // If the type changed, it means we had an incomplete type that was 10759 // completed by the initializer. For example: 10760 // int ary[] = { 1, 3, 5 }; 10761 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 10762 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 10763 VDecl->setType(DclT); 10764 10765 if (!VDecl->isInvalidDecl()) { 10766 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 10767 10768 if (VDecl->hasAttr<BlocksAttr>()) 10769 checkRetainCycles(VDecl, Init); 10770 10771 // It is safe to assign a weak reference into a strong variable. 10772 // Although this code can still have problems: 10773 // id x = self.weakProp; 10774 // id y = self.weakProp; 10775 // we do not warn to warn spuriously when 'x' and 'y' are on separate 10776 // paths through the function. This should be revisited if 10777 // -Wrepeated-use-of-weak is made flow-sensitive. 10778 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 10779 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 10780 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 10781 Init->getLocStart())) 10782 getCurFunction()->markSafeWeakUse(Init); 10783 } 10784 10785 // The initialization is usually a full-expression. 10786 // 10787 // FIXME: If this is a braced initialization of an aggregate, it is not 10788 // an expression, and each individual field initializer is a separate 10789 // full-expression. For instance, in: 10790 // 10791 // struct Temp { ~Temp(); }; 10792 // struct S { S(Temp); }; 10793 // struct T { S a, b; } t = { Temp(), Temp() } 10794 // 10795 // we should destroy the first Temp before constructing the second. 10796 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 10797 false, 10798 VDecl->isConstexpr()); 10799 if (Result.isInvalid()) { 10800 VDecl->setInvalidDecl(); 10801 return; 10802 } 10803 Init = Result.get(); 10804 10805 // Attach the initializer to the decl. 10806 VDecl->setInit(Init); 10807 10808 if (VDecl->isLocalVarDecl()) { 10809 // Don't check the initializer if the declaration is malformed. 10810 if (VDecl->isInvalidDecl()) { 10811 // do nothing 10812 10813 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 10814 // This is true even in OpenCL C++. 10815 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 10816 CheckForConstantInitializer(Init, DclT); 10817 10818 // Otherwise, C++ does not restrict the initializer. 10819 } else if (getLangOpts().CPlusPlus) { 10820 // do nothing 10821 10822 // C99 6.7.8p4: All the expressions in an initializer for an object that has 10823 // static storage duration shall be constant expressions or string literals. 10824 } else if (VDecl->getStorageClass() == SC_Static) { 10825 CheckForConstantInitializer(Init, DclT); 10826 10827 // C89 is stricter than C99 for aggregate initializers. 10828 // C89 6.5.7p3: All the expressions [...] in an initializer list 10829 // for an object that has aggregate or union type shall be 10830 // constant expressions. 10831 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 10832 isa<InitListExpr>(Init)) { 10833 const Expr *Culprit; 10834 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 10835 Diag(Culprit->getExprLoc(), 10836 diag::ext_aggregate_init_not_constant) 10837 << Culprit->getSourceRange(); 10838 } 10839 } 10840 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 10841 VDecl->getLexicalDeclContext()->isRecord()) { 10842 // This is an in-class initialization for a static data member, e.g., 10843 // 10844 // struct S { 10845 // static const int value = 17; 10846 // }; 10847 10848 // C++ [class.mem]p4: 10849 // A member-declarator can contain a constant-initializer only 10850 // if it declares a static member (9.4) of const integral or 10851 // const enumeration type, see 9.4.2. 10852 // 10853 // C++11 [class.static.data]p3: 10854 // If a non-volatile non-inline const static data member is of integral 10855 // or enumeration type, its declaration in the class definition can 10856 // specify a brace-or-equal-initializer in which every initializer-clause 10857 // that is an assignment-expression is a constant expression. A static 10858 // data member of literal type can be declared in the class definition 10859 // with the constexpr specifier; if so, its declaration shall specify a 10860 // brace-or-equal-initializer in which every initializer-clause that is 10861 // an assignment-expression is a constant expression. 10862 10863 // Do nothing on dependent types. 10864 if (DclT->isDependentType()) { 10865 10866 // Allow any 'static constexpr' members, whether or not they are of literal 10867 // type. We separately check that every constexpr variable is of literal 10868 // type. 10869 } else if (VDecl->isConstexpr()) { 10870 10871 // Require constness. 10872 } else if (!DclT.isConstQualified()) { 10873 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 10874 << Init->getSourceRange(); 10875 VDecl->setInvalidDecl(); 10876 10877 // We allow integer constant expressions in all cases. 10878 } else if (DclT->isIntegralOrEnumerationType()) { 10879 // Check whether the expression is a constant expression. 10880 SourceLocation Loc; 10881 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 10882 // In C++11, a non-constexpr const static data member with an 10883 // in-class initializer cannot be volatile. 10884 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 10885 else if (Init->isValueDependent()) 10886 ; // Nothing to check. 10887 else if (Init->isIntegerConstantExpr(Context, &Loc)) 10888 ; // Ok, it's an ICE! 10889 else if (Init->isEvaluatable(Context)) { 10890 // If we can constant fold the initializer through heroics, accept it, 10891 // but report this as a use of an extension for -pedantic. 10892 Diag(Loc, diag::ext_in_class_initializer_non_constant) 10893 << Init->getSourceRange(); 10894 } else { 10895 // Otherwise, this is some crazy unknown case. Report the issue at the 10896 // location provided by the isIntegerConstantExpr failed check. 10897 Diag(Loc, diag::err_in_class_initializer_non_constant) 10898 << Init->getSourceRange(); 10899 VDecl->setInvalidDecl(); 10900 } 10901 10902 // We allow foldable floating-point constants as an extension. 10903 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 10904 // In C++98, this is a GNU extension. In C++11, it is not, but we support 10905 // it anyway and provide a fixit to add the 'constexpr'. 10906 if (getLangOpts().CPlusPlus11) { 10907 Diag(VDecl->getLocation(), 10908 diag::ext_in_class_initializer_float_type_cxx11) 10909 << DclT << Init->getSourceRange(); 10910 Diag(VDecl->getLocStart(), 10911 diag::note_in_class_initializer_float_type_cxx11) 10912 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10913 } else { 10914 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 10915 << DclT << Init->getSourceRange(); 10916 10917 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 10918 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 10919 << Init->getSourceRange(); 10920 VDecl->setInvalidDecl(); 10921 } 10922 } 10923 10924 // Suggest adding 'constexpr' in C++11 for literal types. 10925 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 10926 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 10927 << DclT << Init->getSourceRange() 10928 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 10929 VDecl->setConstexpr(true); 10930 10931 } else { 10932 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 10933 << DclT << Init->getSourceRange(); 10934 VDecl->setInvalidDecl(); 10935 } 10936 } else if (VDecl->isFileVarDecl()) { 10937 // In C, extern is typically used to avoid tentative definitions when 10938 // declaring variables in headers, but adding an intializer makes it a 10939 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 10940 // In C++, extern is often used to give implictly static const variables 10941 // external linkage, so don't warn in that case. If selectany is present, 10942 // this might be header code intended for C and C++ inclusion, so apply the 10943 // C++ rules. 10944 if (VDecl->getStorageClass() == SC_Extern && 10945 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 10946 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 10947 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 10948 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 10949 Diag(VDecl->getLocation(), diag::warn_extern_init); 10950 10951 // C99 6.7.8p4. All file scoped initializers need to be constant. 10952 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 10953 CheckForConstantInitializer(Init, DclT); 10954 } 10955 10956 // We will represent direct-initialization similarly to copy-initialization: 10957 // int x(1); -as-> int x = 1; 10958 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 10959 // 10960 // Clients that want to distinguish between the two forms, can check for 10961 // direct initializer using VarDecl::getInitStyle(). 10962 // A major benefit is that clients that don't particularly care about which 10963 // exactly form was it (like the CodeGen) can handle both cases without 10964 // special case code. 10965 10966 // C++ 8.5p11: 10967 // The form of initialization (using parentheses or '=') is generally 10968 // insignificant, but does matter when the entity being initialized has a 10969 // class type. 10970 if (CXXDirectInit) { 10971 assert(DirectInit && "Call-style initializer must be direct init."); 10972 VDecl->setInitStyle(VarDecl::CallInit); 10973 } else if (DirectInit) { 10974 // This must be list-initialization. No other way is direct-initialization. 10975 VDecl->setInitStyle(VarDecl::ListInit); 10976 } 10977 10978 CheckCompleteVariableDeclaration(VDecl); 10979 } 10980 10981 /// ActOnInitializerError - Given that there was an error parsing an 10982 /// initializer for the given declaration, try to return to some form 10983 /// of sanity. 10984 void Sema::ActOnInitializerError(Decl *D) { 10985 // Our main concern here is re-establishing invariants like "a 10986 // variable's type is either dependent or complete". 10987 if (!D || D->isInvalidDecl()) return; 10988 10989 VarDecl *VD = dyn_cast<VarDecl>(D); 10990 if (!VD) return; 10991 10992 // Bindings are not usable if we can't make sense of the initializer. 10993 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 10994 for (auto *BD : DD->bindings()) 10995 BD->setInvalidDecl(); 10996 10997 // Auto types are meaningless if we can't make sense of the initializer. 10998 if (ParsingInitForAutoVars.count(D)) { 10999 D->setInvalidDecl(); 11000 return; 11001 } 11002 11003 QualType Ty = VD->getType(); 11004 if (Ty->isDependentType()) return; 11005 11006 // Require a complete type. 11007 if (RequireCompleteType(VD->getLocation(), 11008 Context.getBaseElementType(Ty), 11009 diag::err_typecheck_decl_incomplete_type)) { 11010 VD->setInvalidDecl(); 11011 return; 11012 } 11013 11014 // Require a non-abstract type. 11015 if (RequireNonAbstractType(VD->getLocation(), Ty, 11016 diag::err_abstract_type_in_decl, 11017 AbstractVariableType)) { 11018 VD->setInvalidDecl(); 11019 return; 11020 } 11021 11022 // Don't bother complaining about constructors or destructors, 11023 // though. 11024 } 11025 11026 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 11027 // If there is no declaration, there was an error parsing it. Just ignore it. 11028 if (!RealDecl) 11029 return; 11030 11031 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 11032 QualType Type = Var->getType(); 11033 11034 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 11035 if (isa<DecompositionDecl>(RealDecl)) { 11036 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 11037 Var->setInvalidDecl(); 11038 return; 11039 } 11040 11041 if (Type->isUndeducedType() && 11042 DeduceVariableDeclarationType(Var, false, nullptr)) 11043 return; 11044 11045 // C++11 [class.static.data]p3: A static data member can be declared with 11046 // the constexpr specifier; if so, its declaration shall specify 11047 // a brace-or-equal-initializer. 11048 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 11049 // the definition of a variable [...] or the declaration of a static data 11050 // member. 11051 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 11052 !Var->isThisDeclarationADemotedDefinition()) { 11053 if (Var->isStaticDataMember()) { 11054 // C++1z removes the relevant rule; the in-class declaration is always 11055 // a definition there. 11056 if (!getLangOpts().CPlusPlus17) { 11057 Diag(Var->getLocation(), 11058 diag::err_constexpr_static_mem_var_requires_init) 11059 << Var->getDeclName(); 11060 Var->setInvalidDecl(); 11061 return; 11062 } 11063 } else { 11064 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 11065 Var->setInvalidDecl(); 11066 return; 11067 } 11068 } 11069 11070 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 11071 // be initialized. 11072 if (!Var->isInvalidDecl() && 11073 Var->getType().getAddressSpace() == LangAS::opencl_constant && 11074 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 11075 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 11076 Var->setInvalidDecl(); 11077 return; 11078 } 11079 11080 switch (Var->isThisDeclarationADefinition()) { 11081 case VarDecl::Definition: 11082 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 11083 break; 11084 11085 // We have an out-of-line definition of a static data member 11086 // that has an in-class initializer, so we type-check this like 11087 // a declaration. 11088 // 11089 LLVM_FALLTHROUGH; 11090 11091 case VarDecl::DeclarationOnly: 11092 // It's only a declaration. 11093 11094 // Block scope. C99 6.7p7: If an identifier for an object is 11095 // declared with no linkage (C99 6.2.2p6), the type for the 11096 // object shall be complete. 11097 if (!Type->isDependentType() && Var->isLocalVarDecl() && 11098 !Var->hasLinkage() && !Var->isInvalidDecl() && 11099 RequireCompleteType(Var->getLocation(), Type, 11100 diag::err_typecheck_decl_incomplete_type)) 11101 Var->setInvalidDecl(); 11102 11103 // Make sure that the type is not abstract. 11104 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11105 RequireNonAbstractType(Var->getLocation(), Type, 11106 diag::err_abstract_type_in_decl, 11107 AbstractVariableType)) 11108 Var->setInvalidDecl(); 11109 if (!Type->isDependentType() && !Var->isInvalidDecl() && 11110 Var->getStorageClass() == SC_PrivateExtern) { 11111 Diag(Var->getLocation(), diag::warn_private_extern); 11112 Diag(Var->getLocation(), diag::note_private_extern); 11113 } 11114 11115 return; 11116 11117 case VarDecl::TentativeDefinition: 11118 // File scope. C99 6.9.2p2: A declaration of an identifier for an 11119 // object that has file scope without an initializer, and without a 11120 // storage-class specifier or with the storage-class specifier "static", 11121 // constitutes a tentative definition. Note: A tentative definition with 11122 // external linkage is valid (C99 6.2.2p5). 11123 if (!Var->isInvalidDecl()) { 11124 if (const IncompleteArrayType *ArrayT 11125 = Context.getAsIncompleteArrayType(Type)) { 11126 if (RequireCompleteType(Var->getLocation(), 11127 ArrayT->getElementType(), 11128 diag::err_illegal_decl_array_incomplete_type)) 11129 Var->setInvalidDecl(); 11130 } else if (Var->getStorageClass() == SC_Static) { 11131 // C99 6.9.2p3: If the declaration of an identifier for an object is 11132 // a tentative definition and has internal linkage (C99 6.2.2p3), the 11133 // declared type shall not be an incomplete type. 11134 // NOTE: code such as the following 11135 // static struct s; 11136 // struct s { int a; }; 11137 // is accepted by gcc. Hence here we issue a warning instead of 11138 // an error and we do not invalidate the static declaration. 11139 // NOTE: to avoid multiple warnings, only check the first declaration. 11140 if (Var->isFirstDecl()) 11141 RequireCompleteType(Var->getLocation(), Type, 11142 diag::ext_typecheck_decl_incomplete_type); 11143 } 11144 } 11145 11146 // Record the tentative definition; we're done. 11147 if (!Var->isInvalidDecl()) 11148 TentativeDefinitions.push_back(Var); 11149 return; 11150 } 11151 11152 // Provide a specific diagnostic for uninitialized variable 11153 // definitions with incomplete array type. 11154 if (Type->isIncompleteArrayType()) { 11155 Diag(Var->getLocation(), 11156 diag::err_typecheck_incomplete_array_needs_initializer); 11157 Var->setInvalidDecl(); 11158 return; 11159 } 11160 11161 // Provide a specific diagnostic for uninitialized variable 11162 // definitions with reference type. 11163 if (Type->isReferenceType()) { 11164 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 11165 << Var->getDeclName() 11166 << SourceRange(Var->getLocation(), Var->getLocation()); 11167 Var->setInvalidDecl(); 11168 return; 11169 } 11170 11171 // Do not attempt to type-check the default initializer for a 11172 // variable with dependent type. 11173 if (Type->isDependentType()) 11174 return; 11175 11176 if (Var->isInvalidDecl()) 11177 return; 11178 11179 if (!Var->hasAttr<AliasAttr>()) { 11180 if (RequireCompleteType(Var->getLocation(), 11181 Context.getBaseElementType(Type), 11182 diag::err_typecheck_decl_incomplete_type)) { 11183 Var->setInvalidDecl(); 11184 return; 11185 } 11186 } else { 11187 return; 11188 } 11189 11190 // The variable can not have an abstract class type. 11191 if (RequireNonAbstractType(Var->getLocation(), Type, 11192 diag::err_abstract_type_in_decl, 11193 AbstractVariableType)) { 11194 Var->setInvalidDecl(); 11195 return; 11196 } 11197 11198 // Check for jumps past the implicit initializer. C++0x 11199 // clarifies that this applies to a "variable with automatic 11200 // storage duration", not a "local variable". 11201 // C++11 [stmt.dcl]p3 11202 // A program that jumps from a point where a variable with automatic 11203 // storage duration is not in scope to a point where it is in scope is 11204 // ill-formed unless the variable has scalar type, class type with a 11205 // trivial default constructor and a trivial destructor, a cv-qualified 11206 // version of one of these types, or an array of one of the preceding 11207 // types and is declared without an initializer. 11208 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 11209 if (const RecordType *Record 11210 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 11211 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 11212 // Mark the function (if we're in one) for further checking even if the 11213 // looser rules of C++11 do not require such checks, so that we can 11214 // diagnose incompatibilities with C++98. 11215 if (!CXXRecord->isPOD()) 11216 setFunctionHasBranchProtectedScope(); 11217 } 11218 } 11219 11220 // C++03 [dcl.init]p9: 11221 // If no initializer is specified for an object, and the 11222 // object is of (possibly cv-qualified) non-POD class type (or 11223 // array thereof), the object shall be default-initialized; if 11224 // the object is of const-qualified type, the underlying class 11225 // type shall have a user-declared default 11226 // constructor. Otherwise, if no initializer is specified for 11227 // a non- static object, the object and its subobjects, if 11228 // any, have an indeterminate initial value); if the object 11229 // or any of its subobjects are of const-qualified type, the 11230 // program is ill-formed. 11231 // C++0x [dcl.init]p11: 11232 // If no initializer is specified for an object, the object is 11233 // default-initialized; [...]. 11234 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 11235 InitializationKind Kind 11236 = InitializationKind::CreateDefault(Var->getLocation()); 11237 11238 InitializationSequence InitSeq(*this, Entity, Kind, None); 11239 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 11240 if (Init.isInvalid()) 11241 Var->setInvalidDecl(); 11242 else if (Init.get()) { 11243 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 11244 // This is important for template substitution. 11245 Var->setInitStyle(VarDecl::CallInit); 11246 } 11247 11248 CheckCompleteVariableDeclaration(Var); 11249 } 11250 } 11251 11252 void Sema::ActOnCXXForRangeDecl(Decl *D) { 11253 // If there is no declaration, there was an error parsing it. Ignore it. 11254 if (!D) 11255 return; 11256 11257 VarDecl *VD = dyn_cast<VarDecl>(D); 11258 if (!VD) { 11259 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 11260 D->setInvalidDecl(); 11261 return; 11262 } 11263 11264 VD->setCXXForRangeDecl(true); 11265 11266 // for-range-declaration cannot be given a storage class specifier. 11267 int Error = -1; 11268 switch (VD->getStorageClass()) { 11269 case SC_None: 11270 break; 11271 case SC_Extern: 11272 Error = 0; 11273 break; 11274 case SC_Static: 11275 Error = 1; 11276 break; 11277 case SC_PrivateExtern: 11278 Error = 2; 11279 break; 11280 case SC_Auto: 11281 Error = 3; 11282 break; 11283 case SC_Register: 11284 Error = 4; 11285 break; 11286 } 11287 if (Error != -1) { 11288 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 11289 << VD->getDeclName() << Error; 11290 D->setInvalidDecl(); 11291 } 11292 } 11293 11294 StmtResult 11295 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 11296 IdentifierInfo *Ident, 11297 ParsedAttributes &Attrs, 11298 SourceLocation AttrEnd) { 11299 // C++1y [stmt.iter]p1: 11300 // A range-based for statement of the form 11301 // for ( for-range-identifier : for-range-initializer ) statement 11302 // is equivalent to 11303 // for ( auto&& for-range-identifier : for-range-initializer ) statement 11304 DeclSpec DS(Attrs.getPool().getFactory()); 11305 11306 const char *PrevSpec; 11307 unsigned DiagID; 11308 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 11309 getPrintingPolicy()); 11310 11311 Declarator D(DS, DeclaratorContext::ForContext); 11312 D.SetIdentifier(Ident, IdentLoc); 11313 D.takeAttributes(Attrs, AttrEnd); 11314 11315 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 11316 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 11317 EmptyAttrs, IdentLoc); 11318 Decl *Var = ActOnDeclarator(S, D); 11319 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 11320 FinalizeDeclaration(Var); 11321 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 11322 AttrEnd.isValid() ? AttrEnd : IdentLoc); 11323 } 11324 11325 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 11326 if (var->isInvalidDecl()) return; 11327 11328 if (getLangOpts().OpenCL) { 11329 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 11330 // initialiser 11331 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 11332 !var->hasInit()) { 11333 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 11334 << 1 /*Init*/; 11335 var->setInvalidDecl(); 11336 return; 11337 } 11338 } 11339 11340 // In Objective-C, don't allow jumps past the implicit initialization of a 11341 // local retaining variable. 11342 if (getLangOpts().ObjC1 && 11343 var->hasLocalStorage()) { 11344 switch (var->getType().getObjCLifetime()) { 11345 case Qualifiers::OCL_None: 11346 case Qualifiers::OCL_ExplicitNone: 11347 case Qualifiers::OCL_Autoreleasing: 11348 break; 11349 11350 case Qualifiers::OCL_Weak: 11351 case Qualifiers::OCL_Strong: 11352 setFunctionHasBranchProtectedScope(); 11353 break; 11354 } 11355 } 11356 11357 if (var->hasLocalStorage() && 11358 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 11359 setFunctionHasBranchProtectedScope(); 11360 11361 // Warn about externally-visible variables being defined without a 11362 // prior declaration. We only want to do this for global 11363 // declarations, but we also specifically need to avoid doing it for 11364 // class members because the linkage of an anonymous class can 11365 // change if it's later given a typedef name. 11366 if (var->isThisDeclarationADefinition() && 11367 var->getDeclContext()->getRedeclContext()->isFileContext() && 11368 var->isExternallyVisible() && var->hasLinkage() && 11369 !var->isInline() && !var->getDescribedVarTemplate() && 11370 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 11371 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 11372 var->getLocation())) { 11373 // Find a previous declaration that's not a definition. 11374 VarDecl *prev = var->getPreviousDecl(); 11375 while (prev && prev->isThisDeclarationADefinition()) 11376 prev = prev->getPreviousDecl(); 11377 11378 if (!prev) 11379 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 11380 } 11381 11382 // Cache the result of checking for constant initialization. 11383 Optional<bool> CacheHasConstInit; 11384 const Expr *CacheCulprit; 11385 auto checkConstInit = [&]() mutable { 11386 if (!CacheHasConstInit) 11387 CacheHasConstInit = var->getInit()->isConstantInitializer( 11388 Context, var->getType()->isReferenceType(), &CacheCulprit); 11389 return *CacheHasConstInit; 11390 }; 11391 11392 if (var->getTLSKind() == VarDecl::TLS_Static) { 11393 if (var->getType().isDestructedType()) { 11394 // GNU C++98 edits for __thread, [basic.start.term]p3: 11395 // The type of an object with thread storage duration shall not 11396 // have a non-trivial destructor. 11397 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 11398 if (getLangOpts().CPlusPlus11) 11399 Diag(var->getLocation(), diag::note_use_thread_local); 11400 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 11401 if (!checkConstInit()) { 11402 // GNU C++98 edits for __thread, [basic.start.init]p4: 11403 // An object of thread storage duration shall not require dynamic 11404 // initialization. 11405 // FIXME: Need strict checking here. 11406 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 11407 << CacheCulprit->getSourceRange(); 11408 if (getLangOpts().CPlusPlus11) 11409 Diag(var->getLocation(), diag::note_use_thread_local); 11410 } 11411 } 11412 } 11413 11414 // Apply section attributes and pragmas to global variables. 11415 bool GlobalStorage = var->hasGlobalStorage(); 11416 if (GlobalStorage && var->isThisDeclarationADefinition() && 11417 !inTemplateInstantiation()) { 11418 PragmaStack<StringLiteral *> *Stack = nullptr; 11419 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 11420 if (var->getType().isConstQualified()) 11421 Stack = &ConstSegStack; 11422 else if (!var->getInit()) { 11423 Stack = &BSSSegStack; 11424 SectionFlags |= ASTContext::PSF_Write; 11425 } else { 11426 Stack = &DataSegStack; 11427 SectionFlags |= ASTContext::PSF_Write; 11428 } 11429 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 11430 var->addAttr(SectionAttr::CreateImplicit( 11431 Context, SectionAttr::Declspec_allocate, 11432 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 11433 } 11434 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 11435 if (UnifySection(SA->getName(), SectionFlags, var)) 11436 var->dropAttr<SectionAttr>(); 11437 11438 // Apply the init_seg attribute if this has an initializer. If the 11439 // initializer turns out to not be dynamic, we'll end up ignoring this 11440 // attribute. 11441 if (CurInitSeg && var->getInit()) 11442 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 11443 CurInitSegLoc)); 11444 } 11445 11446 // All the following checks are C++ only. 11447 if (!getLangOpts().CPlusPlus) { 11448 // If this variable must be emitted, add it as an initializer for the 11449 // current module. 11450 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11451 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11452 return; 11453 } 11454 11455 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 11456 CheckCompleteDecompositionDeclaration(DD); 11457 11458 QualType type = var->getType(); 11459 if (type->isDependentType()) return; 11460 11461 // __block variables might require us to capture a copy-initializer. 11462 if (var->hasAttr<BlocksAttr>()) { 11463 // It's currently invalid to ever have a __block variable with an 11464 // array type; should we diagnose that here? 11465 11466 // Regardless, we don't want to ignore array nesting when 11467 // constructing this copy. 11468 if (type->isStructureOrClassType()) { 11469 EnterExpressionEvaluationContext scope( 11470 *this, ExpressionEvaluationContext::PotentiallyEvaluated); 11471 SourceLocation poi = var->getLocation(); 11472 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 11473 ExprResult result 11474 = PerformMoveOrCopyInitialization( 11475 InitializedEntity::InitializeBlock(poi, type, false), 11476 var, var->getType(), varRef, /*AllowNRVO=*/true); 11477 if (!result.isInvalid()) { 11478 result = MaybeCreateExprWithCleanups(result); 11479 Expr *init = result.getAs<Expr>(); 11480 Context.setBlockVarCopyInits(var, init); 11481 } 11482 } 11483 } 11484 11485 Expr *Init = var->getInit(); 11486 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 11487 QualType baseType = Context.getBaseElementType(type); 11488 11489 if (Init && !Init->isValueDependent()) { 11490 if (var->isConstexpr()) { 11491 SmallVector<PartialDiagnosticAt, 8> Notes; 11492 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 11493 SourceLocation DiagLoc = var->getLocation(); 11494 // If the note doesn't add any useful information other than a source 11495 // location, fold it into the primary diagnostic. 11496 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 11497 diag::note_invalid_subexpr_in_const_expr) { 11498 DiagLoc = Notes[0].first; 11499 Notes.clear(); 11500 } 11501 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 11502 << var << Init->getSourceRange(); 11503 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 11504 Diag(Notes[I].first, Notes[I].second); 11505 } 11506 } else if (var->isUsableInConstantExpressions(Context)) { 11507 // Check whether the initializer of a const variable of integral or 11508 // enumeration type is an ICE now, since we can't tell whether it was 11509 // initialized by a constant expression if we check later. 11510 var->checkInitIsICE(); 11511 } 11512 11513 // Don't emit further diagnostics about constexpr globals since they 11514 // were just diagnosed. 11515 if (!var->isConstexpr() && GlobalStorage && 11516 var->hasAttr<RequireConstantInitAttr>()) { 11517 // FIXME: Need strict checking in C++03 here. 11518 bool DiagErr = getLangOpts().CPlusPlus11 11519 ? !var->checkInitIsICE() : !checkConstInit(); 11520 if (DiagErr) { 11521 auto attr = var->getAttr<RequireConstantInitAttr>(); 11522 Diag(var->getLocation(), diag::err_require_constant_init_failed) 11523 << Init->getSourceRange(); 11524 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here) 11525 << attr->getRange(); 11526 if (getLangOpts().CPlusPlus11) { 11527 APValue Value; 11528 SmallVector<PartialDiagnosticAt, 8> Notes; 11529 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 11530 for (auto &it : Notes) 11531 Diag(it.first, it.second); 11532 } else { 11533 Diag(CacheCulprit->getExprLoc(), 11534 diag::note_invalid_subexpr_in_const_expr) 11535 << CacheCulprit->getSourceRange(); 11536 } 11537 } 11538 } 11539 else if (!var->isConstexpr() && IsGlobal && 11540 !getDiagnostics().isIgnored(diag::warn_global_constructor, 11541 var->getLocation())) { 11542 // Warn about globals which don't have a constant initializer. Don't 11543 // warn about globals with a non-trivial destructor because we already 11544 // warned about them. 11545 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 11546 if (!(RD && !RD->hasTrivialDestructor())) { 11547 if (!checkConstInit()) 11548 Diag(var->getLocation(), diag::warn_global_constructor) 11549 << Init->getSourceRange(); 11550 } 11551 } 11552 } 11553 11554 // Require the destructor. 11555 if (const RecordType *recordType = baseType->getAs<RecordType>()) 11556 FinalizeVarWithDestructor(var, recordType); 11557 11558 // If this variable must be emitted, add it as an initializer for the current 11559 // module. 11560 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 11561 Context.addModuleInitializer(ModuleScopes.back().Module, var); 11562 } 11563 11564 /// \brief Determines if a variable's alignment is dependent. 11565 static bool hasDependentAlignment(VarDecl *VD) { 11566 if (VD->getType()->isDependentType()) 11567 return true; 11568 for (auto *I : VD->specific_attrs<AlignedAttr>()) 11569 if (I->isAlignmentDependent()) 11570 return true; 11571 return false; 11572 } 11573 11574 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 11575 /// any semantic actions necessary after any initializer has been attached. 11576 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 11577 // Note that we are no longer parsing the initializer for this declaration. 11578 ParsingInitForAutoVars.erase(ThisDecl); 11579 11580 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 11581 if (!VD) 11582 return; 11583 11584 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 11585 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 11586 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 11587 if (PragmaClangBSSSection.Valid) 11588 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context, 11589 PragmaClangBSSSection.SectionName, 11590 PragmaClangBSSSection.PragmaLocation)); 11591 if (PragmaClangDataSection.Valid) 11592 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context, 11593 PragmaClangDataSection.SectionName, 11594 PragmaClangDataSection.PragmaLocation)); 11595 if (PragmaClangRodataSection.Valid) 11596 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context, 11597 PragmaClangRodataSection.SectionName, 11598 PragmaClangRodataSection.PragmaLocation)); 11599 } 11600 11601 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 11602 for (auto *BD : DD->bindings()) { 11603 FinalizeDeclaration(BD); 11604 } 11605 } 11606 11607 checkAttributesAfterMerging(*this, *VD); 11608 11609 // Perform TLS alignment check here after attributes attached to the variable 11610 // which may affect the alignment have been processed. Only perform the check 11611 // if the target has a maximum TLS alignment (zero means no constraints). 11612 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 11613 // Protect the check so that it's not performed on dependent types and 11614 // dependent alignments (we can't determine the alignment in that case). 11615 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 11616 !VD->isInvalidDecl()) { 11617 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 11618 if (Context.getDeclAlign(VD) > MaxAlignChars) { 11619 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 11620 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 11621 << (unsigned)MaxAlignChars.getQuantity(); 11622 } 11623 } 11624 } 11625 11626 if (VD->isStaticLocal()) { 11627 if (FunctionDecl *FD = 11628 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 11629 // Static locals inherit dll attributes from their function. 11630 if (Attr *A = getDLLAttr(FD)) { 11631 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 11632 NewAttr->setInherited(true); 11633 VD->addAttr(NewAttr); 11634 } 11635 // CUDA E.2.9.4: Within the body of a __device__ or __global__ 11636 // function, only __shared__ variables may be declared with 11637 // static storage class. 11638 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() && 11639 CUDADiagIfDeviceCode(VD->getLocation(), 11640 diag::err_device_static_local_var) 11641 << CurrentCUDATarget()) 11642 VD->setInvalidDecl(); 11643 } 11644 } 11645 11646 // Perform check for initializers of device-side global variables. 11647 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 11648 // 7.5). We must also apply the same checks to all __shared__ 11649 // variables whether they are local or not. CUDA also allows 11650 // constant initializers for __constant__ and __device__ variables. 11651 if (getLangOpts().CUDA) { 11652 const Expr *Init = VD->getInit(); 11653 if (Init && VD->hasGlobalStorage()) { 11654 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() || 11655 VD->hasAttr<CUDASharedAttr>()) { 11656 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()); 11657 bool AllowedInit = false; 11658 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) 11659 AllowedInit = 11660 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor()); 11661 // We'll allow constant initializers even if it's a non-empty 11662 // constructor according to CUDA rules. This deviates from NVCC, 11663 // but allows us to handle things like constexpr constructors. 11664 if (!AllowedInit && 11665 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 11666 AllowedInit = VD->getInit()->isConstantInitializer( 11667 Context, VD->getType()->isReferenceType()); 11668 11669 // Also make sure that destructor, if there is one, is empty. 11670 if (AllowedInit) 11671 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl()) 11672 AllowedInit = 11673 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor()); 11674 11675 if (!AllowedInit) { 11676 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>() 11677 ? diag::err_shared_var_init 11678 : diag::err_dynamic_var_init) 11679 << Init->getSourceRange(); 11680 VD->setInvalidDecl(); 11681 } 11682 } else { 11683 // This is a host-side global variable. Check that the initializer is 11684 // callable from the host side. 11685 const FunctionDecl *InitFn = nullptr; 11686 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) { 11687 InitFn = CE->getConstructor(); 11688 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) { 11689 InitFn = CE->getDirectCallee(); 11690 } 11691 if (InitFn) { 11692 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn); 11693 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) { 11694 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer) 11695 << InitFnTarget << InitFn; 11696 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn; 11697 VD->setInvalidDecl(); 11698 } 11699 } 11700 } 11701 } 11702 } 11703 11704 // Grab the dllimport or dllexport attribute off of the VarDecl. 11705 const InheritableAttr *DLLAttr = getDLLAttr(VD); 11706 11707 // Imported static data members cannot be defined out-of-line. 11708 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 11709 if (VD->isStaticDataMember() && VD->isOutOfLine() && 11710 VD->isThisDeclarationADefinition()) { 11711 // We allow definitions of dllimport class template static data members 11712 // with a warning. 11713 CXXRecordDecl *Context = 11714 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 11715 bool IsClassTemplateMember = 11716 isa<ClassTemplatePartialSpecializationDecl>(Context) || 11717 Context->getDescribedClassTemplate(); 11718 11719 Diag(VD->getLocation(), 11720 IsClassTemplateMember 11721 ? diag::warn_attribute_dllimport_static_field_definition 11722 : diag::err_attribute_dllimport_static_field_definition); 11723 Diag(IA->getLocation(), diag::note_attribute); 11724 if (!IsClassTemplateMember) 11725 VD->setInvalidDecl(); 11726 } 11727 } 11728 11729 // dllimport/dllexport variables cannot be thread local, their TLS index 11730 // isn't exported with the variable. 11731 if (DLLAttr && VD->getTLSKind()) { 11732 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 11733 if (F && getDLLAttr(F)) { 11734 assert(VD->isStaticLocal()); 11735 // But if this is a static local in a dlimport/dllexport function, the 11736 // function will never be inlined, which means the var would never be 11737 // imported, so having it marked import/export is safe. 11738 } else { 11739 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 11740 << DLLAttr; 11741 VD->setInvalidDecl(); 11742 } 11743 } 11744 11745 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 11746 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 11747 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 11748 VD->dropAttr<UsedAttr>(); 11749 } 11750 } 11751 11752 const DeclContext *DC = VD->getDeclContext(); 11753 // If there's a #pragma GCC visibility in scope, and this isn't a class 11754 // member, set the visibility of this variable. 11755 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 11756 AddPushedVisibilityAttribute(VD); 11757 11758 // FIXME: Warn on unused var template partial specializations. 11759 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 11760 MarkUnusedFileScopedDecl(VD); 11761 11762 // Now we have parsed the initializer and can update the table of magic 11763 // tag values. 11764 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 11765 !VD->getType()->isIntegralOrEnumerationType()) 11766 return; 11767 11768 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 11769 const Expr *MagicValueExpr = VD->getInit(); 11770 if (!MagicValueExpr) { 11771 continue; 11772 } 11773 llvm::APSInt MagicValueInt; 11774 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 11775 Diag(I->getRange().getBegin(), 11776 diag::err_type_tag_for_datatype_not_ice) 11777 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11778 continue; 11779 } 11780 if (MagicValueInt.getActiveBits() > 64) { 11781 Diag(I->getRange().getBegin(), 11782 diag::err_type_tag_for_datatype_too_large) 11783 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 11784 continue; 11785 } 11786 uint64_t MagicValue = MagicValueInt.getZExtValue(); 11787 RegisterTypeTagForDatatype(I->getArgumentKind(), 11788 MagicValue, 11789 I->getMatchingCType(), 11790 I->getLayoutCompatible(), 11791 I->getMustBeNull()); 11792 } 11793 } 11794 11795 static bool hasDeducedAuto(DeclaratorDecl *DD) { 11796 auto *VD = dyn_cast<VarDecl>(DD); 11797 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 11798 } 11799 11800 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 11801 ArrayRef<Decl *> Group) { 11802 SmallVector<Decl*, 8> Decls; 11803 11804 if (DS.isTypeSpecOwned()) 11805 Decls.push_back(DS.getRepAsDecl()); 11806 11807 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 11808 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 11809 bool DiagnosedMultipleDecomps = false; 11810 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 11811 bool DiagnosedNonDeducedAuto = false; 11812 11813 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11814 if (Decl *D = Group[i]) { 11815 // For declarators, there are some additional syntactic-ish checks we need 11816 // to perform. 11817 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 11818 if (!FirstDeclaratorInGroup) 11819 FirstDeclaratorInGroup = DD; 11820 if (!FirstDecompDeclaratorInGroup) 11821 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 11822 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 11823 !hasDeducedAuto(DD)) 11824 FirstNonDeducedAutoInGroup = DD; 11825 11826 if (FirstDeclaratorInGroup != DD) { 11827 // A decomposition declaration cannot be combined with any other 11828 // declaration in the same group. 11829 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 11830 Diag(FirstDecompDeclaratorInGroup->getLocation(), 11831 diag::err_decomp_decl_not_alone) 11832 << FirstDeclaratorInGroup->getSourceRange() 11833 << DD->getSourceRange(); 11834 DiagnosedMultipleDecomps = true; 11835 } 11836 11837 // A declarator that uses 'auto' in any way other than to declare a 11838 // variable with a deduced type cannot be combined with any other 11839 // declarator in the same group. 11840 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 11841 Diag(FirstNonDeducedAutoInGroup->getLocation(), 11842 diag::err_auto_non_deduced_not_alone) 11843 << FirstNonDeducedAutoInGroup->getType() 11844 ->hasAutoForTrailingReturnType() 11845 << FirstDeclaratorInGroup->getSourceRange() 11846 << DD->getSourceRange(); 11847 DiagnosedNonDeducedAuto = true; 11848 } 11849 } 11850 } 11851 11852 Decls.push_back(D); 11853 } 11854 } 11855 11856 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 11857 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 11858 handleTagNumbering(Tag, S); 11859 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 11860 getLangOpts().CPlusPlus) 11861 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 11862 } 11863 } 11864 11865 return BuildDeclaratorGroup(Decls); 11866 } 11867 11868 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 11869 /// group, performing any necessary semantic checking. 11870 Sema::DeclGroupPtrTy 11871 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 11872 // C++14 [dcl.spec.auto]p7: (DR1347) 11873 // If the type that replaces the placeholder type is not the same in each 11874 // deduction, the program is ill-formed. 11875 if (Group.size() > 1) { 11876 QualType Deduced; 11877 VarDecl *DeducedDecl = nullptr; 11878 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 11879 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 11880 if (!D || D->isInvalidDecl()) 11881 break; 11882 DeducedType *DT = D->getType()->getContainedDeducedType(); 11883 if (!DT || DT->getDeducedType().isNull()) 11884 continue; 11885 if (Deduced.isNull()) { 11886 Deduced = DT->getDeducedType(); 11887 DeducedDecl = D; 11888 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 11889 auto *AT = dyn_cast<AutoType>(DT); 11890 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 11891 diag::err_auto_different_deductions) 11892 << (AT ? (unsigned)AT->getKeyword() : 3) 11893 << Deduced << DeducedDecl->getDeclName() 11894 << DT->getDeducedType() << D->getDeclName() 11895 << DeducedDecl->getInit()->getSourceRange() 11896 << D->getInit()->getSourceRange(); 11897 D->setInvalidDecl(); 11898 break; 11899 } 11900 } 11901 } 11902 11903 ActOnDocumentableDecls(Group); 11904 11905 return DeclGroupPtrTy::make( 11906 DeclGroupRef::Create(Context, Group.data(), Group.size())); 11907 } 11908 11909 void Sema::ActOnDocumentableDecl(Decl *D) { 11910 ActOnDocumentableDecls(D); 11911 } 11912 11913 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 11914 // Don't parse the comment if Doxygen diagnostics are ignored. 11915 if (Group.empty() || !Group[0]) 11916 return; 11917 11918 if (Diags.isIgnored(diag::warn_doc_param_not_found, 11919 Group[0]->getLocation()) && 11920 Diags.isIgnored(diag::warn_unknown_comment_command_name, 11921 Group[0]->getLocation())) 11922 return; 11923 11924 if (Group.size() >= 2) { 11925 // This is a decl group. Normally it will contain only declarations 11926 // produced from declarator list. But in case we have any definitions or 11927 // additional declaration references: 11928 // 'typedef struct S {} S;' 11929 // 'typedef struct S *S;' 11930 // 'struct S *pS;' 11931 // FinalizeDeclaratorGroup adds these as separate declarations. 11932 Decl *MaybeTagDecl = Group[0]; 11933 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 11934 Group = Group.slice(1); 11935 } 11936 } 11937 11938 // See if there are any new comments that are not attached to a decl. 11939 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 11940 if (!Comments.empty() && 11941 !Comments.back()->isAttached()) { 11942 // There is at least one comment that not attached to a decl. 11943 // Maybe it should be attached to one of these decls? 11944 // 11945 // Note that this way we pick up not only comments that precede the 11946 // declaration, but also comments that *follow* the declaration -- thanks to 11947 // the lookahead in the lexer: we've consumed the semicolon and looked 11948 // ahead through comments. 11949 for (unsigned i = 0, e = Group.size(); i != e; ++i) 11950 Context.getCommentForDecl(Group[i], &PP); 11951 } 11952 } 11953 11954 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 11955 /// to introduce parameters into function prototype scope. 11956 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 11957 const DeclSpec &DS = D.getDeclSpec(); 11958 11959 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 11960 11961 // C++03 [dcl.stc]p2 also permits 'auto'. 11962 StorageClass SC = SC_None; 11963 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 11964 SC = SC_Register; 11965 // In C++11, the 'register' storage class specifier is deprecated. 11966 // In C++17, it is not allowed, but we tolerate it as an extension. 11967 if (getLangOpts().CPlusPlus11) { 11968 Diag(DS.getStorageClassSpecLoc(), 11969 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 11970 : diag::warn_deprecated_register) 11971 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 11972 } 11973 } else if (getLangOpts().CPlusPlus && 11974 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 11975 SC = SC_Auto; 11976 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 11977 Diag(DS.getStorageClassSpecLoc(), 11978 diag::err_invalid_storage_class_in_func_decl); 11979 D.getMutableDeclSpec().ClearStorageClassSpecs(); 11980 } 11981 11982 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 11983 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 11984 << DeclSpec::getSpecifierName(TSCS); 11985 if (DS.isInlineSpecified()) 11986 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 11987 << getLangOpts().CPlusPlus17; 11988 if (DS.isConstexprSpecified()) 11989 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 11990 << 0; 11991 11992 DiagnoseFunctionSpecifiers(DS); 11993 11994 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 11995 QualType parmDeclType = TInfo->getType(); 11996 11997 if (getLangOpts().CPlusPlus) { 11998 // Check that there are no default arguments inside the type of this 11999 // parameter. 12000 CheckExtraCXXDefaultArguments(D); 12001 12002 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 12003 if (D.getCXXScopeSpec().isSet()) { 12004 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 12005 << D.getCXXScopeSpec().getRange(); 12006 D.getCXXScopeSpec().clear(); 12007 } 12008 } 12009 12010 // Ensure we have a valid name 12011 IdentifierInfo *II = nullptr; 12012 if (D.hasName()) { 12013 II = D.getIdentifier(); 12014 if (!II) { 12015 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 12016 << GetNameForDeclarator(D).getName(); 12017 D.setInvalidType(true); 12018 } 12019 } 12020 12021 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 12022 if (II) { 12023 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 12024 ForVisibleRedeclaration); 12025 LookupName(R, S); 12026 if (R.isSingleResult()) { 12027 NamedDecl *PrevDecl = R.getFoundDecl(); 12028 if (PrevDecl->isTemplateParameter()) { 12029 // Maybe we will complain about the shadowed template parameter. 12030 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12031 // Just pretend that we didn't see the previous declaration. 12032 PrevDecl = nullptr; 12033 } else if (S->isDeclScope(PrevDecl)) { 12034 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 12035 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12036 12037 // Recover by removing the name 12038 II = nullptr; 12039 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 12040 D.setInvalidType(true); 12041 } 12042 } 12043 } 12044 12045 // Temporarily put parameter variables in the translation unit, not 12046 // the enclosing context. This prevents them from accidentally 12047 // looking like class members in C++. 12048 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 12049 D.getLocStart(), 12050 D.getIdentifierLoc(), II, 12051 parmDeclType, TInfo, 12052 SC); 12053 12054 if (D.isInvalidType()) 12055 New->setInvalidDecl(); 12056 12057 assert(S->isFunctionPrototypeScope()); 12058 assert(S->getFunctionPrototypeDepth() >= 1); 12059 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 12060 S->getNextFunctionPrototypeIndex()); 12061 12062 // Add the parameter declaration into this scope. 12063 S->AddDecl(New); 12064 if (II) 12065 IdResolver.AddDecl(New); 12066 12067 ProcessDeclAttributes(S, New, D); 12068 12069 if (D.getDeclSpec().isModulePrivateSpecified()) 12070 Diag(New->getLocation(), diag::err_module_private_local) 12071 << 1 << New->getDeclName() 12072 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 12073 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 12074 12075 if (New->hasAttr<BlocksAttr>()) { 12076 Diag(New->getLocation(), diag::err_block_on_nonlocal); 12077 } 12078 return New; 12079 } 12080 12081 /// \brief Synthesizes a variable for a parameter arising from a 12082 /// typedef. 12083 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 12084 SourceLocation Loc, 12085 QualType T) { 12086 /* FIXME: setting StartLoc == Loc. 12087 Would it be worth to modify callers so as to provide proper source 12088 location for the unnamed parameters, embedding the parameter's type? */ 12089 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 12090 T, Context.getTrivialTypeSourceInfo(T, Loc), 12091 SC_None, nullptr); 12092 Param->setImplicit(); 12093 return Param; 12094 } 12095 12096 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 12097 // Don't diagnose unused-parameter errors in template instantiations; we 12098 // will already have done so in the template itself. 12099 if (inTemplateInstantiation()) 12100 return; 12101 12102 for (const ParmVarDecl *Parameter : Parameters) { 12103 if (!Parameter->isReferenced() && Parameter->getDeclName() && 12104 !Parameter->hasAttr<UnusedAttr>()) { 12105 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 12106 << Parameter->getDeclName(); 12107 } 12108 } 12109 } 12110 12111 void Sema::DiagnoseSizeOfParametersAndReturnValue( 12112 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 12113 if (LangOpts.NumLargeByValueCopy == 0) // No check. 12114 return; 12115 12116 // Warn if the return value is pass-by-value and larger than the specified 12117 // threshold. 12118 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 12119 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 12120 if (Size > LangOpts.NumLargeByValueCopy) 12121 Diag(D->getLocation(), diag::warn_return_value_size) 12122 << D->getDeclName() << Size; 12123 } 12124 12125 // Warn if any parameter is pass-by-value and larger than the specified 12126 // threshold. 12127 for (const ParmVarDecl *Parameter : Parameters) { 12128 QualType T = Parameter->getType(); 12129 if (T->isDependentType() || !T.isPODType(Context)) 12130 continue; 12131 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 12132 if (Size > LangOpts.NumLargeByValueCopy) 12133 Diag(Parameter->getLocation(), diag::warn_parameter_size) 12134 << Parameter->getDeclName() << Size; 12135 } 12136 } 12137 12138 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 12139 SourceLocation NameLoc, IdentifierInfo *Name, 12140 QualType T, TypeSourceInfo *TSInfo, 12141 StorageClass SC) { 12142 // In ARC, infer a lifetime qualifier for appropriate parameter types. 12143 if (getLangOpts().ObjCAutoRefCount && 12144 T.getObjCLifetime() == Qualifiers::OCL_None && 12145 T->isObjCLifetimeType()) { 12146 12147 Qualifiers::ObjCLifetime lifetime; 12148 12149 // Special cases for arrays: 12150 // - if it's const, use __unsafe_unretained 12151 // - otherwise, it's an error 12152 if (T->isArrayType()) { 12153 if (!T.isConstQualified()) { 12154 DelayedDiagnostics.add( 12155 sema::DelayedDiagnostic::makeForbiddenType( 12156 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 12157 } 12158 lifetime = Qualifiers::OCL_ExplicitNone; 12159 } else { 12160 lifetime = T->getObjCARCImplicitLifetime(); 12161 } 12162 T = Context.getLifetimeQualifiedType(T, lifetime); 12163 } 12164 12165 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 12166 Context.getAdjustedParameterType(T), 12167 TSInfo, SC, nullptr); 12168 12169 // Parameters can not be abstract class types. 12170 // For record types, this is done by the AbstractClassUsageDiagnoser once 12171 // the class has been completely parsed. 12172 if (!CurContext->isRecord() && 12173 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 12174 AbstractParamType)) 12175 New->setInvalidDecl(); 12176 12177 // Parameter declarators cannot be interface types. All ObjC objects are 12178 // passed by reference. 12179 if (T->isObjCObjectType()) { 12180 SourceLocation TypeEndLoc = 12181 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd()); 12182 Diag(NameLoc, 12183 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 12184 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 12185 T = Context.getObjCObjectPointerType(T); 12186 New->setType(T); 12187 } 12188 12189 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 12190 // duration shall not be qualified by an address-space qualifier." 12191 // Since all parameters have automatic store duration, they can not have 12192 // an address space. 12193 if (T.getAddressSpace() != LangAS::Default && 12194 // OpenCL allows function arguments declared to be an array of a type 12195 // to be qualified with an address space. 12196 !(getLangOpts().OpenCL && 12197 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 12198 Diag(NameLoc, diag::err_arg_with_address_space); 12199 New->setInvalidDecl(); 12200 } 12201 12202 return New; 12203 } 12204 12205 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 12206 SourceLocation LocAfterDecls) { 12207 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 12208 12209 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 12210 // for a K&R function. 12211 if (!FTI.hasPrototype) { 12212 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 12213 --i; 12214 if (FTI.Params[i].Param == nullptr) { 12215 SmallString<256> Code; 12216 llvm::raw_svector_ostream(Code) 12217 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 12218 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 12219 << FTI.Params[i].Ident 12220 << FixItHint::CreateInsertion(LocAfterDecls, Code); 12221 12222 // Implicitly declare the argument as type 'int' for lack of a better 12223 // type. 12224 AttributeFactory attrs; 12225 DeclSpec DS(attrs); 12226 const char* PrevSpec; // unused 12227 unsigned DiagID; // unused 12228 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 12229 DiagID, Context.getPrintingPolicy()); 12230 // Use the identifier location for the type source range. 12231 DS.SetRangeStart(FTI.Params[i].IdentLoc); 12232 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 12233 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 12234 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 12235 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 12236 } 12237 } 12238 } 12239 } 12240 12241 Decl * 12242 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 12243 MultiTemplateParamsArg TemplateParameterLists, 12244 SkipBodyInfo *SkipBody) { 12245 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 12246 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 12247 Scope *ParentScope = FnBodyScope->getParent(); 12248 12249 D.setFunctionDefinitionKind(FDK_Definition); 12250 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 12251 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 12252 } 12253 12254 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 12255 Consumer.HandleInlineFunctionDefinition(D); 12256 } 12257 12258 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 12259 const FunctionDecl*& PossibleZeroParamPrototype) { 12260 // Don't warn about invalid declarations. 12261 if (FD->isInvalidDecl()) 12262 return false; 12263 12264 // Or declarations that aren't global. 12265 if (!FD->isGlobal()) 12266 return false; 12267 12268 // Don't warn about C++ member functions. 12269 if (isa<CXXMethodDecl>(FD)) 12270 return false; 12271 12272 // Don't warn about 'main'. 12273 if (FD->isMain()) 12274 return false; 12275 12276 // Don't warn about inline functions. 12277 if (FD->isInlined()) 12278 return false; 12279 12280 // Don't warn about function templates. 12281 if (FD->getDescribedFunctionTemplate()) 12282 return false; 12283 12284 // Don't warn about function template specializations. 12285 if (FD->isFunctionTemplateSpecialization()) 12286 return false; 12287 12288 // Don't warn for OpenCL kernels. 12289 if (FD->hasAttr<OpenCLKernelAttr>()) 12290 return false; 12291 12292 // Don't warn on explicitly deleted functions. 12293 if (FD->isDeleted()) 12294 return false; 12295 12296 bool MissingPrototype = true; 12297 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 12298 Prev; Prev = Prev->getPreviousDecl()) { 12299 // Ignore any declarations that occur in function or method 12300 // scope, because they aren't visible from the header. 12301 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 12302 continue; 12303 12304 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 12305 if (FD->getNumParams() == 0) 12306 PossibleZeroParamPrototype = Prev; 12307 break; 12308 } 12309 12310 return MissingPrototype; 12311 } 12312 12313 void 12314 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 12315 const FunctionDecl *EffectiveDefinition, 12316 SkipBodyInfo *SkipBody) { 12317 const FunctionDecl *Definition = EffectiveDefinition; 12318 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 12319 // If this is a friend function defined in a class template, it does not 12320 // have a body until it is used, nevertheless it is a definition, see 12321 // [temp.inst]p2: 12322 // 12323 // ... for the purpose of determining whether an instantiated redeclaration 12324 // is valid according to [basic.def.odr] and [class.mem], a declaration that 12325 // corresponds to a definition in the template is considered to be a 12326 // definition. 12327 // 12328 // The following code must produce redefinition error: 12329 // 12330 // template<typename T> struct C20 { friend void func_20() {} }; 12331 // C20<int> c20i; 12332 // void func_20() {} 12333 // 12334 for (auto I : FD->redecls()) { 12335 if (I != FD && !I->isInvalidDecl() && 12336 I->getFriendObjectKind() != Decl::FOK_None) { 12337 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 12338 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 12339 // A merged copy of the same function, instantiated as a member of 12340 // the same class, is OK. 12341 if (declaresSameEntity(OrigFD, Original) && 12342 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 12343 cast<Decl>(FD->getLexicalDeclContext()))) 12344 continue; 12345 } 12346 12347 if (Original->isThisDeclarationADefinition()) { 12348 Definition = I; 12349 break; 12350 } 12351 } 12352 } 12353 } 12354 } 12355 if (!Definition) 12356 return; 12357 12358 if (canRedefineFunction(Definition, getLangOpts())) 12359 return; 12360 12361 // Don't emit an error when this is redefinition of a typo-corrected 12362 // definition. 12363 if (TypoCorrectedFunctionDefinitions.count(Definition)) 12364 return; 12365 12366 // If we don't have a visible definition of the function, and it's inline or 12367 // a template, skip the new definition. 12368 if (SkipBody && !hasVisibleDefinition(Definition) && 12369 (Definition->getFormalLinkage() == InternalLinkage || 12370 Definition->isInlined() || 12371 Definition->getDescribedFunctionTemplate() || 12372 Definition->getNumTemplateParameterLists())) { 12373 SkipBody->ShouldSkip = true; 12374 if (auto *TD = Definition->getDescribedFunctionTemplate()) 12375 makeMergedDefinitionVisible(TD); 12376 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 12377 return; 12378 } 12379 12380 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 12381 Definition->getStorageClass() == SC_Extern) 12382 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 12383 << FD->getDeclName() << getLangOpts().CPlusPlus; 12384 else 12385 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 12386 12387 Diag(Definition->getLocation(), diag::note_previous_definition); 12388 FD->setInvalidDecl(); 12389 } 12390 12391 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 12392 Sema &S) { 12393 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 12394 12395 LambdaScopeInfo *LSI = S.PushLambdaScope(); 12396 LSI->CallOperator = CallOperator; 12397 LSI->Lambda = LambdaClass; 12398 LSI->ReturnType = CallOperator->getReturnType(); 12399 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 12400 12401 if (LCD == LCD_None) 12402 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 12403 else if (LCD == LCD_ByCopy) 12404 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 12405 else if (LCD == LCD_ByRef) 12406 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 12407 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 12408 12409 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 12410 LSI->Mutable = !CallOperator->isConst(); 12411 12412 // Add the captures to the LSI so they can be noted as already 12413 // captured within tryCaptureVar. 12414 auto I = LambdaClass->field_begin(); 12415 for (const auto &C : LambdaClass->captures()) { 12416 if (C.capturesVariable()) { 12417 VarDecl *VD = C.getCapturedVar(); 12418 if (VD->isInitCapture()) 12419 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 12420 QualType CaptureType = VD->getType(); 12421 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 12422 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 12423 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 12424 /*EllipsisLoc*/C.isPackExpansion() 12425 ? C.getEllipsisLoc() : SourceLocation(), 12426 CaptureType, /*Expr*/ nullptr); 12427 12428 } else if (C.capturesThis()) { 12429 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 12430 /*Expr*/ nullptr, 12431 C.getCaptureKind() == LCK_StarThis); 12432 } else { 12433 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 12434 } 12435 ++I; 12436 } 12437 } 12438 12439 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 12440 SkipBodyInfo *SkipBody) { 12441 if (!D) { 12442 // Parsing the function declaration failed in some way. Push on a fake scope 12443 // anyway so we can try to parse the function body. 12444 PushFunctionScope(); 12445 return D; 12446 } 12447 12448 FunctionDecl *FD = nullptr; 12449 12450 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 12451 FD = FunTmpl->getTemplatedDecl(); 12452 else 12453 FD = cast<FunctionDecl>(D); 12454 12455 // Check for defining attributes before the check for redefinition. 12456 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 12457 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 12458 FD->dropAttr<AliasAttr>(); 12459 FD->setInvalidDecl(); 12460 } 12461 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 12462 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 12463 FD->dropAttr<IFuncAttr>(); 12464 FD->setInvalidDecl(); 12465 } 12466 12467 // See if this is a redefinition. If 'will have body' is already set, then 12468 // these checks were already performed when it was set. 12469 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 12470 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 12471 12472 // If we're skipping the body, we're done. Don't enter the scope. 12473 if (SkipBody && SkipBody->ShouldSkip) 12474 return D; 12475 } 12476 12477 // Mark this function as "will have a body eventually". This lets users to 12478 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 12479 // this function. 12480 FD->setWillHaveBody(); 12481 12482 // If we are instantiating a generic lambda call operator, push 12483 // a LambdaScopeInfo onto the function stack. But use the information 12484 // that's already been calculated (ActOnLambdaExpr) to prime the current 12485 // LambdaScopeInfo. 12486 // When the template operator is being specialized, the LambdaScopeInfo, 12487 // has to be properly restored so that tryCaptureVariable doesn't try 12488 // and capture any new variables. In addition when calculating potential 12489 // captures during transformation of nested lambdas, it is necessary to 12490 // have the LSI properly restored. 12491 if (isGenericLambdaCallOperatorSpecialization(FD)) { 12492 assert(inTemplateInstantiation() && 12493 "There should be an active template instantiation on the stack " 12494 "when instantiating a generic lambda!"); 12495 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 12496 } else { 12497 // Enter a new function scope 12498 PushFunctionScope(); 12499 } 12500 12501 // Builtin functions cannot be defined. 12502 if (unsigned BuiltinID = FD->getBuiltinID()) { 12503 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 12504 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 12505 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 12506 FD->setInvalidDecl(); 12507 } 12508 } 12509 12510 // The return type of a function definition must be complete 12511 // (C99 6.9.1p3, C++ [dcl.fct]p6). 12512 QualType ResultType = FD->getReturnType(); 12513 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 12514 !FD->isInvalidDecl() && 12515 RequireCompleteType(FD->getLocation(), ResultType, 12516 diag::err_func_def_incomplete_result)) 12517 FD->setInvalidDecl(); 12518 12519 if (FnBodyScope) 12520 PushDeclContext(FnBodyScope, FD); 12521 12522 // Check the validity of our function parameters 12523 CheckParmsForFunctionDef(FD->parameters(), 12524 /*CheckParameterNames=*/true); 12525 12526 // Add non-parameter declarations already in the function to the current 12527 // scope. 12528 if (FnBodyScope) { 12529 for (Decl *NPD : FD->decls()) { 12530 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 12531 if (!NonParmDecl) 12532 continue; 12533 assert(!isa<ParmVarDecl>(NonParmDecl) && 12534 "parameters should not be in newly created FD yet"); 12535 12536 // If the decl has a name, make it accessible in the current scope. 12537 if (NonParmDecl->getDeclName()) 12538 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 12539 12540 // Similarly, dive into enums and fish their constants out, making them 12541 // accessible in this scope. 12542 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 12543 for (auto *EI : ED->enumerators()) 12544 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 12545 } 12546 } 12547 } 12548 12549 // Introduce our parameters into the function scope 12550 for (auto Param : FD->parameters()) { 12551 Param->setOwningFunction(FD); 12552 12553 // If this has an identifier, add it to the scope stack. 12554 if (Param->getIdentifier() && FnBodyScope) { 12555 CheckShadow(FnBodyScope, Param); 12556 12557 PushOnScopeChains(Param, FnBodyScope); 12558 } 12559 } 12560 12561 // Ensure that the function's exception specification is instantiated. 12562 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 12563 ResolveExceptionSpec(D->getLocation(), FPT); 12564 12565 // dllimport cannot be applied to non-inline function definitions. 12566 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 12567 !FD->isTemplateInstantiation()) { 12568 assert(!FD->hasAttr<DLLExportAttr>()); 12569 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 12570 FD->setInvalidDecl(); 12571 return D; 12572 } 12573 // We want to attach documentation to original Decl (which might be 12574 // a function template). 12575 ActOnDocumentableDecl(D); 12576 if (getCurLexicalContext()->isObjCContainer() && 12577 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 12578 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 12579 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 12580 12581 return D; 12582 } 12583 12584 /// \brief Given the set of return statements within a function body, 12585 /// compute the variables that are subject to the named return value 12586 /// optimization. 12587 /// 12588 /// Each of the variables that is subject to the named return value 12589 /// optimization will be marked as NRVO variables in the AST, and any 12590 /// return statement that has a marked NRVO variable as its NRVO candidate can 12591 /// use the named return value optimization. 12592 /// 12593 /// This function applies a very simplistic algorithm for NRVO: if every return 12594 /// statement in the scope of a variable has the same NRVO candidate, that 12595 /// candidate is an NRVO variable. 12596 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 12597 ReturnStmt **Returns = Scope->Returns.data(); 12598 12599 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 12600 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 12601 if (!NRVOCandidate->isNRVOVariable()) 12602 Returns[I]->setNRVOCandidate(nullptr); 12603 } 12604 } 12605 } 12606 12607 bool Sema::canDelayFunctionBody(const Declarator &D) { 12608 // We can't delay parsing the body of a constexpr function template (yet). 12609 if (D.getDeclSpec().isConstexprSpecified()) 12610 return false; 12611 12612 // We can't delay parsing the body of a function template with a deduced 12613 // return type (yet). 12614 if (D.getDeclSpec().hasAutoTypeSpec()) { 12615 // If the placeholder introduces a non-deduced trailing return type, 12616 // we can still delay parsing it. 12617 if (D.getNumTypeObjects()) { 12618 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 12619 if (Outer.Kind == DeclaratorChunk::Function && 12620 Outer.Fun.hasTrailingReturnType()) { 12621 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 12622 return Ty.isNull() || !Ty->isUndeducedType(); 12623 } 12624 } 12625 return false; 12626 } 12627 12628 return true; 12629 } 12630 12631 bool Sema::canSkipFunctionBody(Decl *D) { 12632 // We cannot skip the body of a function (or function template) which is 12633 // constexpr, since we may need to evaluate its body in order to parse the 12634 // rest of the file. 12635 // We cannot skip the body of a function with an undeduced return type, 12636 // because any callers of that function need to know the type. 12637 if (const FunctionDecl *FD = D->getAsFunction()) 12638 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 12639 return false; 12640 return Consumer.shouldSkipFunctionBody(D); 12641 } 12642 12643 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 12644 if (!Decl) 12645 return nullptr; 12646 if (FunctionDecl *FD = Decl->getAsFunction()) 12647 FD->setHasSkippedBody(); 12648 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 12649 MD->setHasSkippedBody(); 12650 return Decl; 12651 } 12652 12653 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 12654 return ActOnFinishFunctionBody(D, BodyArg, false); 12655 } 12656 12657 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 12658 bool IsInstantiation) { 12659 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 12660 12661 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 12662 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 12663 12664 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine()) 12665 CheckCompletedCoroutineBody(FD, Body); 12666 12667 if (FD) { 12668 FD->setBody(Body); 12669 FD->setWillHaveBody(false); 12670 12671 if (getLangOpts().CPlusPlus14) { 12672 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 12673 FD->getReturnType()->isUndeducedType()) { 12674 // If the function has a deduced result type but contains no 'return' 12675 // statements, the result type as written must be exactly 'auto', and 12676 // the deduced result type is 'void'. 12677 if (!FD->getReturnType()->getAs<AutoType>()) { 12678 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 12679 << FD->getReturnType(); 12680 FD->setInvalidDecl(); 12681 } else { 12682 // Substitute 'void' for the 'auto' in the type. 12683 TypeLoc ResultType = getReturnTypeLoc(FD); 12684 Context.adjustDeducedFunctionResultType( 12685 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 12686 } 12687 } 12688 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 12689 // In C++11, we don't use 'auto' deduction rules for lambda call 12690 // operators because we don't support return type deduction. 12691 auto *LSI = getCurLambda(); 12692 if (LSI->HasImplicitReturnType) { 12693 deduceClosureReturnType(*LSI); 12694 12695 // C++11 [expr.prim.lambda]p4: 12696 // [...] if there are no return statements in the compound-statement 12697 // [the deduced type is] the type void 12698 QualType RetType = 12699 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 12700 12701 // Update the return type to the deduced type. 12702 const FunctionProtoType *Proto = 12703 FD->getType()->getAs<FunctionProtoType>(); 12704 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 12705 Proto->getExtProtoInfo())); 12706 } 12707 } 12708 12709 // If the function implicitly returns zero (like 'main') or is naked, 12710 // don't complain about missing return statements. 12711 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 12712 WP.disableCheckFallThrough(); 12713 12714 // MSVC permits the use of pure specifier (=0) on function definition, 12715 // defined at class scope, warn about this non-standard construct. 12716 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 12717 Diag(FD->getLocation(), diag::ext_pure_function_definition); 12718 12719 if (!FD->isInvalidDecl()) { 12720 // Don't diagnose unused parameters of defaulted or deleted functions. 12721 if (!FD->isDeleted() && !FD->isDefaulted()) 12722 DiagnoseUnusedParameters(FD->parameters()); 12723 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 12724 FD->getReturnType(), FD); 12725 12726 // If this is a structor, we need a vtable. 12727 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 12728 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 12729 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 12730 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 12731 12732 // Try to apply the named return value optimization. We have to check 12733 // if we can do this here because lambdas keep return statements around 12734 // to deduce an implicit return type. 12735 if (FD->getReturnType()->isRecordType() && 12736 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 12737 computeNRVO(Body, getCurFunction()); 12738 } 12739 12740 // GNU warning -Wmissing-prototypes: 12741 // Warn if a global function is defined without a previous 12742 // prototype declaration. This warning is issued even if the 12743 // definition itself provides a prototype. The aim is to detect 12744 // global functions that fail to be declared in header files. 12745 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 12746 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 12747 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 12748 12749 if (PossibleZeroParamPrototype) { 12750 // We found a declaration that is not a prototype, 12751 // but that could be a zero-parameter prototype 12752 if (TypeSourceInfo *TI = 12753 PossibleZeroParamPrototype->getTypeSourceInfo()) { 12754 TypeLoc TL = TI->getTypeLoc(); 12755 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 12756 Diag(PossibleZeroParamPrototype->getLocation(), 12757 diag::note_declaration_not_a_prototype) 12758 << PossibleZeroParamPrototype 12759 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 12760 } 12761 } 12762 12763 // GNU warning -Wstrict-prototypes 12764 // Warn if K&R function is defined without a previous declaration. 12765 // This warning is issued only if the definition itself does not provide 12766 // a prototype. Only K&R definitions do not provide a prototype. 12767 // An empty list in a function declarator that is part of a definition 12768 // of that function specifies that the function has no parameters 12769 // (C99 6.7.5.3p14) 12770 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 && 12771 !LangOpts.CPlusPlus) { 12772 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 12773 TypeLoc TL = TI->getTypeLoc(); 12774 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 12775 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 12776 } 12777 } 12778 12779 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 12780 const CXXMethodDecl *KeyFunction; 12781 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 12782 MD->isVirtual() && 12783 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 12784 MD == KeyFunction->getCanonicalDecl()) { 12785 // Update the key-function state if necessary for this ABI. 12786 if (FD->isInlined() && 12787 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 12788 Context.setNonKeyFunction(MD); 12789 12790 // If the newly-chosen key function is already defined, then we 12791 // need to mark the vtable as used retroactively. 12792 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 12793 const FunctionDecl *Definition; 12794 if (KeyFunction && KeyFunction->isDefined(Definition)) 12795 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 12796 } else { 12797 // We just defined they key function; mark the vtable as used. 12798 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 12799 } 12800 } 12801 } 12802 12803 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 12804 "Function parsing confused"); 12805 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 12806 assert(MD == getCurMethodDecl() && "Method parsing confused"); 12807 MD->setBody(Body); 12808 if (!MD->isInvalidDecl()) { 12809 DiagnoseUnusedParameters(MD->parameters()); 12810 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 12811 MD->getReturnType(), MD); 12812 12813 if (Body) 12814 computeNRVO(Body, getCurFunction()); 12815 } 12816 if (getCurFunction()->ObjCShouldCallSuper) { 12817 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 12818 << MD->getSelector().getAsString(); 12819 getCurFunction()->ObjCShouldCallSuper = false; 12820 } 12821 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 12822 const ObjCMethodDecl *InitMethod = nullptr; 12823 bool isDesignated = 12824 MD->isDesignatedInitializerForTheInterface(&InitMethod); 12825 assert(isDesignated && InitMethod); 12826 (void)isDesignated; 12827 12828 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 12829 auto IFace = MD->getClassInterface(); 12830 if (!IFace) 12831 return false; 12832 auto SuperD = IFace->getSuperClass(); 12833 if (!SuperD) 12834 return false; 12835 return SuperD->getIdentifier() == 12836 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 12837 }; 12838 // Don't issue this warning for unavailable inits or direct subclasses 12839 // of NSObject. 12840 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 12841 Diag(MD->getLocation(), 12842 diag::warn_objc_designated_init_missing_super_call); 12843 Diag(InitMethod->getLocation(), 12844 diag::note_objc_designated_init_marked_here); 12845 } 12846 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 12847 } 12848 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 12849 // Don't issue this warning for unavaialable inits. 12850 if (!MD->isUnavailable()) 12851 Diag(MD->getLocation(), 12852 diag::warn_objc_secondary_init_missing_init_call); 12853 getCurFunction()->ObjCWarnForNoInitDelegation = false; 12854 } 12855 } else { 12856 // Parsing the function declaration failed in some way. Pop the fake scope 12857 // we pushed on. 12858 PopFunctionScopeInfo(ActivePolicy, dcl); 12859 return nullptr; 12860 } 12861 12862 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 12863 DiagnoseUnguardedAvailabilityViolations(dcl); 12864 12865 assert(!getCurFunction()->ObjCShouldCallSuper && 12866 "This should only be set for ObjC methods, which should have been " 12867 "handled in the block above."); 12868 12869 // Verify and clean out per-function state. 12870 if (Body && (!FD || !FD->isDefaulted())) { 12871 // C++ constructors that have function-try-blocks can't have return 12872 // statements in the handlers of that block. (C++ [except.handle]p14) 12873 // Verify this. 12874 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 12875 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 12876 12877 // Verify that gotos and switch cases don't jump into scopes illegally. 12878 if (getCurFunction()->NeedsScopeChecking() && 12879 !PP.isCodeCompletionEnabled()) 12880 DiagnoseInvalidJumps(Body); 12881 12882 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 12883 if (!Destructor->getParent()->isDependentType()) 12884 CheckDestructor(Destructor); 12885 12886 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 12887 Destructor->getParent()); 12888 } 12889 12890 // If any errors have occurred, clear out any temporaries that may have 12891 // been leftover. This ensures that these temporaries won't be picked up for 12892 // deletion in some later function. 12893 if (getDiagnostics().hasErrorOccurred() || 12894 getDiagnostics().getSuppressAllDiagnostics()) { 12895 DiscardCleanupsInEvaluationContext(); 12896 } 12897 if (!getDiagnostics().hasUncompilableErrorOccurred() && 12898 !isa<FunctionTemplateDecl>(dcl)) { 12899 // Since the body is valid, issue any analysis-based warnings that are 12900 // enabled. 12901 ActivePolicy = &WP; 12902 } 12903 12904 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 12905 (!CheckConstexprFunctionDecl(FD) || 12906 !CheckConstexprFunctionBody(FD, Body))) 12907 FD->setInvalidDecl(); 12908 12909 if (FD && FD->hasAttr<NakedAttr>()) { 12910 for (const Stmt *S : Body->children()) { 12911 // Allow local register variables without initializer as they don't 12912 // require prologue. 12913 bool RegisterVariables = false; 12914 if (auto *DS = dyn_cast<DeclStmt>(S)) { 12915 for (const auto *Decl : DS->decls()) { 12916 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 12917 RegisterVariables = 12918 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 12919 if (!RegisterVariables) 12920 break; 12921 } 12922 } 12923 } 12924 if (RegisterVariables) 12925 continue; 12926 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 12927 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 12928 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 12929 FD->setInvalidDecl(); 12930 break; 12931 } 12932 } 12933 } 12934 12935 assert(ExprCleanupObjects.size() == 12936 ExprEvalContexts.back().NumCleanupObjects && 12937 "Leftover temporaries in function"); 12938 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 12939 assert(MaybeODRUseExprs.empty() && 12940 "Leftover expressions for odr-use checking"); 12941 } 12942 12943 if (!IsInstantiation) 12944 PopDeclContext(); 12945 12946 PopFunctionScopeInfo(ActivePolicy, dcl); 12947 // If any errors have occurred, clear out any temporaries that may have 12948 // been leftover. This ensures that these temporaries won't be picked up for 12949 // deletion in some later function. 12950 if (getDiagnostics().hasErrorOccurred()) { 12951 DiscardCleanupsInEvaluationContext(); 12952 } 12953 12954 return dcl; 12955 } 12956 12957 /// When we finish delayed parsing of an attribute, we must attach it to the 12958 /// relevant Decl. 12959 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 12960 ParsedAttributes &Attrs) { 12961 // Always attach attributes to the underlying decl. 12962 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 12963 D = TD->getTemplatedDecl(); 12964 ProcessDeclAttributeList(S, D, Attrs.getList()); 12965 12966 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 12967 if (Method->isStatic()) 12968 checkThisInStaticMemberFunctionAttributes(Method); 12969 } 12970 12971 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 12972 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 12973 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 12974 IdentifierInfo &II, Scope *S) { 12975 // Find the scope in which the identifier is injected and the corresponding 12976 // DeclContext. 12977 // FIXME: C89 does not say what happens if there is no enclosing block scope. 12978 // In that case, we inject the declaration into the translation unit scope 12979 // instead. 12980 Scope *BlockScope = S; 12981 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 12982 BlockScope = BlockScope->getParent(); 12983 12984 Scope *ContextScope = BlockScope; 12985 while (!ContextScope->getEntity()) 12986 ContextScope = ContextScope->getParent(); 12987 ContextRAII SavedContext(*this, ContextScope->getEntity()); 12988 12989 // Before we produce a declaration for an implicitly defined 12990 // function, see whether there was a locally-scoped declaration of 12991 // this name as a function or variable. If so, use that 12992 // (non-visible) declaration, and complain about it. 12993 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 12994 if (ExternCPrev) { 12995 // We still need to inject the function into the enclosing block scope so 12996 // that later (non-call) uses can see it. 12997 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 12998 12999 // C89 footnote 38: 13000 // If in fact it is not defined as having type "function returning int", 13001 // the behavior is undefined. 13002 if (!isa<FunctionDecl>(ExternCPrev) || 13003 !Context.typesAreCompatible( 13004 cast<FunctionDecl>(ExternCPrev)->getType(), 13005 Context.getFunctionNoProtoType(Context.IntTy))) { 13006 Diag(Loc, diag::ext_use_out_of_scope_declaration) 13007 << ExternCPrev << !getLangOpts().C99; 13008 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 13009 return ExternCPrev; 13010 } 13011 } 13012 13013 // Extension in C99. Legal in C90, but warn about it. 13014 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 13015 unsigned diag_id; 13016 if (II.getName().startswith("__builtin_")) 13017 diag_id = diag::warn_builtin_unknown; 13018 else if (getLangOpts().C99 || getLangOpts().OpenCL) 13019 diag_id = diag::ext_implicit_function_decl; 13020 else 13021 diag_id = diag::warn_implicit_function_decl; 13022 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL; 13023 13024 // If we found a prior declaration of this function, don't bother building 13025 // another one. We've already pushed that one into scope, so there's nothing 13026 // more to do. 13027 if (ExternCPrev) 13028 return ExternCPrev; 13029 13030 // Because typo correction is expensive, only do it if the implicit 13031 // function declaration is going to be treated as an error. 13032 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 13033 TypoCorrection Corrected; 13034 if (S && 13035 (Corrected = CorrectTypo( 13036 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 13037 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 13038 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 13039 /*ErrorRecovery*/false); 13040 } 13041 13042 // Set a Declarator for the implicit definition: int foo(); 13043 const char *Dummy; 13044 AttributeFactory attrFactory; 13045 DeclSpec DS(attrFactory); 13046 unsigned DiagID; 13047 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 13048 Context.getPrintingPolicy()); 13049 (void)Error; // Silence warning. 13050 assert(!Error && "Error setting up implicit decl!"); 13051 SourceLocation NoLoc; 13052 Declarator D(DS, DeclaratorContext::BlockContext); 13053 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 13054 /*IsAmbiguous=*/false, 13055 /*LParenLoc=*/NoLoc, 13056 /*Params=*/nullptr, 13057 /*NumParams=*/0, 13058 /*EllipsisLoc=*/NoLoc, 13059 /*RParenLoc=*/NoLoc, 13060 /*TypeQuals=*/0, 13061 /*RefQualifierIsLvalueRef=*/true, 13062 /*RefQualifierLoc=*/NoLoc, 13063 /*ConstQualifierLoc=*/NoLoc, 13064 /*VolatileQualifierLoc=*/NoLoc, 13065 /*RestrictQualifierLoc=*/NoLoc, 13066 /*MutableLoc=*/NoLoc, 13067 EST_None, 13068 /*ESpecRange=*/SourceRange(), 13069 /*Exceptions=*/nullptr, 13070 /*ExceptionRanges=*/nullptr, 13071 /*NumExceptions=*/0, 13072 /*NoexceptExpr=*/nullptr, 13073 /*ExceptionSpecTokens=*/nullptr, 13074 /*DeclsInPrototype=*/None, 13075 Loc, Loc, D), 13076 DS.getAttributes(), 13077 SourceLocation()); 13078 D.SetIdentifier(&II, Loc); 13079 13080 // Insert this function into the enclosing block scope. 13081 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 13082 FD->setImplicit(); 13083 13084 AddKnownFunctionAttributes(FD); 13085 13086 return FD; 13087 } 13088 13089 /// \brief Adds any function attributes that we know a priori based on 13090 /// the declaration of this function. 13091 /// 13092 /// These attributes can apply both to implicitly-declared builtins 13093 /// (like __builtin___printf_chk) or to library-declared functions 13094 /// like NSLog or printf. 13095 /// 13096 /// We need to check for duplicate attributes both here and where user-written 13097 /// attributes are applied to declarations. 13098 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 13099 if (FD->isInvalidDecl()) 13100 return; 13101 13102 // If this is a built-in function, map its builtin attributes to 13103 // actual attributes. 13104 if (unsigned BuiltinID = FD->getBuiltinID()) { 13105 // Handle printf-formatting attributes. 13106 unsigned FormatIdx; 13107 bool HasVAListArg; 13108 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 13109 if (!FD->hasAttr<FormatAttr>()) { 13110 const char *fmt = "printf"; 13111 unsigned int NumParams = FD->getNumParams(); 13112 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 13113 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 13114 fmt = "NSString"; 13115 FD->addAttr(FormatAttr::CreateImplicit(Context, 13116 &Context.Idents.get(fmt), 13117 FormatIdx+1, 13118 HasVAListArg ? 0 : FormatIdx+2, 13119 FD->getLocation())); 13120 } 13121 } 13122 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 13123 HasVAListArg)) { 13124 if (!FD->hasAttr<FormatAttr>()) 13125 FD->addAttr(FormatAttr::CreateImplicit(Context, 13126 &Context.Idents.get("scanf"), 13127 FormatIdx+1, 13128 HasVAListArg ? 0 : FormatIdx+2, 13129 FD->getLocation())); 13130 } 13131 13132 // Mark const if we don't care about errno and that is the only thing 13133 // preventing the function from being const. This allows IRgen to use LLVM 13134 // intrinsics for such functions. 13135 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 13136 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 13137 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13138 13139 // We make "fma" on some platforms const because we know it does not set 13140 // errno in those environments even though it could set errno based on the 13141 // C standard. 13142 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 13143 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 13144 !FD->hasAttr<ConstAttr>()) { 13145 switch (BuiltinID) { 13146 case Builtin::BI__builtin_fma: 13147 case Builtin::BI__builtin_fmaf: 13148 case Builtin::BI__builtin_fmal: 13149 case Builtin::BIfma: 13150 case Builtin::BIfmaf: 13151 case Builtin::BIfmal: 13152 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13153 break; 13154 default: 13155 break; 13156 } 13157 } 13158 13159 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 13160 !FD->hasAttr<ReturnsTwiceAttr>()) 13161 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 13162 FD->getLocation())); 13163 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 13164 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13165 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 13166 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 13167 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 13168 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 13169 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 13170 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 13171 // Add the appropriate attribute, depending on the CUDA compilation mode 13172 // and which target the builtin belongs to. For example, during host 13173 // compilation, aux builtins are __device__, while the rest are __host__. 13174 if (getLangOpts().CUDAIsDevice != 13175 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 13176 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 13177 else 13178 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 13179 } 13180 } 13181 13182 // If C++ exceptions are enabled but we are told extern "C" functions cannot 13183 // throw, add an implicit nothrow attribute to any extern "C" function we come 13184 // across. 13185 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 13186 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 13187 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 13188 if (!FPT || FPT->getExceptionSpecType() == EST_None) 13189 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 13190 } 13191 13192 IdentifierInfo *Name = FD->getIdentifier(); 13193 if (!Name) 13194 return; 13195 if ((!getLangOpts().CPlusPlus && 13196 FD->getDeclContext()->isTranslationUnit()) || 13197 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 13198 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 13199 LinkageSpecDecl::lang_c)) { 13200 // Okay: this could be a libc/libm/Objective-C function we know 13201 // about. 13202 } else 13203 return; 13204 13205 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 13206 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 13207 // target-specific builtins, perhaps? 13208 if (!FD->hasAttr<FormatAttr>()) 13209 FD->addAttr(FormatAttr::CreateImplicit(Context, 13210 &Context.Idents.get("printf"), 2, 13211 Name->isStr("vasprintf") ? 0 : 3, 13212 FD->getLocation())); 13213 } 13214 13215 if (Name->isStr("__CFStringMakeConstantString")) { 13216 // We already have a __builtin___CFStringMakeConstantString, 13217 // but builds that use -fno-constant-cfstrings don't go through that. 13218 if (!FD->hasAttr<FormatArgAttr>()) 13219 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 13220 FD->getLocation())); 13221 } 13222 } 13223 13224 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 13225 TypeSourceInfo *TInfo) { 13226 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 13227 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 13228 13229 if (!TInfo) { 13230 assert(D.isInvalidType() && "no declarator info for valid type"); 13231 TInfo = Context.getTrivialTypeSourceInfo(T); 13232 } 13233 13234 // Scope manipulation handled by caller. 13235 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 13236 D.getLocStart(), 13237 D.getIdentifierLoc(), 13238 D.getIdentifier(), 13239 TInfo); 13240 13241 // Bail out immediately if we have an invalid declaration. 13242 if (D.isInvalidType()) { 13243 NewTD->setInvalidDecl(); 13244 return NewTD; 13245 } 13246 13247 if (D.getDeclSpec().isModulePrivateSpecified()) { 13248 if (CurContext->isFunctionOrMethod()) 13249 Diag(NewTD->getLocation(), diag::err_module_private_local) 13250 << 2 << NewTD->getDeclName() 13251 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13252 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13253 else 13254 NewTD->setModulePrivate(); 13255 } 13256 13257 // C++ [dcl.typedef]p8: 13258 // If the typedef declaration defines an unnamed class (or 13259 // enum), the first typedef-name declared by the declaration 13260 // to be that class type (or enum type) is used to denote the 13261 // class type (or enum type) for linkage purposes only. 13262 // We need to check whether the type was declared in the declaration. 13263 switch (D.getDeclSpec().getTypeSpecType()) { 13264 case TST_enum: 13265 case TST_struct: 13266 case TST_interface: 13267 case TST_union: 13268 case TST_class: { 13269 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 13270 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 13271 break; 13272 } 13273 13274 default: 13275 break; 13276 } 13277 13278 return NewTD; 13279 } 13280 13281 /// \brief Check that this is a valid underlying type for an enum declaration. 13282 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 13283 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 13284 QualType T = TI->getType(); 13285 13286 if (T->isDependentType()) 13287 return false; 13288 13289 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 13290 if (BT->isInteger()) 13291 return false; 13292 13293 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 13294 return true; 13295 } 13296 13297 /// Check whether this is a valid redeclaration of a previous enumeration. 13298 /// \return true if the redeclaration was invalid. 13299 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 13300 QualType EnumUnderlyingTy, bool IsFixed, 13301 const EnumDecl *Prev) { 13302 if (IsScoped != Prev->isScoped()) { 13303 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 13304 << Prev->isScoped(); 13305 Diag(Prev->getLocation(), diag::note_previous_declaration); 13306 return true; 13307 } 13308 13309 if (IsFixed && Prev->isFixed()) { 13310 if (!EnumUnderlyingTy->isDependentType() && 13311 !Prev->getIntegerType()->isDependentType() && 13312 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 13313 Prev->getIntegerType())) { 13314 // TODO: Highlight the underlying type of the redeclaration. 13315 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 13316 << EnumUnderlyingTy << Prev->getIntegerType(); 13317 Diag(Prev->getLocation(), diag::note_previous_declaration) 13318 << Prev->getIntegerTypeRange(); 13319 return true; 13320 } 13321 } else if (IsFixed != Prev->isFixed()) { 13322 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 13323 << Prev->isFixed(); 13324 Diag(Prev->getLocation(), diag::note_previous_declaration); 13325 return true; 13326 } 13327 13328 return false; 13329 } 13330 13331 /// \brief Get diagnostic %select index for tag kind for 13332 /// redeclaration diagnostic message. 13333 /// WARNING: Indexes apply to particular diagnostics only! 13334 /// 13335 /// \returns diagnostic %select index. 13336 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 13337 switch (Tag) { 13338 case TTK_Struct: return 0; 13339 case TTK_Interface: return 1; 13340 case TTK_Class: return 2; 13341 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 13342 } 13343 } 13344 13345 /// \brief Determine if tag kind is a class-key compatible with 13346 /// class for redeclaration (class, struct, or __interface). 13347 /// 13348 /// \returns true iff the tag kind is compatible. 13349 static bool isClassCompatTagKind(TagTypeKind Tag) 13350 { 13351 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 13352 } 13353 13354 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 13355 TagTypeKind TTK) { 13356 if (isa<TypedefDecl>(PrevDecl)) 13357 return NTK_Typedef; 13358 else if (isa<TypeAliasDecl>(PrevDecl)) 13359 return NTK_TypeAlias; 13360 else if (isa<ClassTemplateDecl>(PrevDecl)) 13361 return NTK_Template; 13362 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 13363 return NTK_TypeAliasTemplate; 13364 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 13365 return NTK_TemplateTemplateArgument; 13366 switch (TTK) { 13367 case TTK_Struct: 13368 case TTK_Interface: 13369 case TTK_Class: 13370 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 13371 case TTK_Union: 13372 return NTK_NonUnion; 13373 case TTK_Enum: 13374 return NTK_NonEnum; 13375 } 13376 llvm_unreachable("invalid TTK"); 13377 } 13378 13379 /// \brief Determine whether a tag with a given kind is acceptable 13380 /// as a redeclaration of the given tag declaration. 13381 /// 13382 /// \returns true if the new tag kind is acceptable, false otherwise. 13383 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 13384 TagTypeKind NewTag, bool isDefinition, 13385 SourceLocation NewTagLoc, 13386 const IdentifierInfo *Name) { 13387 // C++ [dcl.type.elab]p3: 13388 // The class-key or enum keyword present in the 13389 // elaborated-type-specifier shall agree in kind with the 13390 // declaration to which the name in the elaborated-type-specifier 13391 // refers. This rule also applies to the form of 13392 // elaborated-type-specifier that declares a class-name or 13393 // friend class since it can be construed as referring to the 13394 // definition of the class. Thus, in any 13395 // elaborated-type-specifier, the enum keyword shall be used to 13396 // refer to an enumeration (7.2), the union class-key shall be 13397 // used to refer to a union (clause 9), and either the class or 13398 // struct class-key shall be used to refer to a class (clause 9) 13399 // declared using the class or struct class-key. 13400 TagTypeKind OldTag = Previous->getTagKind(); 13401 if (!isDefinition || !isClassCompatTagKind(NewTag)) 13402 if (OldTag == NewTag) 13403 return true; 13404 13405 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 13406 // Warn about the struct/class tag mismatch. 13407 bool isTemplate = false; 13408 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 13409 isTemplate = Record->getDescribedClassTemplate(); 13410 13411 if (inTemplateInstantiation()) { 13412 // In a template instantiation, do not offer fix-its for tag mismatches 13413 // since they usually mess up the template instead of fixing the problem. 13414 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13415 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13416 << getRedeclDiagFromTagKind(OldTag); 13417 return true; 13418 } 13419 13420 if (isDefinition) { 13421 // On definitions, check previous tags and issue a fix-it for each 13422 // one that doesn't match the current tag. 13423 if (Previous->getDefinition()) { 13424 // Don't suggest fix-its for redefinitions. 13425 return true; 13426 } 13427 13428 bool previousMismatch = false; 13429 for (auto I : Previous->redecls()) { 13430 if (I->getTagKind() != NewTag) { 13431 if (!previousMismatch) { 13432 previousMismatch = true; 13433 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 13434 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13435 << getRedeclDiagFromTagKind(I->getTagKind()); 13436 } 13437 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 13438 << getRedeclDiagFromTagKind(NewTag) 13439 << FixItHint::CreateReplacement(I->getInnerLocStart(), 13440 TypeWithKeyword::getTagTypeKindName(NewTag)); 13441 } 13442 } 13443 return true; 13444 } 13445 13446 // Check for a previous definition. If current tag and definition 13447 // are same type, do nothing. If no definition, but disagree with 13448 // with previous tag type, give a warning, but no fix-it. 13449 const TagDecl *Redecl = Previous->getDefinition() ? 13450 Previous->getDefinition() : Previous; 13451 if (Redecl->getTagKind() == NewTag) { 13452 return true; 13453 } 13454 13455 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 13456 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 13457 << getRedeclDiagFromTagKind(OldTag); 13458 Diag(Redecl->getLocation(), diag::note_previous_use); 13459 13460 // If there is a previous definition, suggest a fix-it. 13461 if (Previous->getDefinition()) { 13462 Diag(NewTagLoc, diag::note_struct_class_suggestion) 13463 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 13464 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 13465 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 13466 } 13467 13468 return true; 13469 } 13470 return false; 13471 } 13472 13473 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 13474 /// from an outer enclosing namespace or file scope inside a friend declaration. 13475 /// This should provide the commented out code in the following snippet: 13476 /// namespace N { 13477 /// struct X; 13478 /// namespace M { 13479 /// struct Y { friend struct /*N::*/ X; }; 13480 /// } 13481 /// } 13482 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 13483 SourceLocation NameLoc) { 13484 // While the decl is in a namespace, do repeated lookup of that name and see 13485 // if we get the same namespace back. If we do not, continue until 13486 // translation unit scope, at which point we have a fully qualified NNS. 13487 SmallVector<IdentifierInfo *, 4> Namespaces; 13488 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13489 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 13490 // This tag should be declared in a namespace, which can only be enclosed by 13491 // other namespaces. Bail if there's an anonymous namespace in the chain. 13492 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 13493 if (!Namespace || Namespace->isAnonymousNamespace()) 13494 return FixItHint(); 13495 IdentifierInfo *II = Namespace->getIdentifier(); 13496 Namespaces.push_back(II); 13497 NamedDecl *Lookup = SemaRef.LookupSingleName( 13498 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 13499 if (Lookup == Namespace) 13500 break; 13501 } 13502 13503 // Once we have all the namespaces, reverse them to go outermost first, and 13504 // build an NNS. 13505 SmallString<64> Insertion; 13506 llvm::raw_svector_ostream OS(Insertion); 13507 if (DC->isTranslationUnit()) 13508 OS << "::"; 13509 std::reverse(Namespaces.begin(), Namespaces.end()); 13510 for (auto *II : Namespaces) 13511 OS << II->getName() << "::"; 13512 return FixItHint::CreateInsertion(NameLoc, Insertion); 13513 } 13514 13515 /// \brief Determine whether a tag originally declared in context \p OldDC can 13516 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 13517 /// found a declaration in \p OldDC as a previous decl, perhaps through a 13518 /// using-declaration). 13519 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 13520 DeclContext *NewDC) { 13521 OldDC = OldDC->getRedeclContext(); 13522 NewDC = NewDC->getRedeclContext(); 13523 13524 if (OldDC->Equals(NewDC)) 13525 return true; 13526 13527 // In MSVC mode, we allow a redeclaration if the contexts are related (either 13528 // encloses the other). 13529 if (S.getLangOpts().MSVCCompat && 13530 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 13531 return true; 13532 13533 return false; 13534 } 13535 13536 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 13537 /// former case, Name will be non-null. In the later case, Name will be null. 13538 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 13539 /// reference/declaration/definition of a tag. 13540 /// 13541 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 13542 /// trailing-type-specifier) other than one in an alias-declaration. 13543 /// 13544 /// \param SkipBody If non-null, will be set to indicate if the caller should 13545 /// skip the definition of this tag and treat it as if it were a declaration. 13546 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 13547 SourceLocation KWLoc, CXXScopeSpec &SS, 13548 IdentifierInfo *Name, SourceLocation NameLoc, 13549 AttributeList *Attr, AccessSpecifier AS, 13550 SourceLocation ModulePrivateLoc, 13551 MultiTemplateParamsArg TemplateParameterLists, 13552 bool &OwnedDecl, bool &IsDependent, 13553 SourceLocation ScopedEnumKWLoc, 13554 bool ScopedEnumUsesClassTag, 13555 TypeResult UnderlyingType, 13556 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 13557 SkipBodyInfo *SkipBody) { 13558 // If this is not a definition, it must have a name. 13559 IdentifierInfo *OrigName = Name; 13560 assert((Name != nullptr || TUK == TUK_Definition) && 13561 "Nameless record must be a definition!"); 13562 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 13563 13564 OwnedDecl = false; 13565 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 13566 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 13567 13568 // FIXME: Check member specializations more carefully. 13569 bool isMemberSpecialization = false; 13570 bool Invalid = false; 13571 13572 // We only need to do this matching if we have template parameters 13573 // or a scope specifier, which also conveniently avoids this work 13574 // for non-C++ cases. 13575 if (TemplateParameterLists.size() > 0 || 13576 (SS.isNotEmpty() && TUK != TUK_Reference)) { 13577 if (TemplateParameterList *TemplateParams = 13578 MatchTemplateParametersToScopeSpecifier( 13579 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 13580 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 13581 if (Kind == TTK_Enum) { 13582 Diag(KWLoc, diag::err_enum_template); 13583 return nullptr; 13584 } 13585 13586 if (TemplateParams->size() > 0) { 13587 // This is a declaration or definition of a class template (which may 13588 // be a member of another template). 13589 13590 if (Invalid) 13591 return nullptr; 13592 13593 OwnedDecl = false; 13594 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 13595 SS, Name, NameLoc, Attr, 13596 TemplateParams, AS, 13597 ModulePrivateLoc, 13598 /*FriendLoc*/SourceLocation(), 13599 TemplateParameterLists.size()-1, 13600 TemplateParameterLists.data(), 13601 SkipBody); 13602 return Result.get(); 13603 } else { 13604 // The "template<>" header is extraneous. 13605 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 13606 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 13607 isMemberSpecialization = true; 13608 } 13609 } 13610 } 13611 13612 // Figure out the underlying type if this a enum declaration. We need to do 13613 // this early, because it's needed to detect if this is an incompatible 13614 // redeclaration. 13615 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 13616 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 13617 13618 if (Kind == TTK_Enum) { 13619 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 13620 // No underlying type explicitly specified, or we failed to parse the 13621 // type, default to int. 13622 EnumUnderlying = Context.IntTy.getTypePtr(); 13623 } else if (UnderlyingType.get()) { 13624 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 13625 // integral type; any cv-qualification is ignored. 13626 TypeSourceInfo *TI = nullptr; 13627 GetTypeFromParser(UnderlyingType.get(), &TI); 13628 EnumUnderlying = TI; 13629 13630 if (CheckEnumUnderlyingType(TI)) 13631 // Recover by falling back to int. 13632 EnumUnderlying = Context.IntTy.getTypePtr(); 13633 13634 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 13635 UPPC_FixedUnderlyingType)) 13636 EnumUnderlying = Context.IntTy.getTypePtr(); 13637 13638 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 13639 // For MSVC ABI compatibility, unfixed enums must use an underlying type 13640 // of 'int'. However, if this is an unfixed forward declaration, don't set 13641 // the underlying type unless the user enables -fms-compatibility. This 13642 // makes unfixed forward declared enums incomplete and is more conforming. 13643 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 13644 EnumUnderlying = Context.IntTy.getTypePtr(); 13645 } 13646 } 13647 13648 DeclContext *SearchDC = CurContext; 13649 DeclContext *DC = CurContext; 13650 bool isStdBadAlloc = false; 13651 bool isStdAlignValT = false; 13652 13653 RedeclarationKind Redecl = forRedeclarationInCurContext(); 13654 if (TUK == TUK_Friend || TUK == TUK_Reference) 13655 Redecl = NotForRedeclaration; 13656 13657 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 13658 /// implemented asks for structural equivalence checking, the returned decl 13659 /// here is passed back to the parser, allowing the tag body to be parsed. 13660 auto createTagFromNewDecl = [&]() -> TagDecl * { 13661 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 13662 // If there is an identifier, use the location of the identifier as the 13663 // location of the decl, otherwise use the location of the struct/union 13664 // keyword. 13665 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 13666 TagDecl *New = nullptr; 13667 13668 if (Kind == TTK_Enum) { 13669 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 13670 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 13671 // If this is an undefined enum, bail. 13672 if (TUK != TUK_Definition && !Invalid) 13673 return nullptr; 13674 if (EnumUnderlying) { 13675 EnumDecl *ED = cast<EnumDecl>(New); 13676 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 13677 ED->setIntegerTypeSourceInfo(TI); 13678 else 13679 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 13680 ED->setPromotionType(ED->getIntegerType()); 13681 } 13682 } else { // struct/union 13683 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 13684 nullptr); 13685 } 13686 13687 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 13688 // Add alignment attributes if necessary; these attributes are checked 13689 // when the ASTContext lays out the structure. 13690 // 13691 // It is important for implementing the correct semantics that this 13692 // happen here (in ActOnTag). The #pragma pack stack is 13693 // maintained as a result of parser callbacks which can occur at 13694 // many points during the parsing of a struct declaration (because 13695 // the #pragma tokens are effectively skipped over during the 13696 // parsing of the struct). 13697 if (TUK == TUK_Definition) { 13698 AddAlignmentAttributesForRecord(RD); 13699 AddMsStructLayoutForRecord(RD); 13700 } 13701 } 13702 New->setLexicalDeclContext(CurContext); 13703 return New; 13704 }; 13705 13706 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 13707 if (Name && SS.isNotEmpty()) { 13708 // We have a nested-name tag ('struct foo::bar'). 13709 13710 // Check for invalid 'foo::'. 13711 if (SS.isInvalid()) { 13712 Name = nullptr; 13713 goto CreateNewDecl; 13714 } 13715 13716 // If this is a friend or a reference to a class in a dependent 13717 // context, don't try to make a decl for it. 13718 if (TUK == TUK_Friend || TUK == TUK_Reference) { 13719 DC = computeDeclContext(SS, false); 13720 if (!DC) { 13721 IsDependent = true; 13722 return nullptr; 13723 } 13724 } else { 13725 DC = computeDeclContext(SS, true); 13726 if (!DC) { 13727 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 13728 << SS.getRange(); 13729 return nullptr; 13730 } 13731 } 13732 13733 if (RequireCompleteDeclContext(SS, DC)) 13734 return nullptr; 13735 13736 SearchDC = DC; 13737 // Look-up name inside 'foo::'. 13738 LookupQualifiedName(Previous, DC); 13739 13740 if (Previous.isAmbiguous()) 13741 return nullptr; 13742 13743 if (Previous.empty()) { 13744 // Name lookup did not find anything. However, if the 13745 // nested-name-specifier refers to the current instantiation, 13746 // and that current instantiation has any dependent base 13747 // classes, we might find something at instantiation time: treat 13748 // this as a dependent elaborated-type-specifier. 13749 // But this only makes any sense for reference-like lookups. 13750 if (Previous.wasNotFoundInCurrentInstantiation() && 13751 (TUK == TUK_Reference || TUK == TUK_Friend)) { 13752 IsDependent = true; 13753 return nullptr; 13754 } 13755 13756 // A tag 'foo::bar' must already exist. 13757 Diag(NameLoc, diag::err_not_tag_in_scope) 13758 << Kind << Name << DC << SS.getRange(); 13759 Name = nullptr; 13760 Invalid = true; 13761 goto CreateNewDecl; 13762 } 13763 } else if (Name) { 13764 // C++14 [class.mem]p14: 13765 // If T is the name of a class, then each of the following shall have a 13766 // name different from T: 13767 // -- every member of class T that is itself a type 13768 if (TUK != TUK_Reference && TUK != TUK_Friend && 13769 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 13770 return nullptr; 13771 13772 // If this is a named struct, check to see if there was a previous forward 13773 // declaration or definition. 13774 // FIXME: We're looking into outer scopes here, even when we 13775 // shouldn't be. Doing so can result in ambiguities that we 13776 // shouldn't be diagnosing. 13777 LookupName(Previous, S); 13778 13779 // When declaring or defining a tag, ignore ambiguities introduced 13780 // by types using'ed into this scope. 13781 if (Previous.isAmbiguous() && 13782 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 13783 LookupResult::Filter F = Previous.makeFilter(); 13784 while (F.hasNext()) { 13785 NamedDecl *ND = F.next(); 13786 if (!ND->getDeclContext()->getRedeclContext()->Equals( 13787 SearchDC->getRedeclContext())) 13788 F.erase(); 13789 } 13790 F.done(); 13791 } 13792 13793 // C++11 [namespace.memdef]p3: 13794 // If the name in a friend declaration is neither qualified nor 13795 // a template-id and the declaration is a function or an 13796 // elaborated-type-specifier, the lookup to determine whether 13797 // the entity has been previously declared shall not consider 13798 // any scopes outside the innermost enclosing namespace. 13799 // 13800 // MSVC doesn't implement the above rule for types, so a friend tag 13801 // declaration may be a redeclaration of a type declared in an enclosing 13802 // scope. They do implement this rule for friend functions. 13803 // 13804 // Does it matter that this should be by scope instead of by 13805 // semantic context? 13806 if (!Previous.empty() && TUK == TUK_Friend) { 13807 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 13808 LookupResult::Filter F = Previous.makeFilter(); 13809 bool FriendSawTagOutsideEnclosingNamespace = false; 13810 while (F.hasNext()) { 13811 NamedDecl *ND = F.next(); 13812 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 13813 if (DC->isFileContext() && 13814 !EnclosingNS->Encloses(ND->getDeclContext())) { 13815 if (getLangOpts().MSVCCompat) 13816 FriendSawTagOutsideEnclosingNamespace = true; 13817 else 13818 F.erase(); 13819 } 13820 } 13821 F.done(); 13822 13823 // Diagnose this MSVC extension in the easy case where lookup would have 13824 // unambiguously found something outside the enclosing namespace. 13825 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 13826 NamedDecl *ND = Previous.getFoundDecl(); 13827 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 13828 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 13829 } 13830 } 13831 13832 // Note: there used to be some attempt at recovery here. 13833 if (Previous.isAmbiguous()) 13834 return nullptr; 13835 13836 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 13837 // FIXME: This makes sure that we ignore the contexts associated 13838 // with C structs, unions, and enums when looking for a matching 13839 // tag declaration or definition. See the similar lookup tweak 13840 // in Sema::LookupName; is there a better way to deal with this? 13841 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 13842 SearchDC = SearchDC->getParent(); 13843 } 13844 } 13845 13846 if (Previous.isSingleResult() && 13847 Previous.getFoundDecl()->isTemplateParameter()) { 13848 // Maybe we will complain about the shadowed template parameter. 13849 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 13850 // Just pretend that we didn't see the previous declaration. 13851 Previous.clear(); 13852 } 13853 13854 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 13855 DC->Equals(getStdNamespace())) { 13856 if (Name->isStr("bad_alloc")) { 13857 // This is a declaration of or a reference to "std::bad_alloc". 13858 isStdBadAlloc = true; 13859 13860 // If std::bad_alloc has been implicitly declared (but made invisible to 13861 // name lookup), fill in this implicit declaration as the previous 13862 // declaration, so that the declarations get chained appropriately. 13863 if (Previous.empty() && StdBadAlloc) 13864 Previous.addDecl(getStdBadAlloc()); 13865 } else if (Name->isStr("align_val_t")) { 13866 isStdAlignValT = true; 13867 if (Previous.empty() && StdAlignValT) 13868 Previous.addDecl(getStdAlignValT()); 13869 } 13870 } 13871 13872 // If we didn't find a previous declaration, and this is a reference 13873 // (or friend reference), move to the correct scope. In C++, we 13874 // also need to do a redeclaration lookup there, just in case 13875 // there's a shadow friend decl. 13876 if (Name && Previous.empty() && 13877 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 13878 if (Invalid) goto CreateNewDecl; 13879 assert(SS.isEmpty()); 13880 13881 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 13882 // C++ [basic.scope.pdecl]p5: 13883 // -- for an elaborated-type-specifier of the form 13884 // 13885 // class-key identifier 13886 // 13887 // if the elaborated-type-specifier is used in the 13888 // decl-specifier-seq or parameter-declaration-clause of a 13889 // function defined in namespace scope, the identifier is 13890 // declared as a class-name in the namespace that contains 13891 // the declaration; otherwise, except as a friend 13892 // declaration, the identifier is declared in the smallest 13893 // non-class, non-function-prototype scope that contains the 13894 // declaration. 13895 // 13896 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 13897 // C structs and unions. 13898 // 13899 // It is an error in C++ to declare (rather than define) an enum 13900 // type, including via an elaborated type specifier. We'll 13901 // diagnose that later; for now, declare the enum in the same 13902 // scope as we would have picked for any other tag type. 13903 // 13904 // GNU C also supports this behavior as part of its incomplete 13905 // enum types extension, while GNU C++ does not. 13906 // 13907 // Find the context where we'll be declaring the tag. 13908 // FIXME: We would like to maintain the current DeclContext as the 13909 // lexical context, 13910 SearchDC = getTagInjectionContext(SearchDC); 13911 13912 // Find the scope where we'll be declaring the tag. 13913 S = getTagInjectionScope(S, getLangOpts()); 13914 } else { 13915 assert(TUK == TUK_Friend); 13916 // C++ [namespace.memdef]p3: 13917 // If a friend declaration in a non-local class first declares a 13918 // class or function, the friend class or function is a member of 13919 // the innermost enclosing namespace. 13920 SearchDC = SearchDC->getEnclosingNamespaceContext(); 13921 } 13922 13923 // In C++, we need to do a redeclaration lookup to properly 13924 // diagnose some problems. 13925 // FIXME: redeclaration lookup is also used (with and without C++) to find a 13926 // hidden declaration so that we don't get ambiguity errors when using a 13927 // type declared by an elaborated-type-specifier. In C that is not correct 13928 // and we should instead merge compatible types found by lookup. 13929 if (getLangOpts().CPlusPlus) { 13930 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13931 LookupQualifiedName(Previous, SearchDC); 13932 } else { 13933 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 13934 LookupName(Previous, S); 13935 } 13936 } 13937 13938 // If we have a known previous declaration to use, then use it. 13939 if (Previous.empty() && SkipBody && SkipBody->Previous) 13940 Previous.addDecl(SkipBody->Previous); 13941 13942 if (!Previous.empty()) { 13943 NamedDecl *PrevDecl = Previous.getFoundDecl(); 13944 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 13945 13946 // It's okay to have a tag decl in the same scope as a typedef 13947 // which hides a tag decl in the same scope. Finding this 13948 // insanity with a redeclaration lookup can only actually happen 13949 // in C++. 13950 // 13951 // This is also okay for elaborated-type-specifiers, which is 13952 // technically forbidden by the current standard but which is 13953 // okay according to the likely resolution of an open issue; 13954 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 13955 if (getLangOpts().CPlusPlus) { 13956 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 13957 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 13958 TagDecl *Tag = TT->getDecl(); 13959 if (Tag->getDeclName() == Name && 13960 Tag->getDeclContext()->getRedeclContext() 13961 ->Equals(TD->getDeclContext()->getRedeclContext())) { 13962 PrevDecl = Tag; 13963 Previous.clear(); 13964 Previous.addDecl(Tag); 13965 Previous.resolveKind(); 13966 } 13967 } 13968 } 13969 } 13970 13971 // If this is a redeclaration of a using shadow declaration, it must 13972 // declare a tag in the same context. In MSVC mode, we allow a 13973 // redefinition if either context is within the other. 13974 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 13975 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 13976 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 13977 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 13978 !(OldTag && isAcceptableTagRedeclContext( 13979 *this, OldTag->getDeclContext(), SearchDC))) { 13980 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 13981 Diag(Shadow->getTargetDecl()->getLocation(), 13982 diag::note_using_decl_target); 13983 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 13984 << 0; 13985 // Recover by ignoring the old declaration. 13986 Previous.clear(); 13987 goto CreateNewDecl; 13988 } 13989 } 13990 13991 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 13992 // If this is a use of a previous tag, or if the tag is already declared 13993 // in the same scope (so that the definition/declaration completes or 13994 // rementions the tag), reuse the decl. 13995 if (TUK == TUK_Reference || TUK == TUK_Friend || 13996 isDeclInScope(DirectPrevDecl, SearchDC, S, 13997 SS.isNotEmpty() || isMemberSpecialization)) { 13998 // Make sure that this wasn't declared as an enum and now used as a 13999 // struct or something similar. 14000 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 14001 TUK == TUK_Definition, KWLoc, 14002 Name)) { 14003 bool SafeToContinue 14004 = (PrevTagDecl->getTagKind() != TTK_Enum && 14005 Kind != TTK_Enum); 14006 if (SafeToContinue) 14007 Diag(KWLoc, diag::err_use_with_wrong_tag) 14008 << Name 14009 << FixItHint::CreateReplacement(SourceRange(KWLoc), 14010 PrevTagDecl->getKindName()); 14011 else 14012 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 14013 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 14014 14015 if (SafeToContinue) 14016 Kind = PrevTagDecl->getTagKind(); 14017 else { 14018 // Recover by making this an anonymous redefinition. 14019 Name = nullptr; 14020 Previous.clear(); 14021 Invalid = true; 14022 } 14023 } 14024 14025 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 14026 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 14027 14028 // If this is an elaborated-type-specifier for a scoped enumeration, 14029 // the 'class' keyword is not necessary and not permitted. 14030 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14031 if (ScopedEnum) 14032 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 14033 << PrevEnum->isScoped() 14034 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 14035 return PrevTagDecl; 14036 } 14037 14038 QualType EnumUnderlyingTy; 14039 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14040 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 14041 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 14042 EnumUnderlyingTy = QualType(T, 0); 14043 14044 // All conflicts with previous declarations are recovered by 14045 // returning the previous declaration, unless this is a definition, 14046 // in which case we want the caller to bail out. 14047 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 14048 ScopedEnum, EnumUnderlyingTy, 14049 IsFixed, PrevEnum)) 14050 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 14051 } 14052 14053 // C++11 [class.mem]p1: 14054 // A member shall not be declared twice in the member-specification, 14055 // except that a nested class or member class template can be declared 14056 // and then later defined. 14057 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 14058 S->isDeclScope(PrevDecl)) { 14059 Diag(NameLoc, diag::ext_member_redeclared); 14060 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 14061 } 14062 14063 if (!Invalid) { 14064 // If this is a use, just return the declaration we found, unless 14065 // we have attributes. 14066 if (TUK == TUK_Reference || TUK == TUK_Friend) { 14067 if (Attr) { 14068 // FIXME: Diagnose these attributes. For now, we create a new 14069 // declaration to hold them. 14070 } else if (TUK == TUK_Reference && 14071 (PrevTagDecl->getFriendObjectKind() == 14072 Decl::FOK_Undeclared || 14073 PrevDecl->getOwningModule() != getCurrentModule()) && 14074 SS.isEmpty()) { 14075 // This declaration is a reference to an existing entity, but 14076 // has different visibility from that entity: it either makes 14077 // a friend visible or it makes a type visible in a new module. 14078 // In either case, create a new declaration. We only do this if 14079 // the declaration would have meant the same thing if no prior 14080 // declaration were found, that is, if it was found in the same 14081 // scope where we would have injected a declaration. 14082 if (!getTagInjectionContext(CurContext)->getRedeclContext() 14083 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 14084 return PrevTagDecl; 14085 // This is in the injected scope, create a new declaration in 14086 // that scope. 14087 S = getTagInjectionScope(S, getLangOpts()); 14088 } else { 14089 return PrevTagDecl; 14090 } 14091 } 14092 14093 // Diagnose attempts to redefine a tag. 14094 if (TUK == TUK_Definition) { 14095 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 14096 // If we're defining a specialization and the previous definition 14097 // is from an implicit instantiation, don't emit an error 14098 // here; we'll catch this in the general case below. 14099 bool IsExplicitSpecializationAfterInstantiation = false; 14100 if (isMemberSpecialization) { 14101 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 14102 IsExplicitSpecializationAfterInstantiation = 14103 RD->getTemplateSpecializationKind() != 14104 TSK_ExplicitSpecialization; 14105 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 14106 IsExplicitSpecializationAfterInstantiation = 14107 ED->getTemplateSpecializationKind() != 14108 TSK_ExplicitSpecialization; 14109 } 14110 14111 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 14112 // not keep more that one definition around (merge them). However, 14113 // ensure the decl passes the structural compatibility check in 14114 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 14115 NamedDecl *Hidden = nullptr; 14116 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 14117 // There is a definition of this tag, but it is not visible. We 14118 // explicitly make use of C++'s one definition rule here, and 14119 // assume that this definition is identical to the hidden one 14120 // we already have. Make the existing definition visible and 14121 // use it in place of this one. 14122 if (!getLangOpts().CPlusPlus) { 14123 // Postpone making the old definition visible until after we 14124 // complete parsing the new one and do the structural 14125 // comparison. 14126 SkipBody->CheckSameAsPrevious = true; 14127 SkipBody->New = createTagFromNewDecl(); 14128 SkipBody->Previous = Hidden; 14129 } else { 14130 SkipBody->ShouldSkip = true; 14131 makeMergedDefinitionVisible(Hidden); 14132 } 14133 return Def; 14134 } else if (!IsExplicitSpecializationAfterInstantiation) { 14135 // A redeclaration in function prototype scope in C isn't 14136 // visible elsewhere, so merely issue a warning. 14137 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 14138 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 14139 else 14140 Diag(NameLoc, diag::err_redefinition) << Name; 14141 notePreviousDefinition(Def, 14142 NameLoc.isValid() ? NameLoc : KWLoc); 14143 // If this is a redefinition, recover by making this 14144 // struct be anonymous, which will make any later 14145 // references get the previous definition. 14146 Name = nullptr; 14147 Previous.clear(); 14148 Invalid = true; 14149 } 14150 } else { 14151 // If the type is currently being defined, complain 14152 // about a nested redefinition. 14153 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 14154 if (TD->isBeingDefined()) { 14155 Diag(NameLoc, diag::err_nested_redefinition) << Name; 14156 Diag(PrevTagDecl->getLocation(), 14157 diag::note_previous_definition); 14158 Name = nullptr; 14159 Previous.clear(); 14160 Invalid = true; 14161 } 14162 } 14163 14164 // Okay, this is definition of a previously declared or referenced 14165 // tag. We're going to create a new Decl for it. 14166 } 14167 14168 // Okay, we're going to make a redeclaration. If this is some kind 14169 // of reference, make sure we build the redeclaration in the same DC 14170 // as the original, and ignore the current access specifier. 14171 if (TUK == TUK_Friend || TUK == TUK_Reference) { 14172 SearchDC = PrevTagDecl->getDeclContext(); 14173 AS = AS_none; 14174 } 14175 } 14176 // If we get here we have (another) forward declaration or we 14177 // have a definition. Just create a new decl. 14178 14179 } else { 14180 // If we get here, this is a definition of a new tag type in a nested 14181 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 14182 // new decl/type. We set PrevDecl to NULL so that the entities 14183 // have distinct types. 14184 Previous.clear(); 14185 } 14186 // If we get here, we're going to create a new Decl. If PrevDecl 14187 // is non-NULL, it's a definition of the tag declared by 14188 // PrevDecl. If it's NULL, we have a new definition. 14189 14190 // Otherwise, PrevDecl is not a tag, but was found with tag 14191 // lookup. This is only actually possible in C++, where a few 14192 // things like templates still live in the tag namespace. 14193 } else { 14194 // Use a better diagnostic if an elaborated-type-specifier 14195 // found the wrong kind of type on the first 14196 // (non-redeclaration) lookup. 14197 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 14198 !Previous.isForRedeclaration()) { 14199 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14200 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 14201 << Kind; 14202 Diag(PrevDecl->getLocation(), diag::note_declared_at); 14203 Invalid = true; 14204 14205 // Otherwise, only diagnose if the declaration is in scope. 14206 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 14207 SS.isNotEmpty() || isMemberSpecialization)) { 14208 // do nothing 14209 14210 // Diagnose implicit declarations introduced by elaborated types. 14211 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 14212 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 14213 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 14214 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14215 Invalid = true; 14216 14217 // Otherwise it's a declaration. Call out a particularly common 14218 // case here. 14219 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 14220 unsigned Kind = 0; 14221 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 14222 Diag(NameLoc, diag::err_tag_definition_of_typedef) 14223 << Name << Kind << TND->getUnderlyingType(); 14224 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 14225 Invalid = true; 14226 14227 // Otherwise, diagnose. 14228 } else { 14229 // The tag name clashes with something else in the target scope, 14230 // issue an error and recover by making this tag be anonymous. 14231 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 14232 notePreviousDefinition(PrevDecl, NameLoc); 14233 Name = nullptr; 14234 Invalid = true; 14235 } 14236 14237 // The existing declaration isn't relevant to us; we're in a 14238 // new scope, so clear out the previous declaration. 14239 Previous.clear(); 14240 } 14241 } 14242 14243 CreateNewDecl: 14244 14245 TagDecl *PrevDecl = nullptr; 14246 if (Previous.isSingleResult()) 14247 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 14248 14249 // If there is an identifier, use the location of the identifier as the 14250 // location of the decl, otherwise use the location of the struct/union 14251 // keyword. 14252 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 14253 14254 // Otherwise, create a new declaration. If there is a previous 14255 // declaration of the same entity, the two will be linked via 14256 // PrevDecl. 14257 TagDecl *New; 14258 14259 bool IsForwardReference = false; 14260 if (Kind == TTK_Enum) { 14261 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14262 // enum X { A, B, C } D; D should chain to X. 14263 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 14264 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 14265 ScopedEnumUsesClassTag, IsFixed); 14266 14267 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 14268 StdAlignValT = cast<EnumDecl>(New); 14269 14270 // If this is an undefined enum, warn. 14271 if (TUK != TUK_Definition && !Invalid) { 14272 TagDecl *Def; 14273 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 14274 cast<EnumDecl>(New)->isFixed()) { 14275 // C++0x: 7.2p2: opaque-enum-declaration. 14276 // Conflicts are diagnosed above. Do nothing. 14277 } 14278 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 14279 Diag(Loc, diag::ext_forward_ref_enum_def) 14280 << New; 14281 Diag(Def->getLocation(), diag::note_previous_definition); 14282 } else { 14283 unsigned DiagID = diag::ext_forward_ref_enum; 14284 if (getLangOpts().MSVCCompat) 14285 DiagID = diag::ext_ms_forward_ref_enum; 14286 else if (getLangOpts().CPlusPlus) 14287 DiagID = diag::err_forward_ref_enum; 14288 Diag(Loc, DiagID); 14289 14290 // If this is a forward-declared reference to an enumeration, make a 14291 // note of it; we won't actually be introducing the declaration into 14292 // the declaration context. 14293 if (TUK == TUK_Reference) 14294 IsForwardReference = true; 14295 } 14296 } 14297 14298 if (EnumUnderlying) { 14299 EnumDecl *ED = cast<EnumDecl>(New); 14300 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 14301 ED->setIntegerTypeSourceInfo(TI); 14302 else 14303 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 14304 ED->setPromotionType(ED->getIntegerType()); 14305 assert(ED->isComplete() && "enum with type should be complete"); 14306 } 14307 } else { 14308 // struct/union/class 14309 14310 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 14311 // struct X { int A; } D; D should chain to X. 14312 if (getLangOpts().CPlusPlus) { 14313 // FIXME: Look for a way to use RecordDecl for simple structs. 14314 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14315 cast_or_null<CXXRecordDecl>(PrevDecl)); 14316 14317 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 14318 StdBadAlloc = cast<CXXRecordDecl>(New); 14319 } else 14320 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 14321 cast_or_null<RecordDecl>(PrevDecl)); 14322 } 14323 14324 // C++11 [dcl.type]p3: 14325 // A type-specifier-seq shall not define a class or enumeration [...]. 14326 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 14327 TUK == TUK_Definition) { 14328 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 14329 << Context.getTagDeclType(New); 14330 Invalid = true; 14331 } 14332 14333 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 14334 DC->getDeclKind() == Decl::Enum) { 14335 Diag(New->getLocation(), diag::err_type_defined_in_enum) 14336 << Context.getTagDeclType(New); 14337 Invalid = true; 14338 } 14339 14340 // Maybe add qualifier info. 14341 if (SS.isNotEmpty()) { 14342 if (SS.isSet()) { 14343 // If this is either a declaration or a definition, check the 14344 // nested-name-specifier against the current context. 14345 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 14346 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 14347 isMemberSpecialization)) 14348 Invalid = true; 14349 14350 New->setQualifierInfo(SS.getWithLocInContext(Context)); 14351 if (TemplateParameterLists.size() > 0) { 14352 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 14353 } 14354 } 14355 else 14356 Invalid = true; 14357 } 14358 14359 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 14360 // Add alignment attributes if necessary; these attributes are checked when 14361 // the ASTContext lays out the structure. 14362 // 14363 // It is important for implementing the correct semantics that this 14364 // happen here (in ActOnTag). The #pragma pack stack is 14365 // maintained as a result of parser callbacks which can occur at 14366 // many points during the parsing of a struct declaration (because 14367 // the #pragma tokens are effectively skipped over during the 14368 // parsing of the struct). 14369 if (TUK == TUK_Definition) { 14370 AddAlignmentAttributesForRecord(RD); 14371 AddMsStructLayoutForRecord(RD); 14372 } 14373 } 14374 14375 if (ModulePrivateLoc.isValid()) { 14376 if (isMemberSpecialization) 14377 Diag(New->getLocation(), diag::err_module_private_specialization) 14378 << 2 14379 << FixItHint::CreateRemoval(ModulePrivateLoc); 14380 // __module_private__ does not apply to local classes. However, we only 14381 // diagnose this as an error when the declaration specifiers are 14382 // freestanding. Here, we just ignore the __module_private__. 14383 else if (!SearchDC->isFunctionOrMethod()) 14384 New->setModulePrivate(); 14385 } 14386 14387 // If this is a specialization of a member class (of a class template), 14388 // check the specialization. 14389 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 14390 Invalid = true; 14391 14392 // If we're declaring or defining a tag in function prototype scope in C, 14393 // note that this type can only be used within the function and add it to 14394 // the list of decls to inject into the function definition scope. 14395 if ((Name || Kind == TTK_Enum) && 14396 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 14397 if (getLangOpts().CPlusPlus) { 14398 // C++ [dcl.fct]p6: 14399 // Types shall not be defined in return or parameter types. 14400 if (TUK == TUK_Definition && !IsTypeSpecifier) { 14401 Diag(Loc, diag::err_type_defined_in_param_type) 14402 << Name; 14403 Invalid = true; 14404 } 14405 } else if (!PrevDecl) { 14406 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 14407 } 14408 } 14409 14410 if (Invalid) 14411 New->setInvalidDecl(); 14412 14413 // Set the lexical context. If the tag has a C++ scope specifier, the 14414 // lexical context will be different from the semantic context. 14415 New->setLexicalDeclContext(CurContext); 14416 14417 // Mark this as a friend decl if applicable. 14418 // In Microsoft mode, a friend declaration also acts as a forward 14419 // declaration so we always pass true to setObjectOfFriendDecl to make 14420 // the tag name visible. 14421 if (TUK == TUK_Friend) 14422 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 14423 14424 // Set the access specifier. 14425 if (!Invalid && SearchDC->isRecord()) 14426 SetMemberAccessSpecifier(New, PrevDecl, AS); 14427 14428 if (PrevDecl) 14429 CheckRedeclarationModuleOwnership(New, PrevDecl); 14430 14431 if (TUK == TUK_Definition) 14432 New->startDefinition(); 14433 14434 if (Attr) 14435 ProcessDeclAttributeList(S, New, Attr); 14436 AddPragmaAttributes(S, New); 14437 14438 // If this has an identifier, add it to the scope stack. 14439 if (TUK == TUK_Friend) { 14440 // We might be replacing an existing declaration in the lookup tables; 14441 // if so, borrow its access specifier. 14442 if (PrevDecl) 14443 New->setAccess(PrevDecl->getAccess()); 14444 14445 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 14446 DC->makeDeclVisibleInContext(New); 14447 if (Name) // can be null along some error paths 14448 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 14449 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 14450 } else if (Name) { 14451 S = getNonFieldDeclScope(S); 14452 PushOnScopeChains(New, S, !IsForwardReference); 14453 if (IsForwardReference) 14454 SearchDC->makeDeclVisibleInContext(New); 14455 } else { 14456 CurContext->addDecl(New); 14457 } 14458 14459 // If this is the C FILE type, notify the AST context. 14460 if (IdentifierInfo *II = New->getIdentifier()) 14461 if (!New->isInvalidDecl() && 14462 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 14463 II->isStr("FILE")) 14464 Context.setFILEDecl(New); 14465 14466 if (PrevDecl) 14467 mergeDeclAttributes(New, PrevDecl); 14468 14469 // If there's a #pragma GCC visibility in scope, set the visibility of this 14470 // record. 14471 AddPushedVisibilityAttribute(New); 14472 14473 if (isMemberSpecialization && !New->isInvalidDecl()) 14474 CompleteMemberSpecialization(New, Previous); 14475 14476 OwnedDecl = true; 14477 // In C++, don't return an invalid declaration. We can't recover well from 14478 // the cases where we make the type anonymous. 14479 if (Invalid && getLangOpts().CPlusPlus) { 14480 if (New->isBeingDefined()) 14481 if (auto RD = dyn_cast<RecordDecl>(New)) 14482 RD->completeDefinition(); 14483 return nullptr; 14484 } else { 14485 return New; 14486 } 14487 } 14488 14489 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 14490 AdjustDeclIfTemplate(TagD); 14491 TagDecl *Tag = cast<TagDecl>(TagD); 14492 14493 // Enter the tag context. 14494 PushDeclContext(S, Tag); 14495 14496 ActOnDocumentableDecl(TagD); 14497 14498 // If there's a #pragma GCC visibility in scope, set the visibility of this 14499 // record. 14500 AddPushedVisibilityAttribute(Tag); 14501 } 14502 14503 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 14504 SkipBodyInfo &SkipBody) { 14505 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 14506 return false; 14507 14508 // Make the previous decl visible. 14509 makeMergedDefinitionVisible(SkipBody.Previous); 14510 return true; 14511 } 14512 14513 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 14514 assert(isa<ObjCContainerDecl>(IDecl) && 14515 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 14516 DeclContext *OCD = cast<DeclContext>(IDecl); 14517 assert(getContainingDC(OCD) == CurContext && 14518 "The next DeclContext should be lexically contained in the current one."); 14519 CurContext = OCD; 14520 return IDecl; 14521 } 14522 14523 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 14524 SourceLocation FinalLoc, 14525 bool IsFinalSpelledSealed, 14526 SourceLocation LBraceLoc) { 14527 AdjustDeclIfTemplate(TagD); 14528 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 14529 14530 FieldCollector->StartClass(); 14531 14532 if (!Record->getIdentifier()) 14533 return; 14534 14535 if (FinalLoc.isValid()) 14536 Record->addAttr(new (Context) 14537 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 14538 14539 // C++ [class]p2: 14540 // [...] The class-name is also inserted into the scope of the 14541 // class itself; this is known as the injected-class-name. For 14542 // purposes of access checking, the injected-class-name is treated 14543 // as if it were a public member name. 14544 CXXRecordDecl *InjectedClassName 14545 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 14546 Record->getLocStart(), Record->getLocation(), 14547 Record->getIdentifier(), 14548 /*PrevDecl=*/nullptr, 14549 /*DelayTypeCreation=*/true); 14550 Context.getTypeDeclType(InjectedClassName, Record); 14551 InjectedClassName->setImplicit(); 14552 InjectedClassName->setAccess(AS_public); 14553 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 14554 InjectedClassName->setDescribedClassTemplate(Template); 14555 PushOnScopeChains(InjectedClassName, S); 14556 assert(InjectedClassName->isInjectedClassName() && 14557 "Broken injected-class-name"); 14558 } 14559 14560 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 14561 SourceRange BraceRange) { 14562 AdjustDeclIfTemplate(TagD); 14563 TagDecl *Tag = cast<TagDecl>(TagD); 14564 Tag->setBraceRange(BraceRange); 14565 14566 // Make sure we "complete" the definition even it is invalid. 14567 if (Tag->isBeingDefined()) { 14568 assert(Tag->isInvalidDecl() && "We should already have completed it"); 14569 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14570 RD->completeDefinition(); 14571 } 14572 14573 if (isa<CXXRecordDecl>(Tag)) { 14574 FieldCollector->FinishClass(); 14575 } 14576 14577 // Exit this scope of this tag's definition. 14578 PopDeclContext(); 14579 14580 if (getCurLexicalContext()->isObjCContainer() && 14581 Tag->getDeclContext()->isFileContext()) 14582 Tag->setTopLevelDeclInObjCContainer(); 14583 14584 // Notify the consumer that we've defined a tag. 14585 if (!Tag->isInvalidDecl()) 14586 Consumer.HandleTagDeclDefinition(Tag); 14587 } 14588 14589 void Sema::ActOnObjCContainerFinishDefinition() { 14590 // Exit this scope of this interface definition. 14591 PopDeclContext(); 14592 } 14593 14594 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 14595 assert(DC == CurContext && "Mismatch of container contexts"); 14596 OriginalLexicalContext = DC; 14597 ActOnObjCContainerFinishDefinition(); 14598 } 14599 14600 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 14601 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 14602 OriginalLexicalContext = nullptr; 14603 } 14604 14605 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 14606 AdjustDeclIfTemplate(TagD); 14607 TagDecl *Tag = cast<TagDecl>(TagD); 14608 Tag->setInvalidDecl(); 14609 14610 // Make sure we "complete" the definition even it is invalid. 14611 if (Tag->isBeingDefined()) { 14612 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 14613 RD->completeDefinition(); 14614 } 14615 14616 // We're undoing ActOnTagStartDefinition here, not 14617 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 14618 // the FieldCollector. 14619 14620 PopDeclContext(); 14621 } 14622 14623 // Note that FieldName may be null for anonymous bitfields. 14624 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 14625 IdentifierInfo *FieldName, 14626 QualType FieldTy, bool IsMsStruct, 14627 Expr *BitWidth, bool *ZeroWidth) { 14628 // Default to true; that shouldn't confuse checks for emptiness 14629 if (ZeroWidth) 14630 *ZeroWidth = true; 14631 14632 // C99 6.7.2.1p4 - verify the field type. 14633 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 14634 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 14635 // Handle incomplete types with specific error. 14636 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 14637 return ExprError(); 14638 if (FieldName) 14639 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 14640 << FieldName << FieldTy << BitWidth->getSourceRange(); 14641 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 14642 << FieldTy << BitWidth->getSourceRange(); 14643 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 14644 UPPC_BitFieldWidth)) 14645 return ExprError(); 14646 14647 // If the bit-width is type- or value-dependent, don't try to check 14648 // it now. 14649 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 14650 return BitWidth; 14651 14652 llvm::APSInt Value; 14653 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 14654 if (ICE.isInvalid()) 14655 return ICE; 14656 BitWidth = ICE.get(); 14657 14658 if (Value != 0 && ZeroWidth) 14659 *ZeroWidth = false; 14660 14661 // Zero-width bitfield is ok for anonymous field. 14662 if (Value == 0 && FieldName) 14663 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 14664 14665 if (Value.isSigned() && Value.isNegative()) { 14666 if (FieldName) 14667 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 14668 << FieldName << Value.toString(10); 14669 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 14670 << Value.toString(10); 14671 } 14672 14673 if (!FieldTy->isDependentType()) { 14674 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 14675 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 14676 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 14677 14678 // Over-wide bitfields are an error in C or when using the MSVC bitfield 14679 // ABI. 14680 bool CStdConstraintViolation = 14681 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 14682 bool MSBitfieldViolation = 14683 Value.ugt(TypeStorageSize) && 14684 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 14685 if (CStdConstraintViolation || MSBitfieldViolation) { 14686 unsigned DiagWidth = 14687 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 14688 if (FieldName) 14689 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 14690 << FieldName << (unsigned)Value.getZExtValue() 14691 << !CStdConstraintViolation << DiagWidth; 14692 14693 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 14694 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 14695 << DiagWidth; 14696 } 14697 14698 // Warn on types where the user might conceivably expect to get all 14699 // specified bits as value bits: that's all integral types other than 14700 // 'bool'. 14701 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 14702 if (FieldName) 14703 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 14704 << FieldName << (unsigned)Value.getZExtValue() 14705 << (unsigned)TypeWidth; 14706 else 14707 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 14708 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 14709 } 14710 } 14711 14712 return BitWidth; 14713 } 14714 14715 /// ActOnField - Each field of a C struct/union is passed into this in order 14716 /// to create a FieldDecl object for it. 14717 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 14718 Declarator &D, Expr *BitfieldWidth) { 14719 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 14720 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 14721 /*InitStyle=*/ICIS_NoInit, AS_public); 14722 return Res; 14723 } 14724 14725 /// HandleField - Analyze a field of a C struct or a C++ data member. 14726 /// 14727 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 14728 SourceLocation DeclStart, 14729 Declarator &D, Expr *BitWidth, 14730 InClassInitStyle InitStyle, 14731 AccessSpecifier AS) { 14732 if (D.isDecompositionDeclarator()) { 14733 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 14734 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 14735 << Decomp.getSourceRange(); 14736 return nullptr; 14737 } 14738 14739 IdentifierInfo *II = D.getIdentifier(); 14740 SourceLocation Loc = DeclStart; 14741 if (II) Loc = D.getIdentifierLoc(); 14742 14743 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 14744 QualType T = TInfo->getType(); 14745 if (getLangOpts().CPlusPlus) { 14746 CheckExtraCXXDefaultArguments(D); 14747 14748 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 14749 UPPC_DataMemberType)) { 14750 D.setInvalidType(); 14751 T = Context.IntTy; 14752 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 14753 } 14754 } 14755 14756 // TR 18037 does not allow fields to be declared with address spaces. 14757 if (T.getQualifiers().hasAddressSpace() || 14758 T->isDependentAddressSpaceType() || 14759 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 14760 Diag(Loc, diag::err_field_with_address_space); 14761 D.setInvalidType(); 14762 } 14763 14764 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 14765 // used as structure or union field: image, sampler, event or block types. 14766 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() || 14767 T->isSamplerT() || T->isBlockPointerType())) { 14768 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 14769 D.setInvalidType(); 14770 } 14771 14772 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 14773 14774 if (D.getDeclSpec().isInlineSpecified()) 14775 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 14776 << getLangOpts().CPlusPlus17; 14777 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 14778 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 14779 diag::err_invalid_thread) 14780 << DeclSpec::getSpecifierName(TSCS); 14781 14782 // Check to see if this name was declared as a member previously 14783 NamedDecl *PrevDecl = nullptr; 14784 LookupResult Previous(*this, II, Loc, LookupMemberName, 14785 ForVisibleRedeclaration); 14786 LookupName(Previous, S); 14787 switch (Previous.getResultKind()) { 14788 case LookupResult::Found: 14789 case LookupResult::FoundUnresolvedValue: 14790 PrevDecl = Previous.getAsSingle<NamedDecl>(); 14791 break; 14792 14793 case LookupResult::FoundOverloaded: 14794 PrevDecl = Previous.getRepresentativeDecl(); 14795 break; 14796 14797 case LookupResult::NotFound: 14798 case LookupResult::NotFoundInCurrentInstantiation: 14799 case LookupResult::Ambiguous: 14800 break; 14801 } 14802 Previous.suppressDiagnostics(); 14803 14804 if (PrevDecl && PrevDecl->isTemplateParameter()) { 14805 // Maybe we will complain about the shadowed template parameter. 14806 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 14807 // Just pretend that we didn't see the previous declaration. 14808 PrevDecl = nullptr; 14809 } 14810 14811 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 14812 PrevDecl = nullptr; 14813 14814 bool Mutable 14815 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 14816 SourceLocation TSSL = D.getLocStart(); 14817 FieldDecl *NewFD 14818 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 14819 TSSL, AS, PrevDecl, &D); 14820 14821 if (NewFD->isInvalidDecl()) 14822 Record->setInvalidDecl(); 14823 14824 if (D.getDeclSpec().isModulePrivateSpecified()) 14825 NewFD->setModulePrivate(); 14826 14827 if (NewFD->isInvalidDecl() && PrevDecl) { 14828 // Don't introduce NewFD into scope; there's already something 14829 // with the same name in the same scope. 14830 } else if (II) { 14831 PushOnScopeChains(NewFD, S); 14832 } else 14833 Record->addDecl(NewFD); 14834 14835 return NewFD; 14836 } 14837 14838 /// \brief Build a new FieldDecl and check its well-formedness. 14839 /// 14840 /// This routine builds a new FieldDecl given the fields name, type, 14841 /// record, etc. \p PrevDecl should refer to any previous declaration 14842 /// with the same name and in the same scope as the field to be 14843 /// created. 14844 /// 14845 /// \returns a new FieldDecl. 14846 /// 14847 /// \todo The Declarator argument is a hack. It will be removed once 14848 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 14849 TypeSourceInfo *TInfo, 14850 RecordDecl *Record, SourceLocation Loc, 14851 bool Mutable, Expr *BitWidth, 14852 InClassInitStyle InitStyle, 14853 SourceLocation TSSL, 14854 AccessSpecifier AS, NamedDecl *PrevDecl, 14855 Declarator *D) { 14856 IdentifierInfo *II = Name.getAsIdentifierInfo(); 14857 bool InvalidDecl = false; 14858 if (D) InvalidDecl = D->isInvalidType(); 14859 14860 // If we receive a broken type, recover by assuming 'int' and 14861 // marking this declaration as invalid. 14862 if (T.isNull()) { 14863 InvalidDecl = true; 14864 T = Context.IntTy; 14865 } 14866 14867 QualType EltTy = Context.getBaseElementType(T); 14868 if (!EltTy->isDependentType()) { 14869 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 14870 // Fields of incomplete type force their record to be invalid. 14871 Record->setInvalidDecl(); 14872 InvalidDecl = true; 14873 } else { 14874 NamedDecl *Def; 14875 EltTy->isIncompleteType(&Def); 14876 if (Def && Def->isInvalidDecl()) { 14877 Record->setInvalidDecl(); 14878 InvalidDecl = true; 14879 } 14880 } 14881 } 14882 14883 // OpenCL v1.2 s6.9.c: bitfields are not supported. 14884 if (BitWidth && getLangOpts().OpenCL) { 14885 Diag(Loc, diag::err_opencl_bitfields); 14886 InvalidDecl = true; 14887 } 14888 14889 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 14890 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 14891 T.hasQualifiers()) { 14892 InvalidDecl = true; 14893 Diag(Loc, diag::err_anon_bitfield_qualifiers); 14894 } 14895 14896 // C99 6.7.2.1p8: A member of a structure or union may have any type other 14897 // than a variably modified type. 14898 if (!InvalidDecl && T->isVariablyModifiedType()) { 14899 bool SizeIsNegative; 14900 llvm::APSInt Oversized; 14901 14902 TypeSourceInfo *FixedTInfo = 14903 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 14904 SizeIsNegative, 14905 Oversized); 14906 if (FixedTInfo) { 14907 Diag(Loc, diag::warn_illegal_constant_array_size); 14908 TInfo = FixedTInfo; 14909 T = FixedTInfo->getType(); 14910 } else { 14911 if (SizeIsNegative) 14912 Diag(Loc, diag::err_typecheck_negative_array_size); 14913 else if (Oversized.getBoolValue()) 14914 Diag(Loc, diag::err_array_too_large) 14915 << Oversized.toString(10); 14916 else 14917 Diag(Loc, diag::err_typecheck_field_variable_size); 14918 InvalidDecl = true; 14919 } 14920 } 14921 14922 // Fields can not have abstract class types 14923 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 14924 diag::err_abstract_type_in_decl, 14925 AbstractFieldType)) 14926 InvalidDecl = true; 14927 14928 bool ZeroWidth = false; 14929 if (InvalidDecl) 14930 BitWidth = nullptr; 14931 // If this is declared as a bit-field, check the bit-field. 14932 if (BitWidth) { 14933 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 14934 &ZeroWidth).get(); 14935 if (!BitWidth) { 14936 InvalidDecl = true; 14937 BitWidth = nullptr; 14938 ZeroWidth = false; 14939 } 14940 } 14941 14942 // Check that 'mutable' is consistent with the type of the declaration. 14943 if (!InvalidDecl && Mutable) { 14944 unsigned DiagID = 0; 14945 if (T->isReferenceType()) 14946 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 14947 : diag::err_mutable_reference; 14948 else if (T.isConstQualified()) 14949 DiagID = diag::err_mutable_const; 14950 14951 if (DiagID) { 14952 SourceLocation ErrLoc = Loc; 14953 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 14954 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 14955 Diag(ErrLoc, DiagID); 14956 if (DiagID != diag::ext_mutable_reference) { 14957 Mutable = false; 14958 InvalidDecl = true; 14959 } 14960 } 14961 } 14962 14963 // C++11 [class.union]p8 (DR1460): 14964 // At most one variant member of a union may have a 14965 // brace-or-equal-initializer. 14966 if (InitStyle != ICIS_NoInit) 14967 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 14968 14969 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 14970 BitWidth, Mutable, InitStyle); 14971 if (InvalidDecl) 14972 NewFD->setInvalidDecl(); 14973 14974 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 14975 Diag(Loc, diag::err_duplicate_member) << II; 14976 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 14977 NewFD->setInvalidDecl(); 14978 } 14979 14980 if (!InvalidDecl && getLangOpts().CPlusPlus) { 14981 if (Record->isUnion()) { 14982 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 14983 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 14984 if (RDecl->getDefinition()) { 14985 // C++ [class.union]p1: An object of a class with a non-trivial 14986 // constructor, a non-trivial copy constructor, a non-trivial 14987 // destructor, or a non-trivial copy assignment operator 14988 // cannot be a member of a union, nor can an array of such 14989 // objects. 14990 if (CheckNontrivialField(NewFD)) 14991 NewFD->setInvalidDecl(); 14992 } 14993 } 14994 14995 // C++ [class.union]p1: If a union contains a member of reference type, 14996 // the program is ill-formed, except when compiling with MSVC extensions 14997 // enabled. 14998 if (EltTy->isReferenceType()) { 14999 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 15000 diag::ext_union_member_of_reference_type : 15001 diag::err_union_member_of_reference_type) 15002 << NewFD->getDeclName() << EltTy; 15003 if (!getLangOpts().MicrosoftExt) 15004 NewFD->setInvalidDecl(); 15005 } 15006 } 15007 } 15008 15009 // FIXME: We need to pass in the attributes given an AST 15010 // representation, not a parser representation. 15011 if (D) { 15012 // FIXME: The current scope is almost... but not entirely... correct here. 15013 ProcessDeclAttributes(getCurScope(), NewFD, *D); 15014 15015 if (NewFD->hasAttrs()) 15016 CheckAlignasUnderalignment(NewFD); 15017 } 15018 15019 // In auto-retain/release, infer strong retension for fields of 15020 // retainable type. 15021 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 15022 NewFD->setInvalidDecl(); 15023 15024 if (T.isObjCGCWeak()) 15025 Diag(Loc, diag::warn_attribute_weak_on_field); 15026 15027 NewFD->setAccess(AS); 15028 return NewFD; 15029 } 15030 15031 bool Sema::CheckNontrivialField(FieldDecl *FD) { 15032 assert(FD); 15033 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 15034 15035 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 15036 return false; 15037 15038 QualType EltTy = Context.getBaseElementType(FD->getType()); 15039 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 15040 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 15041 if (RDecl->getDefinition()) { 15042 // We check for copy constructors before constructors 15043 // because otherwise we'll never get complaints about 15044 // copy constructors. 15045 15046 CXXSpecialMember member = CXXInvalid; 15047 // We're required to check for any non-trivial constructors. Since the 15048 // implicit default constructor is suppressed if there are any 15049 // user-declared constructors, we just need to check that there is a 15050 // trivial default constructor and a trivial copy constructor. (We don't 15051 // worry about move constructors here, since this is a C++98 check.) 15052 if (RDecl->hasNonTrivialCopyConstructor()) 15053 member = CXXCopyConstructor; 15054 else if (!RDecl->hasTrivialDefaultConstructor()) 15055 member = CXXDefaultConstructor; 15056 else if (RDecl->hasNonTrivialCopyAssignment()) 15057 member = CXXCopyAssignment; 15058 else if (RDecl->hasNonTrivialDestructor()) 15059 member = CXXDestructor; 15060 15061 if (member != CXXInvalid) { 15062 if (!getLangOpts().CPlusPlus11 && 15063 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 15064 // Objective-C++ ARC: it is an error to have a non-trivial field of 15065 // a union. However, system headers in Objective-C programs 15066 // occasionally have Objective-C lifetime objects within unions, 15067 // and rather than cause the program to fail, we make those 15068 // members unavailable. 15069 SourceLocation Loc = FD->getLocation(); 15070 if (getSourceManager().isInSystemHeader(Loc)) { 15071 if (!FD->hasAttr<UnavailableAttr>()) 15072 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15073 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 15074 return false; 15075 } 15076 } 15077 15078 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 15079 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 15080 diag::err_illegal_union_or_anon_struct_member) 15081 << FD->getParent()->isUnion() << FD->getDeclName() << member; 15082 DiagnoseNontrivial(RDecl, member); 15083 return !getLangOpts().CPlusPlus11; 15084 } 15085 } 15086 } 15087 15088 return false; 15089 } 15090 15091 /// TranslateIvarVisibility - Translate visibility from a token ID to an 15092 /// AST enum value. 15093 static ObjCIvarDecl::AccessControl 15094 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 15095 switch (ivarVisibility) { 15096 default: llvm_unreachable("Unknown visitibility kind"); 15097 case tok::objc_private: return ObjCIvarDecl::Private; 15098 case tok::objc_public: return ObjCIvarDecl::Public; 15099 case tok::objc_protected: return ObjCIvarDecl::Protected; 15100 case tok::objc_package: return ObjCIvarDecl::Package; 15101 } 15102 } 15103 15104 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 15105 /// in order to create an IvarDecl object for it. 15106 Decl *Sema::ActOnIvar(Scope *S, 15107 SourceLocation DeclStart, 15108 Declarator &D, Expr *BitfieldWidth, 15109 tok::ObjCKeywordKind Visibility) { 15110 15111 IdentifierInfo *II = D.getIdentifier(); 15112 Expr *BitWidth = (Expr*)BitfieldWidth; 15113 SourceLocation Loc = DeclStart; 15114 if (II) Loc = D.getIdentifierLoc(); 15115 15116 // FIXME: Unnamed fields can be handled in various different ways, for 15117 // example, unnamed unions inject all members into the struct namespace! 15118 15119 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 15120 QualType T = TInfo->getType(); 15121 15122 if (BitWidth) { 15123 // 6.7.2.1p3, 6.7.2.1p4 15124 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 15125 if (!BitWidth) 15126 D.setInvalidType(); 15127 } else { 15128 // Not a bitfield. 15129 15130 // validate II. 15131 15132 } 15133 if (T->isReferenceType()) { 15134 Diag(Loc, diag::err_ivar_reference_type); 15135 D.setInvalidType(); 15136 } 15137 // C99 6.7.2.1p8: A member of a structure or union may have any type other 15138 // than a variably modified type. 15139 else if (T->isVariablyModifiedType()) { 15140 Diag(Loc, diag::err_typecheck_ivar_variable_size); 15141 D.setInvalidType(); 15142 } 15143 15144 // Get the visibility (access control) for this ivar. 15145 ObjCIvarDecl::AccessControl ac = 15146 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 15147 : ObjCIvarDecl::None; 15148 // Must set ivar's DeclContext to its enclosing interface. 15149 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 15150 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 15151 return nullptr; 15152 ObjCContainerDecl *EnclosingContext; 15153 if (ObjCImplementationDecl *IMPDecl = 15154 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15155 if (LangOpts.ObjCRuntime.isFragile()) { 15156 // Case of ivar declared in an implementation. Context is that of its class. 15157 EnclosingContext = IMPDecl->getClassInterface(); 15158 assert(EnclosingContext && "Implementation has no class interface!"); 15159 } 15160 else 15161 EnclosingContext = EnclosingDecl; 15162 } else { 15163 if (ObjCCategoryDecl *CDecl = 15164 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15165 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 15166 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 15167 return nullptr; 15168 } 15169 } 15170 EnclosingContext = EnclosingDecl; 15171 } 15172 15173 // Construct the decl. 15174 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 15175 DeclStart, Loc, II, T, 15176 TInfo, ac, (Expr *)BitfieldWidth); 15177 15178 if (II) { 15179 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 15180 ForVisibleRedeclaration); 15181 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 15182 && !isa<TagDecl>(PrevDecl)) { 15183 Diag(Loc, diag::err_duplicate_member) << II; 15184 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 15185 NewID->setInvalidDecl(); 15186 } 15187 } 15188 15189 // Process attributes attached to the ivar. 15190 ProcessDeclAttributes(S, NewID, D); 15191 15192 if (D.isInvalidType()) 15193 NewID->setInvalidDecl(); 15194 15195 // In ARC, infer 'retaining' for ivars of retainable type. 15196 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 15197 NewID->setInvalidDecl(); 15198 15199 if (D.getDeclSpec().isModulePrivateSpecified()) 15200 NewID->setModulePrivate(); 15201 15202 if (II) { 15203 // FIXME: When interfaces are DeclContexts, we'll need to add 15204 // these to the interface. 15205 S->AddDecl(NewID); 15206 IdResolver.AddDecl(NewID); 15207 } 15208 15209 if (LangOpts.ObjCRuntime.isNonFragile() && 15210 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 15211 Diag(Loc, diag::warn_ivars_in_interface); 15212 15213 return NewID; 15214 } 15215 15216 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 15217 /// class and class extensions. For every class \@interface and class 15218 /// extension \@interface, if the last ivar is a bitfield of any type, 15219 /// then add an implicit `char :0` ivar to the end of that interface. 15220 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 15221 SmallVectorImpl<Decl *> &AllIvarDecls) { 15222 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 15223 return; 15224 15225 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 15226 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 15227 15228 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 15229 return; 15230 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 15231 if (!ID) { 15232 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 15233 if (!CD->IsClassExtension()) 15234 return; 15235 } 15236 // No need to add this to end of @implementation. 15237 else 15238 return; 15239 } 15240 // All conditions are met. Add a new bitfield to the tail end of ivars. 15241 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 15242 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 15243 15244 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 15245 DeclLoc, DeclLoc, nullptr, 15246 Context.CharTy, 15247 Context.getTrivialTypeSourceInfo(Context.CharTy, 15248 DeclLoc), 15249 ObjCIvarDecl::Private, BW, 15250 true); 15251 AllIvarDecls.push_back(Ivar); 15252 } 15253 15254 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 15255 ArrayRef<Decl *> Fields, SourceLocation LBrac, 15256 SourceLocation RBrac, AttributeList *Attr) { 15257 assert(EnclosingDecl && "missing record or interface decl"); 15258 15259 // If this is an Objective-C @implementation or category and we have 15260 // new fields here we should reset the layout of the interface since 15261 // it will now change. 15262 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 15263 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 15264 switch (DC->getKind()) { 15265 default: break; 15266 case Decl::ObjCCategory: 15267 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 15268 break; 15269 case Decl::ObjCImplementation: 15270 Context. 15271 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 15272 break; 15273 } 15274 } 15275 15276 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 15277 15278 // Start counting up the number of named members; make sure to include 15279 // members of anonymous structs and unions in the total. 15280 unsigned NumNamedMembers = 0; 15281 if (Record) { 15282 for (const auto *I : Record->decls()) { 15283 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 15284 if (IFD->getDeclName()) 15285 ++NumNamedMembers; 15286 } 15287 } 15288 15289 // Verify that all the fields are okay. 15290 SmallVector<FieldDecl*, 32> RecFields; 15291 15292 bool ObjCFieldLifetimeErrReported = false; 15293 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 15294 i != end; ++i) { 15295 FieldDecl *FD = cast<FieldDecl>(*i); 15296 15297 // Get the type for the field. 15298 const Type *FDTy = FD->getType().getTypePtr(); 15299 15300 if (!FD->isAnonymousStructOrUnion()) { 15301 // Remember all fields written by the user. 15302 RecFields.push_back(FD); 15303 } 15304 15305 // If the field is already invalid for some reason, don't emit more 15306 // diagnostics about it. 15307 if (FD->isInvalidDecl()) { 15308 EnclosingDecl->setInvalidDecl(); 15309 continue; 15310 } 15311 15312 // C99 6.7.2.1p2: 15313 // A structure or union shall not contain a member with 15314 // incomplete or function type (hence, a structure shall not 15315 // contain an instance of itself, but may contain a pointer to 15316 // an instance of itself), except that the last member of a 15317 // structure with more than one named member may have incomplete 15318 // array type; such a structure (and any union containing, 15319 // possibly recursively, a member that is such a structure) 15320 // shall not be a member of a structure or an element of an 15321 // array. 15322 bool IsLastField = (i + 1 == Fields.end()); 15323 if (FDTy->isFunctionType()) { 15324 // Field declared as a function. 15325 Diag(FD->getLocation(), diag::err_field_declared_as_function) 15326 << FD->getDeclName(); 15327 FD->setInvalidDecl(); 15328 EnclosingDecl->setInvalidDecl(); 15329 continue; 15330 } else if (FDTy->isIncompleteArrayType() && 15331 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 15332 if (Record) { 15333 // Flexible array member. 15334 // Microsoft and g++ is more permissive regarding flexible array. 15335 // It will accept flexible array in union and also 15336 // as the sole element of a struct/class. 15337 unsigned DiagID = 0; 15338 if (!Record->isUnion() && !IsLastField) { 15339 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 15340 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 15341 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 15342 FD->setInvalidDecl(); 15343 EnclosingDecl->setInvalidDecl(); 15344 continue; 15345 } else if (Record->isUnion()) 15346 DiagID = getLangOpts().MicrosoftExt 15347 ? diag::ext_flexible_array_union_ms 15348 : getLangOpts().CPlusPlus 15349 ? diag::ext_flexible_array_union_gnu 15350 : diag::err_flexible_array_union; 15351 else if (NumNamedMembers < 1) 15352 DiagID = getLangOpts().MicrosoftExt 15353 ? diag::ext_flexible_array_empty_aggregate_ms 15354 : getLangOpts().CPlusPlus 15355 ? diag::ext_flexible_array_empty_aggregate_gnu 15356 : diag::err_flexible_array_empty_aggregate; 15357 15358 if (DiagID) 15359 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 15360 << Record->getTagKind(); 15361 // While the layout of types that contain virtual bases is not specified 15362 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 15363 // virtual bases after the derived members. This would make a flexible 15364 // array member declared at the end of an object not adjacent to the end 15365 // of the type. 15366 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 15367 if (RD->getNumVBases() != 0) 15368 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 15369 << FD->getDeclName() << Record->getTagKind(); 15370 if (!getLangOpts().C99) 15371 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 15372 << FD->getDeclName() << Record->getTagKind(); 15373 15374 // If the element type has a non-trivial destructor, we would not 15375 // implicitly destroy the elements, so disallow it for now. 15376 // 15377 // FIXME: GCC allows this. We should probably either implicitly delete 15378 // the destructor of the containing class, or just allow this. 15379 QualType BaseElem = Context.getBaseElementType(FD->getType()); 15380 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 15381 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 15382 << FD->getDeclName() << FD->getType(); 15383 FD->setInvalidDecl(); 15384 EnclosingDecl->setInvalidDecl(); 15385 continue; 15386 } 15387 // Okay, we have a legal flexible array member at the end of the struct. 15388 Record->setHasFlexibleArrayMember(true); 15389 } else { 15390 // In ObjCContainerDecl ivars with incomplete array type are accepted, 15391 // unless they are followed by another ivar. That check is done 15392 // elsewhere, after synthesized ivars are known. 15393 } 15394 } else if (!FDTy->isDependentType() && 15395 RequireCompleteType(FD->getLocation(), FD->getType(), 15396 diag::err_field_incomplete)) { 15397 // Incomplete type 15398 FD->setInvalidDecl(); 15399 EnclosingDecl->setInvalidDecl(); 15400 continue; 15401 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 15402 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 15403 // A type which contains a flexible array member is considered to be a 15404 // flexible array member. 15405 Record->setHasFlexibleArrayMember(true); 15406 if (!Record->isUnion()) { 15407 // If this is a struct/class and this is not the last element, reject 15408 // it. Note that GCC supports variable sized arrays in the middle of 15409 // structures. 15410 if (!IsLastField) 15411 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 15412 << FD->getDeclName() << FD->getType(); 15413 else { 15414 // We support flexible arrays at the end of structs in 15415 // other structs as an extension. 15416 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 15417 << FD->getDeclName(); 15418 } 15419 } 15420 } 15421 if (isa<ObjCContainerDecl>(EnclosingDecl) && 15422 RequireNonAbstractType(FD->getLocation(), FD->getType(), 15423 diag::err_abstract_type_in_decl, 15424 AbstractIvarType)) { 15425 // Ivars can not have abstract class types 15426 FD->setInvalidDecl(); 15427 } 15428 if (Record && FDTTy->getDecl()->hasObjectMember()) 15429 Record->setHasObjectMember(true); 15430 if (Record && FDTTy->getDecl()->hasVolatileMember()) 15431 Record->setHasVolatileMember(true); 15432 } else if (FDTy->isObjCObjectType()) { 15433 /// A field cannot be an Objective-c object 15434 Diag(FD->getLocation(), diag::err_statically_allocated_object) 15435 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 15436 QualType T = Context.getObjCObjectPointerType(FD->getType()); 15437 FD->setType(T); 15438 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && 15439 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) { 15440 // It's an error in ARC or Weak if a field has lifetime. 15441 // We don't want to report this in a system header, though, 15442 // so we just make the field unavailable. 15443 // FIXME: that's really not sufficient; we need to make the type 15444 // itself invalid to, say, initialize or copy. 15445 QualType T = FD->getType(); 15446 if (T.hasNonTrivialObjCLifetime()) { 15447 SourceLocation loc = FD->getLocation(); 15448 if (getSourceManager().isInSystemHeader(loc)) { 15449 if (!FD->hasAttr<UnavailableAttr>()) { 15450 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 15451 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 15452 } 15453 } else { 15454 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 15455 << T->isBlockPointerType() << Record->getTagKind(); 15456 } 15457 ObjCFieldLifetimeErrReported = true; 15458 } 15459 } else if (getLangOpts().ObjC1 && 15460 getLangOpts().getGC() != LangOptions::NonGC && 15461 Record && !Record->hasObjectMember()) { 15462 if (FD->getType()->isObjCObjectPointerType() || 15463 FD->getType().isObjCGCStrong()) 15464 Record->setHasObjectMember(true); 15465 else if (Context.getAsArrayType(FD->getType())) { 15466 QualType BaseType = Context.getBaseElementType(FD->getType()); 15467 if (BaseType->isRecordType() && 15468 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 15469 Record->setHasObjectMember(true); 15470 else if (BaseType->isObjCObjectPointerType() || 15471 BaseType.isObjCGCStrong()) 15472 Record->setHasObjectMember(true); 15473 } 15474 } 15475 15476 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) { 15477 QualType FT = FD->getType(); 15478 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) 15479 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 15480 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 15481 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) 15482 Record->setNonTrivialToPrimitiveCopy(true); 15483 if (FT.isDestructedType()) { 15484 Record->setNonTrivialToPrimitiveDestroy(true); 15485 Record->setParamDestroyedInCallee(true); 15486 } 15487 15488 if (const auto *RT = FT->getAs<RecordType>()) { 15489 if (RT->getDecl()->getArgPassingRestrictions() == 15490 RecordDecl::APK_CanNeverPassInRegs) 15491 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15492 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 15493 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 15494 } 15495 15496 if (Record && FD->getType().isVolatileQualified()) 15497 Record->setHasVolatileMember(true); 15498 // Keep track of the number of named members. 15499 if (FD->getIdentifier()) 15500 ++NumNamedMembers; 15501 } 15502 15503 // Okay, we successfully defined 'Record'. 15504 if (Record) { 15505 bool Completed = false; 15506 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15507 if (!CXXRecord->isInvalidDecl()) { 15508 // Set access bits correctly on the directly-declared conversions. 15509 for (CXXRecordDecl::conversion_iterator 15510 I = CXXRecord->conversion_begin(), 15511 E = CXXRecord->conversion_end(); I != E; ++I) 15512 I.setAccess((*I)->getAccess()); 15513 } 15514 15515 if (!CXXRecord->isDependentType()) { 15516 if (CXXRecord->hasUserDeclaredDestructor()) { 15517 // Adjust user-defined destructor exception spec. 15518 if (getLangOpts().CPlusPlus11) 15519 AdjustDestructorExceptionSpec(CXXRecord, 15520 CXXRecord->getDestructor()); 15521 } 15522 15523 // Add any implicitly-declared members to this class. 15524 AddImplicitlyDeclaredMembersToClass(CXXRecord); 15525 15526 if (!CXXRecord->isInvalidDecl()) { 15527 // If we have virtual base classes, we may end up finding multiple 15528 // final overriders for a given virtual function. Check for this 15529 // problem now. 15530 if (CXXRecord->getNumVBases()) { 15531 CXXFinalOverriderMap FinalOverriders; 15532 CXXRecord->getFinalOverriders(FinalOverriders); 15533 15534 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 15535 MEnd = FinalOverriders.end(); 15536 M != MEnd; ++M) { 15537 for (OverridingMethods::iterator SO = M->second.begin(), 15538 SOEnd = M->second.end(); 15539 SO != SOEnd; ++SO) { 15540 assert(SO->second.size() > 0 && 15541 "Virtual function without overriding functions?"); 15542 if (SO->second.size() == 1) 15543 continue; 15544 15545 // C++ [class.virtual]p2: 15546 // In a derived class, if a virtual member function of a base 15547 // class subobject has more than one final overrider the 15548 // program is ill-formed. 15549 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 15550 << (const NamedDecl *)M->first << Record; 15551 Diag(M->first->getLocation(), 15552 diag::note_overridden_virtual_function); 15553 for (OverridingMethods::overriding_iterator 15554 OM = SO->second.begin(), 15555 OMEnd = SO->second.end(); 15556 OM != OMEnd; ++OM) 15557 Diag(OM->Method->getLocation(), diag::note_final_overrider) 15558 << (const NamedDecl *)M->first << OM->Method->getParent(); 15559 15560 Record->setInvalidDecl(); 15561 } 15562 } 15563 CXXRecord->completeDefinition(&FinalOverriders); 15564 Completed = true; 15565 } 15566 } 15567 } 15568 } 15569 15570 if (!Completed) 15571 Record->completeDefinition(); 15572 15573 // We may have deferred checking for a deleted destructor. Check now. 15574 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 15575 auto *Dtor = CXXRecord->getDestructor(); 15576 if (Dtor && Dtor->isImplicit() && 15577 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 15578 CXXRecord->setImplicitDestructorIsDeleted(); 15579 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 15580 } 15581 } 15582 15583 if (Record->hasAttrs()) { 15584 CheckAlignasUnderalignment(Record); 15585 15586 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 15587 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 15588 IA->getRange(), IA->getBestCase(), 15589 IA->getSemanticSpelling()); 15590 } 15591 15592 // Check if the structure/union declaration is a type that can have zero 15593 // size in C. For C this is a language extension, for C++ it may cause 15594 // compatibility problems. 15595 bool CheckForZeroSize; 15596 if (!getLangOpts().CPlusPlus) { 15597 CheckForZeroSize = true; 15598 } else { 15599 // For C++ filter out types that cannot be referenced in C code. 15600 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 15601 CheckForZeroSize = 15602 CXXRecord->getLexicalDeclContext()->isExternCContext() && 15603 !CXXRecord->isDependentType() && 15604 CXXRecord->isCLike(); 15605 } 15606 if (CheckForZeroSize) { 15607 bool ZeroSize = true; 15608 bool IsEmpty = true; 15609 unsigned NonBitFields = 0; 15610 for (RecordDecl::field_iterator I = Record->field_begin(), 15611 E = Record->field_end(); 15612 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 15613 IsEmpty = false; 15614 if (I->isUnnamedBitfield()) { 15615 if (!I->isZeroLengthBitField(Context)) 15616 ZeroSize = false; 15617 } else { 15618 ++NonBitFields; 15619 QualType FieldType = I->getType(); 15620 if (FieldType->isIncompleteType() || 15621 !Context.getTypeSizeInChars(FieldType).isZero()) 15622 ZeroSize = false; 15623 } 15624 } 15625 15626 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 15627 // allowed in C++, but warn if its declaration is inside 15628 // extern "C" block. 15629 if (ZeroSize) { 15630 Diag(RecLoc, getLangOpts().CPlusPlus ? 15631 diag::warn_zero_size_struct_union_in_extern_c : 15632 diag::warn_zero_size_struct_union_compat) 15633 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 15634 } 15635 15636 // Structs without named members are extension in C (C99 6.7.2.1p7), 15637 // but are accepted by GCC. 15638 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 15639 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 15640 diag::ext_no_named_members_in_struct_union) 15641 << Record->isUnion(); 15642 } 15643 } 15644 } else { 15645 ObjCIvarDecl **ClsFields = 15646 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 15647 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 15648 ID->setEndOfDefinitionLoc(RBrac); 15649 // Add ivar's to class's DeclContext. 15650 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15651 ClsFields[i]->setLexicalDeclContext(ID); 15652 ID->addDecl(ClsFields[i]); 15653 } 15654 // Must enforce the rule that ivars in the base classes may not be 15655 // duplicates. 15656 if (ID->getSuperClass()) 15657 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 15658 } else if (ObjCImplementationDecl *IMPDecl = 15659 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 15660 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 15661 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 15662 // Ivar declared in @implementation never belongs to the implementation. 15663 // Only it is in implementation's lexical context. 15664 ClsFields[I]->setLexicalDeclContext(IMPDecl); 15665 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 15666 IMPDecl->setIvarLBraceLoc(LBrac); 15667 IMPDecl->setIvarRBraceLoc(RBrac); 15668 } else if (ObjCCategoryDecl *CDecl = 15669 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 15670 // case of ivars in class extension; all other cases have been 15671 // reported as errors elsewhere. 15672 // FIXME. Class extension does not have a LocEnd field. 15673 // CDecl->setLocEnd(RBrac); 15674 // Add ivar's to class extension's DeclContext. 15675 // Diagnose redeclaration of private ivars. 15676 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 15677 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 15678 if (IDecl) { 15679 if (const ObjCIvarDecl *ClsIvar = 15680 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 15681 Diag(ClsFields[i]->getLocation(), 15682 diag::err_duplicate_ivar_declaration); 15683 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 15684 continue; 15685 } 15686 for (const auto *Ext : IDecl->known_extensions()) { 15687 if (const ObjCIvarDecl *ClsExtIvar 15688 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 15689 Diag(ClsFields[i]->getLocation(), 15690 diag::err_duplicate_ivar_declaration); 15691 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 15692 continue; 15693 } 15694 } 15695 } 15696 ClsFields[i]->setLexicalDeclContext(CDecl); 15697 CDecl->addDecl(ClsFields[i]); 15698 } 15699 CDecl->setIvarLBraceLoc(LBrac); 15700 CDecl->setIvarRBraceLoc(RBrac); 15701 } 15702 } 15703 15704 if (Attr) 15705 ProcessDeclAttributeList(S, Record, Attr); 15706 } 15707 15708 /// \brief Determine whether the given integral value is representable within 15709 /// the given type T. 15710 static bool isRepresentableIntegerValue(ASTContext &Context, 15711 llvm::APSInt &Value, 15712 QualType T) { 15713 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 15714 "Integral type required!"); 15715 unsigned BitWidth = Context.getIntWidth(T); 15716 15717 if (Value.isUnsigned() || Value.isNonNegative()) { 15718 if (T->isSignedIntegerOrEnumerationType()) 15719 --BitWidth; 15720 return Value.getActiveBits() <= BitWidth; 15721 } 15722 return Value.getMinSignedBits() <= BitWidth; 15723 } 15724 15725 // \brief Given an integral type, return the next larger integral type 15726 // (or a NULL type of no such type exists). 15727 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 15728 // FIXME: Int128/UInt128 support, which also needs to be introduced into 15729 // enum checking below. 15730 assert((T->isIntegralType(Context) || 15731 T->isEnumeralType()) && "Integral type required!"); 15732 const unsigned NumTypes = 4; 15733 QualType SignedIntegralTypes[NumTypes] = { 15734 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 15735 }; 15736 QualType UnsignedIntegralTypes[NumTypes] = { 15737 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 15738 Context.UnsignedLongLongTy 15739 }; 15740 15741 unsigned BitWidth = Context.getTypeSize(T); 15742 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 15743 : UnsignedIntegralTypes; 15744 for (unsigned I = 0; I != NumTypes; ++I) 15745 if (Context.getTypeSize(Types[I]) > BitWidth) 15746 return Types[I]; 15747 15748 return QualType(); 15749 } 15750 15751 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 15752 EnumConstantDecl *LastEnumConst, 15753 SourceLocation IdLoc, 15754 IdentifierInfo *Id, 15755 Expr *Val) { 15756 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 15757 llvm::APSInt EnumVal(IntWidth); 15758 QualType EltTy; 15759 15760 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 15761 Val = nullptr; 15762 15763 if (Val) 15764 Val = DefaultLvalueConversion(Val).get(); 15765 15766 if (Val) { 15767 if (Enum->isDependentType() || Val->isTypeDependent()) 15768 EltTy = Context.DependentTy; 15769 else { 15770 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 15771 !getLangOpts().MSVCCompat) { 15772 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 15773 // constant-expression in the enumerator-definition shall be a converted 15774 // constant expression of the underlying type. 15775 EltTy = Enum->getIntegerType(); 15776 ExprResult Converted = 15777 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 15778 CCEK_Enumerator); 15779 if (Converted.isInvalid()) 15780 Val = nullptr; 15781 else 15782 Val = Converted.get(); 15783 } else if (!Val->isValueDependent() && 15784 !(Val = VerifyIntegerConstantExpression(Val, 15785 &EnumVal).get())) { 15786 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 15787 } else { 15788 if (Enum->isComplete()) { 15789 EltTy = Enum->getIntegerType(); 15790 15791 // In Obj-C and Microsoft mode, require the enumeration value to be 15792 // representable in the underlying type of the enumeration. In C++11, 15793 // we perform a non-narrowing conversion as part of converted constant 15794 // expression checking. 15795 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15796 if (getLangOpts().MSVCCompat) { 15797 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 15798 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 15799 } else 15800 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 15801 } else 15802 Val = ImpCastExprToType(Val, EltTy, 15803 EltTy->isBooleanType() ? 15804 CK_IntegralToBoolean : CK_IntegralCast) 15805 .get(); 15806 } else if (getLangOpts().CPlusPlus) { 15807 // C++11 [dcl.enum]p5: 15808 // If the underlying type is not fixed, the type of each enumerator 15809 // is the type of its initializing value: 15810 // - If an initializer is specified for an enumerator, the 15811 // initializing value has the same type as the expression. 15812 EltTy = Val->getType(); 15813 } else { 15814 // C99 6.7.2.2p2: 15815 // The expression that defines the value of an enumeration constant 15816 // shall be an integer constant expression that has a value 15817 // representable as an int. 15818 15819 // Complain if the value is not representable in an int. 15820 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 15821 Diag(IdLoc, diag::ext_enum_value_not_int) 15822 << EnumVal.toString(10) << Val->getSourceRange() 15823 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 15824 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 15825 // Force the type of the expression to 'int'. 15826 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 15827 } 15828 EltTy = Val->getType(); 15829 } 15830 } 15831 } 15832 } 15833 15834 if (!Val) { 15835 if (Enum->isDependentType()) 15836 EltTy = Context.DependentTy; 15837 else if (!LastEnumConst) { 15838 // C++0x [dcl.enum]p5: 15839 // If the underlying type is not fixed, the type of each enumerator 15840 // is the type of its initializing value: 15841 // - If no initializer is specified for the first enumerator, the 15842 // initializing value has an unspecified integral type. 15843 // 15844 // GCC uses 'int' for its unspecified integral type, as does 15845 // C99 6.7.2.2p3. 15846 if (Enum->isFixed()) { 15847 EltTy = Enum->getIntegerType(); 15848 } 15849 else { 15850 EltTy = Context.IntTy; 15851 } 15852 } else { 15853 // Assign the last value + 1. 15854 EnumVal = LastEnumConst->getInitVal(); 15855 ++EnumVal; 15856 EltTy = LastEnumConst->getType(); 15857 15858 // Check for overflow on increment. 15859 if (EnumVal < LastEnumConst->getInitVal()) { 15860 // C++0x [dcl.enum]p5: 15861 // If the underlying type is not fixed, the type of each enumerator 15862 // is the type of its initializing value: 15863 // 15864 // - Otherwise the type of the initializing value is the same as 15865 // the type of the initializing value of the preceding enumerator 15866 // unless the incremented value is not representable in that type, 15867 // in which case the type is an unspecified integral type 15868 // sufficient to contain the incremented value. If no such type 15869 // exists, the program is ill-formed. 15870 QualType T = getNextLargerIntegralType(Context, EltTy); 15871 if (T.isNull() || Enum->isFixed()) { 15872 // There is no integral type larger enough to represent this 15873 // value. Complain, then allow the value to wrap around. 15874 EnumVal = LastEnumConst->getInitVal(); 15875 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 15876 ++EnumVal; 15877 if (Enum->isFixed()) 15878 // When the underlying type is fixed, this is ill-formed. 15879 Diag(IdLoc, diag::err_enumerator_wrapped) 15880 << EnumVal.toString(10) 15881 << EltTy; 15882 else 15883 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 15884 << EnumVal.toString(10); 15885 } else { 15886 EltTy = T; 15887 } 15888 15889 // Retrieve the last enumerator's value, extent that type to the 15890 // type that is supposed to be large enough to represent the incremented 15891 // value, then increment. 15892 EnumVal = LastEnumConst->getInitVal(); 15893 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15894 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 15895 ++EnumVal; 15896 15897 // If we're not in C++, diagnose the overflow of enumerator values, 15898 // which in C99 means that the enumerator value is not representable in 15899 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 15900 // permits enumerator values that are representable in some larger 15901 // integral type. 15902 if (!getLangOpts().CPlusPlus && !T.isNull()) 15903 Diag(IdLoc, diag::warn_enum_value_overflow); 15904 } else if (!getLangOpts().CPlusPlus && 15905 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 15906 // Enforce C99 6.7.2.2p2 even when we compute the next value. 15907 Diag(IdLoc, diag::ext_enum_value_not_int) 15908 << EnumVal.toString(10) << 1; 15909 } 15910 } 15911 } 15912 15913 if (!EltTy->isDependentType()) { 15914 // Make the enumerator value match the signedness and size of the 15915 // enumerator's type. 15916 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 15917 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 15918 } 15919 15920 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 15921 Val, EnumVal); 15922 } 15923 15924 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 15925 SourceLocation IILoc) { 15926 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 15927 !getLangOpts().CPlusPlus) 15928 return SkipBodyInfo(); 15929 15930 // We have an anonymous enum definition. Look up the first enumerator to 15931 // determine if we should merge the definition with an existing one and 15932 // skip the body. 15933 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 15934 forRedeclarationInCurContext()); 15935 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 15936 if (!PrevECD) 15937 return SkipBodyInfo(); 15938 15939 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 15940 NamedDecl *Hidden; 15941 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 15942 SkipBodyInfo Skip; 15943 Skip.Previous = Hidden; 15944 return Skip; 15945 } 15946 15947 return SkipBodyInfo(); 15948 } 15949 15950 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 15951 SourceLocation IdLoc, IdentifierInfo *Id, 15952 AttributeList *Attr, 15953 SourceLocation EqualLoc, Expr *Val) { 15954 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 15955 EnumConstantDecl *LastEnumConst = 15956 cast_or_null<EnumConstantDecl>(lastEnumConst); 15957 15958 // The scope passed in may not be a decl scope. Zip up the scope tree until 15959 // we find one that is. 15960 S = getNonFieldDeclScope(S); 15961 15962 // Verify that there isn't already something declared with this name in this 15963 // scope. 15964 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 15965 ForVisibleRedeclaration); 15966 if (PrevDecl && PrevDecl->isTemplateParameter()) { 15967 // Maybe we will complain about the shadowed template parameter. 15968 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 15969 // Just pretend that we didn't see the previous declaration. 15970 PrevDecl = nullptr; 15971 } 15972 15973 // C++ [class.mem]p15: 15974 // If T is the name of a class, then each of the following shall have a name 15975 // different from T: 15976 // - every enumerator of every member of class T that is an unscoped 15977 // enumerated type 15978 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 15979 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 15980 DeclarationNameInfo(Id, IdLoc)); 15981 15982 EnumConstantDecl *New = 15983 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 15984 if (!New) 15985 return nullptr; 15986 15987 if (PrevDecl) { 15988 // When in C++, we may get a TagDecl with the same name; in this case the 15989 // enum constant will 'hide' the tag. 15990 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 15991 "Received TagDecl when not in C++!"); 15992 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 15993 if (isa<EnumConstantDecl>(PrevDecl)) 15994 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 15995 else 15996 Diag(IdLoc, diag::err_redefinition) << Id; 15997 notePreviousDefinition(PrevDecl, IdLoc); 15998 return nullptr; 15999 } 16000 } 16001 16002 // Process attributes. 16003 if (Attr) ProcessDeclAttributeList(S, New, Attr); 16004 AddPragmaAttributes(S, New); 16005 16006 // Register this decl in the current scope stack. 16007 New->setAccess(TheEnumDecl->getAccess()); 16008 PushOnScopeChains(New, S); 16009 16010 ActOnDocumentableDecl(New); 16011 16012 return New; 16013 } 16014 16015 // Returns true when the enum initial expression does not trigger the 16016 // duplicate enum warning. A few common cases are exempted as follows: 16017 // Element2 = Element1 16018 // Element2 = Element1 + 1 16019 // Element2 = Element1 - 1 16020 // Where Element2 and Element1 are from the same enum. 16021 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 16022 Expr *InitExpr = ECD->getInitExpr(); 16023 if (!InitExpr) 16024 return true; 16025 InitExpr = InitExpr->IgnoreImpCasts(); 16026 16027 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 16028 if (!BO->isAdditiveOp()) 16029 return true; 16030 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 16031 if (!IL) 16032 return true; 16033 if (IL->getValue() != 1) 16034 return true; 16035 16036 InitExpr = BO->getLHS(); 16037 } 16038 16039 // This checks if the elements are from the same enum. 16040 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 16041 if (!DRE) 16042 return true; 16043 16044 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 16045 if (!EnumConstant) 16046 return true; 16047 16048 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 16049 Enum) 16050 return true; 16051 16052 return false; 16053 } 16054 16055 // Emits a warning when an element is implicitly set a value that 16056 // a previous element has already been set to. 16057 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 16058 EnumDecl *Enum, QualType EnumType) { 16059 // Avoid anonymous enums 16060 if (!Enum->getIdentifier()) 16061 return; 16062 16063 // Only check for small enums. 16064 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 16065 return; 16066 16067 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 16068 return; 16069 16070 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 16071 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 16072 16073 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 16074 typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap; 16075 16076 // Use int64_t as a key to avoid needing special handling for DenseMap keys. 16077 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 16078 llvm::APSInt Val = D->getInitVal(); 16079 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 16080 }; 16081 16082 DuplicatesVector DupVector; 16083 ValueToVectorMap EnumMap; 16084 16085 // Populate the EnumMap with all values represented by enum constants without 16086 // an initializer. 16087 for (auto *Element : Elements) { 16088 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 16089 16090 // Null EnumConstantDecl means a previous diagnostic has been emitted for 16091 // this constant. Skip this enum since it may be ill-formed. 16092 if (!ECD) { 16093 return; 16094 } 16095 16096 // Constants with initalizers are handled in the next loop. 16097 if (ECD->getInitExpr()) 16098 continue; 16099 16100 // Duplicate values are handled in the next loop. 16101 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 16102 } 16103 16104 if (EnumMap.size() == 0) 16105 return; 16106 16107 // Create vectors for any values that has duplicates. 16108 for (auto *Element : Elements) { 16109 // The last loop returned if any constant was null. 16110 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 16111 if (!ValidDuplicateEnum(ECD, Enum)) 16112 continue; 16113 16114 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 16115 if (Iter == EnumMap.end()) 16116 continue; 16117 16118 DeclOrVector& Entry = Iter->second; 16119 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 16120 // Ensure constants are different. 16121 if (D == ECD) 16122 continue; 16123 16124 // Create new vector and push values onto it. 16125 auto Vec = llvm::make_unique<ECDVector>(); 16126 Vec->push_back(D); 16127 Vec->push_back(ECD); 16128 16129 // Update entry to point to the duplicates vector. 16130 Entry = Vec.get(); 16131 16132 // Store the vector somewhere we can consult later for quick emission of 16133 // diagnostics. 16134 DupVector.emplace_back(std::move(Vec)); 16135 continue; 16136 } 16137 16138 ECDVector *Vec = Entry.get<ECDVector*>(); 16139 // Make sure constants are not added more than once. 16140 if (*Vec->begin() == ECD) 16141 continue; 16142 16143 Vec->push_back(ECD); 16144 } 16145 16146 // Emit diagnostics. 16147 for (const auto &Vec : DupVector) { 16148 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 16149 16150 // Emit warning for one enum constant. 16151 auto *FirstECD = Vec->front(); 16152 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 16153 << FirstECD << FirstECD->getInitVal().toString(10) 16154 << FirstECD->getSourceRange(); 16155 16156 // Emit one note for each of the remaining enum constants with 16157 // the same value. 16158 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 16159 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 16160 << ECD << ECD->getInitVal().toString(10) 16161 << ECD->getSourceRange(); 16162 } 16163 } 16164 16165 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 16166 bool AllowMask) const { 16167 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 16168 assert(ED->isCompleteDefinition() && "expected enum definition"); 16169 16170 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 16171 llvm::APInt &FlagBits = R.first->second; 16172 16173 if (R.second) { 16174 for (auto *E : ED->enumerators()) { 16175 const auto &EVal = E->getInitVal(); 16176 // Only single-bit enumerators introduce new flag values. 16177 if (EVal.isPowerOf2()) 16178 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 16179 } 16180 } 16181 16182 // A value is in a flag enum if either its bits are a subset of the enum's 16183 // flag bits (the first condition) or we are allowing masks and the same is 16184 // true of its complement (the second condition). When masks are allowed, we 16185 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 16186 // 16187 // While it's true that any value could be used as a mask, the assumption is 16188 // that a mask will have all of the insignificant bits set. Anything else is 16189 // likely a logic error. 16190 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 16191 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 16192 } 16193 16194 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 16195 Decl *EnumDeclX, 16196 ArrayRef<Decl *> Elements, 16197 Scope *S, AttributeList *Attr) { 16198 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 16199 QualType EnumType = Context.getTypeDeclType(Enum); 16200 16201 if (Attr) 16202 ProcessDeclAttributeList(S, Enum, Attr); 16203 16204 if (Enum->isDependentType()) { 16205 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16206 EnumConstantDecl *ECD = 16207 cast_or_null<EnumConstantDecl>(Elements[i]); 16208 if (!ECD) continue; 16209 16210 ECD->setType(EnumType); 16211 } 16212 16213 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 16214 return; 16215 } 16216 16217 // TODO: If the result value doesn't fit in an int, it must be a long or long 16218 // long value. ISO C does not support this, but GCC does as an extension, 16219 // emit a warning. 16220 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 16221 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 16222 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 16223 16224 // Verify that all the values are okay, compute the size of the values, and 16225 // reverse the list. 16226 unsigned NumNegativeBits = 0; 16227 unsigned NumPositiveBits = 0; 16228 16229 // Keep track of whether all elements have type int. 16230 bool AllElementsInt = true; 16231 16232 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 16233 EnumConstantDecl *ECD = 16234 cast_or_null<EnumConstantDecl>(Elements[i]); 16235 if (!ECD) continue; // Already issued a diagnostic. 16236 16237 const llvm::APSInt &InitVal = ECD->getInitVal(); 16238 16239 // Keep track of the size of positive and negative values. 16240 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 16241 NumPositiveBits = std::max(NumPositiveBits, 16242 (unsigned)InitVal.getActiveBits()); 16243 else 16244 NumNegativeBits = std::max(NumNegativeBits, 16245 (unsigned)InitVal.getMinSignedBits()); 16246 16247 // Keep track of whether every enum element has type int (very commmon). 16248 if (AllElementsInt) 16249 AllElementsInt = ECD->getType() == Context.IntTy; 16250 } 16251 16252 // Figure out the type that should be used for this enum. 16253 QualType BestType; 16254 unsigned BestWidth; 16255 16256 // C++0x N3000 [conv.prom]p3: 16257 // An rvalue of an unscoped enumeration type whose underlying 16258 // type is not fixed can be converted to an rvalue of the first 16259 // of the following types that can represent all the values of 16260 // the enumeration: int, unsigned int, long int, unsigned long 16261 // int, long long int, or unsigned long long int. 16262 // C99 6.4.4.3p2: 16263 // An identifier declared as an enumeration constant has type int. 16264 // The C99 rule is modified by a gcc extension 16265 QualType BestPromotionType; 16266 16267 bool Packed = Enum->hasAttr<PackedAttr>(); 16268 // -fshort-enums is the equivalent to specifying the packed attribute on all 16269 // enum definitions. 16270 if (LangOpts.ShortEnums) 16271 Packed = true; 16272 16273 // If the enum already has a type because it is fixed or dictated by the 16274 // target, promote that type instead of analyzing the enumerators. 16275 if (Enum->isComplete()) { 16276 BestType = Enum->getIntegerType(); 16277 if (BestType->isPromotableIntegerType()) 16278 BestPromotionType = Context.getPromotedIntegerType(BestType); 16279 else 16280 BestPromotionType = BestType; 16281 16282 BestWidth = Context.getIntWidth(BestType); 16283 } 16284 else if (NumNegativeBits) { 16285 // If there is a negative value, figure out the smallest integer type (of 16286 // int/long/longlong) that fits. 16287 // If it's packed, check also if it fits a char or a short. 16288 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 16289 BestType = Context.SignedCharTy; 16290 BestWidth = CharWidth; 16291 } else if (Packed && NumNegativeBits <= ShortWidth && 16292 NumPositiveBits < ShortWidth) { 16293 BestType = Context.ShortTy; 16294 BestWidth = ShortWidth; 16295 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 16296 BestType = Context.IntTy; 16297 BestWidth = IntWidth; 16298 } else { 16299 BestWidth = Context.getTargetInfo().getLongWidth(); 16300 16301 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 16302 BestType = Context.LongTy; 16303 } else { 16304 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16305 16306 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 16307 Diag(Enum->getLocation(), diag::ext_enum_too_large); 16308 BestType = Context.LongLongTy; 16309 } 16310 } 16311 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 16312 } else { 16313 // If there is no negative value, figure out the smallest type that fits 16314 // all of the enumerator values. 16315 // If it's packed, check also if it fits a char or a short. 16316 if (Packed && NumPositiveBits <= CharWidth) { 16317 BestType = Context.UnsignedCharTy; 16318 BestPromotionType = Context.IntTy; 16319 BestWidth = CharWidth; 16320 } else if (Packed && NumPositiveBits <= ShortWidth) { 16321 BestType = Context.UnsignedShortTy; 16322 BestPromotionType = Context.IntTy; 16323 BestWidth = ShortWidth; 16324 } else if (NumPositiveBits <= IntWidth) { 16325 BestType = Context.UnsignedIntTy; 16326 BestWidth = IntWidth; 16327 BestPromotionType 16328 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16329 ? Context.UnsignedIntTy : Context.IntTy; 16330 } else if (NumPositiveBits <= 16331 (BestWidth = Context.getTargetInfo().getLongWidth())) { 16332 BestType = Context.UnsignedLongTy; 16333 BestPromotionType 16334 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16335 ? Context.UnsignedLongTy : Context.LongTy; 16336 } else { 16337 BestWidth = Context.getTargetInfo().getLongLongWidth(); 16338 assert(NumPositiveBits <= BestWidth && 16339 "How could an initializer get larger than ULL?"); 16340 BestType = Context.UnsignedLongLongTy; 16341 BestPromotionType 16342 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 16343 ? Context.UnsignedLongLongTy : Context.LongLongTy; 16344 } 16345 } 16346 16347 // Loop over all of the enumerator constants, changing their types to match 16348 // the type of the enum if needed. 16349 for (auto *D : Elements) { 16350 auto *ECD = cast_or_null<EnumConstantDecl>(D); 16351 if (!ECD) continue; // Already issued a diagnostic. 16352 16353 // Standard C says the enumerators have int type, but we allow, as an 16354 // extension, the enumerators to be larger than int size. If each 16355 // enumerator value fits in an int, type it as an int, otherwise type it the 16356 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 16357 // that X has type 'int', not 'unsigned'. 16358 16359 // Determine whether the value fits into an int. 16360 llvm::APSInt InitVal = ECD->getInitVal(); 16361 16362 // If it fits into an integer type, force it. Otherwise force it to match 16363 // the enum decl type. 16364 QualType NewTy; 16365 unsigned NewWidth; 16366 bool NewSign; 16367 if (!getLangOpts().CPlusPlus && 16368 !Enum->isFixed() && 16369 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 16370 NewTy = Context.IntTy; 16371 NewWidth = IntWidth; 16372 NewSign = true; 16373 } else if (ECD->getType() == BestType) { 16374 // Already the right type! 16375 if (getLangOpts().CPlusPlus) 16376 // C++ [dcl.enum]p4: Following the closing brace of an 16377 // enum-specifier, each enumerator has the type of its 16378 // enumeration. 16379 ECD->setType(EnumType); 16380 continue; 16381 } else { 16382 NewTy = BestType; 16383 NewWidth = BestWidth; 16384 NewSign = BestType->isSignedIntegerOrEnumerationType(); 16385 } 16386 16387 // Adjust the APSInt value. 16388 InitVal = InitVal.extOrTrunc(NewWidth); 16389 InitVal.setIsSigned(NewSign); 16390 ECD->setInitVal(InitVal); 16391 16392 // Adjust the Expr initializer and type. 16393 if (ECD->getInitExpr() && 16394 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 16395 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 16396 CK_IntegralCast, 16397 ECD->getInitExpr(), 16398 /*base paths*/ nullptr, 16399 VK_RValue)); 16400 if (getLangOpts().CPlusPlus) 16401 // C++ [dcl.enum]p4: Following the closing brace of an 16402 // enum-specifier, each enumerator has the type of its 16403 // enumeration. 16404 ECD->setType(EnumType); 16405 else 16406 ECD->setType(NewTy); 16407 } 16408 16409 Enum->completeDefinition(BestType, BestPromotionType, 16410 NumPositiveBits, NumNegativeBits); 16411 16412 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 16413 16414 if (Enum->isClosedFlag()) { 16415 for (Decl *D : Elements) { 16416 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 16417 if (!ECD) continue; // Already issued a diagnostic. 16418 16419 llvm::APSInt InitVal = ECD->getInitVal(); 16420 if (InitVal != 0 && !InitVal.isPowerOf2() && 16421 !IsValueInFlagEnum(Enum, InitVal, true)) 16422 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 16423 << ECD << Enum; 16424 } 16425 } 16426 16427 // Now that the enum type is defined, ensure it's not been underaligned. 16428 if (Enum->hasAttrs()) 16429 CheckAlignasUnderalignment(Enum); 16430 } 16431 16432 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 16433 SourceLocation StartLoc, 16434 SourceLocation EndLoc) { 16435 StringLiteral *AsmString = cast<StringLiteral>(expr); 16436 16437 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 16438 AsmString, StartLoc, 16439 EndLoc); 16440 CurContext->addDecl(New); 16441 return New; 16442 } 16443 16444 static void checkModuleImportContext(Sema &S, Module *M, 16445 SourceLocation ImportLoc, DeclContext *DC, 16446 bool FromInclude = false) { 16447 SourceLocation ExternCLoc; 16448 16449 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 16450 switch (LSD->getLanguage()) { 16451 case LinkageSpecDecl::lang_c: 16452 if (ExternCLoc.isInvalid()) 16453 ExternCLoc = LSD->getLocStart(); 16454 break; 16455 case LinkageSpecDecl::lang_cxx: 16456 break; 16457 } 16458 DC = LSD->getParent(); 16459 } 16460 16461 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 16462 DC = DC->getParent(); 16463 16464 if (!isa<TranslationUnitDecl>(DC)) { 16465 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 16466 ? diag::ext_module_import_not_at_top_level_noop 16467 : diag::err_module_import_not_at_top_level_fatal) 16468 << M->getFullModuleName() << DC; 16469 S.Diag(cast<Decl>(DC)->getLocStart(), 16470 diag::note_module_import_not_at_top_level) << DC; 16471 } else if (!M->IsExternC && ExternCLoc.isValid()) { 16472 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 16473 << M->getFullModuleName(); 16474 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 16475 } 16476 } 16477 16478 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc, 16479 SourceLocation ModuleLoc, 16480 ModuleDeclKind MDK, 16481 ModuleIdPath Path) { 16482 assert(getLangOpts().ModulesTS && 16483 "should only have module decl in modules TS"); 16484 16485 // A module implementation unit requires that we are not compiling a module 16486 // of any kind. A module interface unit requires that we are not compiling a 16487 // module map. 16488 switch (getLangOpts().getCompilingModule()) { 16489 case LangOptions::CMK_None: 16490 // It's OK to compile a module interface as a normal translation unit. 16491 break; 16492 16493 case LangOptions::CMK_ModuleInterface: 16494 if (MDK != ModuleDeclKind::Implementation) 16495 break; 16496 16497 // We were asked to compile a module interface unit but this is a module 16498 // implementation unit. That indicates the 'export' is missing. 16499 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 16500 << FixItHint::CreateInsertion(ModuleLoc, "export "); 16501 MDK = ModuleDeclKind::Interface; 16502 break; 16503 16504 case LangOptions::CMK_ModuleMap: 16505 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 16506 return nullptr; 16507 } 16508 16509 assert(ModuleScopes.size() == 1 && "expected to be at global module scope"); 16510 16511 // FIXME: Most of this work should be done by the preprocessor rather than 16512 // here, in order to support macro import. 16513 16514 // Only one module-declaration is permitted per source file. 16515 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 16516 Diag(ModuleLoc, diag::err_module_redeclaration); 16517 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 16518 diag::note_prev_module_declaration); 16519 return nullptr; 16520 } 16521 16522 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 16523 // modules, the dots here are just another character that can appear in a 16524 // module name. 16525 std::string ModuleName; 16526 for (auto &Piece : Path) { 16527 if (!ModuleName.empty()) 16528 ModuleName += "."; 16529 ModuleName += Piece.first->getName(); 16530 } 16531 16532 // If a module name was explicitly specified on the command line, it must be 16533 // correct. 16534 if (!getLangOpts().CurrentModule.empty() && 16535 getLangOpts().CurrentModule != ModuleName) { 16536 Diag(Path.front().second, diag::err_current_module_name_mismatch) 16537 << SourceRange(Path.front().second, Path.back().second) 16538 << getLangOpts().CurrentModule; 16539 return nullptr; 16540 } 16541 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 16542 16543 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 16544 Module *Mod; 16545 16546 switch (MDK) { 16547 case ModuleDeclKind::Interface: { 16548 // We can't have parsed or imported a definition of this module or parsed a 16549 // module map defining it already. 16550 if (auto *M = Map.findModule(ModuleName)) { 16551 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 16552 if (M->DefinitionLoc.isValid()) 16553 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 16554 else if (const auto *FE = M->getASTFile()) 16555 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 16556 << FE->getName(); 16557 Mod = M; 16558 break; 16559 } 16560 16561 // Create a Module for the module that we're defining. 16562 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16563 ModuleScopes.front().Module); 16564 assert(Mod && "module creation should not fail"); 16565 break; 16566 } 16567 16568 case ModuleDeclKind::Partition: 16569 // FIXME: Check we are in a submodule of the named module. 16570 return nullptr; 16571 16572 case ModuleDeclKind::Implementation: 16573 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 16574 PP.getIdentifierInfo(ModuleName), Path[0].second); 16575 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible, 16576 /*IsIncludeDirective=*/false); 16577 if (!Mod) { 16578 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 16579 // Create an empty module interface unit for error recovery. 16580 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 16581 ModuleScopes.front().Module); 16582 } 16583 break; 16584 } 16585 16586 // Switch from the global module to the named module. 16587 ModuleScopes.back().Module = Mod; 16588 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 16589 VisibleModules.setVisible(Mod, ModuleLoc); 16590 16591 // From now on, we have an owning module for all declarations we see. 16592 // However, those declarations are module-private unless explicitly 16593 // exported. 16594 auto *TU = Context.getTranslationUnitDecl(); 16595 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 16596 TU->setLocalOwningModule(Mod); 16597 16598 // FIXME: Create a ModuleDecl. 16599 return nullptr; 16600 } 16601 16602 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 16603 SourceLocation ImportLoc, 16604 ModuleIdPath Path) { 16605 Module *Mod = 16606 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 16607 /*IsIncludeDirective=*/false); 16608 if (!Mod) 16609 return true; 16610 16611 VisibleModules.setVisible(Mod, ImportLoc); 16612 16613 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 16614 16615 // FIXME: we should support importing a submodule within a different submodule 16616 // of the same top-level module. Until we do, make it an error rather than 16617 // silently ignoring the import. 16618 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 16619 // warn on a redundant import of the current module? 16620 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 16621 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) 16622 Diag(ImportLoc, getLangOpts().isCompilingModule() 16623 ? diag::err_module_self_import 16624 : diag::err_module_import_in_implementation) 16625 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 16626 16627 SmallVector<SourceLocation, 2> IdentifierLocs; 16628 Module *ModCheck = Mod; 16629 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 16630 // If we've run out of module parents, just drop the remaining identifiers. 16631 // We need the length to be consistent. 16632 if (!ModCheck) 16633 break; 16634 ModCheck = ModCheck->Parent; 16635 16636 IdentifierLocs.push_back(Path[I].second); 16637 } 16638 16639 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 16640 Mod, IdentifierLocs); 16641 if (!ModuleScopes.empty()) 16642 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 16643 CurContext->addDecl(Import); 16644 16645 // Re-export the module if needed. 16646 if (Import->isExported() && 16647 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) 16648 getCurrentModule()->Exports.emplace_back(Mod, false); 16649 16650 return Import; 16651 } 16652 16653 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16654 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16655 BuildModuleInclude(DirectiveLoc, Mod); 16656 } 16657 16658 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 16659 // Determine whether we're in the #include buffer for a module. The #includes 16660 // in that buffer do not qualify as module imports; they're just an 16661 // implementation detail of us building the module. 16662 // 16663 // FIXME: Should we even get ActOnModuleInclude calls for those? 16664 bool IsInModuleIncludes = 16665 TUKind == TU_Module && 16666 getSourceManager().isWrittenInMainFile(DirectiveLoc); 16667 16668 bool ShouldAddImport = !IsInModuleIncludes; 16669 16670 // If this module import was due to an inclusion directive, create an 16671 // implicit import declaration to capture it in the AST. 16672 if (ShouldAddImport) { 16673 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16674 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16675 DirectiveLoc, Mod, 16676 DirectiveLoc); 16677 if (!ModuleScopes.empty()) 16678 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 16679 TU->addDecl(ImportD); 16680 Consumer.HandleImplicitImportDecl(ImportD); 16681 } 16682 16683 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 16684 VisibleModules.setVisible(Mod, DirectiveLoc); 16685 } 16686 16687 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 16688 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 16689 16690 ModuleScopes.push_back({}); 16691 ModuleScopes.back().Module = Mod; 16692 if (getLangOpts().ModulesLocalVisibility) 16693 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 16694 16695 VisibleModules.setVisible(Mod, DirectiveLoc); 16696 16697 // The enclosing context is now part of this module. 16698 // FIXME: Consider creating a child DeclContext to hold the entities 16699 // lexically within the module. 16700 if (getLangOpts().trackLocalOwningModule()) { 16701 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16702 cast<Decl>(DC)->setModuleOwnershipKind( 16703 getLangOpts().ModulesLocalVisibility 16704 ? Decl::ModuleOwnershipKind::VisibleWhenImported 16705 : Decl::ModuleOwnershipKind::Visible); 16706 cast<Decl>(DC)->setLocalOwningModule(Mod); 16707 } 16708 } 16709 } 16710 16711 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 16712 if (getLangOpts().ModulesLocalVisibility) { 16713 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 16714 // Leaving a module hides namespace names, so our visible namespace cache 16715 // is now out of date. 16716 VisibleNamespaceCache.clear(); 16717 } 16718 16719 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 16720 "left the wrong module scope"); 16721 ModuleScopes.pop_back(); 16722 16723 // We got to the end of processing a local module. Create an 16724 // ImportDecl as we would for an imported module. 16725 FileID File = getSourceManager().getFileID(EomLoc); 16726 SourceLocation DirectiveLoc; 16727 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 16728 // We reached the end of a #included module header. Use the #include loc. 16729 assert(File != getSourceManager().getMainFileID() && 16730 "end of submodule in main source file"); 16731 DirectiveLoc = getSourceManager().getIncludeLoc(File); 16732 } else { 16733 // We reached an EOM pragma. Use the pragma location. 16734 DirectiveLoc = EomLoc; 16735 } 16736 BuildModuleInclude(DirectiveLoc, Mod); 16737 16738 // Any further declarations are in whatever module we returned to. 16739 if (getLangOpts().trackLocalOwningModule()) { 16740 // The parser guarantees that this is the same context that we entered 16741 // the module within. 16742 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 16743 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 16744 if (!getCurrentModule()) 16745 cast<Decl>(DC)->setModuleOwnershipKind( 16746 Decl::ModuleOwnershipKind::Unowned); 16747 } 16748 } 16749 } 16750 16751 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 16752 Module *Mod) { 16753 // Bail if we're not allowed to implicitly import a module here. 16754 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 16755 VisibleModules.isVisible(Mod)) 16756 return; 16757 16758 // Create the implicit import declaration. 16759 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 16760 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 16761 Loc, Mod, Loc); 16762 TU->addDecl(ImportD); 16763 Consumer.HandleImplicitImportDecl(ImportD); 16764 16765 // Make the module visible. 16766 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 16767 VisibleModules.setVisible(Mod, Loc); 16768 } 16769 16770 /// We have parsed the start of an export declaration, including the '{' 16771 /// (if present). 16772 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 16773 SourceLocation LBraceLoc) { 16774 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 16775 16776 // C++ Modules TS draft: 16777 // An export-declaration shall appear in the purview of a module other than 16778 // the global module. 16779 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 16780 Diag(ExportLoc, diag::err_export_not_in_module_interface); 16781 16782 // An export-declaration [...] shall not contain more than one 16783 // export keyword. 16784 // 16785 // The intent here is that an export-declaration cannot appear within another 16786 // export-declaration. 16787 if (D->isExported()) 16788 Diag(ExportLoc, diag::err_export_within_export); 16789 16790 CurContext->addDecl(D); 16791 PushDeclContext(S, D); 16792 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 16793 return D; 16794 } 16795 16796 /// Complete the definition of an export declaration. 16797 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 16798 auto *ED = cast<ExportDecl>(D); 16799 if (RBraceLoc.isValid()) 16800 ED->setRBraceLoc(RBraceLoc); 16801 16802 // FIXME: Diagnose export of internal-linkage declaration (including 16803 // anonymous namespace). 16804 16805 PopDeclContext(); 16806 return D; 16807 } 16808 16809 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 16810 IdentifierInfo* AliasName, 16811 SourceLocation PragmaLoc, 16812 SourceLocation NameLoc, 16813 SourceLocation AliasNameLoc) { 16814 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 16815 LookupOrdinaryName); 16816 AsmLabelAttr *Attr = 16817 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 16818 16819 // If a declaration that: 16820 // 1) declares a function or a variable 16821 // 2) has external linkage 16822 // already exists, add a label attribute to it. 16823 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16824 if (isDeclExternC(PrevDecl)) 16825 PrevDecl->addAttr(Attr); 16826 else 16827 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 16828 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 16829 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 16830 } else 16831 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 16832 } 16833 16834 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 16835 SourceLocation PragmaLoc, 16836 SourceLocation NameLoc) { 16837 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 16838 16839 if (PrevDecl) { 16840 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 16841 } else { 16842 (void)WeakUndeclaredIdentifiers.insert( 16843 std::pair<IdentifierInfo*,WeakInfo> 16844 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 16845 } 16846 } 16847 16848 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 16849 IdentifierInfo* AliasName, 16850 SourceLocation PragmaLoc, 16851 SourceLocation NameLoc, 16852 SourceLocation AliasNameLoc) { 16853 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 16854 LookupOrdinaryName); 16855 WeakInfo W = WeakInfo(Name, NameLoc); 16856 16857 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 16858 if (!PrevDecl->hasAttr<AliasAttr>()) 16859 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 16860 DeclApplyPragmaWeak(TUScope, ND, W); 16861 } else { 16862 (void)WeakUndeclaredIdentifiers.insert( 16863 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 16864 } 16865 } 16866 16867 Decl *Sema::getObjCDeclContext() const { 16868 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 16869 } 16870