1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for declarations. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "TypeLocBuilder.h" 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTLambda.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/CommentDiagnostic.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclTemplate.h" 23 #include "clang/AST/EvaluatedExprVisitor.h" 24 #include "clang/AST/ExprCXX.h" 25 #include "clang/AST/NonTrivialTypeVisitor.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 #include <unordered_map> 51 52 using namespace clang; 53 using namespace sema; 54 55 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 56 if (OwnedType) { 57 Decl *Group[2] = { OwnedType, Ptr }; 58 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 59 } 60 61 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 62 } 63 64 namespace { 65 66 class TypeNameValidatorCCC final : public CorrectionCandidateCallback { 67 public: 68 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false, 69 bool AllowTemplates = false, 70 bool AllowNonTemplates = true) 71 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 72 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) { 73 WantExpressionKeywords = false; 74 WantCXXNamedCasts = false; 75 WantRemainingKeywords = false; 76 } 77 78 bool ValidateCandidate(const TypoCorrection &candidate) override { 79 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 80 if (!AllowInvalidDecl && ND->isInvalidDecl()) 81 return false; 82 83 if (getAsTypeTemplateDecl(ND)) 84 return AllowTemplates; 85 86 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 87 if (!IsType) 88 return false; 89 90 if (AllowNonTemplates) 91 return true; 92 93 // An injected-class-name of a class template (specialization) is valid 94 // as a template or as a non-template. 95 if (AllowTemplates) { 96 auto *RD = dyn_cast<CXXRecordDecl>(ND); 97 if (!RD || !RD->isInjectedClassName()) 98 return false; 99 RD = cast<CXXRecordDecl>(RD->getDeclContext()); 100 return RD->getDescribedClassTemplate() || 101 isa<ClassTemplateSpecializationDecl>(RD); 102 } 103 104 return false; 105 } 106 107 return !WantClassName && candidate.isKeyword(); 108 } 109 110 std::unique_ptr<CorrectionCandidateCallback> clone() override { 111 return std::make_unique<TypeNameValidatorCCC>(*this); 112 } 113 114 private: 115 bool AllowInvalidDecl; 116 bool WantClassName; 117 bool AllowTemplates; 118 bool AllowNonTemplates; 119 }; 120 121 } // end anonymous namespace 122 123 /// Determine whether the token kind starts a simple-type-specifier. 124 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 125 switch (Kind) { 126 // FIXME: Take into account the current language when deciding whether a 127 // token kind is a valid type specifier 128 case tok::kw_short: 129 case tok::kw_long: 130 case tok::kw___int64: 131 case tok::kw___int128: 132 case tok::kw_signed: 133 case tok::kw_unsigned: 134 case tok::kw_void: 135 case tok::kw_char: 136 case tok::kw_int: 137 case tok::kw_half: 138 case tok::kw_float: 139 case tok::kw_double: 140 case tok::kw__Float16: 141 case tok::kw___float128: 142 case tok::kw_wchar_t: 143 case tok::kw_bool: 144 case tok::kw___underlying_type: 145 case tok::kw___auto_type: 146 return true; 147 148 case tok::annot_typename: 149 case tok::kw_char16_t: 150 case tok::kw_char32_t: 151 case tok::kw_typeof: 152 case tok::annot_decltype: 153 case tok::kw_decltype: 154 return getLangOpts().CPlusPlus; 155 156 case tok::kw_char8_t: 157 return getLangOpts().Char8; 158 159 default: 160 break; 161 } 162 163 return false; 164 } 165 166 namespace { 167 enum class UnqualifiedTypeNameLookupResult { 168 NotFound, 169 FoundNonType, 170 FoundType 171 }; 172 } // end anonymous namespace 173 174 /// Tries to perform unqualified lookup of the type decls in bases for 175 /// dependent class. 176 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 177 /// type decl, \a FoundType if only type decls are found. 178 static UnqualifiedTypeNameLookupResult 179 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 180 SourceLocation NameLoc, 181 const CXXRecordDecl *RD) { 182 if (!RD->hasDefinition()) 183 return UnqualifiedTypeNameLookupResult::NotFound; 184 // Look for type decls in base classes. 185 UnqualifiedTypeNameLookupResult FoundTypeDecl = 186 UnqualifiedTypeNameLookupResult::NotFound; 187 for (const auto &Base : RD->bases()) { 188 const CXXRecordDecl *BaseRD = nullptr; 189 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 190 BaseRD = BaseTT->getAsCXXRecordDecl(); 191 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 192 // Look for type decls in dependent base classes that have known primary 193 // templates. 194 if (!TST || !TST->isDependentType()) 195 continue; 196 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 197 if (!TD) 198 continue; 199 if (auto *BasePrimaryTemplate = 200 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) { 201 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl()) 202 BaseRD = BasePrimaryTemplate; 203 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) { 204 if (const ClassTemplatePartialSpecializationDecl *PS = 205 CTD->findPartialSpecialization(Base.getType())) 206 if (PS->getCanonicalDecl() != RD->getCanonicalDecl()) 207 BaseRD = PS; 208 } 209 } 210 } 211 if (BaseRD) { 212 for (NamedDecl *ND : BaseRD->lookup(&II)) { 213 if (!isa<TypeDecl>(ND)) 214 return UnqualifiedTypeNameLookupResult::FoundNonType; 215 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 216 } 217 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 218 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 219 case UnqualifiedTypeNameLookupResult::FoundNonType: 220 return UnqualifiedTypeNameLookupResult::FoundNonType; 221 case UnqualifiedTypeNameLookupResult::FoundType: 222 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 223 break; 224 case UnqualifiedTypeNameLookupResult::NotFound: 225 break; 226 } 227 } 228 } 229 } 230 231 return FoundTypeDecl; 232 } 233 234 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 235 const IdentifierInfo &II, 236 SourceLocation NameLoc) { 237 // Lookup in the parent class template context, if any. 238 const CXXRecordDecl *RD = nullptr; 239 UnqualifiedTypeNameLookupResult FoundTypeDecl = 240 UnqualifiedTypeNameLookupResult::NotFound; 241 for (DeclContext *DC = S.CurContext; 242 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 243 DC = DC->getParent()) { 244 // Look for type decls in dependent base classes that have known primary 245 // templates. 246 RD = dyn_cast<CXXRecordDecl>(DC); 247 if (RD && RD->getDescribedClassTemplate()) 248 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 249 } 250 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 251 return nullptr; 252 253 // We found some types in dependent base classes. Recover as if the user 254 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 255 // lookup during template instantiation. 256 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 257 258 ASTContext &Context = S.Context; 259 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 260 cast<Type>(Context.getRecordType(RD))); 261 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 262 263 CXXScopeSpec SS; 264 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 265 266 TypeLocBuilder Builder; 267 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 268 DepTL.setNameLoc(NameLoc); 269 DepTL.setElaboratedKeywordLoc(SourceLocation()); 270 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 271 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 272 } 273 274 /// If the identifier refers to a type name within this scope, 275 /// return the declaration of that type. 276 /// 277 /// This routine performs ordinary name lookup of the identifier II 278 /// within the given scope, with optional C++ scope specifier SS, to 279 /// determine whether the name refers to a type. If so, returns an 280 /// opaque pointer (actually a QualType) corresponding to that 281 /// type. Otherwise, returns NULL. 282 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 283 Scope *S, CXXScopeSpec *SS, 284 bool isClassName, bool HasTrailingDot, 285 ParsedType ObjectTypePtr, 286 bool IsCtorOrDtorName, 287 bool WantNontrivialTypeSourceInfo, 288 bool IsClassTemplateDeductionContext, 289 IdentifierInfo **CorrectedII) { 290 // FIXME: Consider allowing this outside C++1z mode as an extension. 291 bool AllowDeducedTemplate = IsClassTemplateDeductionContext && 292 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName && 293 !isClassName && !HasTrailingDot; 294 295 // Determine where we will perform name lookup. 296 DeclContext *LookupCtx = nullptr; 297 if (ObjectTypePtr) { 298 QualType ObjectType = ObjectTypePtr.get(); 299 if (ObjectType->isRecordType()) 300 LookupCtx = computeDeclContext(ObjectType); 301 } else if (SS && SS->isNotEmpty()) { 302 LookupCtx = computeDeclContext(*SS, false); 303 304 if (!LookupCtx) { 305 if (isDependentScopeSpecifier(*SS)) { 306 // C++ [temp.res]p3: 307 // A qualified-id that refers to a type and in which the 308 // nested-name-specifier depends on a template-parameter (14.6.2) 309 // shall be prefixed by the keyword typename to indicate that the 310 // qualified-id denotes a type, forming an 311 // elaborated-type-specifier (7.1.5.3). 312 // 313 // We therefore do not perform any name lookup if the result would 314 // refer to a member of an unknown specialization. 315 if (!isClassName && !IsCtorOrDtorName) 316 return nullptr; 317 318 // We know from the grammar that this name refers to a type, 319 // so build a dependent node to describe the type. 320 if (WantNontrivialTypeSourceInfo) 321 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 322 323 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 324 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 325 II, NameLoc); 326 return ParsedType::make(T); 327 } 328 329 return nullptr; 330 } 331 332 if (!LookupCtx->isDependentContext() && 333 RequireCompleteDeclContext(*SS, LookupCtx)) 334 return nullptr; 335 } 336 337 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 338 // lookup for class-names. 339 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 340 LookupOrdinaryName; 341 LookupResult Result(*this, &II, NameLoc, Kind); 342 if (LookupCtx) { 343 // Perform "qualified" name lookup into the declaration context we 344 // computed, which is either the type of the base of a member access 345 // expression or the declaration context associated with a prior 346 // nested-name-specifier. 347 LookupQualifiedName(Result, LookupCtx); 348 349 if (ObjectTypePtr && Result.empty()) { 350 // C++ [basic.lookup.classref]p3: 351 // If the unqualified-id is ~type-name, the type-name is looked up 352 // in the context of the entire postfix-expression. If the type T of 353 // the object expression is of a class type C, the type-name is also 354 // looked up in the scope of class C. At least one of the lookups shall 355 // find a name that refers to (possibly cv-qualified) T. 356 LookupName(Result, S); 357 } 358 } else { 359 // Perform unqualified name lookup. 360 LookupName(Result, S); 361 362 // For unqualified lookup in a class template in MSVC mode, look into 363 // dependent base classes where the primary class template is known. 364 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 365 if (ParsedType TypeInBase = 366 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 367 return TypeInBase; 368 } 369 } 370 371 NamedDecl *IIDecl = nullptr; 372 switch (Result.getResultKind()) { 373 case LookupResult::NotFound: 374 case LookupResult::NotFoundInCurrentInstantiation: 375 if (CorrectedII) { 376 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName, 377 AllowDeducedTemplate); 378 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind, 379 S, SS, CCC, CTK_ErrorRecovery); 380 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 381 TemplateTy Template; 382 bool MemberOfUnknownSpecialization; 383 UnqualifiedId TemplateName; 384 TemplateName.setIdentifier(NewII, NameLoc); 385 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 386 CXXScopeSpec NewSS, *NewSSPtr = SS; 387 if (SS && NNS) { 388 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 389 NewSSPtr = &NewSS; 390 } 391 if (Correction && (NNS || NewII != &II) && 392 // Ignore a correction to a template type as the to-be-corrected 393 // identifier is not a template (typo correction for template names 394 // is handled elsewhere). 395 !(getLangOpts().CPlusPlus && NewSSPtr && 396 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false, 397 Template, MemberOfUnknownSpecialization))) { 398 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 399 isClassName, HasTrailingDot, ObjectTypePtr, 400 IsCtorOrDtorName, 401 WantNontrivialTypeSourceInfo, 402 IsClassTemplateDeductionContext); 403 if (Ty) { 404 diagnoseTypo(Correction, 405 PDiag(diag::err_unknown_type_or_class_name_suggest) 406 << Result.getLookupName() << isClassName); 407 if (SS && NNS) 408 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 409 *CorrectedII = NewII; 410 return Ty; 411 } 412 } 413 } 414 // If typo correction failed or was not performed, fall through 415 LLVM_FALLTHROUGH; 416 case LookupResult::FoundOverloaded: 417 case LookupResult::FoundUnresolvedValue: 418 Result.suppressDiagnostics(); 419 return nullptr; 420 421 case LookupResult::Ambiguous: 422 // Recover from type-hiding ambiguities by hiding the type. We'll 423 // do the lookup again when looking for an object, and we can 424 // diagnose the error then. If we don't do this, then the error 425 // about hiding the type will be immediately followed by an error 426 // that only makes sense if the identifier was treated like a type. 427 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 428 Result.suppressDiagnostics(); 429 return nullptr; 430 } 431 432 // Look to see if we have a type anywhere in the list of results. 433 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 434 Res != ResEnd; ++Res) { 435 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) || 436 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) { 437 if (!IIDecl || 438 (*Res)->getLocation().getRawEncoding() < 439 IIDecl->getLocation().getRawEncoding()) 440 IIDecl = *Res; 441 } 442 } 443 444 if (!IIDecl) { 445 // None of the entities we found is a type, so there is no way 446 // to even assume that the result is a type. In this case, don't 447 // complain about the ambiguity. The parser will either try to 448 // perform this lookup again (e.g., as an object name), which 449 // will produce the ambiguity, or will complain that it expected 450 // a type name. 451 Result.suppressDiagnostics(); 452 return nullptr; 453 } 454 455 // We found a type within the ambiguous lookup; diagnose the 456 // ambiguity and then return that type. This might be the right 457 // answer, or it might not be, but it suppresses any attempt to 458 // perform the name lookup again. 459 break; 460 461 case LookupResult::Found: 462 IIDecl = Result.getFoundDecl(); 463 break; 464 } 465 466 assert(IIDecl && "Didn't find decl"); 467 468 QualType T; 469 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 470 // C++ [class.qual]p2: A lookup that would find the injected-class-name 471 // instead names the constructors of the class, except when naming a class. 472 // This is ill-formed when we're not actually forming a ctor or dtor name. 473 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx); 474 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD); 475 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD && 476 FoundRD->isInjectedClassName() && 477 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent()))) 478 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor) 479 << &II << /*Type*/1; 480 481 DiagnoseUseOfDecl(IIDecl, NameLoc); 482 483 T = Context.getTypeDeclType(TD); 484 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 485 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 486 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 487 if (!HasTrailingDot) 488 T = Context.getObjCInterfaceType(IDecl); 489 } else if (AllowDeducedTemplate) { 490 if (auto *TD = getAsTypeTemplateDecl(IIDecl)) 491 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD), 492 QualType(), false); 493 } 494 495 if (T.isNull()) { 496 // If it's not plausibly a type, suppress diagnostics. 497 Result.suppressDiagnostics(); 498 return nullptr; 499 } 500 501 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 502 // constructor or destructor name (in such a case, the scope specifier 503 // will be attached to the enclosing Expr or Decl node). 504 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName && 505 !isa<ObjCInterfaceDecl>(IIDecl)) { 506 if (WantNontrivialTypeSourceInfo) { 507 // Construct a type with type-source information. 508 TypeLocBuilder Builder; 509 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 510 511 T = getElaboratedType(ETK_None, *SS, T); 512 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 513 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 514 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 515 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 516 } else { 517 T = getElaboratedType(ETK_None, *SS, T); 518 } 519 } 520 521 return ParsedType::make(T); 522 } 523 524 // Builds a fake NNS for the given decl context. 525 static NestedNameSpecifier * 526 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 527 for (;; DC = DC->getLookupParent()) { 528 DC = DC->getPrimaryContext(); 529 auto *ND = dyn_cast<NamespaceDecl>(DC); 530 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 531 return NestedNameSpecifier::Create(Context, nullptr, ND); 532 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 533 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 534 RD->getTypeForDecl()); 535 else if (isa<TranslationUnitDecl>(DC)) 536 return NestedNameSpecifier::GlobalSpecifier(Context); 537 } 538 llvm_unreachable("something isn't in TU scope?"); 539 } 540 541 /// Find the parent class with dependent bases of the innermost enclosing method 542 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end 543 /// up allowing unqualified dependent type names at class-level, which MSVC 544 /// correctly rejects. 545 static const CXXRecordDecl * 546 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) { 547 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) { 548 DC = DC->getPrimaryContext(); 549 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC)) 550 if (MD->getParent()->hasAnyDependentBases()) 551 return MD->getParent(); 552 } 553 return nullptr; 554 } 555 556 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II, 557 SourceLocation NameLoc, 558 bool IsTemplateTypeArg) { 559 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode"); 560 561 NestedNameSpecifier *NNS = nullptr; 562 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) { 563 // If we weren't able to parse a default template argument, delay lookup 564 // until instantiation time by making a non-dependent DependentTypeName. We 565 // pretend we saw a NestedNameSpecifier referring to the current scope, and 566 // lookup is retried. 567 // FIXME: This hurts our diagnostic quality, since we get errors like "no 568 // type named 'Foo' in 'current_namespace'" when the user didn't write any 569 // name specifiers. 570 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext); 571 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 572 } else if (const CXXRecordDecl *RD = 573 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) { 574 // Build a DependentNameType that will perform lookup into RD at 575 // instantiation time. 576 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 577 RD->getTypeForDecl()); 578 579 // Diagnose that this identifier was undeclared, and retry the lookup during 580 // template instantiation. 581 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II 582 << RD; 583 } else { 584 // This is not a situation that we should recover from. 585 return ParsedType(); 586 } 587 588 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 589 590 // Build type location information. We synthesized the qualifier, so we have 591 // to build a fake NestedNameSpecifierLoc. 592 NestedNameSpecifierLocBuilder NNSLocBuilder; 593 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 594 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 595 596 TypeLocBuilder Builder; 597 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 598 DepTL.setNameLoc(NameLoc); 599 DepTL.setElaboratedKeywordLoc(SourceLocation()); 600 DepTL.setQualifierLoc(QualifierLoc); 601 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 602 } 603 604 /// isTagName() - This method is called *for error recovery purposes only* 605 /// to determine if the specified name is a valid tag name ("struct foo"). If 606 /// so, this returns the TST for the tag corresponding to it (TST_enum, 607 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 608 /// cases in C where the user forgot to specify the tag. 609 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 610 // Do a tag name lookup in this scope. 611 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 612 LookupName(R, S, false); 613 R.suppressDiagnostics(); 614 if (R.getResultKind() == LookupResult::Found) 615 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 616 switch (TD->getTagKind()) { 617 case TTK_Struct: return DeclSpec::TST_struct; 618 case TTK_Interface: return DeclSpec::TST_interface; 619 case TTK_Union: return DeclSpec::TST_union; 620 case TTK_Class: return DeclSpec::TST_class; 621 case TTK_Enum: return DeclSpec::TST_enum; 622 } 623 } 624 625 return DeclSpec::TST_unspecified; 626 } 627 628 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 629 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 630 /// then downgrade the missing typename error to a warning. 631 /// This is needed for MSVC compatibility; Example: 632 /// @code 633 /// template<class T> class A { 634 /// public: 635 /// typedef int TYPE; 636 /// }; 637 /// template<class T> class B : public A<T> { 638 /// public: 639 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 640 /// }; 641 /// @endcode 642 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 643 if (CurContext->isRecord()) { 644 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 645 return true; 646 647 const Type *Ty = SS->getScopeRep()->getAsType(); 648 649 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 650 for (const auto &Base : RD->bases()) 651 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 652 return true; 653 return S->isFunctionPrototypeScope(); 654 } 655 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 656 } 657 658 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 659 SourceLocation IILoc, 660 Scope *S, 661 CXXScopeSpec *SS, 662 ParsedType &SuggestedType, 663 bool IsTemplateName) { 664 // Don't report typename errors for editor placeholders. 665 if (II->isEditorPlaceholder()) 666 return; 667 // We don't have anything to suggest (yet). 668 SuggestedType = nullptr; 669 670 // There may have been a typo in the name of the type. Look up typo 671 // results, in case we have something that we can suggest. 672 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false, 673 /*AllowTemplates=*/IsTemplateName, 674 /*AllowNonTemplates=*/!IsTemplateName); 675 if (TypoCorrection Corrected = 676 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 677 CCC, CTK_ErrorRecovery)) { 678 // FIXME: Support error recovery for the template-name case. 679 bool CanRecover = !IsTemplateName; 680 if (Corrected.isKeyword()) { 681 // We corrected to a keyword. 682 diagnoseTypo(Corrected, 683 PDiag(IsTemplateName ? diag::err_no_template_suggest 684 : diag::err_unknown_typename_suggest) 685 << II); 686 II = Corrected.getCorrectionAsIdentifierInfo(); 687 } else { 688 // We found a similarly-named type or interface; suggest that. 689 if (!SS || !SS->isSet()) { 690 diagnoseTypo(Corrected, 691 PDiag(IsTemplateName ? diag::err_no_template_suggest 692 : diag::err_unknown_typename_suggest) 693 << II, CanRecover); 694 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 695 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 696 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 697 II->getName().equals(CorrectedStr); 698 diagnoseTypo(Corrected, 699 PDiag(IsTemplateName 700 ? diag::err_no_member_template_suggest 701 : diag::err_unknown_nested_typename_suggest) 702 << II << DC << DroppedSpecifier << SS->getRange(), 703 CanRecover); 704 } else { 705 llvm_unreachable("could not have corrected a typo here"); 706 } 707 708 if (!CanRecover) 709 return; 710 711 CXXScopeSpec tmpSS; 712 if (Corrected.getCorrectionSpecifier()) 713 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 714 SourceRange(IILoc)); 715 // FIXME: Support class template argument deduction here. 716 SuggestedType = 717 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S, 718 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr, 719 /*IsCtorOrDtorName=*/false, 720 /*WantNontrivialTypeSourceInfo=*/true); 721 } 722 return; 723 } 724 725 if (getLangOpts().CPlusPlus && !IsTemplateName) { 726 // See if II is a class template that the user forgot to pass arguments to. 727 UnqualifiedId Name; 728 Name.setIdentifier(II, IILoc); 729 CXXScopeSpec EmptySS; 730 TemplateTy TemplateResult; 731 bool MemberOfUnknownSpecialization; 732 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 733 Name, nullptr, true, TemplateResult, 734 MemberOfUnknownSpecialization) == TNK_Type_template) { 735 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc); 736 return; 737 } 738 } 739 740 // FIXME: Should we move the logic that tries to recover from a missing tag 741 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 742 743 if (!SS || (!SS->isSet() && !SS->isInvalid())) 744 Diag(IILoc, IsTemplateName ? diag::err_no_template 745 : diag::err_unknown_typename) 746 << II; 747 else if (DeclContext *DC = computeDeclContext(*SS, false)) 748 Diag(IILoc, IsTemplateName ? diag::err_no_member_template 749 : diag::err_typename_nested_not_found) 750 << II << DC << SS->getRange(); 751 else if (isDependentScopeSpecifier(*SS)) { 752 unsigned DiagID = diag::err_typename_missing; 753 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 754 DiagID = diag::ext_typename_missing; 755 756 Diag(SS->getRange().getBegin(), DiagID) 757 << SS->getScopeRep() << II->getName() 758 << SourceRange(SS->getRange().getBegin(), IILoc) 759 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 760 SuggestedType = ActOnTypenameType(S, SourceLocation(), 761 *SS, *II, IILoc).get(); 762 } else { 763 assert(SS && SS->isInvalid() && 764 "Invalid scope specifier has already been diagnosed"); 765 } 766 } 767 768 /// Determine whether the given result set contains either a type name 769 /// or 770 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 771 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 772 NextToken.is(tok::less); 773 774 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 775 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 776 return true; 777 778 if (CheckTemplate && isa<TemplateDecl>(*I)) 779 return true; 780 } 781 782 return false; 783 } 784 785 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 786 Scope *S, CXXScopeSpec &SS, 787 IdentifierInfo *&Name, 788 SourceLocation NameLoc) { 789 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 790 SemaRef.LookupParsedName(R, S, &SS); 791 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 792 StringRef FixItTagName; 793 switch (Tag->getTagKind()) { 794 case TTK_Class: 795 FixItTagName = "class "; 796 break; 797 798 case TTK_Enum: 799 FixItTagName = "enum "; 800 break; 801 802 case TTK_Struct: 803 FixItTagName = "struct "; 804 break; 805 806 case TTK_Interface: 807 FixItTagName = "__interface "; 808 break; 809 810 case TTK_Union: 811 FixItTagName = "union "; 812 break; 813 } 814 815 StringRef TagName = FixItTagName.drop_back(); 816 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 817 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 818 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 819 820 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 821 I != IEnd; ++I) 822 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 823 << Name << TagName; 824 825 // Replace lookup results with just the tag decl. 826 Result.clear(Sema::LookupTagName); 827 SemaRef.LookupParsedName(Result, S, &SS); 828 return true; 829 } 830 831 return false; 832 } 833 834 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 835 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 836 QualType T, SourceLocation NameLoc) { 837 ASTContext &Context = S.Context; 838 839 TypeLocBuilder Builder; 840 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 841 842 T = S.getElaboratedType(ETK_None, SS, T); 843 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 844 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 845 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 846 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 847 } 848 849 Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, 850 IdentifierInfo *&Name, 851 SourceLocation NameLoc, 852 const Token &NextToken, 853 CorrectionCandidateCallback *CCC) { 854 DeclarationNameInfo NameInfo(Name, NameLoc); 855 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 856 857 assert(NextToken.isNot(tok::coloncolon) && 858 "parse nested name specifiers before calling ClassifyName"); 859 if (getLangOpts().CPlusPlus && SS.isSet() && 860 isCurrentClassName(*Name, S, &SS)) { 861 // Per [class.qual]p2, this names the constructors of SS, not the 862 // injected-class-name. We don't have a classification for that. 863 // There's not much point caching this result, since the parser 864 // will reject it later. 865 return NameClassification::Unknown(); 866 } 867 868 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 869 LookupParsedName(Result, S, &SS, !CurMethod); 870 871 if (SS.isInvalid()) 872 return NameClassification::Error(); 873 874 // For unqualified lookup in a class template in MSVC mode, look into 875 // dependent base classes where the primary class template is known. 876 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 877 if (ParsedType TypeInBase = 878 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 879 return TypeInBase; 880 } 881 882 // Perform lookup for Objective-C instance variables (including automatically 883 // synthesized instance variables), if we're in an Objective-C method. 884 // FIXME: This lookup really, really needs to be folded in to the normal 885 // unqualified lookup mechanism. 886 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 887 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name); 888 if (Ivar.isInvalid()) 889 return NameClassification::Error(); 890 if (Ivar.isUsable()) 891 return NameClassification::NonType(cast<NamedDecl>(Ivar.get())); 892 893 // We defer builtin creation until after ivar lookup inside ObjC methods. 894 if (Result.empty()) 895 LookupBuiltin(Result); 896 } 897 898 bool SecondTry = false; 899 bool IsFilteredTemplateName = false; 900 901 Corrected: 902 switch (Result.getResultKind()) { 903 case LookupResult::NotFound: 904 // If an unqualified-id is followed by a '(', then we have a function 905 // call. 906 if (SS.isEmpty() && NextToken.is(tok::l_paren)) { 907 // In C++, this is an ADL-only call. 908 // FIXME: Reference? 909 if (getLangOpts().CPlusPlus) 910 return NameClassification::UndeclaredNonType(); 911 912 // C90 6.3.2.2: 913 // If the expression that precedes the parenthesized argument list in a 914 // function call consists solely of an identifier, and if no 915 // declaration is visible for this identifier, the identifier is 916 // implicitly declared exactly as if, in the innermost block containing 917 // the function call, the declaration 918 // 919 // extern int identifier (); 920 // 921 // appeared. 922 // 923 // We also allow this in C99 as an extension. 924 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) 925 return NameClassification::NonType(D); 926 } 927 928 if (getLangOpts().CPlusPlus2a && SS.isEmpty() && NextToken.is(tok::less)) { 929 // In C++20 onwards, this could be an ADL-only call to a function 930 // template, and we're required to assume that this is a template name. 931 // 932 // FIXME: Find a way to still do typo correction in this case. 933 TemplateName Template = 934 Context.getAssumedTemplateName(NameInfo.getName()); 935 return NameClassification::UndeclaredTemplate(Template); 936 } 937 938 // In C, we first see whether there is a tag type by the same name, in 939 // which case it's likely that the user just forgot to write "enum", 940 // "struct", or "union". 941 if (!getLangOpts().CPlusPlus && !SecondTry && 942 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 943 break; 944 } 945 946 // Perform typo correction to determine if there is another name that is 947 // close to this name. 948 if (!SecondTry && CCC) { 949 SecondTry = true; 950 if (TypoCorrection Corrected = 951 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 952 &SS, *CCC, CTK_ErrorRecovery)) { 953 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 954 unsigned QualifiedDiag = diag::err_no_member_suggest; 955 956 NamedDecl *FirstDecl = Corrected.getFoundDecl(); 957 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl(); 958 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 959 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 960 UnqualifiedDiag = diag::err_no_template_suggest; 961 QualifiedDiag = diag::err_no_member_template_suggest; 962 } else if (UnderlyingFirstDecl && 963 (isa<TypeDecl>(UnderlyingFirstDecl) || 964 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 965 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 966 UnqualifiedDiag = diag::err_unknown_typename_suggest; 967 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 968 } 969 970 if (SS.isEmpty()) { 971 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 972 } else {// FIXME: is this even reachable? Test it. 973 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 974 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 975 Name->getName().equals(CorrectedStr); 976 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 977 << Name << computeDeclContext(SS, false) 978 << DroppedSpecifier << SS.getRange()); 979 } 980 981 // Update the name, so that the caller has the new name. 982 Name = Corrected.getCorrectionAsIdentifierInfo(); 983 984 // Typo correction corrected to a keyword. 985 if (Corrected.isKeyword()) 986 return Name; 987 988 // Also update the LookupResult... 989 // FIXME: This should probably go away at some point 990 Result.clear(); 991 Result.setLookupName(Corrected.getCorrection()); 992 if (FirstDecl) 993 Result.addDecl(FirstDecl); 994 995 // If we found an Objective-C instance variable, let 996 // LookupInObjCMethod build the appropriate expression to 997 // reference the ivar. 998 // FIXME: This is a gross hack. 999 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 1000 DeclResult R = 1001 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier()); 1002 if (R.isInvalid()) 1003 return NameClassification::Error(); 1004 if (R.isUsable()) 1005 return NameClassification::NonType(Ivar); 1006 } 1007 1008 goto Corrected; 1009 } 1010 } 1011 1012 // We failed to correct; just fall through and let the parser deal with it. 1013 Result.suppressDiagnostics(); 1014 return NameClassification::Unknown(); 1015 1016 case LookupResult::NotFoundInCurrentInstantiation: { 1017 // We performed name lookup into the current instantiation, and there were 1018 // dependent bases, so we treat this result the same way as any other 1019 // dependent nested-name-specifier. 1020 1021 // C++ [temp.res]p2: 1022 // A name used in a template declaration or definition and that is 1023 // dependent on a template-parameter is assumed not to name a type 1024 // unless the applicable name lookup finds a type name or the name is 1025 // qualified by the keyword typename. 1026 // 1027 // FIXME: If the next token is '<', we might want to ask the parser to 1028 // perform some heroics to see if we actually have a 1029 // template-argument-list, which would indicate a missing 'template' 1030 // keyword here. 1031 return NameClassification::DependentNonType(); 1032 } 1033 1034 case LookupResult::Found: 1035 case LookupResult::FoundOverloaded: 1036 case LookupResult::FoundUnresolvedValue: 1037 break; 1038 1039 case LookupResult::Ambiguous: 1040 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1041 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true, 1042 /*AllowDependent=*/false)) { 1043 // C++ [temp.local]p3: 1044 // A lookup that finds an injected-class-name (10.2) can result in an 1045 // ambiguity in certain cases (for example, if it is found in more than 1046 // one base class). If all of the injected-class-names that are found 1047 // refer to specializations of the same class template, and if the name 1048 // is followed by a template-argument-list, the reference refers to the 1049 // class template itself and not a specialization thereof, and is not 1050 // ambiguous. 1051 // 1052 // This filtering can make an ambiguous result into an unambiguous one, 1053 // so try again after filtering out template names. 1054 FilterAcceptableTemplateNames(Result); 1055 if (!Result.isAmbiguous()) { 1056 IsFilteredTemplateName = true; 1057 break; 1058 } 1059 } 1060 1061 // Diagnose the ambiguity and return an error. 1062 return NameClassification::Error(); 1063 } 1064 1065 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 1066 (IsFilteredTemplateName || 1067 hasAnyAcceptableTemplateNames( 1068 Result, /*AllowFunctionTemplates=*/true, 1069 /*AllowDependent=*/false, 1070 /*AllowNonTemplateFunctions*/ SS.isEmpty() && 1071 getLangOpts().CPlusPlus2a))) { 1072 // C++ [temp.names]p3: 1073 // After name lookup (3.4) finds that a name is a template-name or that 1074 // an operator-function-id or a literal- operator-id refers to a set of 1075 // overloaded functions any member of which is a function template if 1076 // this is followed by a <, the < is always taken as the delimiter of a 1077 // template-argument-list and never as the less-than operator. 1078 // C++2a [temp.names]p2: 1079 // A name is also considered to refer to a template if it is an 1080 // unqualified-id followed by a < and name lookup finds either one 1081 // or more functions or finds nothing. 1082 if (!IsFilteredTemplateName) 1083 FilterAcceptableTemplateNames(Result); 1084 1085 bool IsFunctionTemplate; 1086 bool IsVarTemplate; 1087 TemplateName Template; 1088 if (Result.end() - Result.begin() > 1) { 1089 IsFunctionTemplate = true; 1090 Template = Context.getOverloadedTemplateName(Result.begin(), 1091 Result.end()); 1092 } else if (!Result.empty()) { 1093 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl( 1094 *Result.begin(), /*AllowFunctionTemplates=*/true, 1095 /*AllowDependent=*/false)); 1096 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 1097 IsVarTemplate = isa<VarTemplateDecl>(TD); 1098 1099 if (SS.isNotEmpty()) 1100 Template = 1101 Context.getQualifiedTemplateName(SS.getScopeRep(), 1102 /*TemplateKeyword=*/false, TD); 1103 else 1104 Template = TemplateName(TD); 1105 } else { 1106 // All results were non-template functions. This is a function template 1107 // name. 1108 IsFunctionTemplate = true; 1109 Template = Context.getAssumedTemplateName(NameInfo.getName()); 1110 } 1111 1112 if (IsFunctionTemplate) { 1113 // Function templates always go through overload resolution, at which 1114 // point we'll perform the various checks (e.g., accessibility) we need 1115 // to based on which function we selected. 1116 Result.suppressDiagnostics(); 1117 1118 return NameClassification::FunctionTemplate(Template); 1119 } 1120 1121 return IsVarTemplate ? NameClassification::VarTemplate(Template) 1122 : NameClassification::TypeTemplate(Template); 1123 } 1124 1125 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 1126 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 1127 DiagnoseUseOfDecl(Type, NameLoc); 1128 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 1129 QualType T = Context.getTypeDeclType(Type); 1130 if (SS.isNotEmpty()) 1131 return buildNestedType(*this, SS, T, NameLoc); 1132 return ParsedType::make(T); 1133 } 1134 1135 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 1136 if (!Class) { 1137 // FIXME: It's unfortunate that we don't have a Type node for handling this. 1138 if (ObjCCompatibleAliasDecl *Alias = 1139 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 1140 Class = Alias->getClassInterface(); 1141 } 1142 1143 if (Class) { 1144 DiagnoseUseOfDecl(Class, NameLoc); 1145 1146 if (NextToken.is(tok::period)) { 1147 // Interface. <something> is parsed as a property reference expression. 1148 // Just return "unknown" as a fall-through for now. 1149 Result.suppressDiagnostics(); 1150 return NameClassification::Unknown(); 1151 } 1152 1153 QualType T = Context.getObjCInterfaceType(Class); 1154 return ParsedType::make(T); 1155 } 1156 1157 if (isa<ConceptDecl>(FirstDecl)) 1158 return NameClassification::Concept( 1159 TemplateName(cast<TemplateDecl>(FirstDecl))); 1160 1161 // We can have a type template here if we're classifying a template argument. 1162 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) && 1163 !isa<VarTemplateDecl>(FirstDecl)) 1164 return NameClassification::TypeTemplate( 1165 TemplateName(cast<TemplateDecl>(FirstDecl))); 1166 1167 // Check for a tag type hidden by a non-type decl in a few cases where it 1168 // seems likely a type is wanted instead of the non-type that was found. 1169 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1170 if ((NextToken.is(tok::identifier) || 1171 (NextIsOp && 1172 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1173 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1174 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1175 DiagnoseUseOfDecl(Type, NameLoc); 1176 QualType T = Context.getTypeDeclType(Type); 1177 if (SS.isNotEmpty()) 1178 return buildNestedType(*this, SS, T, NameLoc); 1179 return ParsedType::make(T); 1180 } 1181 1182 // FIXME: This is context-dependent. We need to defer building the member 1183 // expression until the classification is consumed. 1184 if (FirstDecl->isCXXClassMember()) 1185 return NameClassification::ContextIndependentExpr( 1186 BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, nullptr, 1187 S)); 1188 1189 // If we already know which single declaration is referenced, just annotate 1190 // that declaration directly. 1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1192 if (Result.isSingleResult() && !ADL) 1193 return NameClassification::NonType(Result.getRepresentativeDecl()); 1194 1195 // Build an UnresolvedLookupExpr. Note that this doesn't depend on the 1196 // context in which we performed classification, so it's safe to do now. 1197 return NameClassification::ContextIndependentExpr( 1198 BuildDeclarationNameExpr(SS, Result, ADL)); 1199 } 1200 1201 ExprResult 1202 Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, 1203 SourceLocation NameLoc) { 1204 assert(getLangOpts().CPlusPlus && "ADL-only call in C?"); 1205 CXXScopeSpec SS; 1206 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1207 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 1208 } 1209 1210 ExprResult 1211 Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, 1212 IdentifierInfo *Name, 1213 SourceLocation NameLoc, 1214 bool IsAddressOfOperand) { 1215 DeclarationNameInfo NameInfo(Name, NameLoc); 1216 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 1217 NameInfo, IsAddressOfOperand, 1218 /*TemplateArgs=*/nullptr); 1219 } 1220 1221 ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, 1222 NamedDecl *Found, 1223 SourceLocation NameLoc, 1224 const Token &NextToken) { 1225 if (getCurMethodDecl() && SS.isEmpty()) 1226 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl())) 1227 return BuildIvarRefExpr(S, NameLoc, Ivar); 1228 1229 // Reconstruct the lookup result. 1230 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName); 1231 Result.addDecl(Found); 1232 Result.resolveKind(); 1233 1234 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1235 return BuildDeclarationNameExpr(SS, Result, ADL); 1236 } 1237 1238 Sema::TemplateNameKindForDiagnostics 1239 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) { 1240 auto *TD = Name.getAsTemplateDecl(); 1241 if (!TD) 1242 return TemplateNameKindForDiagnostics::DependentTemplate; 1243 if (isa<ClassTemplateDecl>(TD)) 1244 return TemplateNameKindForDiagnostics::ClassTemplate; 1245 if (isa<FunctionTemplateDecl>(TD)) 1246 return TemplateNameKindForDiagnostics::FunctionTemplate; 1247 if (isa<VarTemplateDecl>(TD)) 1248 return TemplateNameKindForDiagnostics::VarTemplate; 1249 if (isa<TypeAliasTemplateDecl>(TD)) 1250 return TemplateNameKindForDiagnostics::AliasTemplate; 1251 if (isa<TemplateTemplateParmDecl>(TD)) 1252 return TemplateNameKindForDiagnostics::TemplateTemplateParam; 1253 if (isa<ConceptDecl>(TD)) 1254 return TemplateNameKindForDiagnostics::Concept; 1255 return TemplateNameKindForDiagnostics::DependentTemplate; 1256 } 1257 1258 // Determines the context to return to after temporarily entering a 1259 // context. This depends in an unnecessarily complicated way on the 1260 // exact ordering of callbacks from the parser. 1261 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1262 1263 // Functions defined inline within classes aren't parsed until we've 1264 // finished parsing the top-level class, so the top-level class is 1265 // the context we'll need to return to. 1266 // A Lambda call operator whose parent is a class must not be treated 1267 // as an inline member function. A Lambda can be used legally 1268 // either as an in-class member initializer or a default argument. These 1269 // are parsed once the class has been marked complete and so the containing 1270 // context would be the nested class (when the lambda is defined in one); 1271 // If the class is not complete, then the lambda is being used in an 1272 // ill-formed fashion (such as to specify the width of a bit-field, or 1273 // in an array-bound) - in which case we still want to return the 1274 // lexically containing DC (which could be a nested class). 1275 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1276 DC = DC->getLexicalParent(); 1277 1278 // A function not defined within a class will always return to its 1279 // lexical context. 1280 if (!isa<CXXRecordDecl>(DC)) 1281 return DC; 1282 1283 // A C++ inline method/friend is parsed *after* the topmost class 1284 // it was declared in is fully parsed ("complete"); the topmost 1285 // class is the context we need to return to. 1286 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1287 DC = RD; 1288 1289 // Return the declaration context of the topmost class the inline method is 1290 // declared in. 1291 return DC; 1292 } 1293 1294 return DC->getLexicalParent(); 1295 } 1296 1297 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1298 assert(getContainingDC(DC) == CurContext && 1299 "The next DeclContext should be lexically contained in the current one."); 1300 CurContext = DC; 1301 S->setEntity(DC); 1302 } 1303 1304 void Sema::PopDeclContext() { 1305 assert(CurContext && "DeclContext imbalance!"); 1306 1307 CurContext = getContainingDC(CurContext); 1308 assert(CurContext && "Popped translation unit!"); 1309 } 1310 1311 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1312 Decl *D) { 1313 // Unlike PushDeclContext, the context to which we return is not necessarily 1314 // the containing DC of TD, because the new context will be some pre-existing 1315 // TagDecl definition instead of a fresh one. 1316 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1317 CurContext = cast<TagDecl>(D)->getDefinition(); 1318 assert(CurContext && "skipping definition of undefined tag"); 1319 // Start lookups from the parent of the current context; we don't want to look 1320 // into the pre-existing complete definition. 1321 S->setEntity(CurContext->getLookupParent()); 1322 return Result; 1323 } 1324 1325 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1326 CurContext = static_cast<decltype(CurContext)>(Context); 1327 } 1328 1329 /// EnterDeclaratorContext - Used when we must lookup names in the context 1330 /// of a declarator's nested name specifier. 1331 /// 1332 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1333 // C++0x [basic.lookup.unqual]p13: 1334 // A name used in the definition of a static data member of class 1335 // X (after the qualified-id of the static member) is looked up as 1336 // if the name was used in a member function of X. 1337 // C++0x [basic.lookup.unqual]p14: 1338 // If a variable member of a namespace is defined outside of the 1339 // scope of its namespace then any name used in the definition of 1340 // the variable member (after the declarator-id) is looked up as 1341 // if the definition of the variable member occurred in its 1342 // namespace. 1343 // Both of these imply that we should push a scope whose context 1344 // is the semantic context of the declaration. We can't use 1345 // PushDeclContext here because that context is not necessarily 1346 // lexically contained in the current context. Fortunately, 1347 // the containing scope should have the appropriate information. 1348 1349 assert(!S->getEntity() && "scope already has entity"); 1350 1351 #ifndef NDEBUG 1352 Scope *Ancestor = S->getParent(); 1353 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1354 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1355 #endif 1356 1357 CurContext = DC; 1358 S->setEntity(DC); 1359 } 1360 1361 void Sema::ExitDeclaratorContext(Scope *S) { 1362 assert(S->getEntity() == CurContext && "Context imbalance!"); 1363 1364 // Switch back to the lexical context. The safety of this is 1365 // enforced by an assert in EnterDeclaratorContext. 1366 Scope *Ancestor = S->getParent(); 1367 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1368 CurContext = Ancestor->getEntity(); 1369 1370 // We don't need to do anything with the scope, which is going to 1371 // disappear. 1372 } 1373 1374 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1375 // We assume that the caller has already called 1376 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1377 FunctionDecl *FD = D->getAsFunction(); 1378 if (!FD) 1379 return; 1380 1381 // Same implementation as PushDeclContext, but enters the context 1382 // from the lexical parent, rather than the top-level class. 1383 assert(CurContext == FD->getLexicalParent() && 1384 "The next DeclContext should be lexically contained in the current one."); 1385 CurContext = FD; 1386 S->setEntity(CurContext); 1387 1388 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1389 ParmVarDecl *Param = FD->getParamDecl(P); 1390 // If the parameter has an identifier, then add it to the scope 1391 if (Param->getIdentifier()) { 1392 S->AddDecl(Param); 1393 IdResolver.AddDecl(Param); 1394 } 1395 } 1396 } 1397 1398 void Sema::ActOnExitFunctionContext() { 1399 // Same implementation as PopDeclContext, but returns to the lexical parent, 1400 // rather than the top-level class. 1401 assert(CurContext && "DeclContext imbalance!"); 1402 CurContext = CurContext->getLexicalParent(); 1403 assert(CurContext && "Popped translation unit!"); 1404 } 1405 1406 /// Determine whether we allow overloading of the function 1407 /// PrevDecl with another declaration. 1408 /// 1409 /// This routine determines whether overloading is possible, not 1410 /// whether some new function is actually an overload. It will return 1411 /// true in C++ (where we can always provide overloads) or, as an 1412 /// extension, in C when the previous function is already an 1413 /// overloaded function declaration or has the "overloadable" 1414 /// attribute. 1415 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1416 ASTContext &Context, 1417 const FunctionDecl *New) { 1418 if (Context.getLangOpts().CPlusPlus) 1419 return true; 1420 1421 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1422 return true; 1423 1424 return Previous.getResultKind() == LookupResult::Found && 1425 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() || 1426 New->hasAttr<OverloadableAttr>()); 1427 } 1428 1429 /// Add this decl to the scope shadowed decl chains. 1430 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1431 // Move up the scope chain until we find the nearest enclosing 1432 // non-transparent context. The declaration will be introduced into this 1433 // scope. 1434 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1435 S = S->getParent(); 1436 1437 // Add scoped declarations into their context, so that they can be 1438 // found later. Declarations without a context won't be inserted 1439 // into any context. 1440 if (AddToContext) 1441 CurContext->addDecl(D); 1442 1443 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1444 // are function-local declarations. 1445 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1446 !D->getDeclContext()->getRedeclContext()->Equals( 1447 D->getLexicalDeclContext()->getRedeclContext()) && 1448 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1449 return; 1450 1451 // Template instantiations should also not be pushed into scope. 1452 if (isa<FunctionDecl>(D) && 1453 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1454 return; 1455 1456 // If this replaces anything in the current scope, 1457 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1458 IEnd = IdResolver.end(); 1459 for (; I != IEnd; ++I) { 1460 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1461 S->RemoveDecl(*I); 1462 IdResolver.RemoveDecl(*I); 1463 1464 // Should only need to replace one decl. 1465 break; 1466 } 1467 } 1468 1469 S->AddDecl(D); 1470 1471 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1472 // Implicitly-generated labels may end up getting generated in an order that 1473 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1474 // the label at the appropriate place in the identifier chain. 1475 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1476 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1477 if (IDC == CurContext) { 1478 if (!S->isDeclScope(*I)) 1479 continue; 1480 } else if (IDC->Encloses(CurContext)) 1481 break; 1482 } 1483 1484 IdResolver.InsertDeclAfter(I, D); 1485 } else { 1486 IdResolver.AddDecl(D); 1487 } 1488 } 1489 1490 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1491 bool AllowInlineNamespace) { 1492 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1493 } 1494 1495 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1496 DeclContext *TargetDC = DC->getPrimaryContext(); 1497 do { 1498 if (DeclContext *ScopeDC = S->getEntity()) 1499 if (ScopeDC->getPrimaryContext() == TargetDC) 1500 return S; 1501 } while ((S = S->getParent())); 1502 1503 return nullptr; 1504 } 1505 1506 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1507 DeclContext*, 1508 ASTContext&); 1509 1510 /// Filters out lookup results that don't fall within the given scope 1511 /// as determined by isDeclInScope. 1512 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1513 bool ConsiderLinkage, 1514 bool AllowInlineNamespace) { 1515 LookupResult::Filter F = R.makeFilter(); 1516 while (F.hasNext()) { 1517 NamedDecl *D = F.next(); 1518 1519 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1520 continue; 1521 1522 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1523 continue; 1524 1525 F.erase(); 1526 } 1527 1528 F.done(); 1529 } 1530 1531 /// We've determined that \p New is a redeclaration of \p Old. Check that they 1532 /// have compatible owning modules. 1533 bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) { 1534 // FIXME: The Modules TS is not clear about how friend declarations are 1535 // to be treated. It's not meaningful to have different owning modules for 1536 // linkage in redeclarations of the same entity, so for now allow the 1537 // redeclaration and change the owning modules to match. 1538 if (New->getFriendObjectKind() && 1539 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) { 1540 New->setLocalOwningModule(Old->getOwningModule()); 1541 makeMergedDefinitionVisible(New); 1542 return false; 1543 } 1544 1545 Module *NewM = New->getOwningModule(); 1546 Module *OldM = Old->getOwningModule(); 1547 1548 if (NewM && NewM->Kind == Module::PrivateModuleFragment) 1549 NewM = NewM->Parent; 1550 if (OldM && OldM->Kind == Module::PrivateModuleFragment) 1551 OldM = OldM->Parent; 1552 1553 if (NewM == OldM) 1554 return false; 1555 1556 bool NewIsModuleInterface = NewM && NewM->isModulePurview(); 1557 bool OldIsModuleInterface = OldM && OldM->isModulePurview(); 1558 if (NewIsModuleInterface || OldIsModuleInterface) { 1559 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]: 1560 // if a declaration of D [...] appears in the purview of a module, all 1561 // other such declarations shall appear in the purview of the same module 1562 Diag(New->getLocation(), diag::err_mismatched_owning_module) 1563 << New 1564 << NewIsModuleInterface 1565 << (NewIsModuleInterface ? NewM->getFullModuleName() : "") 1566 << OldIsModuleInterface 1567 << (OldIsModuleInterface ? OldM->getFullModuleName() : ""); 1568 Diag(Old->getLocation(), diag::note_previous_declaration); 1569 New->setInvalidDecl(); 1570 return true; 1571 } 1572 1573 return false; 1574 } 1575 1576 static bool isUsingDecl(NamedDecl *D) { 1577 return isa<UsingShadowDecl>(D) || 1578 isa<UnresolvedUsingTypenameDecl>(D) || 1579 isa<UnresolvedUsingValueDecl>(D); 1580 } 1581 1582 /// Removes using shadow declarations from the lookup results. 1583 static void RemoveUsingDecls(LookupResult &R) { 1584 LookupResult::Filter F = R.makeFilter(); 1585 while (F.hasNext()) 1586 if (isUsingDecl(F.next())) 1587 F.erase(); 1588 1589 F.done(); 1590 } 1591 1592 /// Check for this common pattern: 1593 /// @code 1594 /// class S { 1595 /// S(const S&); // DO NOT IMPLEMENT 1596 /// void operator=(const S&); // DO NOT IMPLEMENT 1597 /// }; 1598 /// @endcode 1599 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1600 // FIXME: Should check for private access too but access is set after we get 1601 // the decl here. 1602 if (D->doesThisDeclarationHaveABody()) 1603 return false; 1604 1605 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1606 return CD->isCopyConstructor(); 1607 return D->isCopyAssignmentOperator(); 1608 } 1609 1610 // We need this to handle 1611 // 1612 // typedef struct { 1613 // void *foo() { return 0; } 1614 // } A; 1615 // 1616 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1617 // for example. If 'A', foo will have external linkage. If we have '*A', 1618 // foo will have no linkage. Since we can't know until we get to the end 1619 // of the typedef, this function finds out if D might have non-external linkage. 1620 // Callers should verify at the end of the TU if it D has external linkage or 1621 // not. 1622 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1623 const DeclContext *DC = D->getDeclContext(); 1624 while (!DC->isTranslationUnit()) { 1625 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1626 if (!RD->hasNameForLinkage()) 1627 return true; 1628 } 1629 DC = DC->getParent(); 1630 } 1631 1632 return !D->isExternallyVisible(); 1633 } 1634 1635 // FIXME: This needs to be refactored; some other isInMainFile users want 1636 // these semantics. 1637 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1638 if (S.TUKind != TU_Complete) 1639 return false; 1640 return S.SourceMgr.isInMainFile(Loc); 1641 } 1642 1643 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1644 assert(D); 1645 1646 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1647 return false; 1648 1649 // Ignore all entities declared within templates, and out-of-line definitions 1650 // of members of class templates. 1651 if (D->getDeclContext()->isDependentContext() || 1652 D->getLexicalDeclContext()->isDependentContext()) 1653 return false; 1654 1655 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1656 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1657 return false; 1658 // A non-out-of-line declaration of a member specialization was implicitly 1659 // instantiated; it's the out-of-line declaration that we're interested in. 1660 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1661 FD->getMemberSpecializationInfo() && !FD->isOutOfLine()) 1662 return false; 1663 1664 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1665 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1666 return false; 1667 } else { 1668 // 'static inline' functions are defined in headers; don't warn. 1669 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1670 return false; 1671 } 1672 1673 if (FD->doesThisDeclarationHaveABody() && 1674 Context.DeclMustBeEmitted(FD)) 1675 return false; 1676 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1677 // Constants and utility variables are defined in headers with internal 1678 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1679 // like "inline".) 1680 if (!isMainFileLoc(*this, VD->getLocation())) 1681 return false; 1682 1683 if (Context.DeclMustBeEmitted(VD)) 1684 return false; 1685 1686 if (VD->isStaticDataMember() && 1687 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1688 return false; 1689 if (VD->isStaticDataMember() && 1690 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && 1691 VD->getMemberSpecializationInfo() && !VD->isOutOfLine()) 1692 return false; 1693 1694 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation())) 1695 return false; 1696 } else { 1697 return false; 1698 } 1699 1700 // Only warn for unused decls internal to the translation unit. 1701 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1702 // for inline functions defined in the main source file, for instance. 1703 return mightHaveNonExternalLinkage(D); 1704 } 1705 1706 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1707 if (!D) 1708 return; 1709 1710 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1711 const FunctionDecl *First = FD->getFirstDecl(); 1712 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1713 return; // First should already be in the vector. 1714 } 1715 1716 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1717 const VarDecl *First = VD->getFirstDecl(); 1718 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1719 return; // First should already be in the vector. 1720 } 1721 1722 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1723 UnusedFileScopedDecls.push_back(D); 1724 } 1725 1726 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1727 if (D->isInvalidDecl()) 1728 return false; 1729 1730 bool Referenced = false; 1731 if (auto *DD = dyn_cast<DecompositionDecl>(D)) { 1732 // For a decomposition declaration, warn if none of the bindings are 1733 // referenced, instead of if the variable itself is referenced (which 1734 // it is, by the bindings' expressions). 1735 for (auto *BD : DD->bindings()) { 1736 if (BD->isReferenced()) { 1737 Referenced = true; 1738 break; 1739 } 1740 } 1741 } else if (!D->getDeclName()) { 1742 return false; 1743 } else if (D->isReferenced() || D->isUsed()) { 1744 Referenced = true; 1745 } 1746 1747 if (Referenced || D->hasAttr<UnusedAttr>() || 1748 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1749 return false; 1750 1751 if (isa<LabelDecl>(D)) 1752 return true; 1753 1754 // Except for labels, we only care about unused decls that are local to 1755 // functions. 1756 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1757 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1758 // For dependent types, the diagnostic is deferred. 1759 WithinFunction = 1760 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1761 if (!WithinFunction) 1762 return false; 1763 1764 if (isa<TypedefNameDecl>(D)) 1765 return true; 1766 1767 // White-list anything that isn't a local variable. 1768 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1769 return false; 1770 1771 // Types of valid local variables should be complete, so this should succeed. 1772 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1773 1774 // White-list anything with an __attribute__((unused)) type. 1775 const auto *Ty = VD->getType().getTypePtr(); 1776 1777 // Only look at the outermost level of typedef. 1778 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1779 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1780 return false; 1781 } 1782 1783 // If we failed to complete the type for some reason, or if the type is 1784 // dependent, don't diagnose the variable. 1785 if (Ty->isIncompleteType() || Ty->isDependentType()) 1786 return false; 1787 1788 // Look at the element type to ensure that the warning behaviour is 1789 // consistent for both scalars and arrays. 1790 Ty = Ty->getBaseElementTypeUnsafe(); 1791 1792 if (const TagType *TT = Ty->getAs<TagType>()) { 1793 const TagDecl *Tag = TT->getDecl(); 1794 if (Tag->hasAttr<UnusedAttr>()) 1795 return false; 1796 1797 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1798 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1799 return false; 1800 1801 if (const Expr *Init = VD->getInit()) { 1802 if (const ExprWithCleanups *Cleanups = 1803 dyn_cast<ExprWithCleanups>(Init)) 1804 Init = Cleanups->getSubExpr(); 1805 const CXXConstructExpr *Construct = 1806 dyn_cast<CXXConstructExpr>(Init); 1807 if (Construct && !Construct->isElidable()) { 1808 CXXConstructorDecl *CD = Construct->getConstructor(); 1809 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() && 1810 (VD->getInit()->isValueDependent() || !VD->evaluateValue())) 1811 return false; 1812 } 1813 1814 // Suppress the warning if we don't know how this is constructed, and 1815 // it could possibly be non-trivial constructor. 1816 if (Init->isTypeDependent()) 1817 for (const CXXConstructorDecl *Ctor : RD->ctors()) 1818 if (!Ctor->isTrivial()) 1819 return false; 1820 } 1821 } 1822 } 1823 1824 // TODO: __attribute__((unused)) templates? 1825 } 1826 1827 return true; 1828 } 1829 1830 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1831 FixItHint &Hint) { 1832 if (isa<LabelDecl>(D)) { 1833 SourceLocation AfterColon = Lexer::findLocationAfterToken( 1834 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), 1835 true); 1836 if (AfterColon.isInvalid()) 1837 return; 1838 Hint = FixItHint::CreateRemoval( 1839 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon)); 1840 } 1841 } 1842 1843 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1844 if (D->getTypeForDecl()->isDependentType()) 1845 return; 1846 1847 for (auto *TmpD : D->decls()) { 1848 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1849 DiagnoseUnusedDecl(T); 1850 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1851 DiagnoseUnusedNestedTypedefs(R); 1852 } 1853 } 1854 1855 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1856 /// unless they are marked attr(unused). 1857 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1858 if (!ShouldDiagnoseUnusedDecl(D)) 1859 return; 1860 1861 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1862 // typedefs can be referenced later on, so the diagnostics are emitted 1863 // at end-of-translation-unit. 1864 UnusedLocalTypedefNameCandidates.insert(TD); 1865 return; 1866 } 1867 1868 FixItHint Hint; 1869 GenerateFixForUnusedDecl(D, Context, Hint); 1870 1871 unsigned DiagID; 1872 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1873 DiagID = diag::warn_unused_exception_param; 1874 else if (isa<LabelDecl>(D)) 1875 DiagID = diag::warn_unused_label; 1876 else 1877 DiagID = diag::warn_unused_variable; 1878 1879 Diag(D->getLocation(), DiagID) << D << Hint; 1880 } 1881 1882 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1883 // Verify that we have no forward references left. If so, there was a goto 1884 // or address of a label taken, but no definition of it. Label fwd 1885 // definitions are indicated with a null substmt which is also not a resolved 1886 // MS inline assembly label name. 1887 bool Diagnose = false; 1888 if (L->isMSAsmLabel()) 1889 Diagnose = !L->isResolvedMSAsmLabel(); 1890 else 1891 Diagnose = L->getStmt() == nullptr; 1892 if (Diagnose) 1893 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1894 } 1895 1896 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1897 S->mergeNRVOIntoParent(); 1898 1899 if (S->decl_empty()) return; 1900 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1901 "Scope shouldn't contain decls!"); 1902 1903 for (auto *TmpD : S->decls()) { 1904 assert(TmpD && "This decl didn't get pushed??"); 1905 1906 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1907 NamedDecl *D = cast<NamedDecl>(TmpD); 1908 1909 // Diagnose unused variables in this scope. 1910 if (!S->hasUnrecoverableErrorOccurred()) { 1911 DiagnoseUnusedDecl(D); 1912 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1913 DiagnoseUnusedNestedTypedefs(RD); 1914 } 1915 1916 if (!D->getDeclName()) continue; 1917 1918 // If this was a forward reference to a label, verify it was defined. 1919 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1920 CheckPoppedLabel(LD, *this); 1921 1922 // Remove this name from our lexical scope, and warn on it if we haven't 1923 // already. 1924 IdResolver.RemoveDecl(D); 1925 auto ShadowI = ShadowingDecls.find(D); 1926 if (ShadowI != ShadowingDecls.end()) { 1927 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) { 1928 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field) 1929 << D << FD << FD->getParent(); 1930 Diag(FD->getLocation(), diag::note_previous_declaration); 1931 } 1932 ShadowingDecls.erase(ShadowI); 1933 } 1934 } 1935 } 1936 1937 /// Look for an Objective-C class in the translation unit. 1938 /// 1939 /// \param Id The name of the Objective-C class we're looking for. If 1940 /// typo-correction fixes this name, the Id will be updated 1941 /// to the fixed name. 1942 /// 1943 /// \param IdLoc The location of the name in the translation unit. 1944 /// 1945 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1946 /// if there is no class with the given name. 1947 /// 1948 /// \returns The declaration of the named Objective-C class, or NULL if the 1949 /// class could not be found. 1950 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1951 SourceLocation IdLoc, 1952 bool DoTypoCorrection) { 1953 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1954 // creation from this context. 1955 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1956 1957 if (!IDecl && DoTypoCorrection) { 1958 // Perform typo correction at the given location, but only if we 1959 // find an Objective-C class name. 1960 DeclFilterCCC<ObjCInterfaceDecl> CCC{}; 1961 if (TypoCorrection C = 1962 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, 1963 TUScope, nullptr, CCC, CTK_ErrorRecovery)) { 1964 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1965 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1966 Id = IDecl->getIdentifier(); 1967 } 1968 } 1969 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1970 // This routine must always return a class definition, if any. 1971 if (Def && Def->getDefinition()) 1972 Def = Def->getDefinition(); 1973 return Def; 1974 } 1975 1976 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1977 /// from S, where a non-field would be declared. This routine copes 1978 /// with the difference between C and C++ scoping rules in structs and 1979 /// unions. For example, the following code is well-formed in C but 1980 /// ill-formed in C++: 1981 /// @code 1982 /// struct S6 { 1983 /// enum { BAR } e; 1984 /// }; 1985 /// 1986 /// void test_S6() { 1987 /// struct S6 a; 1988 /// a.e = BAR; 1989 /// } 1990 /// @endcode 1991 /// For the declaration of BAR, this routine will return a different 1992 /// scope. The scope S will be the scope of the unnamed enumeration 1993 /// within S6. In C++, this routine will return the scope associated 1994 /// with S6, because the enumeration's scope is a transparent 1995 /// context but structures can contain non-field names. In C, this 1996 /// routine will return the translation unit scope, since the 1997 /// enumeration's scope is a transparent context and structures cannot 1998 /// contain non-field names. 1999 Scope *Sema::getNonFieldDeclScope(Scope *S) { 2000 while (((S->getFlags() & Scope::DeclScope) == 0) || 2001 (S->getEntity() && S->getEntity()->isTransparentContext()) || 2002 (S->isClassScope() && !getLangOpts().CPlusPlus)) 2003 S = S->getParent(); 2004 return S; 2005 } 2006 2007 /// Looks up the declaration of "struct objc_super" and 2008 /// saves it for later use in building builtin declaration of 2009 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 2010 /// pre-existing declaration exists no action takes place. 2011 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 2012 IdentifierInfo *II) { 2013 if (!II->isStr("objc_msgSendSuper")) 2014 return; 2015 ASTContext &Context = ThisSema.Context; 2016 2017 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 2018 SourceLocation(), Sema::LookupTagName); 2019 ThisSema.LookupName(Result, S); 2020 if (Result.getResultKind() == LookupResult::Found) 2021 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 2022 Context.setObjCSuperType(Context.getTagDeclType(TD)); 2023 } 2024 2025 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, 2026 ASTContext::GetBuiltinTypeError Error) { 2027 switch (Error) { 2028 case ASTContext::GE_None: 2029 return ""; 2030 case ASTContext::GE_Missing_type: 2031 return BuiltinInfo.getHeaderName(ID); 2032 case ASTContext::GE_Missing_stdio: 2033 return "stdio.h"; 2034 case ASTContext::GE_Missing_setjmp: 2035 return "setjmp.h"; 2036 case ASTContext::GE_Missing_ucontext: 2037 return "ucontext.h"; 2038 } 2039 llvm_unreachable("unhandled error kind"); 2040 } 2041 2042 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 2043 /// file scope. lazily create a decl for it. ForRedeclaration is true 2044 /// if we're creating this built-in in anticipation of redeclaring the 2045 /// built-in. 2046 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2047 Scope *S, bool ForRedeclaration, 2048 SourceLocation Loc) { 2049 LookupPredefedObjCSuperType(*this, S, II); 2050 2051 ASTContext::GetBuiltinTypeError Error; 2052 QualType R = Context.GetBuiltinType(ID, Error); 2053 if (Error) { 2054 if (!ForRedeclaration) 2055 return nullptr; 2056 2057 // If we have a builtin without an associated type we should not emit a 2058 // warning when we were not able to find a type for it. 2059 if (Error == ASTContext::GE_Missing_type) 2060 return nullptr; 2061 2062 // If we could not find a type for setjmp it is because the jmp_buf type was 2063 // not defined prior to the setjmp declaration. 2064 if (Error == ASTContext::GE_Missing_setjmp) { 2065 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf) 2066 << Context.BuiltinInfo.getName(ID); 2067 return nullptr; 2068 } 2069 2070 // Generally, we emit a warning that the declaration requires the 2071 // appropriate header. 2072 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 2073 << getHeaderName(Context.BuiltinInfo, ID, Error) 2074 << Context.BuiltinInfo.getName(ID); 2075 return nullptr; 2076 } 2077 2078 if (!ForRedeclaration && 2079 (Context.BuiltinInfo.isPredefinedLibFunction(ID) || 2080 Context.BuiltinInfo.isHeaderDependentFunction(ID))) { 2081 Diag(Loc, diag::ext_implicit_lib_function_decl) 2082 << Context.BuiltinInfo.getName(ID) << R; 2083 if (Context.BuiltinInfo.getHeaderName(ID) && 2084 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 2085 Diag(Loc, diag::note_include_header_or_declare) 2086 << Context.BuiltinInfo.getHeaderName(ID) 2087 << Context.BuiltinInfo.getName(ID); 2088 } 2089 2090 if (R.isNull()) 2091 return nullptr; 2092 2093 DeclContext *Parent = Context.getTranslationUnitDecl(); 2094 if (getLangOpts().CPlusPlus) { 2095 LinkageSpecDecl *CLinkageDecl = 2096 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 2097 LinkageSpecDecl::lang_c, false); 2098 CLinkageDecl->setImplicit(); 2099 Parent->addDecl(CLinkageDecl); 2100 Parent = CLinkageDecl; 2101 } 2102 2103 FunctionDecl *New = FunctionDecl::Create(Context, 2104 Parent, 2105 Loc, Loc, II, R, /*TInfo=*/nullptr, 2106 SC_Extern, 2107 false, 2108 R->isFunctionProtoType()); 2109 New->setImplicit(); 2110 2111 // Create Decl objects for each parameter, adding them to the 2112 // FunctionDecl. 2113 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 2114 SmallVector<ParmVarDecl*, 16> Params; 2115 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 2116 ParmVarDecl *parm = 2117 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 2118 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 2119 SC_None, nullptr); 2120 parm->setScopeInfo(0, i); 2121 Params.push_back(parm); 2122 } 2123 New->setParams(Params); 2124 } 2125 2126 AddKnownFunctionAttributes(New); 2127 RegisterLocallyScopedExternCDecl(New, S); 2128 2129 // TUScope is the translation-unit scope to insert this function into. 2130 // FIXME: This is hideous. We need to teach PushOnScopeChains to 2131 // relate Scopes to DeclContexts, and probably eliminate CurContext 2132 // entirely, but we're not there yet. 2133 DeclContext *SavedContext = CurContext; 2134 CurContext = Parent; 2135 PushOnScopeChains(New, TUScope); 2136 CurContext = SavedContext; 2137 return New; 2138 } 2139 2140 /// Typedef declarations don't have linkage, but they still denote the same 2141 /// entity if their types are the same. 2142 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 2143 /// isSameEntity. 2144 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 2145 TypedefNameDecl *Decl, 2146 LookupResult &Previous) { 2147 // This is only interesting when modules are enabled. 2148 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 2149 return; 2150 2151 // Empty sets are uninteresting. 2152 if (Previous.empty()) 2153 return; 2154 2155 LookupResult::Filter Filter = Previous.makeFilter(); 2156 while (Filter.hasNext()) { 2157 NamedDecl *Old = Filter.next(); 2158 2159 // Non-hidden declarations are never ignored. 2160 if (S.isVisible(Old)) 2161 continue; 2162 2163 // Declarations of the same entity are not ignored, even if they have 2164 // different linkages. 2165 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2166 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 2167 Decl->getUnderlyingType())) 2168 continue; 2169 2170 // If both declarations give a tag declaration a typedef name for linkage 2171 // purposes, then they declare the same entity. 2172 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 2173 Decl->getAnonDeclWithTypedefName()) 2174 continue; 2175 } 2176 2177 Filter.erase(); 2178 } 2179 2180 Filter.done(); 2181 } 2182 2183 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 2184 QualType OldType; 2185 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 2186 OldType = OldTypedef->getUnderlyingType(); 2187 else 2188 OldType = Context.getTypeDeclType(Old); 2189 QualType NewType = New->getUnderlyingType(); 2190 2191 if (NewType->isVariablyModifiedType()) { 2192 // Must not redefine a typedef with a variably-modified type. 2193 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2194 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 2195 << Kind << NewType; 2196 if (Old->getLocation().isValid()) 2197 notePreviousDefinition(Old, New->getLocation()); 2198 New->setInvalidDecl(); 2199 return true; 2200 } 2201 2202 if (OldType != NewType && 2203 !OldType->isDependentType() && 2204 !NewType->isDependentType() && 2205 !Context.hasSameType(OldType, NewType)) { 2206 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 2207 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 2208 << Kind << NewType << OldType; 2209 if (Old->getLocation().isValid()) 2210 notePreviousDefinition(Old, New->getLocation()); 2211 New->setInvalidDecl(); 2212 return true; 2213 } 2214 return false; 2215 } 2216 2217 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 2218 /// same name and scope as a previous declaration 'Old'. Figure out 2219 /// how to resolve this situation, merging decls or emitting 2220 /// diagnostics as appropriate. If there was an error, set New to be invalid. 2221 /// 2222 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, 2223 LookupResult &OldDecls) { 2224 // If the new decl is known invalid already, don't bother doing any 2225 // merging checks. 2226 if (New->isInvalidDecl()) return; 2227 2228 // Allow multiple definitions for ObjC built-in typedefs. 2229 // FIXME: Verify the underlying types are equivalent! 2230 if (getLangOpts().ObjC) { 2231 const IdentifierInfo *TypeID = New->getIdentifier(); 2232 switch (TypeID->getLength()) { 2233 default: break; 2234 case 2: 2235 { 2236 if (!TypeID->isStr("id")) 2237 break; 2238 QualType T = New->getUnderlyingType(); 2239 if (!T->isPointerType()) 2240 break; 2241 if (!T->isVoidPointerType()) { 2242 QualType PT = T->castAs<PointerType>()->getPointeeType(); 2243 if (!PT->isStructureType()) 2244 break; 2245 } 2246 Context.setObjCIdRedefinitionType(T); 2247 // Install the built-in type for 'id', ignoring the current definition. 2248 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 2249 return; 2250 } 2251 case 5: 2252 if (!TypeID->isStr("Class")) 2253 break; 2254 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 2255 // Install the built-in type for 'Class', ignoring the current definition. 2256 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 2257 return; 2258 case 3: 2259 if (!TypeID->isStr("SEL")) 2260 break; 2261 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 2262 // Install the built-in type for 'SEL', ignoring the current definition. 2263 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 2264 return; 2265 } 2266 // Fall through - the typedef name was not a builtin type. 2267 } 2268 2269 // Verify the old decl was also a type. 2270 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 2271 if (!Old) { 2272 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2273 << New->getDeclName(); 2274 2275 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 2276 if (OldD->getLocation().isValid()) 2277 notePreviousDefinition(OldD, New->getLocation()); 2278 2279 return New->setInvalidDecl(); 2280 } 2281 2282 // If the old declaration is invalid, just give up here. 2283 if (Old->isInvalidDecl()) 2284 return New->setInvalidDecl(); 2285 2286 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 2287 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 2288 auto *NewTag = New->getAnonDeclWithTypedefName(); 2289 NamedDecl *Hidden = nullptr; 2290 if (OldTag && NewTag && 2291 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 2292 !hasVisibleDefinition(OldTag, &Hidden)) { 2293 // There is a definition of this tag, but it is not visible. Use it 2294 // instead of our tag. 2295 New->setTypeForDecl(OldTD->getTypeForDecl()); 2296 if (OldTD->isModed()) 2297 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 2298 OldTD->getUnderlyingType()); 2299 else 2300 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 2301 2302 // Make the old tag definition visible. 2303 makeMergedDefinitionVisible(Hidden); 2304 2305 // If this was an unscoped enumeration, yank all of its enumerators 2306 // out of the scope. 2307 if (isa<EnumDecl>(NewTag)) { 2308 Scope *EnumScope = getNonFieldDeclScope(S); 2309 for (auto *D : NewTag->decls()) { 2310 auto *ED = cast<EnumConstantDecl>(D); 2311 assert(EnumScope->isDeclScope(ED)); 2312 EnumScope->RemoveDecl(ED); 2313 IdResolver.RemoveDecl(ED); 2314 ED->getLexicalDeclContext()->removeDecl(ED); 2315 } 2316 } 2317 } 2318 } 2319 2320 // If the typedef types are not identical, reject them in all languages and 2321 // with any extensions enabled. 2322 if (isIncompatibleTypedef(Old, New)) 2323 return; 2324 2325 // The types match. Link up the redeclaration chain and merge attributes if 2326 // the old declaration was a typedef. 2327 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2328 New->setPreviousDecl(Typedef); 2329 mergeDeclAttributes(New, Old); 2330 } 2331 2332 if (getLangOpts().MicrosoftExt) 2333 return; 2334 2335 if (getLangOpts().CPlusPlus) { 2336 // C++ [dcl.typedef]p2: 2337 // In a given non-class scope, a typedef specifier can be used to 2338 // redefine the name of any type declared in that scope to refer 2339 // to the type to which it already refers. 2340 if (!isa<CXXRecordDecl>(CurContext)) 2341 return; 2342 2343 // C++0x [dcl.typedef]p4: 2344 // In a given class scope, a typedef specifier can be used to redefine 2345 // any class-name declared in that scope that is not also a typedef-name 2346 // to refer to the type to which it already refers. 2347 // 2348 // This wording came in via DR424, which was a correction to the 2349 // wording in DR56, which accidentally banned code like: 2350 // 2351 // struct S { 2352 // typedef struct A { } A; 2353 // }; 2354 // 2355 // in the C++03 standard. We implement the C++0x semantics, which 2356 // allow the above but disallow 2357 // 2358 // struct S { 2359 // typedef int I; 2360 // typedef int I; 2361 // }; 2362 // 2363 // since that was the intent of DR56. 2364 if (!isa<TypedefNameDecl>(Old)) 2365 return; 2366 2367 Diag(New->getLocation(), diag::err_redefinition) 2368 << New->getDeclName(); 2369 notePreviousDefinition(Old, New->getLocation()); 2370 return New->setInvalidDecl(); 2371 } 2372 2373 // Modules always permit redefinition of typedefs, as does C11. 2374 if (getLangOpts().Modules || getLangOpts().C11) 2375 return; 2376 2377 // If we have a redefinition of a typedef in C, emit a warning. This warning 2378 // is normally mapped to an error, but can be controlled with 2379 // -Wtypedef-redefinition. If either the original or the redefinition is 2380 // in a system header, don't emit this for compatibility with GCC. 2381 if (getDiagnostics().getSuppressSystemWarnings() && 2382 // Some standard types are defined implicitly in Clang (e.g. OpenCL). 2383 (Old->isImplicit() || 2384 Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2385 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2386 return; 2387 2388 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2389 << New->getDeclName(); 2390 notePreviousDefinition(Old, New->getLocation()); 2391 } 2392 2393 /// DeclhasAttr - returns true if decl Declaration already has the target 2394 /// attribute. 2395 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2396 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2397 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2398 for (const auto *i : D->attrs()) 2399 if (i->getKind() == A->getKind()) { 2400 if (Ann) { 2401 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2402 return true; 2403 continue; 2404 } 2405 // FIXME: Don't hardcode this check 2406 if (OA && isa<OwnershipAttr>(i)) 2407 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2408 return true; 2409 } 2410 2411 return false; 2412 } 2413 2414 static bool isAttributeTargetADefinition(Decl *D) { 2415 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2416 return VD->isThisDeclarationADefinition(); 2417 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2418 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2419 return true; 2420 } 2421 2422 /// Merge alignment attributes from \p Old to \p New, taking into account the 2423 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2424 /// 2425 /// \return \c true if any attributes were added to \p New. 2426 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2427 // Look for alignas attributes on Old, and pick out whichever attribute 2428 // specifies the strictest alignment requirement. 2429 AlignedAttr *OldAlignasAttr = nullptr; 2430 AlignedAttr *OldStrictestAlignAttr = nullptr; 2431 unsigned OldAlign = 0; 2432 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2433 // FIXME: We have no way of representing inherited dependent alignments 2434 // in a case like: 2435 // template<int A, int B> struct alignas(A) X; 2436 // template<int A, int B> struct alignas(B) X {}; 2437 // For now, we just ignore any alignas attributes which are not on the 2438 // definition in such a case. 2439 if (I->isAlignmentDependent()) 2440 return false; 2441 2442 if (I->isAlignas()) 2443 OldAlignasAttr = I; 2444 2445 unsigned Align = I->getAlignment(S.Context); 2446 if (Align > OldAlign) { 2447 OldAlign = Align; 2448 OldStrictestAlignAttr = I; 2449 } 2450 } 2451 2452 // Look for alignas attributes on New. 2453 AlignedAttr *NewAlignasAttr = nullptr; 2454 unsigned NewAlign = 0; 2455 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2456 if (I->isAlignmentDependent()) 2457 return false; 2458 2459 if (I->isAlignas()) 2460 NewAlignasAttr = I; 2461 2462 unsigned Align = I->getAlignment(S.Context); 2463 if (Align > NewAlign) 2464 NewAlign = Align; 2465 } 2466 2467 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2468 // Both declarations have 'alignas' attributes. We require them to match. 2469 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2470 // fall short. (If two declarations both have alignas, they must both match 2471 // every definition, and so must match each other if there is a definition.) 2472 2473 // If either declaration only contains 'alignas(0)' specifiers, then it 2474 // specifies the natural alignment for the type. 2475 if (OldAlign == 0 || NewAlign == 0) { 2476 QualType Ty; 2477 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2478 Ty = VD->getType(); 2479 else 2480 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2481 2482 if (OldAlign == 0) 2483 OldAlign = S.Context.getTypeAlign(Ty); 2484 if (NewAlign == 0) 2485 NewAlign = S.Context.getTypeAlign(Ty); 2486 } 2487 2488 if (OldAlign != NewAlign) { 2489 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2490 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2491 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2492 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2493 } 2494 } 2495 2496 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2497 // C++11 [dcl.align]p6: 2498 // if any declaration of an entity has an alignment-specifier, 2499 // every defining declaration of that entity shall specify an 2500 // equivalent alignment. 2501 // C11 6.7.5/7: 2502 // If the definition of an object does not have an alignment 2503 // specifier, any other declaration of that object shall also 2504 // have no alignment specifier. 2505 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2506 << OldAlignasAttr; 2507 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2508 << OldAlignasAttr; 2509 } 2510 2511 bool AnyAdded = false; 2512 2513 // Ensure we have an attribute representing the strictest alignment. 2514 if (OldAlign > NewAlign) { 2515 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2516 Clone->setInherited(true); 2517 New->addAttr(Clone); 2518 AnyAdded = true; 2519 } 2520 2521 // Ensure we have an alignas attribute if the old declaration had one. 2522 if (OldAlignasAttr && !NewAlignasAttr && 2523 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2524 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2525 Clone->setInherited(true); 2526 New->addAttr(Clone); 2527 AnyAdded = true; 2528 } 2529 2530 return AnyAdded; 2531 } 2532 2533 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2534 const InheritableAttr *Attr, 2535 Sema::AvailabilityMergeKind AMK) { 2536 // This function copies an attribute Attr from a previous declaration to the 2537 // new declaration D if the new declaration doesn't itself have that attribute 2538 // yet or if that attribute allows duplicates. 2539 // If you're adding a new attribute that requires logic different from 2540 // "use explicit attribute on decl if present, else use attribute from 2541 // previous decl", for example if the attribute needs to be consistent 2542 // between redeclarations, you need to call a custom merge function here. 2543 InheritableAttr *NewAttr = nullptr; 2544 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2545 NewAttr = S.mergeAvailabilityAttr( 2546 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(), 2547 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(), 2548 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK, 2549 AA->getPriority()); 2550 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2551 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility()); 2552 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2553 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility()); 2554 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2555 NewAttr = S.mergeDLLImportAttr(D, *ImportA); 2556 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2557 NewAttr = S.mergeDLLExportAttr(D, *ExportA); 2558 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2559 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(), 2560 FA->getFirstArg()); 2561 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2562 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName()); 2563 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr)) 2564 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName()); 2565 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2566 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(), 2567 IA->getInheritanceModel()); 2568 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2569 NewAttr = S.mergeAlwaysInlineAttr(D, *AA, 2570 &S.Context.Idents.get(AA->getSpelling())); 2571 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) && 2572 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) || 2573 isa<CUDAGlobalAttr>(Attr))) { 2574 // CUDA target attributes are part of function signature for 2575 // overloading purposes and must not be merged. 2576 return false; 2577 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2578 NewAttr = S.mergeMinSizeAttr(D, *MA); 2579 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2580 NewAttr = S.mergeOptimizeNoneAttr(D, *OA); 2581 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2582 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA); 2583 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2584 NewAttr = S.mergeCommonAttr(D, *CommonA); 2585 else if (isa<AlignedAttr>(Attr)) 2586 // AlignedAttrs are handled separately, because we need to handle all 2587 // such attributes on a declaration at the same time. 2588 NewAttr = nullptr; 2589 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2590 (AMK == Sema::AMK_Override || 2591 AMK == Sema::AMK_ProtocolImplementation)) 2592 NewAttr = nullptr; 2593 else if (const auto *UA = dyn_cast<UuidAttr>(Attr)) 2594 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid()); 2595 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr)) 2596 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA); 2597 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr)) 2598 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA); 2599 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr)) 2600 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2601 2602 if (NewAttr) { 2603 NewAttr->setInherited(true); 2604 D->addAttr(NewAttr); 2605 if (isa<MSInheritanceAttr>(NewAttr)) 2606 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 2607 return true; 2608 } 2609 2610 return false; 2611 } 2612 2613 static const NamedDecl *getDefinition(const Decl *D) { 2614 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2615 return TD->getDefinition(); 2616 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2617 const VarDecl *Def = VD->getDefinition(); 2618 if (Def) 2619 return Def; 2620 return VD->getActingDefinition(); 2621 } 2622 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 2623 return FD->getDefinition(); 2624 return nullptr; 2625 } 2626 2627 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2628 for (const auto *Attribute : D->attrs()) 2629 if (Attribute->getKind() == Kind) 2630 return true; 2631 return false; 2632 } 2633 2634 /// checkNewAttributesAfterDef - If we already have a definition, check that 2635 /// there are no new attributes in this declaration. 2636 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2637 if (!New->hasAttrs()) 2638 return; 2639 2640 const NamedDecl *Def = getDefinition(Old); 2641 if (!Def || Def == New) 2642 return; 2643 2644 AttrVec &NewAttributes = New->getAttrs(); 2645 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2646 const Attr *NewAttribute = NewAttributes[I]; 2647 2648 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) { 2649 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2650 Sema::SkipBodyInfo SkipBody; 2651 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2652 2653 // If we're skipping this definition, drop the "alias" attribute. 2654 if (SkipBody.ShouldSkip) { 2655 NewAttributes.erase(NewAttributes.begin() + I); 2656 --E; 2657 continue; 2658 } 2659 } else { 2660 VarDecl *VD = cast<VarDecl>(New); 2661 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2662 VarDecl::TentativeDefinition 2663 ? diag::err_alias_after_tentative 2664 : diag::err_redefinition; 2665 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2666 if (Diag == diag::err_redefinition) 2667 S.notePreviousDefinition(Def, VD->getLocation()); 2668 else 2669 S.Diag(Def->getLocation(), diag::note_previous_definition); 2670 VD->setInvalidDecl(); 2671 } 2672 ++I; 2673 continue; 2674 } 2675 2676 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2677 // Tentative definitions are only interesting for the alias check above. 2678 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2679 ++I; 2680 continue; 2681 } 2682 } 2683 2684 if (hasAttribute(Def, NewAttribute->getKind())) { 2685 ++I; 2686 continue; // regular attr merging will take care of validating this. 2687 } 2688 2689 if (isa<C11NoReturnAttr>(NewAttribute)) { 2690 // C's _Noreturn is allowed to be added to a function after it is defined. 2691 ++I; 2692 continue; 2693 } else if (isa<UuidAttr>(NewAttribute)) { 2694 // msvc will allow a subsequent definition to add an uuid to a class 2695 ++I; 2696 continue; 2697 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2698 if (AA->isAlignas()) { 2699 // C++11 [dcl.align]p6: 2700 // if any declaration of an entity has an alignment-specifier, 2701 // every defining declaration of that entity shall specify an 2702 // equivalent alignment. 2703 // C11 6.7.5/7: 2704 // If the definition of an object does not have an alignment 2705 // specifier, any other declaration of that object shall also 2706 // have no alignment specifier. 2707 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2708 << AA; 2709 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2710 << AA; 2711 NewAttributes.erase(NewAttributes.begin() + I); 2712 --E; 2713 continue; 2714 } 2715 } else if (isa<SelectAnyAttr>(NewAttribute) && 2716 cast<VarDecl>(New)->isInline() && 2717 !cast<VarDecl>(New)->isInlineSpecified()) { 2718 // Don't warn about applying selectany to implicitly inline variables. 2719 // Older compilers and language modes would require the use of selectany 2720 // to make such variables inline, and it would have no effect if we 2721 // honored it. 2722 ++I; 2723 continue; 2724 } 2725 2726 S.Diag(NewAttribute->getLocation(), 2727 diag::warn_attribute_precede_definition); 2728 S.Diag(Def->getLocation(), diag::note_previous_definition); 2729 NewAttributes.erase(NewAttributes.begin() + I); 2730 --E; 2731 } 2732 } 2733 2734 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, 2735 const ConstInitAttr *CIAttr, 2736 bool AttrBeforeInit) { 2737 SourceLocation InsertLoc = InitDecl->getInnerLocStart(); 2738 2739 // Figure out a good way to write this specifier on the old declaration. 2740 // FIXME: We should just use the spelling of CIAttr, but we don't preserve 2741 // enough of the attribute list spelling information to extract that without 2742 // heroics. 2743 std::string SuitableSpelling; 2744 if (S.getLangOpts().CPlusPlus2a) 2745 SuitableSpelling = std::string( 2746 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit})); 2747 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2748 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2749 InsertLoc, {tok::l_square, tok::l_square, 2750 S.PP.getIdentifierInfo("clang"), tok::coloncolon, 2751 S.PP.getIdentifierInfo("require_constant_initialization"), 2752 tok::r_square, tok::r_square})); 2753 if (SuitableSpelling.empty()) 2754 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling( 2755 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren, 2756 S.PP.getIdentifierInfo("require_constant_initialization"), 2757 tok::r_paren, tok::r_paren})); 2758 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus2a) 2759 SuitableSpelling = "constinit"; 2760 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11) 2761 SuitableSpelling = "[[clang::require_constant_initialization]]"; 2762 if (SuitableSpelling.empty()) 2763 SuitableSpelling = "__attribute__((require_constant_initialization))"; 2764 SuitableSpelling += " "; 2765 2766 if (AttrBeforeInit) { 2767 // extern constinit int a; 2768 // int a = 0; // error (missing 'constinit'), accepted as extension 2769 assert(CIAttr->isConstinit() && "should not diagnose this for attribute"); 2770 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing) 2771 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2772 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here); 2773 } else { 2774 // int a = 0; 2775 // constinit extern int a; // error (missing 'constinit') 2776 S.Diag(CIAttr->getLocation(), 2777 CIAttr->isConstinit() ? diag::err_constinit_added_too_late 2778 : diag::warn_require_const_init_added_too_late) 2779 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation())); 2780 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here) 2781 << CIAttr->isConstinit() 2782 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling); 2783 } 2784 } 2785 2786 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2787 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2788 AvailabilityMergeKind AMK) { 2789 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2790 UsedAttr *NewAttr = OldAttr->clone(Context); 2791 NewAttr->setInherited(true); 2792 New->addAttr(NewAttr); 2793 } 2794 2795 if (!Old->hasAttrs() && !New->hasAttrs()) 2796 return; 2797 2798 // [dcl.constinit]p1: 2799 // If the [constinit] specifier is applied to any declaration of a 2800 // variable, it shall be applied to the initializing declaration. 2801 const auto *OldConstInit = Old->getAttr<ConstInitAttr>(); 2802 const auto *NewConstInit = New->getAttr<ConstInitAttr>(); 2803 if (bool(OldConstInit) != bool(NewConstInit)) { 2804 const auto *OldVD = cast<VarDecl>(Old); 2805 auto *NewVD = cast<VarDecl>(New); 2806 2807 // Find the initializing declaration. Note that we might not have linked 2808 // the new declaration into the redeclaration chain yet. 2809 const VarDecl *InitDecl = OldVD->getInitializingDeclaration(); 2810 if (!InitDecl && 2811 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition())) 2812 InitDecl = NewVD; 2813 2814 if (InitDecl == NewVD) { 2815 // This is the initializing declaration. If it would inherit 'constinit', 2816 // that's ill-formed. (Note that we do not apply this to the attribute 2817 // form). 2818 if (OldConstInit && OldConstInit->isConstinit()) 2819 diagnoseMissingConstinit(*this, NewVD, OldConstInit, 2820 /*AttrBeforeInit=*/true); 2821 } else if (NewConstInit) { 2822 // This is the first time we've been told that this declaration should 2823 // have a constant initializer. If we already saw the initializing 2824 // declaration, this is too late. 2825 if (InitDecl && InitDecl != NewVD) { 2826 diagnoseMissingConstinit(*this, InitDecl, NewConstInit, 2827 /*AttrBeforeInit=*/false); 2828 NewVD->dropAttr<ConstInitAttr>(); 2829 } 2830 } 2831 } 2832 2833 // Attributes declared post-definition are currently ignored. 2834 checkNewAttributesAfterDef(*this, New, Old); 2835 2836 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) { 2837 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) { 2838 if (!OldA->isEquivalent(NewA)) { 2839 // This redeclaration changes __asm__ label. 2840 Diag(New->getLocation(), diag::err_different_asm_label); 2841 Diag(OldA->getLocation(), diag::note_previous_declaration); 2842 } 2843 } else if (Old->isUsed()) { 2844 // This redeclaration adds an __asm__ label to a declaration that has 2845 // already been ODR-used. 2846 Diag(New->getLocation(), diag::err_late_asm_label_name) 2847 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange(); 2848 } 2849 } 2850 2851 // Re-declaration cannot add abi_tag's. 2852 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) { 2853 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) { 2854 for (const auto &NewTag : NewAbiTagAttr->tags()) { 2855 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(), 2856 NewTag) == OldAbiTagAttr->tags_end()) { 2857 Diag(NewAbiTagAttr->getLocation(), 2858 diag::err_new_abi_tag_on_redeclaration) 2859 << NewTag; 2860 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration); 2861 } 2862 } 2863 } else { 2864 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration); 2865 Diag(Old->getLocation(), diag::note_previous_declaration); 2866 } 2867 } 2868 2869 // This redeclaration adds a section attribute. 2870 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) { 2871 if (auto *VD = dyn_cast<VarDecl>(New)) { 2872 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) { 2873 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration); 2874 Diag(Old->getLocation(), diag::note_previous_declaration); 2875 } 2876 } 2877 } 2878 2879 // Redeclaration adds code-seg attribute. 2880 const auto *NewCSA = New->getAttr<CodeSegAttr>(); 2881 if (NewCSA && !Old->hasAttr<CodeSegAttr>() && 2882 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) { 2883 Diag(New->getLocation(), diag::warn_mismatched_section) 2884 << 0 /*codeseg*/; 2885 Diag(Old->getLocation(), diag::note_previous_declaration); 2886 } 2887 2888 if (!Old->hasAttrs()) 2889 return; 2890 2891 bool foundAny = New->hasAttrs(); 2892 2893 // Ensure that any moving of objects within the allocated map is done before 2894 // we process them. 2895 if (!foundAny) New->setAttrs(AttrVec()); 2896 2897 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2898 // Ignore deprecated/unavailable/availability attributes if requested. 2899 AvailabilityMergeKind LocalAMK = AMK_None; 2900 if (isa<DeprecatedAttr>(I) || 2901 isa<UnavailableAttr>(I) || 2902 isa<AvailabilityAttr>(I)) { 2903 switch (AMK) { 2904 case AMK_None: 2905 continue; 2906 2907 case AMK_Redeclaration: 2908 case AMK_Override: 2909 case AMK_ProtocolImplementation: 2910 LocalAMK = AMK; 2911 break; 2912 } 2913 } 2914 2915 // Already handled. 2916 if (isa<UsedAttr>(I)) 2917 continue; 2918 2919 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2920 foundAny = true; 2921 } 2922 2923 if (mergeAlignedAttrs(*this, New, Old)) 2924 foundAny = true; 2925 2926 if (!foundAny) New->dropAttrs(); 2927 } 2928 2929 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2930 /// to the new one. 2931 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2932 const ParmVarDecl *oldDecl, 2933 Sema &S) { 2934 // C++11 [dcl.attr.depend]p2: 2935 // The first declaration of a function shall specify the 2936 // carries_dependency attribute for its declarator-id if any declaration 2937 // of the function specifies the carries_dependency attribute. 2938 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2939 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2940 S.Diag(CDA->getLocation(), 2941 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2942 // Find the first declaration of the parameter. 2943 // FIXME: Should we build redeclaration chains for function parameters? 2944 const FunctionDecl *FirstFD = 2945 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2946 const ParmVarDecl *FirstVD = 2947 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2948 S.Diag(FirstVD->getLocation(), 2949 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2950 } 2951 2952 if (!oldDecl->hasAttrs()) 2953 return; 2954 2955 bool foundAny = newDecl->hasAttrs(); 2956 2957 // Ensure that any moving of objects within the allocated map is 2958 // done before we process them. 2959 if (!foundAny) newDecl->setAttrs(AttrVec()); 2960 2961 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2962 if (!DeclHasAttr(newDecl, I)) { 2963 InheritableAttr *newAttr = 2964 cast<InheritableParamAttr>(I->clone(S.Context)); 2965 newAttr->setInherited(true); 2966 newDecl->addAttr(newAttr); 2967 foundAny = true; 2968 } 2969 } 2970 2971 if (!foundAny) newDecl->dropAttrs(); 2972 } 2973 2974 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2975 const ParmVarDecl *OldParam, 2976 Sema &S) { 2977 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2978 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2979 if (*Oldnullability != *Newnullability) { 2980 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2981 << DiagNullabilityKind( 2982 *Newnullability, 2983 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2984 != 0)) 2985 << DiagNullabilityKind( 2986 *Oldnullability, 2987 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2988 != 0)); 2989 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2990 } 2991 } else { 2992 QualType NewT = NewParam->getType(); 2993 NewT = S.Context.getAttributedType( 2994 AttributedType::getNullabilityAttrKind(*Oldnullability), 2995 NewT, NewT); 2996 NewParam->setType(NewT); 2997 } 2998 } 2999 } 3000 3001 namespace { 3002 3003 /// Used in MergeFunctionDecl to keep track of function parameters in 3004 /// C. 3005 struct GNUCompatibleParamWarning { 3006 ParmVarDecl *OldParm; 3007 ParmVarDecl *NewParm; 3008 QualType PromotedType; 3009 }; 3010 3011 } // end anonymous namespace 3012 3013 // Determine whether the previous declaration was a definition, implicit 3014 // declaration, or a declaration. 3015 template <typename T> 3016 static std::pair<diag::kind, SourceLocation> 3017 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 3018 diag::kind PrevDiag; 3019 SourceLocation OldLocation = Old->getLocation(); 3020 if (Old->isThisDeclarationADefinition()) 3021 PrevDiag = diag::note_previous_definition; 3022 else if (Old->isImplicit()) { 3023 PrevDiag = diag::note_previous_implicit_declaration; 3024 if (OldLocation.isInvalid()) 3025 OldLocation = New->getLocation(); 3026 } else 3027 PrevDiag = diag::note_previous_declaration; 3028 return std::make_pair(PrevDiag, OldLocation); 3029 } 3030 3031 /// canRedefineFunction - checks if a function can be redefined. Currently, 3032 /// only extern inline functions can be redefined, and even then only in 3033 /// GNU89 mode. 3034 static bool canRedefineFunction(const FunctionDecl *FD, 3035 const LangOptions& LangOpts) { 3036 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 3037 !LangOpts.CPlusPlus && 3038 FD->isInlineSpecified() && 3039 FD->getStorageClass() == SC_Extern); 3040 } 3041 3042 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 3043 const AttributedType *AT = T->getAs<AttributedType>(); 3044 while (AT && !AT->isCallingConv()) 3045 AT = AT->getModifiedType()->getAs<AttributedType>(); 3046 return AT; 3047 } 3048 3049 template <typename T> 3050 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 3051 const DeclContext *DC = Old->getDeclContext(); 3052 if (DC->isRecord()) 3053 return false; 3054 3055 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 3056 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 3057 return true; 3058 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 3059 return true; 3060 return false; 3061 } 3062 3063 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 3064 static bool isExternC(VarTemplateDecl *) { return false; } 3065 3066 /// Check whether a redeclaration of an entity introduced by a 3067 /// using-declaration is valid, given that we know it's not an overload 3068 /// (nor a hidden tag declaration). 3069 template<typename ExpectedDecl> 3070 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 3071 ExpectedDecl *New) { 3072 // C++11 [basic.scope.declarative]p4: 3073 // Given a set of declarations in a single declarative region, each of 3074 // which specifies the same unqualified name, 3075 // -- they shall all refer to the same entity, or all refer to functions 3076 // and function templates; or 3077 // -- exactly one declaration shall declare a class name or enumeration 3078 // name that is not a typedef name and the other declarations shall all 3079 // refer to the same variable or enumerator, or all refer to functions 3080 // and function templates; in this case the class name or enumeration 3081 // name is hidden (3.3.10). 3082 3083 // C++11 [namespace.udecl]p14: 3084 // If a function declaration in namespace scope or block scope has the 3085 // same name and the same parameter-type-list as a function introduced 3086 // by a using-declaration, and the declarations do not declare the same 3087 // function, the program is ill-formed. 3088 3089 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 3090 if (Old && 3091 !Old->getDeclContext()->getRedeclContext()->Equals( 3092 New->getDeclContext()->getRedeclContext()) && 3093 !(isExternC(Old) && isExternC(New))) 3094 Old = nullptr; 3095 3096 if (!Old) { 3097 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 3098 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 3099 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 3100 return true; 3101 } 3102 return false; 3103 } 3104 3105 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, 3106 const FunctionDecl *B) { 3107 assert(A->getNumParams() == B->getNumParams()); 3108 3109 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) { 3110 const auto *AttrA = A->getAttr<PassObjectSizeAttr>(); 3111 const auto *AttrB = B->getAttr<PassObjectSizeAttr>(); 3112 if (AttrA == AttrB) 3113 return true; 3114 return AttrA && AttrB && AttrA->getType() == AttrB->getType() && 3115 AttrA->isDynamic() == AttrB->isDynamic(); 3116 }; 3117 3118 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq); 3119 } 3120 3121 /// If necessary, adjust the semantic declaration context for a qualified 3122 /// declaration to name the correct inline namespace within the qualifier. 3123 static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, 3124 DeclaratorDecl *OldD) { 3125 // The only case where we need to update the DeclContext is when 3126 // redeclaration lookup for a qualified name finds a declaration 3127 // in an inline namespace within the context named by the qualifier: 3128 // 3129 // inline namespace N { int f(); } 3130 // int ::f(); // Sema DC needs adjusting from :: to N::. 3131 // 3132 // For unqualified declarations, the semantic context *can* change 3133 // along the redeclaration chain (for local extern declarations, 3134 // extern "C" declarations, and friend declarations in particular). 3135 if (!NewD->getQualifier()) 3136 return; 3137 3138 // NewD is probably already in the right context. 3139 auto *NamedDC = NewD->getDeclContext()->getRedeclContext(); 3140 auto *SemaDC = OldD->getDeclContext()->getRedeclContext(); 3141 if (NamedDC->Equals(SemaDC)) 3142 return; 3143 3144 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) || 3145 NewD->isInvalidDecl() || OldD->isInvalidDecl()) && 3146 "unexpected context for redeclaration"); 3147 3148 auto *LexDC = NewD->getLexicalDeclContext(); 3149 auto FixSemaDC = [=](NamedDecl *D) { 3150 if (!D) 3151 return; 3152 D->setDeclContext(SemaDC); 3153 D->setLexicalDeclContext(LexDC); 3154 }; 3155 3156 FixSemaDC(NewD); 3157 if (auto *FD = dyn_cast<FunctionDecl>(NewD)) 3158 FixSemaDC(FD->getDescribedFunctionTemplate()); 3159 else if (auto *VD = dyn_cast<VarDecl>(NewD)) 3160 FixSemaDC(VD->getDescribedVarTemplate()); 3161 } 3162 3163 /// MergeFunctionDecl - We just parsed a function 'New' from 3164 /// declarator D which has the same name and scope as a previous 3165 /// declaration 'Old'. Figure out how to resolve this situation, 3166 /// merging decls or emitting diagnostics as appropriate. 3167 /// 3168 /// In C++, New and Old must be declarations that are not 3169 /// overloaded. Use IsOverload to determine whether New and Old are 3170 /// overloaded, and to select the Old declaration that New should be 3171 /// merged with. 3172 /// 3173 /// Returns true if there was an error, false otherwise. 3174 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 3175 Scope *S, bool MergeTypeWithOld) { 3176 // Verify the old decl was also a function. 3177 FunctionDecl *Old = OldD->getAsFunction(); 3178 if (!Old) { 3179 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 3180 if (New->getFriendObjectKind()) { 3181 Diag(New->getLocation(), diag::err_using_decl_friend); 3182 Diag(Shadow->getTargetDecl()->getLocation(), 3183 diag::note_using_decl_target); 3184 Diag(Shadow->getUsingDecl()->getLocation(), 3185 diag::note_using_decl) << 0; 3186 return true; 3187 } 3188 3189 // Check whether the two declarations might declare the same function. 3190 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 3191 return true; 3192 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 3193 } else { 3194 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3195 << New->getDeclName(); 3196 notePreviousDefinition(OldD, New->getLocation()); 3197 return true; 3198 } 3199 } 3200 3201 // If the old declaration is invalid, just give up here. 3202 if (Old->isInvalidDecl()) 3203 return true; 3204 3205 // Disallow redeclaration of some builtins. 3206 if (!getASTContext().canBuiltinBeRedeclared(Old)) { 3207 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName(); 3208 Diag(Old->getLocation(), diag::note_previous_builtin_declaration) 3209 << Old << Old->getType(); 3210 return true; 3211 } 3212 3213 diag::kind PrevDiag; 3214 SourceLocation OldLocation; 3215 std::tie(PrevDiag, OldLocation) = 3216 getNoteDiagForInvalidRedeclaration(Old, New); 3217 3218 // Don't complain about this if we're in GNU89 mode and the old function 3219 // is an extern inline function. 3220 // Don't complain about specializations. They are not supposed to have 3221 // storage classes. 3222 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 3223 New->getStorageClass() == SC_Static && 3224 Old->hasExternalFormalLinkage() && 3225 !New->getTemplateSpecializationInfo() && 3226 !canRedefineFunction(Old, getLangOpts())) { 3227 if (getLangOpts().MicrosoftExt) { 3228 Diag(New->getLocation(), diag::ext_static_non_static) << New; 3229 Diag(OldLocation, PrevDiag); 3230 } else { 3231 Diag(New->getLocation(), diag::err_static_non_static) << New; 3232 Diag(OldLocation, PrevDiag); 3233 return true; 3234 } 3235 } 3236 3237 if (New->hasAttr<InternalLinkageAttr>() && 3238 !Old->hasAttr<InternalLinkageAttr>()) { 3239 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3240 << New->getDeclName(); 3241 notePreviousDefinition(Old, New->getLocation()); 3242 New->dropAttr<InternalLinkageAttr>(); 3243 } 3244 3245 if (CheckRedeclarationModuleOwnership(New, Old)) 3246 return true; 3247 3248 if (!getLangOpts().CPlusPlus) { 3249 bool OldOvl = Old->hasAttr<OverloadableAttr>(); 3250 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) { 3251 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch) 3252 << New << OldOvl; 3253 3254 // Try our best to find a decl that actually has the overloadable 3255 // attribute for the note. In most cases (e.g. programs with only one 3256 // broken declaration/definition), this won't matter. 3257 // 3258 // FIXME: We could do this if we juggled some extra state in 3259 // OverloadableAttr, rather than just removing it. 3260 const Decl *DiagOld = Old; 3261 if (OldOvl) { 3262 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) { 3263 const auto *A = D->getAttr<OverloadableAttr>(); 3264 return A && !A->isImplicit(); 3265 }); 3266 // If we've implicitly added *all* of the overloadable attrs to this 3267 // chain, emitting a "previous redecl" note is pointless. 3268 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter; 3269 } 3270 3271 if (DiagOld) 3272 Diag(DiagOld->getLocation(), 3273 diag::note_attribute_overloadable_prev_overload) 3274 << OldOvl; 3275 3276 if (OldOvl) 3277 New->addAttr(OverloadableAttr::CreateImplicit(Context)); 3278 else 3279 New->dropAttr<OverloadableAttr>(); 3280 } 3281 } 3282 3283 // If a function is first declared with a calling convention, but is later 3284 // declared or defined without one, all following decls assume the calling 3285 // convention of the first. 3286 // 3287 // It's OK if a function is first declared without a calling convention, 3288 // but is later declared or defined with the default calling convention. 3289 // 3290 // To test if either decl has an explicit calling convention, we look for 3291 // AttributedType sugar nodes on the type as written. If they are missing or 3292 // were canonicalized away, we assume the calling convention was implicit. 3293 // 3294 // Note also that we DO NOT return at this point, because we still have 3295 // other tests to run. 3296 QualType OldQType = Context.getCanonicalType(Old->getType()); 3297 QualType NewQType = Context.getCanonicalType(New->getType()); 3298 const FunctionType *OldType = cast<FunctionType>(OldQType); 3299 const FunctionType *NewType = cast<FunctionType>(NewQType); 3300 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 3301 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 3302 bool RequiresAdjustment = false; 3303 3304 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 3305 FunctionDecl *First = Old->getFirstDecl(); 3306 const FunctionType *FT = 3307 First->getType().getCanonicalType()->castAs<FunctionType>(); 3308 FunctionType::ExtInfo FI = FT->getExtInfo(); 3309 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 3310 if (!NewCCExplicit) { 3311 // Inherit the CC from the previous declaration if it was specified 3312 // there but not here. 3313 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3314 RequiresAdjustment = true; 3315 } else if (New->getBuiltinID()) { 3316 // Calling Conventions on a Builtin aren't really useful and setting a 3317 // default calling convention and cdecl'ing some builtin redeclarations is 3318 // common, so warn and ignore the calling convention on the redeclaration. 3319 Diag(New->getLocation(), diag::warn_cconv_unsupported) 3320 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3321 << (int)CallingConventionIgnoredReason::BuiltinFunction; 3322 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 3323 RequiresAdjustment = true; 3324 } else { 3325 // Calling conventions aren't compatible, so complain. 3326 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 3327 Diag(New->getLocation(), diag::err_cconv_change) 3328 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 3329 << !FirstCCExplicit 3330 << (!FirstCCExplicit ? "" : 3331 FunctionType::getNameForCallConv(FI.getCC())); 3332 3333 // Put the note on the first decl, since it is the one that matters. 3334 Diag(First->getLocation(), diag::note_previous_declaration); 3335 return true; 3336 } 3337 } 3338 3339 // FIXME: diagnose the other way around? 3340 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 3341 NewTypeInfo = NewTypeInfo.withNoReturn(true); 3342 RequiresAdjustment = true; 3343 } 3344 3345 // Merge regparm attribute. 3346 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 3347 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 3348 if (NewTypeInfo.getHasRegParm()) { 3349 Diag(New->getLocation(), diag::err_regparm_mismatch) 3350 << NewType->getRegParmType() 3351 << OldType->getRegParmType(); 3352 Diag(OldLocation, diag::note_previous_declaration); 3353 return true; 3354 } 3355 3356 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 3357 RequiresAdjustment = true; 3358 } 3359 3360 // Merge ns_returns_retained attribute. 3361 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 3362 if (NewTypeInfo.getProducesResult()) { 3363 Diag(New->getLocation(), diag::err_function_attribute_mismatch) 3364 << "'ns_returns_retained'"; 3365 Diag(OldLocation, diag::note_previous_declaration); 3366 return true; 3367 } 3368 3369 NewTypeInfo = NewTypeInfo.withProducesResult(true); 3370 RequiresAdjustment = true; 3371 } 3372 3373 if (OldTypeInfo.getNoCallerSavedRegs() != 3374 NewTypeInfo.getNoCallerSavedRegs()) { 3375 if (NewTypeInfo.getNoCallerSavedRegs()) { 3376 AnyX86NoCallerSavedRegistersAttr *Attr = 3377 New->getAttr<AnyX86NoCallerSavedRegistersAttr>(); 3378 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr; 3379 Diag(OldLocation, diag::note_previous_declaration); 3380 return true; 3381 } 3382 3383 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true); 3384 RequiresAdjustment = true; 3385 } 3386 3387 if (RequiresAdjustment) { 3388 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 3389 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 3390 New->setType(QualType(AdjustedType, 0)); 3391 NewQType = Context.getCanonicalType(New->getType()); 3392 } 3393 3394 // If this redeclaration makes the function inline, we may need to add it to 3395 // UndefinedButUsed. 3396 if (!Old->isInlined() && New->isInlined() && 3397 !New->hasAttr<GNUInlineAttr>() && 3398 !getLangOpts().GNUInline && 3399 Old->isUsed(false) && 3400 !Old->isDefined() && !New->isThisDeclarationADefinition()) 3401 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 3402 SourceLocation())); 3403 3404 // If this redeclaration makes it newly gnu_inline, we don't want to warn 3405 // about it. 3406 if (New->hasAttr<GNUInlineAttr>() && 3407 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 3408 UndefinedButUsed.erase(Old->getCanonicalDecl()); 3409 } 3410 3411 // If pass_object_size params don't match up perfectly, this isn't a valid 3412 // redeclaration. 3413 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() && 3414 !hasIdenticalPassObjectSizeAttrs(Old, New)) { 3415 Diag(New->getLocation(), diag::err_different_pass_object_size_params) 3416 << New->getDeclName(); 3417 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3418 return true; 3419 } 3420 3421 if (getLangOpts().CPlusPlus) { 3422 // C++1z [over.load]p2 3423 // Certain function declarations cannot be overloaded: 3424 // -- Function declarations that differ only in the return type, 3425 // the exception specification, or both cannot be overloaded. 3426 3427 // Check the exception specifications match. This may recompute the type of 3428 // both Old and New if it resolved exception specifications, so grab the 3429 // types again after this. Because this updates the type, we do this before 3430 // any of the other checks below, which may update the "de facto" NewQType 3431 // but do not necessarily update the type of New. 3432 if (CheckEquivalentExceptionSpec(Old, New)) 3433 return true; 3434 OldQType = Context.getCanonicalType(Old->getType()); 3435 NewQType = Context.getCanonicalType(New->getType()); 3436 3437 // Go back to the type source info to compare the declared return types, 3438 // per C++1y [dcl.type.auto]p13: 3439 // Redeclarations or specializations of a function or function template 3440 // with a declared return type that uses a placeholder type shall also 3441 // use that placeholder, not a deduced type. 3442 QualType OldDeclaredReturnType = Old->getDeclaredReturnType(); 3443 QualType NewDeclaredReturnType = New->getDeclaredReturnType(); 3444 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 3445 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType, 3446 OldDeclaredReturnType)) { 3447 QualType ResQT; 3448 if (NewDeclaredReturnType->isObjCObjectPointerType() && 3449 OldDeclaredReturnType->isObjCObjectPointerType()) 3450 // FIXME: This does the wrong thing for a deduced return type. 3451 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 3452 if (ResQT.isNull()) { 3453 if (New->isCXXClassMember() && New->isOutOfLine()) 3454 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 3455 << New << New->getReturnTypeSourceRange(); 3456 else 3457 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 3458 << New->getReturnTypeSourceRange(); 3459 Diag(OldLocation, PrevDiag) << Old << Old->getType() 3460 << Old->getReturnTypeSourceRange(); 3461 return true; 3462 } 3463 else 3464 NewQType = ResQT; 3465 } 3466 3467 QualType OldReturnType = OldType->getReturnType(); 3468 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 3469 if (OldReturnType != NewReturnType) { 3470 // If this function has a deduced return type and has already been 3471 // defined, copy the deduced value from the old declaration. 3472 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 3473 if (OldAT && OldAT->isDeduced()) { 3474 New->setType( 3475 SubstAutoType(New->getType(), 3476 OldAT->isDependentType() ? Context.DependentTy 3477 : OldAT->getDeducedType())); 3478 NewQType = Context.getCanonicalType( 3479 SubstAutoType(NewQType, 3480 OldAT->isDependentType() ? Context.DependentTy 3481 : OldAT->getDeducedType())); 3482 } 3483 } 3484 3485 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 3486 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 3487 if (OldMethod && NewMethod) { 3488 // Preserve triviality. 3489 NewMethod->setTrivial(OldMethod->isTrivial()); 3490 3491 // MSVC allows explicit template specialization at class scope: 3492 // 2 CXXMethodDecls referring to the same function will be injected. 3493 // We don't want a redeclaration error. 3494 bool IsClassScopeExplicitSpecialization = 3495 OldMethod->isFunctionTemplateSpecialization() && 3496 NewMethod->isFunctionTemplateSpecialization(); 3497 bool isFriend = NewMethod->getFriendObjectKind(); 3498 3499 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 3500 !IsClassScopeExplicitSpecialization) { 3501 // -- Member function declarations with the same name and the 3502 // same parameter types cannot be overloaded if any of them 3503 // is a static member function declaration. 3504 if (OldMethod->isStatic() != NewMethod->isStatic()) { 3505 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 3506 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3507 return true; 3508 } 3509 3510 // C++ [class.mem]p1: 3511 // [...] A member shall not be declared twice in the 3512 // member-specification, except that a nested class or member 3513 // class template can be declared and then later defined. 3514 if (!inTemplateInstantiation()) { 3515 unsigned NewDiag; 3516 if (isa<CXXConstructorDecl>(OldMethod)) 3517 NewDiag = diag::err_constructor_redeclared; 3518 else if (isa<CXXDestructorDecl>(NewMethod)) 3519 NewDiag = diag::err_destructor_redeclared; 3520 else if (isa<CXXConversionDecl>(NewMethod)) 3521 NewDiag = diag::err_conv_function_redeclared; 3522 else 3523 NewDiag = diag::err_member_redeclared; 3524 3525 Diag(New->getLocation(), NewDiag); 3526 } else { 3527 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 3528 << New << New->getType(); 3529 } 3530 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3531 return true; 3532 3533 // Complain if this is an explicit declaration of a special 3534 // member that was initially declared implicitly. 3535 // 3536 // As an exception, it's okay to befriend such methods in order 3537 // to permit the implicit constructor/destructor/operator calls. 3538 } else if (OldMethod->isImplicit()) { 3539 if (isFriend) { 3540 NewMethod->setImplicit(); 3541 } else { 3542 Diag(NewMethod->getLocation(), 3543 diag::err_definition_of_implicitly_declared_member) 3544 << New << getSpecialMember(OldMethod); 3545 return true; 3546 } 3547 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) { 3548 Diag(NewMethod->getLocation(), 3549 diag::err_definition_of_explicitly_defaulted_member) 3550 << getSpecialMember(OldMethod); 3551 return true; 3552 } 3553 } 3554 3555 // C++11 [dcl.attr.noreturn]p1: 3556 // The first declaration of a function shall specify the noreturn 3557 // attribute if any declaration of that function specifies the noreturn 3558 // attribute. 3559 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 3560 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 3561 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 3562 Diag(Old->getFirstDecl()->getLocation(), 3563 diag::note_noreturn_missing_first_decl); 3564 } 3565 3566 // C++11 [dcl.attr.depend]p2: 3567 // The first declaration of a function shall specify the 3568 // carries_dependency attribute for its declarator-id if any declaration 3569 // of the function specifies the carries_dependency attribute. 3570 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 3571 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 3572 Diag(CDA->getLocation(), 3573 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 3574 Diag(Old->getFirstDecl()->getLocation(), 3575 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 3576 } 3577 3578 // (C++98 8.3.5p3): 3579 // All declarations for a function shall agree exactly in both the 3580 // return type and the parameter-type-list. 3581 // We also want to respect all the extended bits except noreturn. 3582 3583 // noreturn should now match unless the old type info didn't have it. 3584 QualType OldQTypeForComparison = OldQType; 3585 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 3586 auto *OldType = OldQType->castAs<FunctionProtoType>(); 3587 const FunctionType *OldTypeForComparison 3588 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 3589 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 3590 assert(OldQTypeForComparison.isCanonical()); 3591 } 3592 3593 if (haveIncompatibleLanguageLinkages(Old, New)) { 3594 // As a special case, retain the language linkage from previous 3595 // declarations of a friend function as an extension. 3596 // 3597 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 3598 // and is useful because there's otherwise no way to specify language 3599 // linkage within class scope. 3600 // 3601 // Check cautiously as the friend object kind isn't yet complete. 3602 if (New->getFriendObjectKind() != Decl::FOK_None) { 3603 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 3604 Diag(OldLocation, PrevDiag); 3605 } else { 3606 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3607 Diag(OldLocation, PrevDiag); 3608 return true; 3609 } 3610 } 3611 3612 // If the function types are compatible, merge the declarations. Ignore the 3613 // exception specifier because it was already checked above in 3614 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics 3615 // about incompatible types under -fms-compatibility. 3616 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison, 3617 NewQType)) 3618 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3619 3620 // If the types are imprecise (due to dependent constructs in friends or 3621 // local extern declarations), it's OK if they differ. We'll check again 3622 // during instantiation. 3623 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType)) 3624 return false; 3625 3626 // Fall through for conflicting redeclarations and redefinitions. 3627 } 3628 3629 // C: Function types need to be compatible, not identical. This handles 3630 // duplicate function decls like "void f(int); void f(enum X);" properly. 3631 if (!getLangOpts().CPlusPlus && 3632 Context.typesAreCompatible(OldQType, NewQType)) { 3633 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 3634 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 3635 const FunctionProtoType *OldProto = nullptr; 3636 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 3637 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 3638 // The old declaration provided a function prototype, but the 3639 // new declaration does not. Merge in the prototype. 3640 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3641 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3642 NewQType = 3643 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3644 OldProto->getExtProtoInfo()); 3645 New->setType(NewQType); 3646 New->setHasInheritedPrototype(); 3647 3648 // Synthesize parameters with the same types. 3649 SmallVector<ParmVarDecl*, 16> Params; 3650 for (const auto &ParamType : OldProto->param_types()) { 3651 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3652 SourceLocation(), nullptr, 3653 ParamType, /*TInfo=*/nullptr, 3654 SC_None, nullptr); 3655 Param->setScopeInfo(0, Params.size()); 3656 Param->setImplicit(); 3657 Params.push_back(Param); 3658 } 3659 3660 New->setParams(Params); 3661 } 3662 3663 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3664 } 3665 3666 // Check if the function types are compatible when pointer size address 3667 // spaces are ignored. 3668 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType)) 3669 return false; 3670 3671 // GNU C permits a K&R definition to follow a prototype declaration 3672 // if the declared types of the parameters in the K&R definition 3673 // match the types in the prototype declaration, even when the 3674 // promoted types of the parameters from the K&R definition differ 3675 // from the types in the prototype. GCC then keeps the types from 3676 // the prototype. 3677 // 3678 // If a variadic prototype is followed by a non-variadic K&R definition, 3679 // the K&R definition becomes variadic. This is sort of an edge case, but 3680 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3681 // C99 6.9.1p8. 3682 if (!getLangOpts().CPlusPlus && 3683 Old->hasPrototype() && !New->hasPrototype() && 3684 New->getType()->getAs<FunctionProtoType>() && 3685 Old->getNumParams() == New->getNumParams()) { 3686 SmallVector<QualType, 16> ArgTypes; 3687 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3688 const FunctionProtoType *OldProto 3689 = Old->getType()->getAs<FunctionProtoType>(); 3690 const FunctionProtoType *NewProto 3691 = New->getType()->getAs<FunctionProtoType>(); 3692 3693 // Determine whether this is the GNU C extension. 3694 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3695 NewProto->getReturnType()); 3696 bool LooseCompatible = !MergedReturn.isNull(); 3697 for (unsigned Idx = 0, End = Old->getNumParams(); 3698 LooseCompatible && Idx != End; ++Idx) { 3699 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3700 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3701 if (Context.typesAreCompatible(OldParm->getType(), 3702 NewProto->getParamType(Idx))) { 3703 ArgTypes.push_back(NewParm->getType()); 3704 } else if (Context.typesAreCompatible(OldParm->getType(), 3705 NewParm->getType(), 3706 /*CompareUnqualified=*/true)) { 3707 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3708 NewProto->getParamType(Idx) }; 3709 Warnings.push_back(Warn); 3710 ArgTypes.push_back(NewParm->getType()); 3711 } else 3712 LooseCompatible = false; 3713 } 3714 3715 if (LooseCompatible) { 3716 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3717 Diag(Warnings[Warn].NewParm->getLocation(), 3718 diag::ext_param_promoted_not_compatible_with_prototype) 3719 << Warnings[Warn].PromotedType 3720 << Warnings[Warn].OldParm->getType(); 3721 if (Warnings[Warn].OldParm->getLocation().isValid()) 3722 Diag(Warnings[Warn].OldParm->getLocation(), 3723 diag::note_previous_declaration); 3724 } 3725 3726 if (MergeTypeWithOld) 3727 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3728 OldProto->getExtProtoInfo())); 3729 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3730 } 3731 3732 // Fall through to diagnose conflicting types. 3733 } 3734 3735 // A function that has already been declared has been redeclared or 3736 // defined with a different type; show an appropriate diagnostic. 3737 3738 // If the previous declaration was an implicitly-generated builtin 3739 // declaration, then at the very least we should use a specialized note. 3740 unsigned BuiltinID; 3741 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3742 // If it's actually a library-defined builtin function like 'malloc' 3743 // or 'printf', just warn about the incompatible redeclaration. 3744 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3745 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3746 Diag(OldLocation, diag::note_previous_builtin_declaration) 3747 << Old << Old->getType(); 3748 3749 // If this is a global redeclaration, just forget hereafter 3750 // about the "builtin-ness" of the function. 3751 // 3752 // Doing this for local extern declarations is problematic. If 3753 // the builtin declaration remains visible, a second invalid 3754 // local declaration will produce a hard error; if it doesn't 3755 // remain visible, a single bogus local redeclaration (which is 3756 // actually only a warning) could break all the downstream code. 3757 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3758 New->getIdentifier()->revertBuiltin(); 3759 3760 return false; 3761 } 3762 3763 PrevDiag = diag::note_previous_builtin_declaration; 3764 } 3765 3766 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3767 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3768 return true; 3769 } 3770 3771 /// Completes the merge of two function declarations that are 3772 /// known to be compatible. 3773 /// 3774 /// This routine handles the merging of attributes and other 3775 /// properties of function declarations from the old declaration to 3776 /// the new declaration, once we know that New is in fact a 3777 /// redeclaration of Old. 3778 /// 3779 /// \returns false 3780 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3781 Scope *S, bool MergeTypeWithOld) { 3782 // Merge the attributes 3783 mergeDeclAttributes(New, Old); 3784 3785 // Merge "pure" flag. 3786 if (Old->isPure()) 3787 New->setPure(); 3788 3789 // Merge "used" flag. 3790 if (Old->getMostRecentDecl()->isUsed(false)) 3791 New->setIsUsed(); 3792 3793 // Merge attributes from the parameters. These can mismatch with K&R 3794 // declarations. 3795 if (New->getNumParams() == Old->getNumParams()) 3796 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3797 ParmVarDecl *NewParam = New->getParamDecl(i); 3798 ParmVarDecl *OldParam = Old->getParamDecl(i); 3799 mergeParamDeclAttributes(NewParam, OldParam, *this); 3800 mergeParamDeclTypes(NewParam, OldParam, *this); 3801 } 3802 3803 if (getLangOpts().CPlusPlus) 3804 return MergeCXXFunctionDecl(New, Old, S); 3805 3806 // Merge the function types so the we get the composite types for the return 3807 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3808 // was visible. 3809 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3810 if (!Merged.isNull() && MergeTypeWithOld) 3811 New->setType(Merged); 3812 3813 return false; 3814 } 3815 3816 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3817 ObjCMethodDecl *oldMethod) { 3818 // Merge the attributes, including deprecated/unavailable 3819 AvailabilityMergeKind MergeKind = 3820 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3821 ? AMK_ProtocolImplementation 3822 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3823 : AMK_Override; 3824 3825 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3826 3827 // Merge attributes from the parameters. 3828 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3829 oe = oldMethod->param_end(); 3830 for (ObjCMethodDecl::param_iterator 3831 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3832 ni != ne && oi != oe; ++ni, ++oi) 3833 mergeParamDeclAttributes(*ni, *oi, *this); 3834 3835 CheckObjCMethodOverride(newMethod, oldMethod); 3836 } 3837 3838 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) { 3839 assert(!S.Context.hasSameType(New->getType(), Old->getType())); 3840 3841 S.Diag(New->getLocation(), New->isThisDeclarationADefinition() 3842 ? diag::err_redefinition_different_type 3843 : diag::err_redeclaration_different_type) 3844 << New->getDeclName() << New->getType() << Old->getType(); 3845 3846 diag::kind PrevDiag; 3847 SourceLocation OldLocation; 3848 std::tie(PrevDiag, OldLocation) 3849 = getNoteDiagForInvalidRedeclaration(Old, New); 3850 S.Diag(OldLocation, PrevDiag); 3851 New->setInvalidDecl(); 3852 } 3853 3854 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3855 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3856 /// emitting diagnostics as appropriate. 3857 /// 3858 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3859 /// to here in AddInitializerToDecl. We can't check them before the initializer 3860 /// is attached. 3861 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3862 bool MergeTypeWithOld) { 3863 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3864 return; 3865 3866 QualType MergedT; 3867 if (getLangOpts().CPlusPlus) { 3868 if (New->getType()->isUndeducedType()) { 3869 // We don't know what the new type is until the initializer is attached. 3870 return; 3871 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3872 // These could still be something that needs exception specs checked. 3873 return MergeVarDeclExceptionSpecs(New, Old); 3874 } 3875 // C++ [basic.link]p10: 3876 // [...] the types specified by all declarations referring to a given 3877 // object or function shall be identical, except that declarations for an 3878 // array object can specify array types that differ by the presence or 3879 // absence of a major array bound (8.3.4). 3880 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) { 3881 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3882 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3883 3884 // We are merging a variable declaration New into Old. If it has an array 3885 // bound, and that bound differs from Old's bound, we should diagnose the 3886 // mismatch. 3887 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) { 3888 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD; 3889 PrevVD = PrevVD->getPreviousDecl()) { 3890 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType()); 3891 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType()) 3892 continue; 3893 3894 if (!Context.hasSameType(NewArray, PrevVDTy)) 3895 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD); 3896 } 3897 } 3898 3899 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) { 3900 if (Context.hasSameType(OldArray->getElementType(), 3901 NewArray->getElementType())) 3902 MergedT = New->getType(); 3903 } 3904 // FIXME: Check visibility. New is hidden but has a complete type. If New 3905 // has no array bound, it should not inherit one from Old, if Old is not 3906 // visible. 3907 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) { 3908 if (Context.hasSameType(OldArray->getElementType(), 3909 NewArray->getElementType())) 3910 MergedT = Old->getType(); 3911 } 3912 } 3913 else if (New->getType()->isObjCObjectPointerType() && 3914 Old->getType()->isObjCObjectPointerType()) { 3915 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3916 Old->getType()); 3917 } 3918 } else { 3919 // C 6.2.7p2: 3920 // All declarations that refer to the same object or function shall have 3921 // compatible type. 3922 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3923 } 3924 if (MergedT.isNull()) { 3925 // It's OK if we couldn't merge types if either type is dependent, for a 3926 // block-scope variable. In other cases (static data members of class 3927 // templates, variable templates, ...), we require the types to be 3928 // equivalent. 3929 // FIXME: The C++ standard doesn't say anything about this. 3930 if ((New->getType()->isDependentType() || 3931 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3932 // If the old type was dependent, we can't merge with it, so the new type 3933 // becomes dependent for now. We'll reproduce the original type when we 3934 // instantiate the TypeSourceInfo for the variable. 3935 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3936 New->setType(Context.DependentTy); 3937 return; 3938 } 3939 return diagnoseVarDeclTypeMismatch(*this, New, Old); 3940 } 3941 3942 // Don't actually update the type on the new declaration if the old 3943 // declaration was an extern declaration in a different scope. 3944 if (MergeTypeWithOld) 3945 New->setType(MergedT); 3946 } 3947 3948 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3949 LookupResult &Previous) { 3950 // C11 6.2.7p4: 3951 // For an identifier with internal or external linkage declared 3952 // in a scope in which a prior declaration of that identifier is 3953 // visible, if the prior declaration specifies internal or 3954 // external linkage, the type of the identifier at the later 3955 // declaration becomes the composite type. 3956 // 3957 // If the variable isn't visible, we do not merge with its type. 3958 if (Previous.isShadowed()) 3959 return false; 3960 3961 if (S.getLangOpts().CPlusPlus) { 3962 // C++11 [dcl.array]p3: 3963 // If there is a preceding declaration of the entity in the same 3964 // scope in which the bound was specified, an omitted array bound 3965 // is taken to be the same as in that earlier declaration. 3966 return NewVD->isPreviousDeclInSameBlockScope() || 3967 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3968 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3969 } else { 3970 // If the old declaration was function-local, don't merge with its 3971 // type unless we're in the same function. 3972 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3973 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3974 } 3975 } 3976 3977 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3978 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3979 /// situation, merging decls or emitting diagnostics as appropriate. 3980 /// 3981 /// Tentative definition rules (C99 6.9.2p2) are checked by 3982 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3983 /// definitions here, since the initializer hasn't been attached. 3984 /// 3985 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3986 // If the new decl is already invalid, don't do any other checking. 3987 if (New->isInvalidDecl()) 3988 return; 3989 3990 if (!shouldLinkPossiblyHiddenDecl(Previous, New)) 3991 return; 3992 3993 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3994 3995 // Verify the old decl was also a variable or variable template. 3996 VarDecl *Old = nullptr; 3997 VarTemplateDecl *OldTemplate = nullptr; 3998 if (Previous.isSingleResult()) { 3999 if (NewTemplate) { 4000 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 4001 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 4002 4003 if (auto *Shadow = 4004 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4005 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 4006 return New->setInvalidDecl(); 4007 } else { 4008 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 4009 4010 if (auto *Shadow = 4011 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 4012 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 4013 return New->setInvalidDecl(); 4014 } 4015 } 4016 if (!Old) { 4017 Diag(New->getLocation(), diag::err_redefinition_different_kind) 4018 << New->getDeclName(); 4019 notePreviousDefinition(Previous.getRepresentativeDecl(), 4020 New->getLocation()); 4021 return New->setInvalidDecl(); 4022 } 4023 4024 // Ensure the template parameters are compatible. 4025 if (NewTemplate && 4026 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 4027 OldTemplate->getTemplateParameters(), 4028 /*Complain=*/true, TPL_TemplateMatch)) 4029 return New->setInvalidDecl(); 4030 4031 // C++ [class.mem]p1: 4032 // A member shall not be declared twice in the member-specification [...] 4033 // 4034 // Here, we need only consider static data members. 4035 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 4036 Diag(New->getLocation(), diag::err_duplicate_member) 4037 << New->getIdentifier(); 4038 Diag(Old->getLocation(), diag::note_previous_declaration); 4039 New->setInvalidDecl(); 4040 } 4041 4042 mergeDeclAttributes(New, Old); 4043 // Warn if an already-declared variable is made a weak_import in a subsequent 4044 // declaration 4045 if (New->hasAttr<WeakImportAttr>() && 4046 Old->getStorageClass() == SC_None && 4047 !Old->hasAttr<WeakImportAttr>()) { 4048 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 4049 notePreviousDefinition(Old, New->getLocation()); 4050 // Remove weak_import attribute on new declaration. 4051 New->dropAttr<WeakImportAttr>(); 4052 } 4053 4054 if (New->hasAttr<InternalLinkageAttr>() && 4055 !Old->hasAttr<InternalLinkageAttr>()) { 4056 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 4057 << New->getDeclName(); 4058 notePreviousDefinition(Old, New->getLocation()); 4059 New->dropAttr<InternalLinkageAttr>(); 4060 } 4061 4062 // Merge the types. 4063 VarDecl *MostRecent = Old->getMostRecentDecl(); 4064 if (MostRecent != Old) { 4065 MergeVarDeclTypes(New, MostRecent, 4066 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 4067 if (New->isInvalidDecl()) 4068 return; 4069 } 4070 4071 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 4072 if (New->isInvalidDecl()) 4073 return; 4074 4075 diag::kind PrevDiag; 4076 SourceLocation OldLocation; 4077 std::tie(PrevDiag, OldLocation) = 4078 getNoteDiagForInvalidRedeclaration(Old, New); 4079 4080 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 4081 if (New->getStorageClass() == SC_Static && 4082 !New->isStaticDataMember() && 4083 Old->hasExternalFormalLinkage()) { 4084 if (getLangOpts().MicrosoftExt) { 4085 Diag(New->getLocation(), diag::ext_static_non_static) 4086 << New->getDeclName(); 4087 Diag(OldLocation, PrevDiag); 4088 } else { 4089 Diag(New->getLocation(), diag::err_static_non_static) 4090 << New->getDeclName(); 4091 Diag(OldLocation, PrevDiag); 4092 return New->setInvalidDecl(); 4093 } 4094 } 4095 // C99 6.2.2p4: 4096 // For an identifier declared with the storage-class specifier 4097 // extern in a scope in which a prior declaration of that 4098 // identifier is visible,23) if the prior declaration specifies 4099 // internal or external linkage, the linkage of the identifier at 4100 // the later declaration is the same as the linkage specified at 4101 // the prior declaration. If no prior declaration is visible, or 4102 // if the prior declaration specifies no linkage, then the 4103 // identifier has external linkage. 4104 if (New->hasExternalStorage() && Old->hasLinkage()) 4105 /* Okay */; 4106 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 4107 !New->isStaticDataMember() && 4108 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 4109 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 4110 Diag(OldLocation, PrevDiag); 4111 return New->setInvalidDecl(); 4112 } 4113 4114 // Check if extern is followed by non-extern and vice-versa. 4115 if (New->hasExternalStorage() && 4116 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 4117 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 4118 Diag(OldLocation, PrevDiag); 4119 return New->setInvalidDecl(); 4120 } 4121 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 4122 !New->hasExternalStorage()) { 4123 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 4124 Diag(OldLocation, PrevDiag); 4125 return New->setInvalidDecl(); 4126 } 4127 4128 if (CheckRedeclarationModuleOwnership(New, Old)) 4129 return; 4130 4131 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 4132 4133 // FIXME: The test for external storage here seems wrong? We still 4134 // need to check for mismatches. 4135 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 4136 // Don't complain about out-of-line definitions of static members. 4137 !(Old->getLexicalDeclContext()->isRecord() && 4138 !New->getLexicalDeclContext()->isRecord())) { 4139 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 4140 Diag(OldLocation, PrevDiag); 4141 return New->setInvalidDecl(); 4142 } 4143 4144 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) { 4145 if (VarDecl *Def = Old->getDefinition()) { 4146 // C++1z [dcl.fcn.spec]p4: 4147 // If the definition of a variable appears in a translation unit before 4148 // its first declaration as inline, the program is ill-formed. 4149 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New; 4150 Diag(Def->getLocation(), diag::note_previous_definition); 4151 } 4152 } 4153 4154 // If this redeclaration makes the variable inline, we may need to add it to 4155 // UndefinedButUsed. 4156 if (!Old->isInline() && New->isInline() && Old->isUsed(false) && 4157 !Old->getDefinition() && !New->isThisDeclarationADefinition()) 4158 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 4159 SourceLocation())); 4160 4161 if (New->getTLSKind() != Old->getTLSKind()) { 4162 if (!Old->getTLSKind()) { 4163 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 4164 Diag(OldLocation, PrevDiag); 4165 } else if (!New->getTLSKind()) { 4166 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 4167 Diag(OldLocation, PrevDiag); 4168 } else { 4169 // Do not allow redeclaration to change the variable between requiring 4170 // static and dynamic initialization. 4171 // FIXME: GCC allows this, but uses the TLS keyword on the first 4172 // declaration to determine the kind. Do we need to be compatible here? 4173 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 4174 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 4175 Diag(OldLocation, PrevDiag); 4176 } 4177 } 4178 4179 // C++ doesn't have tentative definitions, so go right ahead and check here. 4180 if (getLangOpts().CPlusPlus && 4181 New->isThisDeclarationADefinition() == VarDecl::Definition) { 4182 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() && 4183 Old->getCanonicalDecl()->isConstexpr()) { 4184 // This definition won't be a definition any more once it's been merged. 4185 Diag(New->getLocation(), 4186 diag::warn_deprecated_redundant_constexpr_static_def); 4187 } else if (VarDecl *Def = Old->getDefinition()) { 4188 if (checkVarDeclRedefinition(Def, New)) 4189 return; 4190 } 4191 } 4192 4193 if (haveIncompatibleLanguageLinkages(Old, New)) { 4194 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 4195 Diag(OldLocation, PrevDiag); 4196 New->setInvalidDecl(); 4197 return; 4198 } 4199 4200 // Merge "used" flag. 4201 if (Old->getMostRecentDecl()->isUsed(false)) 4202 New->setIsUsed(); 4203 4204 // Keep a chain of previous declarations. 4205 New->setPreviousDecl(Old); 4206 if (NewTemplate) 4207 NewTemplate->setPreviousDecl(OldTemplate); 4208 adjustDeclContextForDeclaratorDecl(New, Old); 4209 4210 // Inherit access appropriately. 4211 New->setAccess(Old->getAccess()); 4212 if (NewTemplate) 4213 NewTemplate->setAccess(New->getAccess()); 4214 4215 if (Old->isInline()) 4216 New->setImplicitlyInline(); 4217 } 4218 4219 void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) { 4220 SourceManager &SrcMgr = getSourceManager(); 4221 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New); 4222 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation()); 4223 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first); 4224 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first); 4225 auto &HSI = PP.getHeaderSearchInfo(); 4226 StringRef HdrFilename = 4227 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation())); 4228 4229 auto noteFromModuleOrInclude = [&](Module *Mod, 4230 SourceLocation IncLoc) -> bool { 4231 // Redefinition errors with modules are common with non modular mapped 4232 // headers, example: a non-modular header H in module A that also gets 4233 // included directly in a TU. Pointing twice to the same header/definition 4234 // is confusing, try to get better diagnostics when modules is on. 4235 if (IncLoc.isValid()) { 4236 if (Mod) { 4237 Diag(IncLoc, diag::note_redefinition_modules_same_file) 4238 << HdrFilename.str() << Mod->getFullModuleName(); 4239 if (!Mod->DefinitionLoc.isInvalid()) 4240 Diag(Mod->DefinitionLoc, diag::note_defined_here) 4241 << Mod->getFullModuleName(); 4242 } else { 4243 Diag(IncLoc, diag::note_redefinition_include_same_file) 4244 << HdrFilename.str(); 4245 } 4246 return true; 4247 } 4248 4249 return false; 4250 }; 4251 4252 // Is it the same file and same offset? Provide more information on why 4253 // this leads to a redefinition error. 4254 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) { 4255 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first); 4256 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first); 4257 bool EmittedDiag = 4258 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc); 4259 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc); 4260 4261 // If the header has no guards, emit a note suggesting one. 4262 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld)) 4263 Diag(Old->getLocation(), diag::note_use_ifdef_guards); 4264 4265 if (EmittedDiag) 4266 return; 4267 } 4268 4269 // Redefinition coming from different files or couldn't do better above. 4270 if (Old->getLocation().isValid()) 4271 Diag(Old->getLocation(), diag::note_previous_definition); 4272 } 4273 4274 /// We've just determined that \p Old and \p New both appear to be definitions 4275 /// of the same variable. Either diagnose or fix the problem. 4276 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) { 4277 if (!hasVisibleDefinition(Old) && 4278 (New->getFormalLinkage() == InternalLinkage || 4279 New->isInline() || 4280 New->getDescribedVarTemplate() || 4281 New->getNumTemplateParameterLists() || 4282 New->getDeclContext()->isDependentContext())) { 4283 // The previous definition is hidden, and multiple definitions are 4284 // permitted (in separate TUs). Demote this to a declaration. 4285 New->demoteThisDefinitionToDeclaration(); 4286 4287 // Make the canonical definition visible. 4288 if (auto *OldTD = Old->getDescribedVarTemplate()) 4289 makeMergedDefinitionVisible(OldTD); 4290 makeMergedDefinitionVisible(Old); 4291 return false; 4292 } else { 4293 Diag(New->getLocation(), diag::err_redefinition) << New; 4294 notePreviousDefinition(Old, New->getLocation()); 4295 New->setInvalidDecl(); 4296 return true; 4297 } 4298 } 4299 4300 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4301 /// no declarator (e.g. "struct foo;") is parsed. 4302 Decl * 4303 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4304 RecordDecl *&AnonRecord) { 4305 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false, 4306 AnonRecord); 4307 } 4308 4309 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 4310 // disambiguate entities defined in different scopes. 4311 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 4312 // compatibility. 4313 // We will pick our mangling number depending on which version of MSVC is being 4314 // targeted. 4315 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 4316 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 4317 ? S->getMSCurManglingNumber() 4318 : S->getMSLastManglingNumber(); 4319 } 4320 4321 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 4322 if (!Context.getLangOpts().CPlusPlus) 4323 return; 4324 4325 if (isa<CXXRecordDecl>(Tag->getParent())) { 4326 // If this tag is the direct child of a class, number it if 4327 // it is anonymous. 4328 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 4329 return; 4330 MangleNumberingContext &MCtx = 4331 Context.getManglingNumberContext(Tag->getParent()); 4332 Context.setManglingNumber( 4333 Tag, MCtx.getManglingNumber( 4334 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4335 return; 4336 } 4337 4338 // If this tag isn't a direct child of a class, number it if it is local. 4339 MangleNumberingContext *MCtx; 4340 Decl *ManglingContextDecl; 4341 std::tie(MCtx, ManglingContextDecl) = 4342 getCurrentMangleNumberContext(Tag->getDeclContext()); 4343 if (MCtx) { 4344 Context.setManglingNumber( 4345 Tag, MCtx->getManglingNumber( 4346 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 4347 } 4348 } 4349 4350 namespace { 4351 struct NonCLikeKind { 4352 enum { 4353 None, 4354 BaseClass, 4355 DefaultMemberInit, 4356 Lambda, 4357 Friend, 4358 OtherMember, 4359 Invalid, 4360 } Kind = None; 4361 SourceRange Range; 4362 4363 explicit operator bool() { return Kind != None; } 4364 }; 4365 } 4366 4367 /// Determine whether a class is C-like, according to the rules of C++ 4368 /// [dcl.typedef] for anonymous classes with typedef names for linkage. 4369 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) { 4370 if (RD->isInvalidDecl()) 4371 return {NonCLikeKind::Invalid, {}}; 4372 4373 // C++ [dcl.typedef]p9: [P1766R1] 4374 // An unnamed class with a typedef name for linkage purposes shall not 4375 // 4376 // -- have any base classes 4377 if (RD->getNumBases()) 4378 return {NonCLikeKind::BaseClass, 4379 SourceRange(RD->bases_begin()->getBeginLoc(), 4380 RD->bases_end()[-1].getEndLoc())}; 4381 bool Invalid = false; 4382 for (Decl *D : RD->decls()) { 4383 // Don't complain about things we already diagnosed. 4384 if (D->isInvalidDecl()) { 4385 Invalid = true; 4386 continue; 4387 } 4388 4389 // -- have any [...] default member initializers 4390 if (auto *FD = dyn_cast<FieldDecl>(D)) { 4391 if (FD->hasInClassInitializer()) { 4392 auto *Init = FD->getInClassInitializer(); 4393 return {NonCLikeKind::DefaultMemberInit, 4394 Init ? Init->getSourceRange() : D->getSourceRange()}; 4395 } 4396 continue; 4397 } 4398 4399 // FIXME: We don't allow friend declarations. This violates the wording of 4400 // P1766, but not the intent. 4401 if (isa<FriendDecl>(D)) 4402 return {NonCLikeKind::Friend, D->getSourceRange()}; 4403 4404 // -- declare any members other than non-static data members, member 4405 // enumerations, or member classes, 4406 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) || 4407 isa<EnumDecl>(D)) 4408 continue; 4409 auto *MemberRD = dyn_cast<CXXRecordDecl>(D); 4410 if (!MemberRD) 4411 return {NonCLikeKind::OtherMember, D->getSourceRange()}; 4412 4413 // -- contain a lambda-expression, 4414 if (MemberRD->isLambda()) 4415 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()}; 4416 4417 // and all member classes shall also satisfy these requirements 4418 // (recursively). 4419 if (MemberRD->isThisDeclarationADefinition()) { 4420 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD)) 4421 return Kind; 4422 } 4423 } 4424 4425 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}}; 4426 } 4427 4428 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 4429 TypedefNameDecl *NewTD) { 4430 if (TagFromDeclSpec->isInvalidDecl()) 4431 return; 4432 4433 // Do nothing if the tag already has a name for linkage purposes. 4434 if (TagFromDeclSpec->hasNameForLinkage()) 4435 return; 4436 4437 // A well-formed anonymous tag must always be a TUK_Definition. 4438 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 4439 4440 // The type must match the tag exactly; no qualifiers allowed. 4441 if (!Context.hasSameType(NewTD->getUnderlyingType(), 4442 Context.getTagDeclType(TagFromDeclSpec))) { 4443 if (getLangOpts().CPlusPlus) 4444 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 4445 return; 4446 } 4447 4448 // C++ [dcl.typedef]p9: [P1766R1, applied as DR] 4449 // An unnamed class with a typedef name for linkage purposes shall [be 4450 // C-like]. 4451 // 4452 // FIXME: Also diagnose if we've already computed the linkage. That ideally 4453 // shouldn't happen, but there are constructs that the language rule doesn't 4454 // disallow for which we can't reasonably avoid computing linkage early. 4455 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec); 4456 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD) 4457 : NonCLikeKind(); 4458 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed(); 4459 if (NonCLike || ChangesLinkage) { 4460 if (NonCLike.Kind == NonCLikeKind::Invalid) 4461 return; 4462 4463 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef; 4464 if (ChangesLinkage) { 4465 // If the linkage changes, we can't accept this as an extension. 4466 if (NonCLike.Kind == NonCLikeKind::None) 4467 DiagID = diag::err_typedef_changes_linkage; 4468 else 4469 DiagID = diag::err_non_c_like_anon_struct_in_typedef; 4470 } 4471 4472 SourceLocation FixitLoc = 4473 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart()); 4474 llvm::SmallString<40> TextToInsert; 4475 TextToInsert += ' '; 4476 TextToInsert += NewTD->getIdentifier()->getName(); 4477 4478 Diag(FixitLoc, DiagID) 4479 << isa<TypeAliasDecl>(NewTD) 4480 << FixItHint::CreateInsertion(FixitLoc, TextToInsert); 4481 if (NonCLike.Kind != NonCLikeKind::None) { 4482 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct) 4483 << NonCLike.Kind - 1 << NonCLike.Range; 4484 } 4485 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here) 4486 << NewTD << isa<TypeAliasDecl>(NewTD); 4487 4488 if (ChangesLinkage) 4489 return; 4490 } 4491 4492 // Otherwise, set this as the anon-decl typedef for the tag. 4493 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 4494 } 4495 4496 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 4497 switch (T) { 4498 case DeclSpec::TST_class: 4499 return 0; 4500 case DeclSpec::TST_struct: 4501 return 1; 4502 case DeclSpec::TST_interface: 4503 return 2; 4504 case DeclSpec::TST_union: 4505 return 3; 4506 case DeclSpec::TST_enum: 4507 return 4; 4508 default: 4509 llvm_unreachable("unexpected type specifier"); 4510 } 4511 } 4512 4513 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 4514 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 4515 /// parameters to cope with template friend declarations. 4516 Decl * 4517 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, 4518 MultiTemplateParamsArg TemplateParams, 4519 bool IsExplicitInstantiation, 4520 RecordDecl *&AnonRecord) { 4521 Decl *TagD = nullptr; 4522 TagDecl *Tag = nullptr; 4523 if (DS.getTypeSpecType() == DeclSpec::TST_class || 4524 DS.getTypeSpecType() == DeclSpec::TST_struct || 4525 DS.getTypeSpecType() == DeclSpec::TST_interface || 4526 DS.getTypeSpecType() == DeclSpec::TST_union || 4527 DS.getTypeSpecType() == DeclSpec::TST_enum) { 4528 TagD = DS.getRepAsDecl(); 4529 4530 if (!TagD) // We probably had an error 4531 return nullptr; 4532 4533 // Note that the above type specs guarantee that the 4534 // type rep is a Decl, whereas in many of the others 4535 // it's a Type. 4536 if (isa<TagDecl>(TagD)) 4537 Tag = cast<TagDecl>(TagD); 4538 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 4539 Tag = CTD->getTemplatedDecl(); 4540 } 4541 4542 if (Tag) { 4543 handleTagNumbering(Tag, S); 4544 Tag->setFreeStanding(); 4545 if (Tag->isInvalidDecl()) 4546 return Tag; 4547 } 4548 4549 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 4550 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 4551 // or incomplete types shall not be restrict-qualified." 4552 if (TypeQuals & DeclSpec::TQ_restrict) 4553 Diag(DS.getRestrictSpecLoc(), 4554 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 4555 << DS.getSourceRange(); 4556 } 4557 4558 if (DS.isInlineSpecified()) 4559 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 4560 << getLangOpts().CPlusPlus17; 4561 4562 if (DS.hasConstexprSpecifier()) { 4563 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 4564 // and definitions of functions and variables. 4565 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to 4566 // the declaration of a function or function template 4567 if (Tag) 4568 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 4569 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) 4570 << DS.getConstexprSpecifier(); 4571 else 4572 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind) 4573 << DS.getConstexprSpecifier(); 4574 // Don't emit warnings after this error. 4575 return TagD; 4576 } 4577 4578 DiagnoseFunctionSpecifiers(DS); 4579 4580 if (DS.isFriendSpecified()) { 4581 // If we're dealing with a decl but not a TagDecl, assume that 4582 // whatever routines created it handled the friendship aspect. 4583 if (TagD && !Tag) 4584 return nullptr; 4585 return ActOnFriendTypeDecl(S, DS, TemplateParams); 4586 } 4587 4588 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 4589 bool IsExplicitSpecialization = 4590 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 4591 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 4592 !IsExplicitInstantiation && !IsExplicitSpecialization && 4593 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) { 4594 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 4595 // nested-name-specifier unless it is an explicit instantiation 4596 // or an explicit specialization. 4597 // 4598 // FIXME: We allow class template partial specializations here too, per the 4599 // obvious intent of DR1819. 4600 // 4601 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 4602 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 4603 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 4604 return nullptr; 4605 } 4606 4607 // Track whether this decl-specifier declares anything. 4608 bool DeclaresAnything = true; 4609 4610 // Handle anonymous struct definitions. 4611 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 4612 if (!Record->getDeclName() && Record->isCompleteDefinition() && 4613 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 4614 if (getLangOpts().CPlusPlus || 4615 Record->getDeclContext()->isRecord()) { 4616 // If CurContext is a DeclContext that can contain statements, 4617 // RecursiveASTVisitor won't visit the decls that 4618 // BuildAnonymousStructOrUnion() will put into CurContext. 4619 // Also store them here so that they can be part of the 4620 // DeclStmt that gets created in this case. 4621 // FIXME: Also return the IndirectFieldDecls created by 4622 // BuildAnonymousStructOr union, for the same reason? 4623 if (CurContext->isFunctionOrMethod()) 4624 AnonRecord = Record; 4625 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 4626 Context.getPrintingPolicy()); 4627 } 4628 4629 DeclaresAnything = false; 4630 } 4631 } 4632 4633 // C11 6.7.2.1p2: 4634 // A struct-declaration that does not declare an anonymous structure or 4635 // anonymous union shall contain a struct-declarator-list. 4636 // 4637 // This rule also existed in C89 and C99; the grammar for struct-declaration 4638 // did not permit a struct-declaration without a struct-declarator-list. 4639 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 4640 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 4641 // Check for Microsoft C extension: anonymous struct/union member. 4642 // Handle 2 kinds of anonymous struct/union: 4643 // struct STRUCT; 4644 // union UNION; 4645 // and 4646 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 4647 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 4648 if ((Tag && Tag->getDeclName()) || 4649 DS.getTypeSpecType() == DeclSpec::TST_typename) { 4650 RecordDecl *Record = nullptr; 4651 if (Tag) 4652 Record = dyn_cast<RecordDecl>(Tag); 4653 else if (const RecordType *RT = 4654 DS.getRepAsType().get()->getAsStructureType()) 4655 Record = RT->getDecl(); 4656 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 4657 Record = UT->getDecl(); 4658 4659 if (Record && getLangOpts().MicrosoftExt) { 4660 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record) 4661 << Record->isUnion() << DS.getSourceRange(); 4662 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 4663 } 4664 4665 DeclaresAnything = false; 4666 } 4667 } 4668 4669 // Skip all the checks below if we have a type error. 4670 if (DS.getTypeSpecType() == DeclSpec::TST_error || 4671 (TagD && TagD->isInvalidDecl())) 4672 return TagD; 4673 4674 if (getLangOpts().CPlusPlus && 4675 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 4676 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 4677 if (Enum->enumerator_begin() == Enum->enumerator_end() && 4678 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 4679 DeclaresAnything = false; 4680 4681 if (!DS.isMissingDeclaratorOk()) { 4682 // Customize diagnostic for a typedef missing a name. 4683 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 4684 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name) 4685 << DS.getSourceRange(); 4686 else 4687 DeclaresAnything = false; 4688 } 4689 4690 if (DS.isModulePrivateSpecified() && 4691 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 4692 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 4693 << Tag->getTagKind() 4694 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 4695 4696 ActOnDocumentableDecl(TagD); 4697 4698 // C 6.7/2: 4699 // A declaration [...] shall declare at least a declarator [...], a tag, 4700 // or the members of an enumeration. 4701 // C++ [dcl.dcl]p3: 4702 // [If there are no declarators], and except for the declaration of an 4703 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 4704 // names into the program, or shall redeclare a name introduced by a 4705 // previous declaration. 4706 if (!DeclaresAnything) { 4707 // In C, we allow this as a (popular) extension / bug. Don't bother 4708 // producing further diagnostics for redundant qualifiers after this. 4709 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 4710 return TagD; 4711 } 4712 4713 // C++ [dcl.stc]p1: 4714 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 4715 // init-declarator-list of the declaration shall not be empty. 4716 // C++ [dcl.fct.spec]p1: 4717 // If a cv-qualifier appears in a decl-specifier-seq, the 4718 // init-declarator-list of the declaration shall not be empty. 4719 // 4720 // Spurious qualifiers here appear to be valid in C. 4721 unsigned DiagID = diag::warn_standalone_specifier; 4722 if (getLangOpts().CPlusPlus) 4723 DiagID = diag::ext_standalone_specifier; 4724 4725 // Note that a linkage-specification sets a storage class, but 4726 // 'extern "C" struct foo;' is actually valid and not theoretically 4727 // useless. 4728 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4729 if (SCS == DeclSpec::SCS_mutable) 4730 // Since mutable is not a viable storage class specifier in C, there is 4731 // no reason to treat it as an extension. Instead, diagnose as an error. 4732 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 4733 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 4734 Diag(DS.getStorageClassSpecLoc(), DiagID) 4735 << DeclSpec::getSpecifierName(SCS); 4736 } 4737 4738 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 4739 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 4740 << DeclSpec::getSpecifierName(TSCS); 4741 if (DS.getTypeQualifiers()) { 4742 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4743 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 4744 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4745 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 4746 // Restrict is covered above. 4747 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4748 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 4749 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 4750 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned"; 4751 } 4752 4753 // Warn about ignored type attributes, for example: 4754 // __attribute__((aligned)) struct A; 4755 // Attributes should be placed after tag to apply to type declaration. 4756 if (!DS.getAttributes().empty()) { 4757 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 4758 if (TypeSpecType == DeclSpec::TST_class || 4759 TypeSpecType == DeclSpec::TST_struct || 4760 TypeSpecType == DeclSpec::TST_interface || 4761 TypeSpecType == DeclSpec::TST_union || 4762 TypeSpecType == DeclSpec::TST_enum) { 4763 for (const ParsedAttr &AL : DS.getAttributes()) 4764 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored) 4765 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType); 4766 } 4767 } 4768 4769 return TagD; 4770 } 4771 4772 /// We are trying to inject an anonymous member into the given scope; 4773 /// check if there's an existing declaration that can't be overloaded. 4774 /// 4775 /// \return true if this is a forbidden redeclaration 4776 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 4777 Scope *S, 4778 DeclContext *Owner, 4779 DeclarationName Name, 4780 SourceLocation NameLoc, 4781 bool IsUnion) { 4782 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 4783 Sema::ForVisibleRedeclaration); 4784 if (!SemaRef.LookupName(R, S)) return false; 4785 4786 // Pick a representative declaration. 4787 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 4788 assert(PrevDecl && "Expected a non-null Decl"); 4789 4790 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 4791 return false; 4792 4793 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl) 4794 << IsUnion << Name; 4795 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 4796 4797 return true; 4798 } 4799 4800 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 4801 /// anonymous struct or union AnonRecord into the owning context Owner 4802 /// and scope S. This routine will be invoked just after we realize 4803 /// that an unnamed union or struct is actually an anonymous union or 4804 /// struct, e.g., 4805 /// 4806 /// @code 4807 /// union { 4808 /// int i; 4809 /// float f; 4810 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 4811 /// // f into the surrounding scope.x 4812 /// @endcode 4813 /// 4814 /// This routine is recursive, injecting the names of nested anonymous 4815 /// structs/unions into the owning context and scope as well. 4816 static bool 4817 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, 4818 RecordDecl *AnonRecord, AccessSpecifier AS, 4819 SmallVectorImpl<NamedDecl *> &Chaining) { 4820 bool Invalid = false; 4821 4822 // Look every FieldDecl and IndirectFieldDecl with a name. 4823 for (auto *D : AnonRecord->decls()) { 4824 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 4825 cast<NamedDecl>(D)->getDeclName()) { 4826 ValueDecl *VD = cast<ValueDecl>(D); 4827 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 4828 VD->getLocation(), 4829 AnonRecord->isUnion())) { 4830 // C++ [class.union]p2: 4831 // The names of the members of an anonymous union shall be 4832 // distinct from the names of any other entity in the 4833 // scope in which the anonymous union is declared. 4834 Invalid = true; 4835 } else { 4836 // C++ [class.union]p2: 4837 // For the purpose of name lookup, after the anonymous union 4838 // definition, the members of the anonymous union are 4839 // considered to have been defined in the scope in which the 4840 // anonymous union is declared. 4841 unsigned OldChainingSize = Chaining.size(); 4842 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 4843 Chaining.append(IF->chain_begin(), IF->chain_end()); 4844 else 4845 Chaining.push_back(VD); 4846 4847 assert(Chaining.size() >= 2); 4848 NamedDecl **NamedChain = 4849 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 4850 for (unsigned i = 0; i < Chaining.size(); i++) 4851 NamedChain[i] = Chaining[i]; 4852 4853 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 4854 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 4855 VD->getType(), {NamedChain, Chaining.size()}); 4856 4857 for (const auto *Attr : VD->attrs()) 4858 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 4859 4860 IndirectField->setAccess(AS); 4861 IndirectField->setImplicit(); 4862 SemaRef.PushOnScopeChains(IndirectField, S); 4863 4864 // That includes picking up the appropriate access specifier. 4865 if (AS != AS_none) IndirectField->setAccess(AS); 4866 4867 Chaining.resize(OldChainingSize); 4868 } 4869 } 4870 } 4871 4872 return Invalid; 4873 } 4874 4875 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4876 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4877 /// illegal input values are mapped to SC_None. 4878 static StorageClass 4879 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4880 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4881 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4882 "Parser allowed 'typedef' as storage class VarDecl."); 4883 switch (StorageClassSpec) { 4884 case DeclSpec::SCS_unspecified: return SC_None; 4885 case DeclSpec::SCS_extern: 4886 if (DS.isExternInLinkageSpec()) 4887 return SC_None; 4888 return SC_Extern; 4889 case DeclSpec::SCS_static: return SC_Static; 4890 case DeclSpec::SCS_auto: return SC_Auto; 4891 case DeclSpec::SCS_register: return SC_Register; 4892 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4893 // Illegal SCSs map to None: error reporting is up to the caller. 4894 case DeclSpec::SCS_mutable: // Fall through. 4895 case DeclSpec::SCS_typedef: return SC_None; 4896 } 4897 llvm_unreachable("unknown storage class specifier"); 4898 } 4899 4900 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4901 assert(Record->hasInClassInitializer()); 4902 4903 for (const auto *I : Record->decls()) { 4904 const auto *FD = dyn_cast<FieldDecl>(I); 4905 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4906 FD = IFD->getAnonField(); 4907 if (FD && FD->hasInClassInitializer()) 4908 return FD->getLocation(); 4909 } 4910 4911 llvm_unreachable("couldn't find in-class initializer"); 4912 } 4913 4914 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4915 SourceLocation DefaultInitLoc) { 4916 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4917 return; 4918 4919 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4920 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4921 } 4922 4923 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4924 CXXRecordDecl *AnonUnion) { 4925 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4926 return; 4927 4928 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4929 } 4930 4931 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4932 /// anonymous structure or union. Anonymous unions are a C++ feature 4933 /// (C++ [class.union]) and a C11 feature; anonymous structures 4934 /// are a C11 feature and GNU C++ extension. 4935 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4936 AccessSpecifier AS, 4937 RecordDecl *Record, 4938 const PrintingPolicy &Policy) { 4939 DeclContext *Owner = Record->getDeclContext(); 4940 4941 // Diagnose whether this anonymous struct/union is an extension. 4942 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4943 Diag(Record->getLocation(), diag::ext_anonymous_union); 4944 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4945 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4946 else if (!Record->isUnion() && !getLangOpts().C11) 4947 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4948 4949 // C and C++ require different kinds of checks for anonymous 4950 // structs/unions. 4951 bool Invalid = false; 4952 if (getLangOpts().CPlusPlus) { 4953 const char *PrevSpec = nullptr; 4954 if (Record->isUnion()) { 4955 // C++ [class.union]p6: 4956 // C++17 [class.union.anon]p2: 4957 // Anonymous unions declared in a named namespace or in the 4958 // global namespace shall be declared static. 4959 unsigned DiagID; 4960 DeclContext *OwnerScope = Owner->getRedeclContext(); 4961 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4962 (OwnerScope->isTranslationUnit() || 4963 (OwnerScope->isNamespace() && 4964 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) { 4965 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4966 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4967 4968 // Recover by adding 'static'. 4969 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4970 PrevSpec, DiagID, Policy); 4971 } 4972 // C++ [class.union]p6: 4973 // A storage class is not allowed in a declaration of an 4974 // anonymous union in a class scope. 4975 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4976 isa<RecordDecl>(Owner)) { 4977 Diag(DS.getStorageClassSpecLoc(), 4978 diag::err_anonymous_union_with_storage_spec) 4979 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4980 4981 // Recover by removing the storage specifier. 4982 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4983 SourceLocation(), 4984 PrevSpec, DiagID, Context.getPrintingPolicy()); 4985 } 4986 } 4987 4988 // Ignore const/volatile/restrict qualifiers. 4989 if (DS.getTypeQualifiers()) { 4990 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4991 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4992 << Record->isUnion() << "const" 4993 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4994 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4995 Diag(DS.getVolatileSpecLoc(), 4996 diag::ext_anonymous_struct_union_qualified) 4997 << Record->isUnion() << "volatile" 4998 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4999 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 5000 Diag(DS.getRestrictSpecLoc(), 5001 diag::ext_anonymous_struct_union_qualified) 5002 << Record->isUnion() << "restrict" 5003 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 5004 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 5005 Diag(DS.getAtomicSpecLoc(), 5006 diag::ext_anonymous_struct_union_qualified) 5007 << Record->isUnion() << "_Atomic" 5008 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 5009 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned) 5010 Diag(DS.getUnalignedSpecLoc(), 5011 diag::ext_anonymous_struct_union_qualified) 5012 << Record->isUnion() << "__unaligned" 5013 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc()); 5014 5015 DS.ClearTypeQualifiers(); 5016 } 5017 5018 // C++ [class.union]p2: 5019 // The member-specification of an anonymous union shall only 5020 // define non-static data members. [Note: nested types and 5021 // functions cannot be declared within an anonymous union. ] 5022 for (auto *Mem : Record->decls()) { 5023 // Ignore invalid declarations; we already diagnosed them. 5024 if (Mem->isInvalidDecl()) 5025 continue; 5026 5027 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 5028 // C++ [class.union]p3: 5029 // An anonymous union shall not have private or protected 5030 // members (clause 11). 5031 assert(FD->getAccess() != AS_none); 5032 if (FD->getAccess() != AS_public) { 5033 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 5034 << Record->isUnion() << (FD->getAccess() == AS_protected); 5035 Invalid = true; 5036 } 5037 5038 // C++ [class.union]p1 5039 // An object of a class with a non-trivial constructor, a non-trivial 5040 // copy constructor, a non-trivial destructor, or a non-trivial copy 5041 // assignment operator cannot be a member of a union, nor can an 5042 // array of such objects. 5043 if (CheckNontrivialField(FD)) 5044 Invalid = true; 5045 } else if (Mem->isImplicit()) { 5046 // Any implicit members are fine. 5047 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 5048 // This is a type that showed up in an 5049 // elaborated-type-specifier inside the anonymous struct or 5050 // union, but which actually declares a type outside of the 5051 // anonymous struct or union. It's okay. 5052 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 5053 if (!MemRecord->isAnonymousStructOrUnion() && 5054 MemRecord->getDeclName()) { 5055 // Visual C++ allows type definition in anonymous struct or union. 5056 if (getLangOpts().MicrosoftExt) 5057 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 5058 << Record->isUnion(); 5059 else { 5060 // This is a nested type declaration. 5061 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 5062 << Record->isUnion(); 5063 Invalid = true; 5064 } 5065 } else { 5066 // This is an anonymous type definition within another anonymous type. 5067 // This is a popular extension, provided by Plan9, MSVC and GCC, but 5068 // not part of standard C++. 5069 Diag(MemRecord->getLocation(), 5070 diag::ext_anonymous_record_with_anonymous_type) 5071 << Record->isUnion(); 5072 } 5073 } else if (isa<AccessSpecDecl>(Mem)) { 5074 // Any access specifier is fine. 5075 } else if (isa<StaticAssertDecl>(Mem)) { 5076 // In C++1z, static_assert declarations are also fine. 5077 } else { 5078 // We have something that isn't a non-static data 5079 // member. Complain about it. 5080 unsigned DK = diag::err_anonymous_record_bad_member; 5081 if (isa<TypeDecl>(Mem)) 5082 DK = diag::err_anonymous_record_with_type; 5083 else if (isa<FunctionDecl>(Mem)) 5084 DK = diag::err_anonymous_record_with_function; 5085 else if (isa<VarDecl>(Mem)) 5086 DK = diag::err_anonymous_record_with_static; 5087 5088 // Visual C++ allows type definition in anonymous struct or union. 5089 if (getLangOpts().MicrosoftExt && 5090 DK == diag::err_anonymous_record_with_type) 5091 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 5092 << Record->isUnion(); 5093 else { 5094 Diag(Mem->getLocation(), DK) << Record->isUnion(); 5095 Invalid = true; 5096 } 5097 } 5098 } 5099 5100 // C++11 [class.union]p8 (DR1460): 5101 // At most one variant member of a union may have a 5102 // brace-or-equal-initializer. 5103 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 5104 Owner->isRecord()) 5105 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 5106 cast<CXXRecordDecl>(Record)); 5107 } 5108 5109 if (!Record->isUnion() && !Owner->isRecord()) { 5110 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 5111 << getLangOpts().CPlusPlus; 5112 Invalid = true; 5113 } 5114 5115 // C++ [dcl.dcl]p3: 5116 // [If there are no declarators], and except for the declaration of an 5117 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 5118 // names into the program 5119 // C++ [class.mem]p2: 5120 // each such member-declaration shall either declare at least one member 5121 // name of the class or declare at least one unnamed bit-field 5122 // 5123 // For C this is an error even for a named struct, and is diagnosed elsewhere. 5124 if (getLangOpts().CPlusPlus && Record->field_empty()) 5125 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange(); 5126 5127 // Mock up a declarator. 5128 Declarator Dc(DS, DeclaratorContext::MemberContext); 5129 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5130 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 5131 5132 // Create a declaration for this anonymous struct/union. 5133 NamedDecl *Anon = nullptr; 5134 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 5135 Anon = FieldDecl::Create( 5136 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(), 5137 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo, 5138 /*BitWidth=*/nullptr, /*Mutable=*/false, 5139 /*InitStyle=*/ICIS_NoInit); 5140 Anon->setAccess(AS); 5141 ProcessDeclAttributes(S, Anon, Dc); 5142 5143 if (getLangOpts().CPlusPlus) 5144 FieldCollector->Add(cast<FieldDecl>(Anon)); 5145 } else { 5146 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 5147 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 5148 if (SCSpec == DeclSpec::SCS_mutable) { 5149 // mutable can only appear on non-static class members, so it's always 5150 // an error here 5151 Diag(Record->getLocation(), diag::err_mutable_nonmember); 5152 Invalid = true; 5153 SC = SC_None; 5154 } 5155 5156 assert(DS.getAttributes().empty() && "No attribute expected"); 5157 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(), 5158 Record->getLocation(), /*IdentifierInfo=*/nullptr, 5159 Context.getTypeDeclType(Record), TInfo, SC); 5160 5161 // Default-initialize the implicit variable. This initialization will be 5162 // trivial in almost all cases, except if a union member has an in-class 5163 // initializer: 5164 // union { int n = 0; }; 5165 ActOnUninitializedDecl(Anon); 5166 } 5167 Anon->setImplicit(); 5168 5169 // Mark this as an anonymous struct/union type. 5170 Record->setAnonymousStructOrUnion(true); 5171 5172 // Add the anonymous struct/union object to the current 5173 // context. We'll be referencing this object when we refer to one of 5174 // its members. 5175 Owner->addDecl(Anon); 5176 5177 // Inject the members of the anonymous struct/union into the owning 5178 // context and into the identifier resolver chain for name lookup 5179 // purposes. 5180 SmallVector<NamedDecl*, 2> Chain; 5181 Chain.push_back(Anon); 5182 5183 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain)) 5184 Invalid = true; 5185 5186 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 5187 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5188 MangleNumberingContext *MCtx; 5189 Decl *ManglingContextDecl; 5190 std::tie(MCtx, ManglingContextDecl) = 5191 getCurrentMangleNumberContext(NewVD->getDeclContext()); 5192 if (MCtx) { 5193 Context.setManglingNumber( 5194 NewVD, MCtx->getManglingNumber( 5195 NewVD, getMSManglingNumber(getLangOpts(), S))); 5196 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5197 } 5198 } 5199 } 5200 5201 if (Invalid) 5202 Anon->setInvalidDecl(); 5203 5204 return Anon; 5205 } 5206 5207 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 5208 /// Microsoft C anonymous structure. 5209 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 5210 /// Example: 5211 /// 5212 /// struct A { int a; }; 5213 /// struct B { struct A; int b; }; 5214 /// 5215 /// void foo() { 5216 /// B var; 5217 /// var.a = 3; 5218 /// } 5219 /// 5220 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 5221 RecordDecl *Record) { 5222 assert(Record && "expected a record!"); 5223 5224 // Mock up a declarator. 5225 Declarator Dc(DS, DeclaratorContext::TypeNameContext); 5226 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 5227 assert(TInfo && "couldn't build declarator info for anonymous struct"); 5228 5229 auto *ParentDecl = cast<RecordDecl>(CurContext); 5230 QualType RecTy = Context.getTypeDeclType(Record); 5231 5232 // Create a declaration for this anonymous struct. 5233 NamedDecl *Anon = 5234 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(), 5235 /*IdentifierInfo=*/nullptr, RecTy, TInfo, 5236 /*BitWidth=*/nullptr, /*Mutable=*/false, 5237 /*InitStyle=*/ICIS_NoInit); 5238 Anon->setImplicit(); 5239 5240 // Add the anonymous struct object to the current context. 5241 CurContext->addDecl(Anon); 5242 5243 // Inject the members of the anonymous struct into the current 5244 // context and into the identifier resolver chain for name lookup 5245 // purposes. 5246 SmallVector<NamedDecl*, 2> Chain; 5247 Chain.push_back(Anon); 5248 5249 RecordDecl *RecordDef = Record->getDefinition(); 5250 if (RequireCompleteType(Anon->getLocation(), RecTy, 5251 diag::err_field_incomplete) || 5252 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 5253 AS_none, Chain)) { 5254 Anon->setInvalidDecl(); 5255 ParentDecl->setInvalidDecl(); 5256 } 5257 5258 return Anon; 5259 } 5260 5261 /// GetNameForDeclarator - Determine the full declaration name for the 5262 /// given Declarator. 5263 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 5264 return GetNameFromUnqualifiedId(D.getName()); 5265 } 5266 5267 /// Retrieves the declaration name from a parsed unqualified-id. 5268 DeclarationNameInfo 5269 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 5270 DeclarationNameInfo NameInfo; 5271 NameInfo.setLoc(Name.StartLocation); 5272 5273 switch (Name.getKind()) { 5274 5275 case UnqualifiedIdKind::IK_ImplicitSelfParam: 5276 case UnqualifiedIdKind::IK_Identifier: 5277 NameInfo.setName(Name.Identifier); 5278 return NameInfo; 5279 5280 case UnqualifiedIdKind::IK_DeductionGuideName: { 5281 // C++ [temp.deduct.guide]p3: 5282 // The simple-template-id shall name a class template specialization. 5283 // The template-name shall be the same identifier as the template-name 5284 // of the simple-template-id. 5285 // These together intend to imply that the template-name shall name a 5286 // class template. 5287 // FIXME: template<typename T> struct X {}; 5288 // template<typename T> using Y = X<T>; 5289 // Y(int) -> Y<int>; 5290 // satisfies these rules but does not name a class template. 5291 TemplateName TN = Name.TemplateName.get().get(); 5292 auto *Template = TN.getAsTemplateDecl(); 5293 if (!Template || !isa<ClassTemplateDecl>(Template)) { 5294 Diag(Name.StartLocation, 5295 diag::err_deduction_guide_name_not_class_template) 5296 << (int)getTemplateNameKindForDiagnostics(TN) << TN; 5297 if (Template) 5298 Diag(Template->getLocation(), diag::note_template_decl_here); 5299 return DeclarationNameInfo(); 5300 } 5301 5302 NameInfo.setName( 5303 Context.DeclarationNames.getCXXDeductionGuideName(Template)); 5304 return NameInfo; 5305 } 5306 5307 case UnqualifiedIdKind::IK_OperatorFunctionId: 5308 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 5309 Name.OperatorFunctionId.Operator)); 5310 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 5311 = Name.OperatorFunctionId.SymbolLocations[0]; 5312 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 5313 = Name.EndLocation.getRawEncoding(); 5314 return NameInfo; 5315 5316 case UnqualifiedIdKind::IK_LiteralOperatorId: 5317 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 5318 Name.Identifier)); 5319 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 5320 return NameInfo; 5321 5322 case UnqualifiedIdKind::IK_ConversionFunctionId: { 5323 TypeSourceInfo *TInfo; 5324 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 5325 if (Ty.isNull()) 5326 return DeclarationNameInfo(); 5327 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 5328 Context.getCanonicalType(Ty))); 5329 NameInfo.setNamedTypeInfo(TInfo); 5330 return NameInfo; 5331 } 5332 5333 case UnqualifiedIdKind::IK_ConstructorName: { 5334 TypeSourceInfo *TInfo; 5335 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 5336 if (Ty.isNull()) 5337 return DeclarationNameInfo(); 5338 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5339 Context.getCanonicalType(Ty))); 5340 NameInfo.setNamedTypeInfo(TInfo); 5341 return NameInfo; 5342 } 5343 5344 case UnqualifiedIdKind::IK_ConstructorTemplateId: { 5345 // In well-formed code, we can only have a constructor 5346 // template-id that refers to the current context, so go there 5347 // to find the actual type being constructed. 5348 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 5349 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 5350 return DeclarationNameInfo(); 5351 5352 // Determine the type of the class being constructed. 5353 QualType CurClassType = Context.getTypeDeclType(CurClass); 5354 5355 // FIXME: Check two things: that the template-id names the same type as 5356 // CurClassType, and that the template-id does not occur when the name 5357 // was qualified. 5358 5359 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 5360 Context.getCanonicalType(CurClassType))); 5361 // FIXME: should we retrieve TypeSourceInfo? 5362 NameInfo.setNamedTypeInfo(nullptr); 5363 return NameInfo; 5364 } 5365 5366 case UnqualifiedIdKind::IK_DestructorName: { 5367 TypeSourceInfo *TInfo; 5368 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 5369 if (Ty.isNull()) 5370 return DeclarationNameInfo(); 5371 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 5372 Context.getCanonicalType(Ty))); 5373 NameInfo.setNamedTypeInfo(TInfo); 5374 return NameInfo; 5375 } 5376 5377 case UnqualifiedIdKind::IK_TemplateId: { 5378 TemplateName TName = Name.TemplateId->Template.get(); 5379 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 5380 return Context.getNameForTemplate(TName, TNameLoc); 5381 } 5382 5383 } // switch (Name.getKind()) 5384 5385 llvm_unreachable("Unknown name kind"); 5386 } 5387 5388 static QualType getCoreType(QualType Ty) { 5389 do { 5390 if (Ty->isPointerType() || Ty->isReferenceType()) 5391 Ty = Ty->getPointeeType(); 5392 else if (Ty->isArrayType()) 5393 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 5394 else 5395 return Ty.withoutLocalFastQualifiers(); 5396 } while (true); 5397 } 5398 5399 /// hasSimilarParameters - Determine whether the C++ functions Declaration 5400 /// and Definition have "nearly" matching parameters. This heuristic is 5401 /// used to improve diagnostics in the case where an out-of-line function 5402 /// definition doesn't match any declaration within the class or namespace. 5403 /// Also sets Params to the list of indices to the parameters that differ 5404 /// between the declaration and the definition. If hasSimilarParameters 5405 /// returns true and Params is empty, then all of the parameters match. 5406 static bool hasSimilarParameters(ASTContext &Context, 5407 FunctionDecl *Declaration, 5408 FunctionDecl *Definition, 5409 SmallVectorImpl<unsigned> &Params) { 5410 Params.clear(); 5411 if (Declaration->param_size() != Definition->param_size()) 5412 return false; 5413 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 5414 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 5415 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 5416 5417 // The parameter types are identical 5418 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy)) 5419 continue; 5420 5421 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 5422 QualType DefParamBaseTy = getCoreType(DefParamTy); 5423 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 5424 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 5425 5426 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 5427 (DeclTyName && DeclTyName == DefTyName)) 5428 Params.push_back(Idx); 5429 else // The two parameters aren't even close 5430 return false; 5431 } 5432 5433 return true; 5434 } 5435 5436 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 5437 /// declarator needs to be rebuilt in the current instantiation. 5438 /// Any bits of declarator which appear before the name are valid for 5439 /// consideration here. That's specifically the type in the decl spec 5440 /// and the base type in any member-pointer chunks. 5441 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 5442 DeclarationName Name) { 5443 // The types we specifically need to rebuild are: 5444 // - typenames, typeofs, and decltypes 5445 // - types which will become injected class names 5446 // Of course, we also need to rebuild any type referencing such a 5447 // type. It's safest to just say "dependent", but we call out a 5448 // few cases here. 5449 5450 DeclSpec &DS = D.getMutableDeclSpec(); 5451 switch (DS.getTypeSpecType()) { 5452 case DeclSpec::TST_typename: 5453 case DeclSpec::TST_typeofType: 5454 case DeclSpec::TST_underlyingType: 5455 case DeclSpec::TST_atomic: { 5456 // Grab the type from the parser. 5457 TypeSourceInfo *TSI = nullptr; 5458 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 5459 if (T.isNull() || !T->isDependentType()) break; 5460 5461 // Make sure there's a type source info. This isn't really much 5462 // of a waste; most dependent types should have type source info 5463 // attached already. 5464 if (!TSI) 5465 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 5466 5467 // Rebuild the type in the current instantiation. 5468 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 5469 if (!TSI) return true; 5470 5471 // Store the new type back in the decl spec. 5472 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 5473 DS.UpdateTypeRep(LocType); 5474 break; 5475 } 5476 5477 case DeclSpec::TST_decltype: 5478 case DeclSpec::TST_typeofExpr: { 5479 Expr *E = DS.getRepAsExpr(); 5480 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 5481 if (Result.isInvalid()) return true; 5482 DS.UpdateExprRep(Result.get()); 5483 break; 5484 } 5485 5486 default: 5487 // Nothing to do for these decl specs. 5488 break; 5489 } 5490 5491 // It doesn't matter what order we do this in. 5492 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 5493 DeclaratorChunk &Chunk = D.getTypeObject(I); 5494 5495 // The only type information in the declarator which can come 5496 // before the declaration name is the base type of a member 5497 // pointer. 5498 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 5499 continue; 5500 5501 // Rebuild the scope specifier in-place. 5502 CXXScopeSpec &SS = Chunk.Mem.Scope(); 5503 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 5504 return true; 5505 } 5506 5507 return false; 5508 } 5509 5510 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 5511 D.setFunctionDefinitionKind(FDK_Declaration); 5512 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 5513 5514 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 5515 Dcl && Dcl->getDeclContext()->isFileContext()) 5516 Dcl->setTopLevelDeclInObjCContainer(); 5517 5518 if (getLangOpts().OpenCL) 5519 setCurrentOpenCLExtensionForDecl(Dcl); 5520 5521 return Dcl; 5522 } 5523 5524 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 5525 /// If T is the name of a class, then each of the following shall have a 5526 /// name different from T: 5527 /// - every static data member of class T; 5528 /// - every member function of class T 5529 /// - every member of class T that is itself a type; 5530 /// \returns true if the declaration name violates these rules. 5531 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 5532 DeclarationNameInfo NameInfo) { 5533 DeclarationName Name = NameInfo.getName(); 5534 5535 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC); 5536 while (Record && Record->isAnonymousStructOrUnion()) 5537 Record = dyn_cast<CXXRecordDecl>(Record->getParent()); 5538 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) { 5539 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 5540 return true; 5541 } 5542 5543 return false; 5544 } 5545 5546 /// Diagnose a declaration whose declarator-id has the given 5547 /// nested-name-specifier. 5548 /// 5549 /// \param SS The nested-name-specifier of the declarator-id. 5550 /// 5551 /// \param DC The declaration context to which the nested-name-specifier 5552 /// resolves. 5553 /// 5554 /// \param Name The name of the entity being declared. 5555 /// 5556 /// \param Loc The location of the name of the entity being declared. 5557 /// 5558 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus 5559 /// we're declaring an explicit / partial specialization / instantiation. 5560 /// 5561 /// \returns true if we cannot safely recover from this error, false otherwise. 5562 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 5563 DeclarationName Name, 5564 SourceLocation Loc, bool IsTemplateId) { 5565 DeclContext *Cur = CurContext; 5566 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 5567 Cur = Cur->getParent(); 5568 5569 // If the user provided a superfluous scope specifier that refers back to the 5570 // class in which the entity is already declared, diagnose and ignore it. 5571 // 5572 // class X { 5573 // void X::f(); 5574 // }; 5575 // 5576 // Note, it was once ill-formed to give redundant qualification in all 5577 // contexts, but that rule was removed by DR482. 5578 if (Cur->Equals(DC)) { 5579 if (Cur->isRecord()) { 5580 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 5581 : diag::err_member_extra_qualification) 5582 << Name << FixItHint::CreateRemoval(SS.getRange()); 5583 SS.clear(); 5584 } else { 5585 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 5586 } 5587 return false; 5588 } 5589 5590 // Check whether the qualifying scope encloses the scope of the original 5591 // declaration. For a template-id, we perform the checks in 5592 // CheckTemplateSpecializationScope. 5593 if (!Cur->Encloses(DC) && !IsTemplateId) { 5594 if (Cur->isRecord()) 5595 Diag(Loc, diag::err_member_qualification) 5596 << Name << SS.getRange(); 5597 else if (isa<TranslationUnitDecl>(DC)) 5598 Diag(Loc, diag::err_invalid_declarator_global_scope) 5599 << Name << SS.getRange(); 5600 else if (isa<FunctionDecl>(Cur)) 5601 Diag(Loc, diag::err_invalid_declarator_in_function) 5602 << Name << SS.getRange(); 5603 else if (isa<BlockDecl>(Cur)) 5604 Diag(Loc, diag::err_invalid_declarator_in_block) 5605 << Name << SS.getRange(); 5606 else 5607 Diag(Loc, diag::err_invalid_declarator_scope) 5608 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 5609 5610 return true; 5611 } 5612 5613 if (Cur->isRecord()) { 5614 // Cannot qualify members within a class. 5615 Diag(Loc, diag::err_member_qualification) 5616 << Name << SS.getRange(); 5617 SS.clear(); 5618 5619 // C++ constructors and destructors with incorrect scopes can break 5620 // our AST invariants by having the wrong underlying types. If 5621 // that's the case, then drop this declaration entirely. 5622 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 5623 Name.getNameKind() == DeclarationName::CXXDestructorName) && 5624 !Context.hasSameType(Name.getCXXNameType(), 5625 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 5626 return true; 5627 5628 return false; 5629 } 5630 5631 // C++11 [dcl.meaning]p1: 5632 // [...] "The nested-name-specifier of the qualified declarator-id shall 5633 // not begin with a decltype-specifer" 5634 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 5635 while (SpecLoc.getPrefix()) 5636 SpecLoc = SpecLoc.getPrefix(); 5637 if (dyn_cast_or_null<DecltypeType>( 5638 SpecLoc.getNestedNameSpecifier()->getAsType())) 5639 Diag(Loc, diag::err_decltype_in_declarator) 5640 << SpecLoc.getTypeLoc().getSourceRange(); 5641 5642 return false; 5643 } 5644 5645 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 5646 MultiTemplateParamsArg TemplateParamLists) { 5647 // TODO: consider using NameInfo for diagnostic. 5648 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 5649 DeclarationName Name = NameInfo.getName(); 5650 5651 // All of these full declarators require an identifier. If it doesn't have 5652 // one, the ParsedFreeStandingDeclSpec action should be used. 5653 if (D.isDecompositionDeclarator()) { 5654 return ActOnDecompositionDeclarator(S, D, TemplateParamLists); 5655 } else if (!Name) { 5656 if (!D.isInvalidType()) // Reject this if we think it is valid. 5657 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident) 5658 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 5659 return nullptr; 5660 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 5661 return nullptr; 5662 5663 // The scope passed in may not be a decl scope. Zip up the scope tree until 5664 // we find one that is. 5665 while ((S->getFlags() & Scope::DeclScope) == 0 || 5666 (S->getFlags() & Scope::TemplateParamScope) != 0) 5667 S = S->getParent(); 5668 5669 DeclContext *DC = CurContext; 5670 if (D.getCXXScopeSpec().isInvalid()) 5671 D.setInvalidType(); 5672 else if (D.getCXXScopeSpec().isSet()) { 5673 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 5674 UPPC_DeclarationQualifier)) 5675 return nullptr; 5676 5677 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 5678 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 5679 if (!DC || isa<EnumDecl>(DC)) { 5680 // If we could not compute the declaration context, it's because the 5681 // declaration context is dependent but does not refer to a class, 5682 // class template, or class template partial specialization. Complain 5683 // and return early, to avoid the coming semantic disaster. 5684 Diag(D.getIdentifierLoc(), 5685 diag::err_template_qualified_declarator_no_match) 5686 << D.getCXXScopeSpec().getScopeRep() 5687 << D.getCXXScopeSpec().getRange(); 5688 return nullptr; 5689 } 5690 bool IsDependentContext = DC->isDependentContext(); 5691 5692 if (!IsDependentContext && 5693 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 5694 return nullptr; 5695 5696 // If a class is incomplete, do not parse entities inside it. 5697 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 5698 Diag(D.getIdentifierLoc(), 5699 diag::err_member_def_undefined_record) 5700 << Name << DC << D.getCXXScopeSpec().getRange(); 5701 return nullptr; 5702 } 5703 if (!D.getDeclSpec().isFriendSpecified()) { 5704 if (diagnoseQualifiedDeclaration( 5705 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(), 5706 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) { 5707 if (DC->isRecord()) 5708 return nullptr; 5709 5710 D.setInvalidType(); 5711 } 5712 } 5713 5714 // Check whether we need to rebuild the type of the given 5715 // declaration in the current instantiation. 5716 if (EnteringContext && IsDependentContext && 5717 TemplateParamLists.size() != 0) { 5718 ContextRAII SavedContext(*this, DC); 5719 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 5720 D.setInvalidType(); 5721 } 5722 } 5723 5724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 5725 QualType R = TInfo->getType(); 5726 5727 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 5728 UPPC_DeclarationType)) 5729 D.setInvalidType(); 5730 5731 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 5732 forRedeclarationInCurContext()); 5733 5734 // See if this is a redefinition of a variable in the same scope. 5735 if (!D.getCXXScopeSpec().isSet()) { 5736 bool IsLinkageLookup = false; 5737 bool CreateBuiltins = false; 5738 5739 // If the declaration we're planning to build will be a function 5740 // or object with linkage, then look for another declaration with 5741 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 5742 // 5743 // If the declaration we're planning to build will be declared with 5744 // external linkage in the translation unit, create any builtin with 5745 // the same name. 5746 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 5747 /* Do nothing*/; 5748 else if (CurContext->isFunctionOrMethod() && 5749 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 5750 R->isFunctionType())) { 5751 IsLinkageLookup = true; 5752 CreateBuiltins = 5753 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 5754 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 5755 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 5756 CreateBuiltins = true; 5757 5758 if (IsLinkageLookup) { 5759 Previous.clear(LookupRedeclarationWithLinkage); 5760 Previous.setRedeclarationKind(ForExternalRedeclaration); 5761 } 5762 5763 LookupName(Previous, S, CreateBuiltins); 5764 } else { // Something like "int foo::x;" 5765 LookupQualifiedName(Previous, DC); 5766 5767 // C++ [dcl.meaning]p1: 5768 // When the declarator-id is qualified, the declaration shall refer to a 5769 // previously declared member of the class or namespace to which the 5770 // qualifier refers (or, in the case of a namespace, of an element of the 5771 // inline namespace set of that namespace (7.3.1)) or to a specialization 5772 // thereof; [...] 5773 // 5774 // Note that we already checked the context above, and that we do not have 5775 // enough information to make sure that Previous contains the declaration 5776 // we want to match. For example, given: 5777 // 5778 // class X { 5779 // void f(); 5780 // void f(float); 5781 // }; 5782 // 5783 // void X::f(int) { } // ill-formed 5784 // 5785 // In this case, Previous will point to the overload set 5786 // containing the two f's declared in X, but neither of them 5787 // matches. 5788 5789 // C++ [dcl.meaning]p1: 5790 // [...] the member shall not merely have been introduced by a 5791 // using-declaration in the scope of the class or namespace nominated by 5792 // the nested-name-specifier of the declarator-id. 5793 RemoveUsingDecls(Previous); 5794 } 5795 5796 if (Previous.isSingleResult() && 5797 Previous.getFoundDecl()->isTemplateParameter()) { 5798 // Maybe we will complain about the shadowed template parameter. 5799 if (!D.isInvalidType()) 5800 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 5801 Previous.getFoundDecl()); 5802 5803 // Just pretend that we didn't see the previous declaration. 5804 Previous.clear(); 5805 } 5806 5807 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 5808 // Forget that the previous declaration is the injected-class-name. 5809 Previous.clear(); 5810 5811 // In C++, the previous declaration we find might be a tag type 5812 // (class or enum). In this case, the new declaration will hide the 5813 // tag type. Note that this applies to functions, function templates, and 5814 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates. 5815 if (Previous.isSingleTagDecl() && 5816 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 5817 (TemplateParamLists.size() == 0 || R->isFunctionType())) 5818 Previous.clear(); 5819 5820 // Check that there are no default arguments other than in the parameters 5821 // of a function declaration (C++ only). 5822 if (getLangOpts().CPlusPlus) 5823 CheckExtraCXXDefaultArguments(D); 5824 5825 NamedDecl *New; 5826 5827 bool AddToScope = true; 5828 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 5829 if (TemplateParamLists.size()) { 5830 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 5831 return nullptr; 5832 } 5833 5834 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 5835 } else if (R->isFunctionType()) { 5836 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 5837 TemplateParamLists, 5838 AddToScope); 5839 } else { 5840 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 5841 AddToScope); 5842 } 5843 5844 if (!New) 5845 return nullptr; 5846 5847 // If this has an identifier and is not a function template specialization, 5848 // add it to the scope stack. 5849 if (New->getDeclName() && AddToScope) 5850 PushOnScopeChains(New, S); 5851 5852 if (isInOpenMPDeclareTargetContext()) 5853 checkDeclIsAllowedInOpenMPTarget(nullptr, New); 5854 5855 return New; 5856 } 5857 5858 /// Helper method to turn variable array types into constant array 5859 /// types in certain situations which would otherwise be errors (for 5860 /// GCC compatibility). 5861 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 5862 ASTContext &Context, 5863 bool &SizeIsNegative, 5864 llvm::APSInt &Oversized) { 5865 // This method tries to turn a variable array into a constant 5866 // array even when the size isn't an ICE. This is necessary 5867 // for compatibility with code that depends on gcc's buggy 5868 // constant expression folding, like struct {char x[(int)(char*)2];} 5869 SizeIsNegative = false; 5870 Oversized = 0; 5871 5872 if (T->isDependentType()) 5873 return QualType(); 5874 5875 QualifierCollector Qs; 5876 const Type *Ty = Qs.strip(T); 5877 5878 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 5879 QualType Pointee = PTy->getPointeeType(); 5880 QualType FixedType = 5881 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 5882 Oversized); 5883 if (FixedType.isNull()) return FixedType; 5884 FixedType = Context.getPointerType(FixedType); 5885 return Qs.apply(Context, FixedType); 5886 } 5887 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 5888 QualType Inner = PTy->getInnerType(); 5889 QualType FixedType = 5890 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5891 Oversized); 5892 if (FixedType.isNull()) return FixedType; 5893 FixedType = Context.getParenType(FixedType); 5894 return Qs.apply(Context, FixedType); 5895 } 5896 5897 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5898 if (!VLATy) 5899 return QualType(); 5900 // FIXME: We should probably handle this case 5901 if (VLATy->getElementType()->isVariablyModifiedType()) 5902 return QualType(); 5903 5904 Expr::EvalResult Result; 5905 if (!VLATy->getSizeExpr() || 5906 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context)) 5907 return QualType(); 5908 5909 llvm::APSInt Res = Result.Val.getInt(); 5910 5911 // Check whether the array size is negative. 5912 if (Res.isSigned() && Res.isNegative()) { 5913 SizeIsNegative = true; 5914 return QualType(); 5915 } 5916 5917 // Check whether the array is too large to be addressed. 5918 unsigned ActiveSizeBits 5919 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5920 Res); 5921 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5922 Oversized = Res; 5923 return QualType(); 5924 } 5925 5926 return Context.getConstantArrayType( 5927 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0); 5928 } 5929 5930 static void 5931 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5932 SrcTL = SrcTL.getUnqualifiedLoc(); 5933 DstTL = DstTL.getUnqualifiedLoc(); 5934 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5935 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5936 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5937 DstPTL.getPointeeLoc()); 5938 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5939 return; 5940 } 5941 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5942 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5943 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5944 DstPTL.getInnerLoc()); 5945 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5946 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5947 return; 5948 } 5949 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5950 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5951 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5952 TypeLoc DstElemTL = DstATL.getElementLoc(); 5953 DstElemTL.initializeFullCopy(SrcElemTL); 5954 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5955 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5956 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5957 } 5958 5959 /// Helper method to turn variable array types into constant array 5960 /// types in certain situations which would otherwise be errors (for 5961 /// GCC compatibility). 5962 static TypeSourceInfo* 5963 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5964 ASTContext &Context, 5965 bool &SizeIsNegative, 5966 llvm::APSInt &Oversized) { 5967 QualType FixedTy 5968 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5969 SizeIsNegative, Oversized); 5970 if (FixedTy.isNull()) 5971 return nullptr; 5972 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5973 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5974 FixedTInfo->getTypeLoc()); 5975 return FixedTInfo; 5976 } 5977 5978 /// Register the given locally-scoped extern "C" declaration so 5979 /// that it can be found later for redeclarations. We include any extern "C" 5980 /// declaration that is not visible in the translation unit here, not just 5981 /// function-scope declarations. 5982 void 5983 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5984 if (!getLangOpts().CPlusPlus && 5985 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5986 // Don't need to track declarations in the TU in C. 5987 return; 5988 5989 // Note that we have a locally-scoped external with this name. 5990 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5991 } 5992 5993 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5994 // FIXME: We can have multiple results via __attribute__((overloadable)). 5995 auto Result = Context.getExternCContextDecl()->lookup(Name); 5996 return Result.empty() ? nullptr : *Result.begin(); 5997 } 5998 5999 /// Diagnose function specifiers on a declaration of an identifier that 6000 /// does not identify a function. 6001 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 6002 // FIXME: We should probably indicate the identifier in question to avoid 6003 // confusion for constructs like "virtual int a(), b;" 6004 if (DS.isVirtualSpecified()) 6005 Diag(DS.getVirtualSpecLoc(), 6006 diag::err_virtual_non_function); 6007 6008 if (DS.hasExplicitSpecifier()) 6009 Diag(DS.getExplicitSpecLoc(), 6010 diag::err_explicit_non_function); 6011 6012 if (DS.isNoreturnSpecified()) 6013 Diag(DS.getNoreturnSpecLoc(), 6014 diag::err_noreturn_non_function); 6015 } 6016 6017 NamedDecl* 6018 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 6019 TypeSourceInfo *TInfo, LookupResult &Previous) { 6020 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 6021 if (D.getCXXScopeSpec().isSet()) { 6022 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 6023 << D.getCXXScopeSpec().getRange(); 6024 D.setInvalidType(); 6025 // Pretend we didn't see the scope specifier. 6026 DC = CurContext; 6027 Previous.clear(); 6028 } 6029 6030 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6031 6032 if (D.getDeclSpec().isInlineSpecified()) 6033 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6034 << getLangOpts().CPlusPlus17; 6035 if (D.getDeclSpec().hasConstexprSpecifier()) 6036 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 6037 << 1 << D.getDeclSpec().getConstexprSpecifier(); 6038 6039 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) { 6040 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName) 6041 Diag(D.getName().StartLocation, 6042 diag::err_deduction_guide_invalid_specifier) 6043 << "typedef"; 6044 else 6045 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 6046 << D.getName().getSourceRange(); 6047 return nullptr; 6048 } 6049 6050 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 6051 if (!NewTD) return nullptr; 6052 6053 // Handle attributes prior to checking for duplicates in MergeVarDecl 6054 ProcessDeclAttributes(S, NewTD, D); 6055 6056 CheckTypedefForVariablyModifiedType(S, NewTD); 6057 6058 bool Redeclaration = D.isRedeclaration(); 6059 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 6060 D.setRedeclaration(Redeclaration); 6061 return ND; 6062 } 6063 6064 void 6065 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 6066 // C99 6.7.7p2: If a typedef name specifies a variably modified type 6067 // then it shall have block scope. 6068 // Note that variably modified types must be fixed before merging the decl so 6069 // that redeclarations will match. 6070 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 6071 QualType T = TInfo->getType(); 6072 if (T->isVariablyModifiedType()) { 6073 setFunctionHasBranchProtectedScope(); 6074 6075 if (S->getFnParent() == nullptr) { 6076 bool SizeIsNegative; 6077 llvm::APSInt Oversized; 6078 TypeSourceInfo *FixedTInfo = 6079 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6080 SizeIsNegative, 6081 Oversized); 6082 if (FixedTInfo) { 6083 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 6084 NewTD->setTypeSourceInfo(FixedTInfo); 6085 } else { 6086 if (SizeIsNegative) 6087 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 6088 else if (T->isVariableArrayType()) 6089 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 6090 else if (Oversized.getBoolValue()) 6091 Diag(NewTD->getLocation(), diag::err_array_too_large) 6092 << Oversized.toString(10); 6093 else 6094 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 6095 NewTD->setInvalidDecl(); 6096 } 6097 } 6098 } 6099 } 6100 6101 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 6102 /// declares a typedef-name, either using the 'typedef' type specifier or via 6103 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 6104 NamedDecl* 6105 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 6106 LookupResult &Previous, bool &Redeclaration) { 6107 6108 // Find the shadowed declaration before filtering for scope. 6109 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous); 6110 6111 // Merge the decl with the existing one if appropriate. If the decl is 6112 // in an outer scope, it isn't the same thing. 6113 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 6114 /*AllowInlineNamespace*/false); 6115 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 6116 if (!Previous.empty()) { 6117 Redeclaration = true; 6118 MergeTypedefNameDecl(S, NewTD, Previous); 6119 } else { 6120 inferGslPointerAttribute(NewTD); 6121 } 6122 6123 if (ShadowedDecl && !Redeclaration) 6124 CheckShadow(NewTD, ShadowedDecl, Previous); 6125 6126 // If this is the C FILE type, notify the AST context. 6127 if (IdentifierInfo *II = NewTD->getIdentifier()) 6128 if (!NewTD->isInvalidDecl() && 6129 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6130 if (II->isStr("FILE")) 6131 Context.setFILEDecl(NewTD); 6132 else if (II->isStr("jmp_buf")) 6133 Context.setjmp_bufDecl(NewTD); 6134 else if (II->isStr("sigjmp_buf")) 6135 Context.setsigjmp_bufDecl(NewTD); 6136 else if (II->isStr("ucontext_t")) 6137 Context.setucontext_tDecl(NewTD); 6138 } 6139 6140 return NewTD; 6141 } 6142 6143 /// Determines whether the given declaration is an out-of-scope 6144 /// previous declaration. 6145 /// 6146 /// This routine should be invoked when name lookup has found a 6147 /// previous declaration (PrevDecl) that is not in the scope where a 6148 /// new declaration by the same name is being introduced. If the new 6149 /// declaration occurs in a local scope, previous declarations with 6150 /// linkage may still be considered previous declarations (C99 6151 /// 6.2.2p4-5, C++ [basic.link]p6). 6152 /// 6153 /// \param PrevDecl the previous declaration found by name 6154 /// lookup 6155 /// 6156 /// \param DC the context in which the new declaration is being 6157 /// declared. 6158 /// 6159 /// \returns true if PrevDecl is an out-of-scope previous declaration 6160 /// for a new delcaration with the same name. 6161 static bool 6162 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 6163 ASTContext &Context) { 6164 if (!PrevDecl) 6165 return false; 6166 6167 if (!PrevDecl->hasLinkage()) 6168 return false; 6169 6170 if (Context.getLangOpts().CPlusPlus) { 6171 // C++ [basic.link]p6: 6172 // If there is a visible declaration of an entity with linkage 6173 // having the same name and type, ignoring entities declared 6174 // outside the innermost enclosing namespace scope, the block 6175 // scope declaration declares that same entity and receives the 6176 // linkage of the previous declaration. 6177 DeclContext *OuterContext = DC->getRedeclContext(); 6178 if (!OuterContext->isFunctionOrMethod()) 6179 // This rule only applies to block-scope declarations. 6180 return false; 6181 6182 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 6183 if (PrevOuterContext->isRecord()) 6184 // We found a member function: ignore it. 6185 return false; 6186 6187 // Find the innermost enclosing namespace for the new and 6188 // previous declarations. 6189 OuterContext = OuterContext->getEnclosingNamespaceContext(); 6190 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 6191 6192 // The previous declaration is in a different namespace, so it 6193 // isn't the same function. 6194 if (!OuterContext->Equals(PrevOuterContext)) 6195 return false; 6196 } 6197 6198 return true; 6199 } 6200 6201 static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) { 6202 CXXScopeSpec &SS = D.getCXXScopeSpec(); 6203 if (!SS.isSet()) return; 6204 DD->setQualifierInfo(SS.getWithLocInContext(S.Context)); 6205 } 6206 6207 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 6208 QualType type = decl->getType(); 6209 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 6210 if (lifetime == Qualifiers::OCL_Autoreleasing) { 6211 // Various kinds of declaration aren't allowed to be __autoreleasing. 6212 unsigned kind = -1U; 6213 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6214 if (var->hasAttr<BlocksAttr>()) 6215 kind = 0; // __block 6216 else if (!var->hasLocalStorage()) 6217 kind = 1; // global 6218 } else if (isa<ObjCIvarDecl>(decl)) { 6219 kind = 3; // ivar 6220 } else if (isa<FieldDecl>(decl)) { 6221 kind = 2; // field 6222 } 6223 6224 if (kind != -1U) { 6225 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 6226 << kind; 6227 } 6228 } else if (lifetime == Qualifiers::OCL_None) { 6229 // Try to infer lifetime. 6230 if (!type->isObjCLifetimeType()) 6231 return false; 6232 6233 lifetime = type->getObjCARCImplicitLifetime(); 6234 type = Context.getLifetimeQualifiedType(type, lifetime); 6235 decl->setType(type); 6236 } 6237 6238 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 6239 // Thread-local variables cannot have lifetime. 6240 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 6241 var->getTLSKind()) { 6242 Diag(var->getLocation(), diag::err_arc_thread_ownership) 6243 << var->getType(); 6244 return true; 6245 } 6246 } 6247 6248 return false; 6249 } 6250 6251 void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) { 6252 if (Decl->getType().hasAddressSpace()) 6253 return; 6254 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) { 6255 QualType Type = Var->getType(); 6256 if (Type->isSamplerT() || Type->isVoidType()) 6257 return; 6258 LangAS ImplAS = LangAS::opencl_private; 6259 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) && 6260 Var->hasGlobalStorage()) 6261 ImplAS = LangAS::opencl_global; 6262 // If the original type from a decayed type is an array type and that array 6263 // type has no address space yet, deduce it now. 6264 if (auto DT = dyn_cast<DecayedType>(Type)) { 6265 auto OrigTy = DT->getOriginalType(); 6266 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) { 6267 // Add the address space to the original array type and then propagate 6268 // that to the element type through `getAsArrayType`. 6269 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS); 6270 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0); 6271 // Re-generate the decayed type. 6272 Type = Context.getDecayedType(OrigTy); 6273 } 6274 } 6275 Type = Context.getAddrSpaceQualType(Type, ImplAS); 6276 // Apply any qualifiers (including address space) from the array type to 6277 // the element type. This implements C99 6.7.3p8: "If the specification of 6278 // an array type includes any type qualifiers, the element type is so 6279 // qualified, not the array type." 6280 if (Type->isArrayType()) 6281 Type = QualType(Context.getAsArrayType(Type), 0); 6282 Decl->setType(Type); 6283 } 6284 } 6285 6286 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 6287 // Ensure that an auto decl is deduced otherwise the checks below might cache 6288 // the wrong linkage. 6289 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 6290 6291 // 'weak' only applies to declarations with external linkage. 6292 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 6293 if (!ND.isExternallyVisible()) { 6294 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 6295 ND.dropAttr<WeakAttr>(); 6296 } 6297 } 6298 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 6299 if (ND.isExternallyVisible()) { 6300 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 6301 ND.dropAttr<WeakRefAttr>(); 6302 ND.dropAttr<AliasAttr>(); 6303 } 6304 } 6305 6306 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 6307 if (VD->hasInit()) { 6308 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 6309 assert(VD->isThisDeclarationADefinition() && 6310 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 6311 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0; 6312 VD->dropAttr<AliasAttr>(); 6313 } 6314 } 6315 } 6316 6317 // 'selectany' only applies to externally visible variable declarations. 6318 // It does not apply to functions. 6319 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 6320 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 6321 S.Diag(Attr->getLocation(), 6322 diag::err_attribute_selectany_non_extern_data); 6323 ND.dropAttr<SelectAnyAttr>(); 6324 } 6325 } 6326 6327 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 6328 auto *VD = dyn_cast<VarDecl>(&ND); 6329 bool IsAnonymousNS = false; 6330 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6331 if (VD) { 6332 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext()); 6333 while (NS && !IsAnonymousNS) { 6334 IsAnonymousNS = NS->isAnonymousNamespace(); 6335 NS = dyn_cast<NamespaceDecl>(NS->getParent()); 6336 } 6337 } 6338 // dll attributes require external linkage. Static locals may have external 6339 // linkage but still cannot be explicitly imported or exported. 6340 // In Microsoft mode, a variable defined in anonymous namespace must have 6341 // external linkage in order to be exported. 6342 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft; 6343 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) || 6344 (!AnonNSInMicrosoftMode && 6345 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) { 6346 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 6347 << &ND << Attr; 6348 ND.setInvalidDecl(); 6349 } 6350 } 6351 6352 // Virtual functions cannot be marked as 'notail'. 6353 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 6354 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 6355 if (MD->isVirtual()) { 6356 S.Diag(ND.getLocation(), 6357 diag::err_invalid_attribute_on_virtual_function) 6358 << Attr; 6359 ND.dropAttr<NotTailCalledAttr>(); 6360 } 6361 6362 // Check the attributes on the function type, if any. 6363 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) { 6364 // Don't declare this variable in the second operand of the for-statement; 6365 // GCC miscompiles that by ending its lifetime before evaluating the 6366 // third operand. See gcc.gnu.org/PR86769. 6367 AttributedTypeLoc ATL; 6368 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc(); 6369 (ATL = TL.getAsAdjusted<AttributedTypeLoc>()); 6370 TL = ATL.getModifiedLoc()) { 6371 // The [[lifetimebound]] attribute can be applied to the implicit object 6372 // parameter of a non-static member function (other than a ctor or dtor) 6373 // by applying it to the function type. 6374 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) { 6375 const auto *MD = dyn_cast<CXXMethodDecl>(FD); 6376 if (!MD || MD->isStatic()) { 6377 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param) 6378 << !MD << A->getRange(); 6379 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) { 6380 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor) 6381 << isa<CXXDestructorDecl>(MD) << A->getRange(); 6382 } 6383 } 6384 } 6385 } 6386 } 6387 6388 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 6389 NamedDecl *NewDecl, 6390 bool IsSpecialization, 6391 bool IsDefinition) { 6392 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl()) 6393 return; 6394 6395 bool IsTemplate = false; 6396 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) { 6397 OldDecl = OldTD->getTemplatedDecl(); 6398 IsTemplate = true; 6399 if (!IsSpecialization) 6400 IsDefinition = false; 6401 } 6402 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) { 6403 NewDecl = NewTD->getTemplatedDecl(); 6404 IsTemplate = true; 6405 } 6406 6407 if (!OldDecl || !NewDecl) 6408 return; 6409 6410 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 6411 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 6412 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 6413 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 6414 6415 // dllimport and dllexport are inheritable attributes so we have to exclude 6416 // inherited attribute instances. 6417 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 6418 (NewExportAttr && !NewExportAttr->isInherited()); 6419 6420 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 6421 // the only exception being explicit specializations. 6422 // Implicitly generated declarations are also excluded for now because there 6423 // is no other way to switch these to use dllimport or dllexport. 6424 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 6425 6426 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 6427 // Allow with a warning for free functions and global variables. 6428 bool JustWarn = false; 6429 if (!OldDecl->isCXXClassMember()) { 6430 auto *VD = dyn_cast<VarDecl>(OldDecl); 6431 if (VD && !VD->getDescribedVarTemplate()) 6432 JustWarn = true; 6433 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 6434 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 6435 JustWarn = true; 6436 } 6437 6438 // We cannot change a declaration that's been used because IR has already 6439 // been emitted. Dllimported functions will still work though (modulo 6440 // address equality) as they can use the thunk. 6441 if (OldDecl->isUsed()) 6442 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 6443 JustWarn = false; 6444 6445 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 6446 : diag::err_attribute_dll_redeclaration; 6447 S.Diag(NewDecl->getLocation(), DiagID) 6448 << NewDecl 6449 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 6450 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6451 if (!JustWarn) { 6452 NewDecl->setInvalidDecl(); 6453 return; 6454 } 6455 } 6456 6457 // A redeclaration is not allowed to drop a dllimport attribute, the only 6458 // exceptions being inline function definitions (except for function 6459 // templates), local extern declarations, qualified friend declarations or 6460 // special MSVC extension: in the last case, the declaration is treated as if 6461 // it were marked dllexport. 6462 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 6463 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft(); 6464 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) { 6465 // Ignore static data because out-of-line definitions are diagnosed 6466 // separately. 6467 IsStaticDataMember = VD->isStaticDataMember(); 6468 IsDefinition = VD->isThisDeclarationADefinition(S.Context) != 6469 VarDecl::DeclarationOnly; 6470 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 6471 IsInline = FD->isInlined(); 6472 IsQualifiedFriend = FD->getQualifier() && 6473 FD->getFriendObjectKind() == Decl::FOK_Declared; 6474 } 6475 6476 if (OldImportAttr && !HasNewAttr && 6477 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember && 6478 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 6479 if (IsMicrosoft && IsDefinition) { 6480 S.Diag(NewDecl->getLocation(), 6481 diag::warn_redeclaration_without_import_attribute) 6482 << NewDecl; 6483 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6484 NewDecl->dropAttr<DLLImportAttr>(); 6485 NewDecl->addAttr( 6486 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange())); 6487 } else { 6488 S.Diag(NewDecl->getLocation(), 6489 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 6490 << NewDecl << OldImportAttr; 6491 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 6492 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 6493 OldDecl->dropAttr<DLLImportAttr>(); 6494 NewDecl->dropAttr<DLLImportAttr>(); 6495 } 6496 } else if (IsInline && OldImportAttr && !IsMicrosoft) { 6497 // In MinGW, seeing a function declared inline drops the dllimport 6498 // attribute. 6499 OldDecl->dropAttr<DLLImportAttr>(); 6500 NewDecl->dropAttr<DLLImportAttr>(); 6501 S.Diag(NewDecl->getLocation(), 6502 diag::warn_dllimport_dropped_from_inline_function) 6503 << NewDecl << OldImportAttr; 6504 } 6505 6506 // A specialization of a class template member function is processed here 6507 // since it's a redeclaration. If the parent class is dllexport, the 6508 // specialization inherits that attribute. This doesn't happen automatically 6509 // since the parent class isn't instantiated until later. 6510 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) { 6511 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization && 6512 !NewImportAttr && !NewExportAttr) { 6513 if (const DLLExportAttr *ParentExportAttr = 6514 MD->getParent()->getAttr<DLLExportAttr>()) { 6515 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context); 6516 NewAttr->setInherited(true); 6517 NewDecl->addAttr(NewAttr); 6518 } 6519 } 6520 } 6521 } 6522 6523 /// Given that we are within the definition of the given function, 6524 /// will that definition behave like C99's 'inline', where the 6525 /// definition is discarded except for optimization purposes? 6526 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 6527 // Try to avoid calling GetGVALinkageForFunction. 6528 6529 // All cases of this require the 'inline' keyword. 6530 if (!FD->isInlined()) return false; 6531 6532 // This is only possible in C++ with the gnu_inline attribute. 6533 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 6534 return false; 6535 6536 // Okay, go ahead and call the relatively-more-expensive function. 6537 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 6538 } 6539 6540 /// Determine whether a variable is extern "C" prior to attaching 6541 /// an initializer. We can't just call isExternC() here, because that 6542 /// will also compute and cache whether the declaration is externally 6543 /// visible, which might change when we attach the initializer. 6544 /// 6545 /// This can only be used if the declaration is known to not be a 6546 /// redeclaration of an internal linkage declaration. 6547 /// 6548 /// For instance: 6549 /// 6550 /// auto x = []{}; 6551 /// 6552 /// Attaching the initializer here makes this declaration not externally 6553 /// visible, because its type has internal linkage. 6554 /// 6555 /// FIXME: This is a hack. 6556 template<typename T> 6557 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 6558 if (S.getLangOpts().CPlusPlus) { 6559 // In C++, the overloadable attribute negates the effects of extern "C". 6560 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 6561 return false; 6562 6563 // So do CUDA's host/device attributes. 6564 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() || 6565 D->template hasAttr<CUDAHostAttr>())) 6566 return false; 6567 } 6568 return D->isExternC(); 6569 } 6570 6571 static bool shouldConsiderLinkage(const VarDecl *VD) { 6572 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 6573 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) || 6574 isa<OMPDeclareMapperDecl>(DC)) 6575 return VD->hasExternalStorage(); 6576 if (DC->isFileContext()) 6577 return true; 6578 if (DC->isRecord()) 6579 return false; 6580 if (isa<RequiresExprBodyDecl>(DC)) 6581 return false; 6582 llvm_unreachable("Unexpected context"); 6583 } 6584 6585 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 6586 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 6587 if (DC->isFileContext() || DC->isFunctionOrMethod() || 6588 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC)) 6589 return true; 6590 if (DC->isRecord()) 6591 return false; 6592 llvm_unreachable("Unexpected context"); 6593 } 6594 6595 static bool hasParsedAttr(Scope *S, const Declarator &PD, 6596 ParsedAttr::Kind Kind) { 6597 // Check decl attributes on the DeclSpec. 6598 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind)) 6599 return true; 6600 6601 // Walk the declarator structure, checking decl attributes that were in a type 6602 // position to the decl itself. 6603 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 6604 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind)) 6605 return true; 6606 } 6607 6608 // Finally, check attributes on the decl itself. 6609 return PD.getAttributes().hasAttribute(Kind); 6610 } 6611 6612 /// Adjust the \c DeclContext for a function or variable that might be a 6613 /// function-local external declaration. 6614 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 6615 if (!DC->isFunctionOrMethod()) 6616 return false; 6617 6618 // If this is a local extern function or variable declared within a function 6619 // template, don't add it into the enclosing namespace scope until it is 6620 // instantiated; it might have a dependent type right now. 6621 if (DC->isDependentContext()) 6622 return true; 6623 6624 // C++11 [basic.link]p7: 6625 // When a block scope declaration of an entity with linkage is not found to 6626 // refer to some other declaration, then that entity is a member of the 6627 // innermost enclosing namespace. 6628 // 6629 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 6630 // semantically-enclosing namespace, not a lexically-enclosing one. 6631 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 6632 DC = DC->getParent(); 6633 return true; 6634 } 6635 6636 /// Returns true if given declaration has external C language linkage. 6637 static bool isDeclExternC(const Decl *D) { 6638 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 6639 return FD->isExternC(); 6640 if (const auto *VD = dyn_cast<VarDecl>(D)) 6641 return VD->isExternC(); 6642 6643 llvm_unreachable("Unknown type of decl!"); 6644 } 6645 /// Returns true if there hasn't been any invalid type diagnosed. 6646 static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D, 6647 DeclContext *DC, QualType R) { 6648 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument. 6649 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function 6650 // argument. 6651 if (R->isImageType() || R->isPipeType()) { 6652 Se.Diag(D.getIdentifierLoc(), 6653 diag::err_opencl_type_can_only_be_used_as_function_parameter) 6654 << R; 6655 D.setInvalidType(); 6656 return false; 6657 } 6658 6659 // OpenCL v1.2 s6.9.r: 6660 // The event type cannot be used to declare a program scope variable. 6661 // OpenCL v2.0 s6.9.q: 6662 // The clk_event_t and reserve_id_t types cannot be declared in program 6663 // scope. 6664 if (NULL == S->getParent()) { 6665 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) { 6666 Se.Diag(D.getIdentifierLoc(), 6667 diag::err_invalid_type_for_program_scope_var) 6668 << R; 6669 D.setInvalidType(); 6670 return false; 6671 } 6672 } 6673 6674 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 6675 QualType NR = R; 6676 while (NR->isPointerType()) { 6677 if (NR->isFunctionPointerType()) { 6678 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer); 6679 D.setInvalidType(); 6680 return false; 6681 } 6682 NR = NR->getPointeeType(); 6683 } 6684 6685 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) { 6686 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 6687 // half array type (unless the cl_khr_fp16 extension is enabled). 6688 if (Se.Context.getBaseElementType(R)->isHalfType()) { 6689 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 6690 D.setInvalidType(); 6691 return false; 6692 } 6693 } 6694 6695 // OpenCL v1.2 s6.9.r: 6696 // The event type cannot be used with the __local, __constant and __global 6697 // address space qualifiers. 6698 if (R->isEventT()) { 6699 if (R.getAddressSpace() != LangAS::opencl_private) { 6700 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual); 6701 D.setInvalidType(); 6702 return false; 6703 } 6704 } 6705 6706 // C++ for OpenCL does not allow the thread_local storage qualifier. 6707 // OpenCL C does not support thread_local either, and 6708 // also reject all other thread storage class specifiers. 6709 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec(); 6710 if (TSC != TSCS_unspecified) { 6711 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus; 6712 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6713 diag::err_opencl_unknown_type_specifier) 6714 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString() 6715 << DeclSpec::getSpecifierName(TSC) << 1; 6716 D.setInvalidType(); 6717 return false; 6718 } 6719 6720 if (R->isSamplerT()) { 6721 // OpenCL v1.2 s6.9.b p4: 6722 // The sampler type cannot be used with the __local and __global address 6723 // space qualifiers. 6724 if (R.getAddressSpace() == LangAS::opencl_local || 6725 R.getAddressSpace() == LangAS::opencl_global) { 6726 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 6727 D.setInvalidType(); 6728 } 6729 6730 // OpenCL v1.2 s6.12.14.1: 6731 // A global sampler must be declared with either the constant address 6732 // space qualifier or with the const qualifier. 6733 if (DC->isTranslationUnit() && 6734 !(R.getAddressSpace() == LangAS::opencl_constant || 6735 R.isConstQualified())) { 6736 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler); 6737 D.setInvalidType(); 6738 } 6739 if (D.isInvalidType()) 6740 return false; 6741 } 6742 return true; 6743 } 6744 6745 NamedDecl *Sema::ActOnVariableDeclarator( 6746 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, 6747 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, 6748 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) { 6749 QualType R = TInfo->getType(); 6750 DeclarationName Name = GetNameForDeclarator(D).getName(); 6751 6752 IdentifierInfo *II = Name.getAsIdentifierInfo(); 6753 6754 if (D.isDecompositionDeclarator()) { 6755 // Take the name of the first declarator as our name for diagnostic 6756 // purposes. 6757 auto &Decomp = D.getDecompositionDeclarator(); 6758 if (!Decomp.bindings().empty()) { 6759 II = Decomp.bindings()[0].Name; 6760 Name = II; 6761 } 6762 } else if (!II) { 6763 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name; 6764 return nullptr; 6765 } 6766 6767 6768 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 6769 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 6770 6771 // dllimport globals without explicit storage class are treated as extern. We 6772 // have to change the storage class this early to get the right DeclContext. 6773 if (SC == SC_None && !DC->isRecord() && 6774 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) && 6775 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport)) 6776 SC = SC_Extern; 6777 6778 DeclContext *OriginalDC = DC; 6779 bool IsLocalExternDecl = SC == SC_Extern && 6780 adjustContextForLocalExternDecl(DC); 6781 6782 if (SCSpec == DeclSpec::SCS_mutable) { 6783 // mutable can only appear on non-static class members, so it's always 6784 // an error here 6785 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 6786 D.setInvalidType(); 6787 SC = SC_None; 6788 } 6789 6790 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 6791 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 6792 D.getDeclSpec().getStorageClassSpecLoc())) { 6793 // In C++11, the 'register' storage class specifier is deprecated. 6794 // Suppress the warning in system macros, it's used in macros in some 6795 // popular C system headers, such as in glibc's htonl() macro. 6796 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6797 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 6798 : diag::warn_deprecated_register) 6799 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6800 } 6801 6802 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 6803 6804 if (!DC->isRecord() && S->getFnParent() == nullptr) { 6805 // C99 6.9p2: The storage-class specifiers auto and register shall not 6806 // appear in the declaration specifiers in an external declaration. 6807 // Global Register+Asm is a GNU extension we support. 6808 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 6809 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 6810 D.setInvalidType(); 6811 } 6812 } 6813 6814 bool IsMemberSpecialization = false; 6815 bool IsVariableTemplateSpecialization = false; 6816 bool IsPartialSpecialization = false; 6817 bool IsVariableTemplate = false; 6818 VarDecl *NewVD = nullptr; 6819 VarTemplateDecl *NewTemplate = nullptr; 6820 TemplateParameterList *TemplateParams = nullptr; 6821 if (!getLangOpts().CPlusPlus) { 6822 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), 6823 II, R, TInfo, SC); 6824 6825 if (R->getContainedDeducedType()) 6826 ParsingInitForAutoVars.insert(NewVD); 6827 6828 if (D.isInvalidType()) 6829 NewVD->setInvalidDecl(); 6830 6831 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() && 6832 NewVD->hasLocalStorage()) 6833 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(), 6834 NTCUC_AutoVar, NTCUK_Destruct); 6835 } else { 6836 bool Invalid = false; 6837 6838 if (DC->isRecord() && !CurContext->isRecord()) { 6839 // This is an out-of-line definition of a static data member. 6840 switch (SC) { 6841 case SC_None: 6842 break; 6843 case SC_Static: 6844 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6845 diag::err_static_out_of_line) 6846 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6847 break; 6848 case SC_Auto: 6849 case SC_Register: 6850 case SC_Extern: 6851 // [dcl.stc] p2: The auto or register specifiers shall be applied only 6852 // to names of variables declared in a block or to function parameters. 6853 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 6854 // of class members 6855 6856 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6857 diag::err_storage_class_for_static_member) 6858 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 6859 break; 6860 case SC_PrivateExtern: 6861 llvm_unreachable("C storage class in c++!"); 6862 } 6863 } 6864 6865 if (SC == SC_Static && CurContext->isRecord()) { 6866 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 6867 // C++ [class.static.data]p2: 6868 // A static data member shall not be a direct member of an unnamed 6869 // or local class 6870 // FIXME: or of a (possibly indirectly) nested class thereof. 6871 if (RD->isLocalClass()) { 6872 Diag(D.getIdentifierLoc(), 6873 diag::err_static_data_member_not_allowed_in_local_class) 6874 << Name << RD->getDeclName() << RD->getTagKind(); 6875 } else if (!RD->getDeclName()) { 6876 Diag(D.getIdentifierLoc(), 6877 diag::err_static_data_member_not_allowed_in_anon_struct) 6878 << Name << RD->getTagKind(); 6879 Invalid = true; 6880 } else if (RD->isUnion()) { 6881 // C++98 [class.union]p1: If a union contains a static data member, 6882 // the program is ill-formed. C++11 drops this restriction. 6883 Diag(D.getIdentifierLoc(), 6884 getLangOpts().CPlusPlus11 6885 ? diag::warn_cxx98_compat_static_data_member_in_union 6886 : diag::ext_static_data_member_in_union) << Name; 6887 } 6888 } 6889 } 6890 6891 // Match up the template parameter lists with the scope specifier, then 6892 // determine whether we have a template or a template specialization. 6893 bool InvalidScope = false; 6894 TemplateParams = MatchTemplateParametersToScopeSpecifier( 6895 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 6896 D.getCXXScopeSpec(), 6897 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 6898 ? D.getName().TemplateId 6899 : nullptr, 6900 TemplateParamLists, 6901 /*never a friend*/ false, IsMemberSpecialization, InvalidScope); 6902 Invalid |= InvalidScope; 6903 6904 if (TemplateParams) { 6905 if (!TemplateParams->size() && 6906 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 6907 // There is an extraneous 'template<>' for this variable. Complain 6908 // about it, but allow the declaration of the variable. 6909 Diag(TemplateParams->getTemplateLoc(), 6910 diag::err_template_variable_noparams) 6911 << II 6912 << SourceRange(TemplateParams->getTemplateLoc(), 6913 TemplateParams->getRAngleLoc()); 6914 TemplateParams = nullptr; 6915 } else { 6916 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 6917 // This is an explicit specialization or a partial specialization. 6918 // FIXME: Check that we can declare a specialization here. 6919 IsVariableTemplateSpecialization = true; 6920 IsPartialSpecialization = TemplateParams->size() > 0; 6921 } else { // if (TemplateParams->size() > 0) 6922 // This is a template declaration. 6923 IsVariableTemplate = true; 6924 6925 // Check that we can declare a template here. 6926 if (CheckTemplateDeclScope(S, TemplateParams)) 6927 return nullptr; 6928 6929 // Only C++1y supports variable templates (N3651). 6930 Diag(D.getIdentifierLoc(), 6931 getLangOpts().CPlusPlus14 6932 ? diag::warn_cxx11_compat_variable_template 6933 : diag::ext_variable_template); 6934 } 6935 } 6936 } else { 6937 assert((Invalid || 6938 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && 6939 "should have a 'template<>' for this decl"); 6940 } 6941 6942 if (IsVariableTemplateSpecialization) { 6943 SourceLocation TemplateKWLoc = 6944 TemplateParamLists.size() > 0 6945 ? TemplateParamLists[0]->getTemplateLoc() 6946 : SourceLocation(); 6947 DeclResult Res = ActOnVarTemplateSpecialization( 6948 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 6949 IsPartialSpecialization); 6950 if (Res.isInvalid()) 6951 return nullptr; 6952 NewVD = cast<VarDecl>(Res.get()); 6953 AddToScope = false; 6954 } else if (D.isDecompositionDeclarator()) { 6955 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(), 6956 D.getIdentifierLoc(), R, TInfo, SC, 6957 Bindings); 6958 } else 6959 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), 6960 D.getIdentifierLoc(), II, R, TInfo, SC); 6961 6962 // If this is supposed to be a variable template, create it as such. 6963 if (IsVariableTemplate) { 6964 NewTemplate = 6965 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 6966 TemplateParams, NewVD); 6967 NewVD->setDescribedVarTemplate(NewTemplate); 6968 } 6969 6970 // If this decl has an auto type in need of deduction, make a note of the 6971 // Decl so we can diagnose uses of it in its own initializer. 6972 if (R->getContainedDeducedType()) 6973 ParsingInitForAutoVars.insert(NewVD); 6974 6975 if (D.isInvalidType() || Invalid) { 6976 NewVD->setInvalidDecl(); 6977 if (NewTemplate) 6978 NewTemplate->setInvalidDecl(); 6979 } 6980 6981 SetNestedNameSpecifier(*this, NewVD, D); 6982 6983 // If we have any template parameter lists that don't directly belong to 6984 // the variable (matching the scope specifier), store them. 6985 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 6986 if (TemplateParamLists.size() > VDTemplateParamLists) 6987 NewVD->setTemplateParameterListsInfo( 6988 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 6989 } 6990 6991 if (D.getDeclSpec().isInlineSpecified()) { 6992 if (!getLangOpts().CPlusPlus) { 6993 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 6994 << 0; 6995 } else if (CurContext->isFunctionOrMethod()) { 6996 // 'inline' is not allowed on block scope variable declaration. 6997 Diag(D.getDeclSpec().getInlineSpecLoc(), 6998 diag::err_inline_declaration_block_scope) << Name 6999 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7000 } else { 7001 Diag(D.getDeclSpec().getInlineSpecLoc(), 7002 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable 7003 : diag::ext_inline_variable); 7004 NewVD->setInlineSpecified(); 7005 } 7006 } 7007 7008 // Set the lexical context. If the declarator has a C++ scope specifier, the 7009 // lexical context will be different from the semantic context. 7010 NewVD->setLexicalDeclContext(CurContext); 7011 if (NewTemplate) 7012 NewTemplate->setLexicalDeclContext(CurContext); 7013 7014 if (IsLocalExternDecl) { 7015 if (D.isDecompositionDeclarator()) 7016 for (auto *B : Bindings) 7017 B->setLocalExternDecl(); 7018 else 7019 NewVD->setLocalExternDecl(); 7020 } 7021 7022 bool EmitTLSUnsupportedError = false; 7023 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 7024 // C++11 [dcl.stc]p4: 7025 // When thread_local is applied to a variable of block scope the 7026 // storage-class-specifier static is implied if it does not appear 7027 // explicitly. 7028 // Core issue: 'static' is not implied if the variable is declared 7029 // 'extern'. 7030 if (NewVD->hasLocalStorage() && 7031 (SCSpec != DeclSpec::SCS_unspecified || 7032 TSCS != DeclSpec::TSCS_thread_local || 7033 !DC->isFunctionOrMethod())) 7034 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7035 diag::err_thread_non_global) 7036 << DeclSpec::getSpecifierName(TSCS); 7037 else if (!Context.getTargetInfo().isTLSSupported()) { 7038 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7039 // Postpone error emission until we've collected attributes required to 7040 // figure out whether it's a host or device variable and whether the 7041 // error should be ignored. 7042 EmitTLSUnsupportedError = true; 7043 // We still need to mark the variable as TLS so it shows up in AST with 7044 // proper storage class for other tools to use even if we're not going 7045 // to emit any code for it. 7046 NewVD->setTSCSpec(TSCS); 7047 } else 7048 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7049 diag::err_thread_unsupported); 7050 } else 7051 NewVD->setTSCSpec(TSCS); 7052 } 7053 7054 switch (D.getDeclSpec().getConstexprSpecifier()) { 7055 case CSK_unspecified: 7056 break; 7057 7058 case CSK_consteval: 7059 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7060 diag::err_constexpr_wrong_decl_kind) 7061 << D.getDeclSpec().getConstexprSpecifier(); 7062 LLVM_FALLTHROUGH; 7063 7064 case CSK_constexpr: 7065 NewVD->setConstexpr(true); 7066 // C++1z [dcl.spec.constexpr]p1: 7067 // A static data member declared with the constexpr specifier is 7068 // implicitly an inline variable. 7069 if (NewVD->isStaticDataMember() && 7070 (getLangOpts().CPlusPlus17 || 7071 Context.getTargetInfo().getCXXABI().isMicrosoft())) 7072 NewVD->setImplicitlyInline(); 7073 break; 7074 7075 case CSK_constinit: 7076 if (!NewVD->hasGlobalStorage()) 7077 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7078 diag::err_constinit_local_variable); 7079 else 7080 NewVD->addAttr(ConstInitAttr::Create( 7081 Context, D.getDeclSpec().getConstexprSpecLoc(), 7082 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit)); 7083 break; 7084 } 7085 7086 // C99 6.7.4p3 7087 // An inline definition of a function with external linkage shall 7088 // not contain a definition of a modifiable object with static or 7089 // thread storage duration... 7090 // We only apply this when the function is required to be defined 7091 // elsewhere, i.e. when the function is not 'extern inline'. Note 7092 // that a local variable with thread storage duration still has to 7093 // be marked 'static'. Also note that it's possible to get these 7094 // semantics in C++ using __attribute__((gnu_inline)). 7095 if (SC == SC_Static && S->getFnParent() != nullptr && 7096 !NewVD->getType().isConstQualified()) { 7097 FunctionDecl *CurFD = getCurFunctionDecl(); 7098 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 7099 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7100 diag::warn_static_local_in_extern_inline); 7101 MaybeSuggestAddingStaticToDecl(CurFD); 7102 } 7103 } 7104 7105 if (D.getDeclSpec().isModulePrivateSpecified()) { 7106 if (IsVariableTemplateSpecialization) 7107 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7108 << (IsPartialSpecialization ? 1 : 0) 7109 << FixItHint::CreateRemoval( 7110 D.getDeclSpec().getModulePrivateSpecLoc()); 7111 else if (IsMemberSpecialization) 7112 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 7113 << 2 7114 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7115 else if (NewVD->hasLocalStorage()) 7116 Diag(NewVD->getLocation(), diag::err_module_private_local) 7117 << 0 << NewVD->getDeclName() 7118 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 7119 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 7120 else { 7121 NewVD->setModulePrivate(); 7122 if (NewTemplate) 7123 NewTemplate->setModulePrivate(); 7124 for (auto *B : Bindings) 7125 B->setModulePrivate(); 7126 } 7127 } 7128 7129 if (getLangOpts().OpenCL) { 7130 7131 deduceOpenCLAddressSpace(NewVD); 7132 7133 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType()); 7134 } 7135 7136 // Handle attributes prior to checking for duplicates in MergeVarDecl 7137 ProcessDeclAttributes(S, NewVD, D); 7138 7139 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) { 7140 if (EmitTLSUnsupportedError && 7141 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) || 7142 (getLangOpts().OpenMPIsDevice && 7143 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD)))) 7144 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7145 diag::err_thread_unsupported); 7146 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 7147 // storage [duration]." 7148 if (SC == SC_None && S->getFnParent() != nullptr && 7149 (NewVD->hasAttr<CUDASharedAttr>() || 7150 NewVD->hasAttr<CUDAConstantAttr>())) { 7151 NewVD->setStorageClass(SC_Static); 7152 } 7153 } 7154 7155 // Ensure that dllimport globals without explicit storage class are treated as 7156 // extern. The storage class is set above using parsed attributes. Now we can 7157 // check the VarDecl itself. 7158 assert(!NewVD->hasAttr<DLLImportAttr>() || 7159 NewVD->getAttr<DLLImportAttr>()->isInherited() || 7160 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 7161 7162 // In auto-retain/release, infer strong retension for variables of 7163 // retainable type. 7164 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 7165 NewVD->setInvalidDecl(); 7166 7167 // Handle GNU asm-label extension (encoded as an attribute). 7168 if (Expr *E = (Expr*)D.getAsmLabel()) { 7169 // The parser guarantees this is a string. 7170 StringLiteral *SE = cast<StringLiteral>(E); 7171 StringRef Label = SE->getString(); 7172 if (S->getFnParent() != nullptr) { 7173 switch (SC) { 7174 case SC_None: 7175 case SC_Auto: 7176 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 7177 break; 7178 case SC_Register: 7179 // Local Named register 7180 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 7181 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 7182 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7183 break; 7184 case SC_Static: 7185 case SC_Extern: 7186 case SC_PrivateExtern: 7187 break; 7188 } 7189 } else if (SC == SC_Register) { 7190 // Global Named register 7191 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) { 7192 const auto &TI = Context.getTargetInfo(); 7193 bool HasSizeMismatch; 7194 7195 if (!TI.isValidGCCRegisterName(Label)) 7196 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 7197 else if (!TI.validateGlobalRegisterVariable(Label, 7198 Context.getTypeSize(R), 7199 HasSizeMismatch)) 7200 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label; 7201 else if (HasSizeMismatch) 7202 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label; 7203 } 7204 7205 if (!R->isIntegralType(Context) && !R->isPointerType()) { 7206 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type); 7207 NewVD->setInvalidDecl(true); 7208 } 7209 } 7210 7211 NewVD->addAttr(AsmLabelAttr::Create(Context, Label, 7212 /*IsLiteralLabel=*/true, 7213 SE->getStrTokenLoc(0))); 7214 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7215 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7216 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 7217 if (I != ExtnameUndeclaredIdentifiers.end()) { 7218 if (isDeclExternC(NewVD)) { 7219 NewVD->addAttr(I->second); 7220 ExtnameUndeclaredIdentifiers.erase(I); 7221 } else 7222 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 7223 << /*Variable*/1 << NewVD; 7224 } 7225 } 7226 7227 // Find the shadowed declaration before filtering for scope. 7228 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty() 7229 ? getShadowedDeclaration(NewVD, Previous) 7230 : nullptr; 7231 7232 // Don't consider existing declarations that are in a different 7233 // scope and are out-of-semantic-context declarations (if the new 7234 // declaration has linkage). 7235 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 7236 D.getCXXScopeSpec().isNotEmpty() || 7237 IsMemberSpecialization || 7238 IsVariableTemplateSpecialization); 7239 7240 // Check whether the previous declaration is in the same block scope. This 7241 // affects whether we merge types with it, per C++11 [dcl.array]p3. 7242 if (getLangOpts().CPlusPlus && 7243 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 7244 NewVD->setPreviousDeclInSameBlockScope( 7245 Previous.isSingleResult() && !Previous.isShadowed() && 7246 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 7247 7248 if (!getLangOpts().CPlusPlus) { 7249 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7250 } else { 7251 // If this is an explicit specialization of a static data member, check it. 7252 if (IsMemberSpecialization && !NewVD->isInvalidDecl() && 7253 CheckMemberSpecialization(NewVD, Previous)) 7254 NewVD->setInvalidDecl(); 7255 7256 // Merge the decl with the existing one if appropriate. 7257 if (!Previous.empty()) { 7258 if (Previous.isSingleResult() && 7259 isa<FieldDecl>(Previous.getFoundDecl()) && 7260 D.getCXXScopeSpec().isSet()) { 7261 // The user tried to define a non-static data member 7262 // out-of-line (C++ [dcl.meaning]p1). 7263 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 7264 << D.getCXXScopeSpec().getRange(); 7265 Previous.clear(); 7266 NewVD->setInvalidDecl(); 7267 } 7268 } else if (D.getCXXScopeSpec().isSet()) { 7269 // No previous declaration in the qualifying scope. 7270 Diag(D.getIdentifierLoc(), diag::err_no_member) 7271 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 7272 << D.getCXXScopeSpec().getRange(); 7273 NewVD->setInvalidDecl(); 7274 } 7275 7276 if (!IsVariableTemplateSpecialization) 7277 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 7278 7279 if (NewTemplate) { 7280 VarTemplateDecl *PrevVarTemplate = 7281 NewVD->getPreviousDecl() 7282 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 7283 : nullptr; 7284 7285 // Check the template parameter list of this declaration, possibly 7286 // merging in the template parameter list from the previous variable 7287 // template declaration. 7288 if (CheckTemplateParameterList( 7289 TemplateParams, 7290 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 7291 : nullptr, 7292 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 7293 DC->isDependentContext()) 7294 ? TPC_ClassTemplateMember 7295 : TPC_VarTemplate)) 7296 NewVD->setInvalidDecl(); 7297 7298 // If we are providing an explicit specialization of a static variable 7299 // template, make a note of that. 7300 if (PrevVarTemplate && 7301 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 7302 PrevVarTemplate->setMemberSpecialization(); 7303 } 7304 } 7305 7306 // Diagnose shadowed variables iff this isn't a redeclaration. 7307 if (ShadowedDecl && !D.isRedeclaration()) 7308 CheckShadow(NewVD, ShadowedDecl, Previous); 7309 7310 ProcessPragmaWeak(S, NewVD); 7311 7312 // If this is the first declaration of an extern C variable, update 7313 // the map of such variables. 7314 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 7315 isIncompleteDeclExternC(*this, NewVD)) 7316 RegisterLocallyScopedExternCDecl(NewVD, S); 7317 7318 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 7319 MangleNumberingContext *MCtx; 7320 Decl *ManglingContextDecl; 7321 std::tie(MCtx, ManglingContextDecl) = 7322 getCurrentMangleNumberContext(NewVD->getDeclContext()); 7323 if (MCtx) { 7324 Context.setManglingNumber( 7325 NewVD, MCtx->getManglingNumber( 7326 NewVD, getMSManglingNumber(getLangOpts(), S))); 7327 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 7328 } 7329 } 7330 7331 // Special handling of variable named 'main'. 7332 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") && 7333 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 7334 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 7335 7336 // C++ [basic.start.main]p3 7337 // A program that declares a variable main at global scope is ill-formed. 7338 if (getLangOpts().CPlusPlus) 7339 Diag(D.getBeginLoc(), diag::err_main_global_variable); 7340 7341 // In C, and external-linkage variable named main results in undefined 7342 // behavior. 7343 else if (NewVD->hasExternalFormalLinkage()) 7344 Diag(D.getBeginLoc(), diag::warn_main_redefined); 7345 } 7346 7347 if (D.isRedeclaration() && !Previous.empty()) { 7348 NamedDecl *Prev = Previous.getRepresentativeDecl(); 7349 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization, 7350 D.isFunctionDefinition()); 7351 } 7352 7353 if (NewTemplate) { 7354 if (NewVD->isInvalidDecl()) 7355 NewTemplate->setInvalidDecl(); 7356 ActOnDocumentableDecl(NewTemplate); 7357 return NewTemplate; 7358 } 7359 7360 if (IsMemberSpecialization && !NewVD->isInvalidDecl()) 7361 CompleteMemberSpecialization(NewVD, Previous); 7362 7363 return NewVD; 7364 } 7365 7366 /// Enum describing the %select options in diag::warn_decl_shadow. 7367 enum ShadowedDeclKind { 7368 SDK_Local, 7369 SDK_Global, 7370 SDK_StaticMember, 7371 SDK_Field, 7372 SDK_Typedef, 7373 SDK_Using 7374 }; 7375 7376 /// Determine what kind of declaration we're shadowing. 7377 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, 7378 const DeclContext *OldDC) { 7379 if (isa<TypeAliasDecl>(ShadowedDecl)) 7380 return SDK_Using; 7381 else if (isa<TypedefDecl>(ShadowedDecl)) 7382 return SDK_Typedef; 7383 else if (isa<RecordDecl>(OldDC)) 7384 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember; 7385 7386 return OldDC->isFileContext() ? SDK_Global : SDK_Local; 7387 } 7388 7389 /// Return the location of the capture if the given lambda captures the given 7390 /// variable \p VD, or an invalid source location otherwise. 7391 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, 7392 const VarDecl *VD) { 7393 for (const Capture &Capture : LSI->Captures) { 7394 if (Capture.isVariableCapture() && Capture.getVariable() == VD) 7395 return Capture.getLocation(); 7396 } 7397 return SourceLocation(); 7398 } 7399 7400 static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, 7401 const LookupResult &R) { 7402 // Only diagnose if we're shadowing an unambiguous field or variable. 7403 if (R.getResultKind() != LookupResult::Found) 7404 return false; 7405 7406 // Return false if warning is ignored. 7407 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()); 7408 } 7409 7410 /// Return the declaration shadowed by the given variable \p D, or null 7411 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7412 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D, 7413 const LookupResult &R) { 7414 if (!shouldWarnIfShadowedDecl(Diags, R)) 7415 return nullptr; 7416 7417 // Don't diagnose declarations at file scope. 7418 if (D->hasGlobalStorage()) 7419 return nullptr; 7420 7421 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7422 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl) 7423 ? ShadowedDecl 7424 : nullptr; 7425 } 7426 7427 /// Return the declaration shadowed by the given typedef \p D, or null 7428 /// if it doesn't shadow any declaration or shadowing warnings are disabled. 7429 NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D, 7430 const LookupResult &R) { 7431 // Don't warn if typedef declaration is part of a class 7432 if (D->getDeclContext()->isRecord()) 7433 return nullptr; 7434 7435 if (!shouldWarnIfShadowedDecl(Diags, R)) 7436 return nullptr; 7437 7438 NamedDecl *ShadowedDecl = R.getFoundDecl(); 7439 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr; 7440 } 7441 7442 /// Diagnose variable or built-in function shadowing. Implements 7443 /// -Wshadow. 7444 /// 7445 /// This method is called whenever a VarDecl is added to a "useful" 7446 /// scope. 7447 /// 7448 /// \param ShadowedDecl the declaration that is shadowed by the given variable 7449 /// \param R the lookup of the name 7450 /// 7451 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, 7452 const LookupResult &R) { 7453 DeclContext *NewDC = D->getDeclContext(); 7454 7455 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) { 7456 // Fields are not shadowed by variables in C++ static methods. 7457 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 7458 if (MD->isStatic()) 7459 return; 7460 7461 // Fields shadowed by constructor parameters are a special case. Usually 7462 // the constructor initializes the field with the parameter. 7463 if (isa<CXXConstructorDecl>(NewDC)) 7464 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) { 7465 // Remember that this was shadowed so we can either warn about its 7466 // modification or its existence depending on warning settings. 7467 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD}); 7468 return; 7469 } 7470 } 7471 7472 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 7473 if (shadowedVar->isExternC()) { 7474 // For shadowing external vars, make sure that we point to the global 7475 // declaration, not a locally scoped extern declaration. 7476 for (auto I : shadowedVar->redecls()) 7477 if (I->isFileVarDecl()) { 7478 ShadowedDecl = I; 7479 break; 7480 } 7481 } 7482 7483 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext(); 7484 7485 unsigned WarningDiag = diag::warn_decl_shadow; 7486 SourceLocation CaptureLoc; 7487 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC && 7488 isa<CXXMethodDecl>(NewDC)) { 7489 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) { 7490 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) { 7491 if (RD->getLambdaCaptureDefault() == LCD_None) { 7492 // Try to avoid warnings for lambdas with an explicit capture list. 7493 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction()); 7494 // Warn only when the lambda captures the shadowed decl explicitly. 7495 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl)); 7496 if (CaptureLoc.isInvalid()) 7497 WarningDiag = diag::warn_decl_shadow_uncaptured_local; 7498 } else { 7499 // Remember that this was shadowed so we can avoid the warning if the 7500 // shadowed decl isn't captured and the warning settings allow it. 7501 cast<LambdaScopeInfo>(getCurFunction()) 7502 ->ShadowingDecls.push_back( 7503 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)}); 7504 return; 7505 } 7506 } 7507 7508 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) { 7509 // A variable can't shadow a local variable in an enclosing scope, if 7510 // they are separated by a non-capturing declaration context. 7511 for (DeclContext *ParentDC = NewDC; 7512 ParentDC && !ParentDC->Equals(OldDC); 7513 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) { 7514 // Only block literals, captured statements, and lambda expressions 7515 // can capture; other scopes don't. 7516 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) && 7517 !isLambdaCallOperator(ParentDC)) { 7518 return; 7519 } 7520 } 7521 } 7522 } 7523 } 7524 7525 // Only warn about certain kinds of shadowing for class members. 7526 if (NewDC && NewDC->isRecord()) { 7527 // In particular, don't warn about shadowing non-class members. 7528 if (!OldDC->isRecord()) 7529 return; 7530 7531 // TODO: should we warn about static data members shadowing 7532 // static data members from base classes? 7533 7534 // TODO: don't diagnose for inaccessible shadowed members. 7535 // This is hard to do perfectly because we might friend the 7536 // shadowing context, but that's just a false negative. 7537 } 7538 7539 7540 DeclarationName Name = R.getLookupName(); 7541 7542 // Emit warning and note. 7543 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 7544 return; 7545 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC); 7546 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC; 7547 if (!CaptureLoc.isInvalid()) 7548 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7549 << Name << /*explicitly*/ 1; 7550 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7551 } 7552 7553 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD 7554 /// when these variables are captured by the lambda. 7555 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) { 7556 for (const auto &Shadow : LSI->ShadowingDecls) { 7557 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl; 7558 // Try to avoid the warning when the shadowed decl isn't captured. 7559 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl); 7560 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7561 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid() 7562 ? diag::warn_decl_shadow_uncaptured_local 7563 : diag::warn_decl_shadow) 7564 << Shadow.VD->getDeclName() 7565 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC; 7566 if (!CaptureLoc.isInvalid()) 7567 Diag(CaptureLoc, diag::note_var_explicitly_captured_here) 7568 << Shadow.VD->getDeclName() << /*explicitly*/ 0; 7569 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7570 } 7571 } 7572 7573 /// Check -Wshadow without the advantage of a previous lookup. 7574 void Sema::CheckShadow(Scope *S, VarDecl *D) { 7575 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 7576 return; 7577 7578 LookupResult R(*this, D->getDeclName(), D->getLocation(), 7579 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration); 7580 LookupName(R, S); 7581 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R)) 7582 CheckShadow(D, ShadowedDecl, R); 7583 } 7584 7585 /// Check if 'E', which is an expression that is about to be modified, refers 7586 /// to a constructor parameter that shadows a field. 7587 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) { 7588 // Quickly ignore expressions that can't be shadowing ctor parameters. 7589 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty()) 7590 return; 7591 E = E->IgnoreParenImpCasts(); 7592 auto *DRE = dyn_cast<DeclRefExpr>(E); 7593 if (!DRE) 7594 return; 7595 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl()); 7596 auto I = ShadowingDecls.find(D); 7597 if (I == ShadowingDecls.end()) 7598 return; 7599 const NamedDecl *ShadowedDecl = I->second; 7600 const DeclContext *OldDC = ShadowedDecl->getDeclContext(); 7601 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC; 7602 Diag(D->getLocation(), diag::note_var_declared_here) << D; 7603 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 7604 7605 // Avoid issuing multiple warnings about the same decl. 7606 ShadowingDecls.erase(I); 7607 } 7608 7609 /// Check for conflict between this global or extern "C" declaration and 7610 /// previous global or extern "C" declarations. This is only used in C++. 7611 template<typename T> 7612 static bool checkGlobalOrExternCConflict( 7613 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 7614 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 7615 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 7616 7617 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 7618 // The common case: this global doesn't conflict with any extern "C" 7619 // declaration. 7620 return false; 7621 } 7622 7623 if (Prev) { 7624 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 7625 // Both the old and new declarations have C language linkage. This is a 7626 // redeclaration. 7627 Previous.clear(); 7628 Previous.addDecl(Prev); 7629 return true; 7630 } 7631 7632 // This is a global, non-extern "C" declaration, and there is a previous 7633 // non-global extern "C" declaration. Diagnose if this is a variable 7634 // declaration. 7635 if (!isa<VarDecl>(ND)) 7636 return false; 7637 } else { 7638 // The declaration is extern "C". Check for any declaration in the 7639 // translation unit which might conflict. 7640 if (IsGlobal) { 7641 // We have already performed the lookup into the translation unit. 7642 IsGlobal = false; 7643 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 7644 I != E; ++I) { 7645 if (isa<VarDecl>(*I)) { 7646 Prev = *I; 7647 break; 7648 } 7649 } 7650 } else { 7651 DeclContext::lookup_result R = 7652 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 7653 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 7654 I != E; ++I) { 7655 if (isa<VarDecl>(*I)) { 7656 Prev = *I; 7657 break; 7658 } 7659 // FIXME: If we have any other entity with this name in global scope, 7660 // the declaration is ill-formed, but that is a defect: it breaks the 7661 // 'stat' hack, for instance. Only variables can have mangled name 7662 // clashes with extern "C" declarations, so only they deserve a 7663 // diagnostic. 7664 } 7665 } 7666 7667 if (!Prev) 7668 return false; 7669 } 7670 7671 // Use the first declaration's location to ensure we point at something which 7672 // is lexically inside an extern "C" linkage-spec. 7673 assert(Prev && "should have found a previous declaration to diagnose"); 7674 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 7675 Prev = FD->getFirstDecl(); 7676 else 7677 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 7678 7679 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 7680 << IsGlobal << ND; 7681 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 7682 << IsGlobal; 7683 return false; 7684 } 7685 7686 /// Apply special rules for handling extern "C" declarations. Returns \c true 7687 /// if we have found that this is a redeclaration of some prior entity. 7688 /// 7689 /// Per C++ [dcl.link]p6: 7690 /// Two declarations [for a function or variable] with C language linkage 7691 /// with the same name that appear in different scopes refer to the same 7692 /// [entity]. An entity with C language linkage shall not be declared with 7693 /// the same name as an entity in global scope. 7694 template<typename T> 7695 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 7696 LookupResult &Previous) { 7697 if (!S.getLangOpts().CPlusPlus) { 7698 // In C, when declaring a global variable, look for a corresponding 'extern' 7699 // variable declared in function scope. We don't need this in C++, because 7700 // we find local extern decls in the surrounding file-scope DeclContext. 7701 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7702 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 7703 Previous.clear(); 7704 Previous.addDecl(Prev); 7705 return true; 7706 } 7707 } 7708 return false; 7709 } 7710 7711 // A declaration in the translation unit can conflict with an extern "C" 7712 // declaration. 7713 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 7714 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 7715 7716 // An extern "C" declaration can conflict with a declaration in the 7717 // translation unit or can be a redeclaration of an extern "C" declaration 7718 // in another scope. 7719 if (isIncompleteDeclExternC(S,ND)) 7720 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 7721 7722 // Neither global nor extern "C": nothing to do. 7723 return false; 7724 } 7725 7726 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 7727 // If the decl is already known invalid, don't check it. 7728 if (NewVD->isInvalidDecl()) 7729 return; 7730 7731 QualType T = NewVD->getType(); 7732 7733 // Defer checking an 'auto' type until its initializer is attached. 7734 if (T->isUndeducedType()) 7735 return; 7736 7737 if (NewVD->hasAttrs()) 7738 CheckAlignasUnderalignment(NewVD); 7739 7740 if (T->isObjCObjectType()) { 7741 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 7742 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 7743 T = Context.getObjCObjectPointerType(T); 7744 NewVD->setType(T); 7745 } 7746 7747 // Emit an error if an address space was applied to decl with local storage. 7748 // This includes arrays of objects with address space qualifiers, but not 7749 // automatic variables that point to other address spaces. 7750 // ISO/IEC TR 18037 S5.1.2 7751 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() && 7752 T.getAddressSpace() != LangAS::Default) { 7753 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0; 7754 NewVD->setInvalidDecl(); 7755 return; 7756 } 7757 7758 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program 7759 // scope. 7760 if (getLangOpts().OpenCLVersion == 120 && 7761 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") && 7762 NewVD->isStaticLocal()) { 7763 Diag(NewVD->getLocation(), diag::err_static_function_scope); 7764 NewVD->setInvalidDecl(); 7765 return; 7766 } 7767 7768 if (getLangOpts().OpenCL) { 7769 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported. 7770 if (NewVD->hasAttr<BlocksAttr>()) { 7771 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type); 7772 return; 7773 } 7774 7775 if (T->isBlockPointerType()) { 7776 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and 7777 // can't use 'extern' storage class. 7778 if (!T.isConstQualified()) { 7779 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration) 7780 << 0 /*const*/; 7781 NewVD->setInvalidDecl(); 7782 return; 7783 } 7784 if (NewVD->hasExternalStorage()) { 7785 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration); 7786 NewVD->setInvalidDecl(); 7787 return; 7788 } 7789 } 7790 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the 7791 // __constant address space. 7792 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static 7793 // variables inside a function can also be declared in the global 7794 // address space. 7795 // C++ for OpenCL inherits rule from OpenCL C v2.0. 7796 // FIXME: Adding local AS in C++ for OpenCL might make sense. 7797 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() || 7798 NewVD->hasExternalStorage()) { 7799 if (!T->isSamplerT() && 7800 !(T.getAddressSpace() == LangAS::opencl_constant || 7801 (T.getAddressSpace() == LangAS::opencl_global && 7802 (getLangOpts().OpenCLVersion == 200 || 7803 getLangOpts().OpenCLCPlusPlus)))) { 7804 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1; 7805 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus) 7806 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7807 << Scope << "global or constant"; 7808 else 7809 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 7810 << Scope << "constant"; 7811 NewVD->setInvalidDecl(); 7812 return; 7813 } 7814 } else { 7815 if (T.getAddressSpace() == LangAS::opencl_global) { 7816 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7817 << 1 /*is any function*/ << "global"; 7818 NewVD->setInvalidDecl(); 7819 return; 7820 } 7821 if (T.getAddressSpace() == LangAS::opencl_constant || 7822 T.getAddressSpace() == LangAS::opencl_local) { 7823 FunctionDecl *FD = getCurFunctionDecl(); 7824 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables 7825 // in functions. 7826 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 7827 if (T.getAddressSpace() == LangAS::opencl_constant) 7828 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7829 << 0 /*non-kernel only*/ << "constant"; 7830 else 7831 Diag(NewVD->getLocation(), diag::err_opencl_function_variable) 7832 << 0 /*non-kernel only*/ << "local"; 7833 NewVD->setInvalidDecl(); 7834 return; 7835 } 7836 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be 7837 // in the outermost scope of a kernel function. 7838 if (FD && FD->hasAttr<OpenCLKernelAttr>()) { 7839 if (!getCurScope()->isFunctionScope()) { 7840 if (T.getAddressSpace() == LangAS::opencl_constant) 7841 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7842 << "constant"; 7843 else 7844 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope) 7845 << "local"; 7846 NewVD->setInvalidDecl(); 7847 return; 7848 } 7849 } 7850 } else if (T.getAddressSpace() != LangAS::opencl_private && 7851 // If we are parsing a template we didn't deduce an addr 7852 // space yet. 7853 T.getAddressSpace() != LangAS::Default) { 7854 // Do not allow other address spaces on automatic variable. 7855 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1; 7856 NewVD->setInvalidDecl(); 7857 return; 7858 } 7859 } 7860 } 7861 7862 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 7863 && !NewVD->hasAttr<BlocksAttr>()) { 7864 if (getLangOpts().getGC() != LangOptions::NonGC) 7865 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 7866 else { 7867 assert(!getLangOpts().ObjCAutoRefCount); 7868 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 7869 } 7870 } 7871 7872 bool isVM = T->isVariablyModifiedType(); 7873 if (isVM || NewVD->hasAttr<CleanupAttr>() || 7874 NewVD->hasAttr<BlocksAttr>()) 7875 setFunctionHasBranchProtectedScope(); 7876 7877 if ((isVM && NewVD->hasLinkage()) || 7878 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 7879 bool SizeIsNegative; 7880 llvm::APSInt Oversized; 7881 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo( 7882 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized); 7883 QualType FixedT; 7884 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType()) 7885 FixedT = FixedTInfo->getType(); 7886 else if (FixedTInfo) { 7887 // Type and type-as-written are canonically different. We need to fix up 7888 // both types separately. 7889 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative, 7890 Oversized); 7891 } 7892 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) { 7893 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 7894 // FIXME: This won't give the correct result for 7895 // int a[10][n]; 7896 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 7897 7898 if (NewVD->isFileVarDecl()) 7899 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 7900 << SizeRange; 7901 else if (NewVD->isStaticLocal()) 7902 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 7903 << SizeRange; 7904 else 7905 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 7906 << SizeRange; 7907 NewVD->setInvalidDecl(); 7908 return; 7909 } 7910 7911 if (!FixedTInfo) { 7912 if (NewVD->isFileVarDecl()) 7913 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 7914 else 7915 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 7916 NewVD->setInvalidDecl(); 7917 return; 7918 } 7919 7920 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 7921 NewVD->setType(FixedT); 7922 NewVD->setTypeSourceInfo(FixedTInfo); 7923 } 7924 7925 if (T->isVoidType()) { 7926 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 7927 // of objects and functions. 7928 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 7929 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 7930 << T; 7931 NewVD->setInvalidDecl(); 7932 return; 7933 } 7934 } 7935 7936 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 7937 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 7938 NewVD->setInvalidDecl(); 7939 return; 7940 } 7941 7942 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 7943 Diag(NewVD->getLocation(), diag::err_block_on_vm); 7944 NewVD->setInvalidDecl(); 7945 return; 7946 } 7947 7948 if (NewVD->isConstexpr() && !T->isDependentType() && 7949 RequireLiteralType(NewVD->getLocation(), T, 7950 diag::err_constexpr_var_non_literal)) { 7951 NewVD->setInvalidDecl(); 7952 return; 7953 } 7954 } 7955 7956 /// Perform semantic checking on a newly-created variable 7957 /// declaration. 7958 /// 7959 /// This routine performs all of the type-checking required for a 7960 /// variable declaration once it has been built. It is used both to 7961 /// check variables after they have been parsed and their declarators 7962 /// have been translated into a declaration, and to check variables 7963 /// that have been instantiated from a template. 7964 /// 7965 /// Sets NewVD->isInvalidDecl() if an error was encountered. 7966 /// 7967 /// Returns true if the variable declaration is a redeclaration. 7968 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 7969 CheckVariableDeclarationType(NewVD); 7970 7971 // If the decl is already known invalid, don't check it. 7972 if (NewVD->isInvalidDecl()) 7973 return false; 7974 7975 // If we did not find anything by this name, look for a non-visible 7976 // extern "C" declaration with the same name. 7977 if (Previous.empty() && 7978 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 7979 Previous.setShadowed(); 7980 7981 if (!Previous.empty()) { 7982 MergeVarDecl(NewVD, Previous); 7983 return true; 7984 } 7985 return false; 7986 } 7987 7988 namespace { 7989 struct FindOverriddenMethod { 7990 Sema *S; 7991 CXXMethodDecl *Method; 7992 7993 /// Member lookup function that determines whether a given C++ 7994 /// method overrides a method in a base class, to be used with 7995 /// CXXRecordDecl::lookupInBases(). 7996 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 7997 RecordDecl *BaseRecord = 7998 Specifier->getType()->castAs<RecordType>()->getDecl(); 7999 8000 DeclarationName Name = Method->getDeclName(); 8001 8002 // FIXME: Do we care about other names here too? 8003 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8004 // We really want to find the base class destructor here. 8005 QualType T = S->Context.getTypeDeclType(BaseRecord); 8006 CanQualType CT = S->Context.getCanonicalType(T); 8007 8008 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 8009 } 8010 8011 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 8012 Path.Decls = Path.Decls.slice(1)) { 8013 NamedDecl *D = Path.Decls.front(); 8014 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 8015 if (MD->isVirtual() && 8016 !S->IsOverload( 8017 Method, MD, /*UseMemberUsingDeclRules=*/false, 8018 /*ConsiderCudaAttrs=*/true, 8019 // C++2a [class.virtual]p2 does not consider requires clauses 8020 // when overriding. 8021 /*ConsiderRequiresClauses=*/false)) 8022 return true; 8023 } 8024 } 8025 8026 return false; 8027 } 8028 }; 8029 8030 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 8031 } // end anonymous namespace 8032 8033 /// Report an error regarding overriding, along with any relevant 8034 /// overridden methods. 8035 /// 8036 /// \param DiagID the primary error to report. 8037 /// \param MD the overriding method. 8038 /// \param OEK which overrides to include as notes. 8039 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 8040 OverrideErrorKind OEK = OEK_All) { 8041 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 8042 for (const CXXMethodDecl *O : MD->overridden_methods()) { 8043 // This check (& the OEK parameter) could be replaced by a predicate, but 8044 // without lambdas that would be overkill. This is still nicer than writing 8045 // out the diag loop 3 times. 8046 if ((OEK == OEK_All) || 8047 (OEK == OEK_NonDeleted && !O->isDeleted()) || 8048 (OEK == OEK_Deleted && O->isDeleted())) 8049 S.Diag(O->getLocation(), diag::note_overridden_virtual_function); 8050 } 8051 } 8052 8053 /// AddOverriddenMethods - See if a method overrides any in the base classes, 8054 /// and if so, check that it's a valid override and remember it. 8055 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 8056 // Look for methods in base classes that this method might override. 8057 CXXBasePaths Paths; 8058 FindOverriddenMethod FOM; 8059 FOM.Method = MD; 8060 FOM.S = this; 8061 bool hasDeletedOverridenMethods = false; 8062 bool hasNonDeletedOverridenMethods = false; 8063 bool AddedAny = false; 8064 if (DC->lookupInBases(FOM, Paths)) { 8065 for (auto *I : Paths.found_decls()) { 8066 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 8067 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 8068 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 8069 !CheckOverridingFunctionAttributes(MD, OldMD) && 8070 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 8071 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 8072 hasDeletedOverridenMethods |= OldMD->isDeleted(); 8073 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 8074 AddedAny = true; 8075 } 8076 } 8077 } 8078 } 8079 8080 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 8081 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 8082 } 8083 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 8084 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 8085 } 8086 8087 return AddedAny; 8088 } 8089 8090 namespace { 8091 // Struct for holding all of the extra arguments needed by 8092 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 8093 struct ActOnFDArgs { 8094 Scope *S; 8095 Declarator &D; 8096 MultiTemplateParamsArg TemplateParamLists; 8097 bool AddToScope; 8098 }; 8099 } // end anonymous namespace 8100 8101 namespace { 8102 8103 // Callback to only accept typo corrections that have a non-zero edit distance. 8104 // Also only accept corrections that have the same parent decl. 8105 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback { 8106 public: 8107 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 8108 CXXRecordDecl *Parent) 8109 : Context(Context), OriginalFD(TypoFD), 8110 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 8111 8112 bool ValidateCandidate(const TypoCorrection &candidate) override { 8113 if (candidate.getEditDistance() == 0) 8114 return false; 8115 8116 SmallVector<unsigned, 1> MismatchedParams; 8117 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 8118 CDeclEnd = candidate.end(); 8119 CDecl != CDeclEnd; ++CDecl) { 8120 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8121 8122 if (FD && !FD->hasBody() && 8123 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 8124 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 8125 CXXRecordDecl *Parent = MD->getParent(); 8126 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 8127 return true; 8128 } else if (!ExpectedParent) { 8129 return true; 8130 } 8131 } 8132 } 8133 8134 return false; 8135 } 8136 8137 std::unique_ptr<CorrectionCandidateCallback> clone() override { 8138 return std::make_unique<DifferentNameValidatorCCC>(*this); 8139 } 8140 8141 private: 8142 ASTContext &Context; 8143 FunctionDecl *OriginalFD; 8144 CXXRecordDecl *ExpectedParent; 8145 }; 8146 8147 } // end anonymous namespace 8148 8149 void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) { 8150 TypoCorrectedFunctionDefinitions.insert(F); 8151 } 8152 8153 /// Generate diagnostics for an invalid function redeclaration. 8154 /// 8155 /// This routine handles generating the diagnostic messages for an invalid 8156 /// function redeclaration, including finding possible similar declarations 8157 /// or performing typo correction if there are no previous declarations with 8158 /// the same name. 8159 /// 8160 /// Returns a NamedDecl iff typo correction was performed and substituting in 8161 /// the new declaration name does not cause new errors. 8162 static NamedDecl *DiagnoseInvalidRedeclaration( 8163 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 8164 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 8165 DeclarationName Name = NewFD->getDeclName(); 8166 DeclContext *NewDC = NewFD->getDeclContext(); 8167 SmallVector<unsigned, 1> MismatchedParams; 8168 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 8169 TypoCorrection Correction; 8170 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 8171 unsigned DiagMsg = 8172 IsLocalFriend ? diag::err_no_matching_local_friend : 8173 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match : 8174 diag::err_member_decl_does_not_match; 8175 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 8176 IsLocalFriend ? Sema::LookupLocalFriendName 8177 : Sema::LookupOrdinaryName, 8178 Sema::ForVisibleRedeclaration); 8179 8180 NewFD->setInvalidDecl(); 8181 if (IsLocalFriend) 8182 SemaRef.LookupName(Prev, S); 8183 else 8184 SemaRef.LookupQualifiedName(Prev, NewDC); 8185 assert(!Prev.isAmbiguous() && 8186 "Cannot have an ambiguity in previous-declaration lookup"); 8187 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8188 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD, 8189 MD ? MD->getParent() : nullptr); 8190 if (!Prev.empty()) { 8191 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 8192 Func != FuncEnd; ++Func) { 8193 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 8194 if (FD && 8195 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8196 // Add 1 to the index so that 0 can mean the mismatch didn't 8197 // involve a parameter 8198 unsigned ParamNum = 8199 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 8200 NearMatches.push_back(std::make_pair(FD, ParamNum)); 8201 } 8202 } 8203 // If the qualified name lookup yielded nothing, try typo correction 8204 } else if ((Correction = SemaRef.CorrectTypo( 8205 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 8206 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery, 8207 IsLocalFriend ? nullptr : NewDC))) { 8208 // Set up everything for the call to ActOnFunctionDeclarator 8209 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 8210 ExtraArgs.D.getIdentifierLoc()); 8211 Previous.clear(); 8212 Previous.setLookupName(Correction.getCorrection()); 8213 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 8214 CDeclEnd = Correction.end(); 8215 CDecl != CDeclEnd; ++CDecl) { 8216 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 8217 if (FD && !FD->hasBody() && 8218 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 8219 Previous.addDecl(FD); 8220 } 8221 } 8222 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 8223 8224 NamedDecl *Result; 8225 // Retry building the function declaration with the new previous 8226 // declarations, and with errors suppressed. 8227 { 8228 // Trap errors. 8229 Sema::SFINAETrap Trap(SemaRef); 8230 8231 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 8232 // pieces need to verify the typo-corrected C++ declaration and hopefully 8233 // eliminate the need for the parameter pack ExtraArgs. 8234 Result = SemaRef.ActOnFunctionDeclarator( 8235 ExtraArgs.S, ExtraArgs.D, 8236 Correction.getCorrectionDecl()->getDeclContext(), 8237 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 8238 ExtraArgs.AddToScope); 8239 8240 if (Trap.hasErrorOccurred()) 8241 Result = nullptr; 8242 } 8243 8244 if (Result) { 8245 // Determine which correction we picked. 8246 Decl *Canonical = Result->getCanonicalDecl(); 8247 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 8248 I != E; ++I) 8249 if ((*I)->getCanonicalDecl() == Canonical) 8250 Correction.setCorrectionDecl(*I); 8251 8252 // Let Sema know about the correction. 8253 SemaRef.MarkTypoCorrectedFunctionDefinition(Result); 8254 SemaRef.diagnoseTypo( 8255 Correction, 8256 SemaRef.PDiag(IsLocalFriend 8257 ? diag::err_no_matching_local_friend_suggest 8258 : diag::err_member_decl_does_not_match_suggest) 8259 << Name << NewDC << IsDefinition); 8260 return Result; 8261 } 8262 8263 // Pretend the typo correction never occurred 8264 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 8265 ExtraArgs.D.getIdentifierLoc()); 8266 ExtraArgs.D.setRedeclaration(wasRedeclaration); 8267 Previous.clear(); 8268 Previous.setLookupName(Name); 8269 } 8270 8271 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 8272 << Name << NewDC << IsDefinition << NewFD->getLocation(); 8273 8274 bool NewFDisConst = false; 8275 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 8276 NewFDisConst = NewMD->isConst(); 8277 8278 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 8279 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 8280 NearMatch != NearMatchEnd; ++NearMatch) { 8281 FunctionDecl *FD = NearMatch->first; 8282 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 8283 bool FDisConst = MD && MD->isConst(); 8284 bool IsMember = MD || !IsLocalFriend; 8285 8286 // FIXME: These notes are poorly worded for the local friend case. 8287 if (unsigned Idx = NearMatch->second) { 8288 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 8289 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 8290 if (Loc.isInvalid()) Loc = FD->getLocation(); 8291 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 8292 : diag::note_local_decl_close_param_match) 8293 << Idx << FDParam->getType() 8294 << NewFD->getParamDecl(Idx - 1)->getType(); 8295 } else if (FDisConst != NewFDisConst) { 8296 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 8297 << NewFDisConst << FD->getSourceRange().getEnd(); 8298 } else 8299 SemaRef.Diag(FD->getLocation(), 8300 IsMember ? diag::note_member_def_close_match 8301 : diag::note_local_decl_close_match); 8302 } 8303 return nullptr; 8304 } 8305 8306 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 8307 switch (D.getDeclSpec().getStorageClassSpec()) { 8308 default: llvm_unreachable("Unknown storage class!"); 8309 case DeclSpec::SCS_auto: 8310 case DeclSpec::SCS_register: 8311 case DeclSpec::SCS_mutable: 8312 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8313 diag::err_typecheck_sclass_func); 8314 D.getMutableDeclSpec().ClearStorageClassSpecs(); 8315 D.setInvalidType(); 8316 break; 8317 case DeclSpec::SCS_unspecified: break; 8318 case DeclSpec::SCS_extern: 8319 if (D.getDeclSpec().isExternInLinkageSpec()) 8320 return SC_None; 8321 return SC_Extern; 8322 case DeclSpec::SCS_static: { 8323 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 8324 // C99 6.7.1p5: 8325 // The declaration of an identifier for a function that has 8326 // block scope shall have no explicit storage-class specifier 8327 // other than extern 8328 // See also (C++ [dcl.stc]p4). 8329 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 8330 diag::err_static_block_func); 8331 break; 8332 } else 8333 return SC_Static; 8334 } 8335 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 8336 } 8337 8338 // No explicit storage class has already been returned 8339 return SC_None; 8340 } 8341 8342 static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 8343 DeclContext *DC, QualType &R, 8344 TypeSourceInfo *TInfo, 8345 StorageClass SC, 8346 bool &IsVirtualOkay) { 8347 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 8348 DeclarationName Name = NameInfo.getName(); 8349 8350 FunctionDecl *NewFD = nullptr; 8351 bool isInline = D.getDeclSpec().isInlineSpecified(); 8352 8353 if (!SemaRef.getLangOpts().CPlusPlus) { 8354 // Determine whether the function was written with a 8355 // prototype. This true when: 8356 // - there is a prototype in the declarator, or 8357 // - the type R of the function is some kind of typedef or other non- 8358 // attributed reference to a type name (which eventually refers to a 8359 // function type). 8360 bool HasPrototype = 8361 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 8362 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType()); 8363 8364 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8365 R, TInfo, SC, isInline, HasPrototype, 8366 CSK_unspecified, 8367 /*TrailingRequiresClause=*/nullptr); 8368 if (D.isInvalidType()) 8369 NewFD->setInvalidDecl(); 8370 8371 return NewFD; 8372 } 8373 8374 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier(); 8375 8376 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier(); 8377 if (ConstexprKind == CSK_constinit) { 8378 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(), 8379 diag::err_constexpr_wrong_decl_kind) 8380 << ConstexprKind; 8381 ConstexprKind = CSK_unspecified; 8382 D.getMutableDeclSpec().ClearConstexprSpec(); 8383 } 8384 Expr *TrailingRequiresClause = D.getTrailingRequiresClause(); 8385 8386 // Check that the return type is not an abstract class type. 8387 // For record types, this is done by the AbstractClassUsageDiagnoser once 8388 // the class has been completely parsed. 8389 if (!DC->isRecord() && 8390 SemaRef.RequireNonAbstractType( 8391 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(), 8392 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 8393 D.setInvalidType(); 8394 8395 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 8396 // This is a C++ constructor declaration. 8397 assert(DC->isRecord() && 8398 "Constructors can only be declared in a member context"); 8399 8400 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 8401 return CXXConstructorDecl::Create( 8402 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8403 TInfo, ExplicitSpecifier, isInline, 8404 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(), 8405 TrailingRequiresClause); 8406 8407 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8408 // This is a C++ destructor declaration. 8409 if (DC->isRecord()) { 8410 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 8411 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 8412 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 8413 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo, 8414 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind, 8415 TrailingRequiresClause); 8416 8417 // If the destructor needs an implicit exception specification, set it 8418 // now. FIXME: It'd be nice to be able to create the right type to start 8419 // with, but the type needs to reference the destructor declaration. 8420 if (SemaRef.getLangOpts().CPlusPlus11) 8421 SemaRef.AdjustDestructorExceptionSpec(NewDD); 8422 8423 IsVirtualOkay = true; 8424 return NewDD; 8425 8426 } else { 8427 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 8428 D.setInvalidType(); 8429 8430 // Create a FunctionDecl to satisfy the function definition parsing 8431 // code path. 8432 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8433 D.getIdentifierLoc(), Name, R, TInfo, SC, 8434 isInline, 8435 /*hasPrototype=*/true, ConstexprKind, 8436 TrailingRequiresClause); 8437 } 8438 8439 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 8440 if (!DC->isRecord()) { 8441 SemaRef.Diag(D.getIdentifierLoc(), 8442 diag::err_conv_function_not_member); 8443 return nullptr; 8444 } 8445 8446 SemaRef.CheckConversionDeclarator(D, R, SC); 8447 if (D.isInvalidType()) 8448 return nullptr; 8449 8450 IsVirtualOkay = true; 8451 return CXXConversionDecl::Create( 8452 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8453 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(), 8454 TrailingRequiresClause); 8455 8456 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) { 8457 if (TrailingRequiresClause) 8458 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(), 8459 diag::err_trailing_requires_clause_on_deduction_guide) 8460 << TrailingRequiresClause->getSourceRange(); 8461 SemaRef.CheckDeductionGuideDeclarator(D, R, SC); 8462 8463 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), 8464 ExplicitSpecifier, NameInfo, R, TInfo, 8465 D.getEndLoc()); 8466 } else if (DC->isRecord()) { 8467 // If the name of the function is the same as the name of the record, 8468 // then this must be an invalid constructor that has a return type. 8469 // (The parser checks for a return type and makes the declarator a 8470 // constructor if it has no return type). 8471 if (Name.getAsIdentifierInfo() && 8472 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 8473 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 8474 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 8475 << SourceRange(D.getIdentifierLoc()); 8476 return nullptr; 8477 } 8478 8479 // This is a C++ method declaration. 8480 CXXMethodDecl *Ret = CXXMethodDecl::Create( 8481 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R, 8482 TInfo, SC, isInline, ConstexprKind, SourceLocation(), 8483 TrailingRequiresClause); 8484 IsVirtualOkay = !Ret->isStatic(); 8485 return Ret; 8486 } else { 8487 bool isFriend = 8488 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 8489 if (!isFriend && SemaRef.CurContext->isRecord()) 8490 return nullptr; 8491 8492 // Determine whether the function was written with a 8493 // prototype. This true when: 8494 // - we're in C++ (where every function has a prototype), 8495 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo, 8496 R, TInfo, SC, isInline, true /*HasPrototype*/, 8497 ConstexprKind, TrailingRequiresClause); 8498 } 8499 } 8500 8501 enum OpenCLParamType { 8502 ValidKernelParam, 8503 PtrPtrKernelParam, 8504 PtrKernelParam, 8505 InvalidAddrSpacePtrKernelParam, 8506 InvalidKernelParam, 8507 RecordKernelParam 8508 }; 8509 8510 static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) { 8511 // Size dependent types are just typedefs to normal integer types 8512 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to 8513 // integers other than by their names. 8514 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"}; 8515 8516 // Remove typedefs one by one until we reach a typedef 8517 // for a size dependent type. 8518 QualType DesugaredTy = Ty; 8519 do { 8520 ArrayRef<StringRef> Names(SizeTypeNames); 8521 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString()); 8522 if (Names.end() != Match) 8523 return true; 8524 8525 Ty = DesugaredTy; 8526 DesugaredTy = Ty.getSingleStepDesugaredType(C); 8527 } while (DesugaredTy != Ty); 8528 8529 return false; 8530 } 8531 8532 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) { 8533 if (PT->isPointerType()) { 8534 QualType PointeeType = PT->getPointeeType(); 8535 if (PointeeType->isPointerType()) 8536 return PtrPtrKernelParam; 8537 if (PointeeType.getAddressSpace() == LangAS::opencl_generic || 8538 PointeeType.getAddressSpace() == LangAS::opencl_private || 8539 PointeeType.getAddressSpace() == LangAS::Default) 8540 return InvalidAddrSpacePtrKernelParam; 8541 return PtrKernelParam; 8542 } 8543 8544 // OpenCL v1.2 s6.9.k: 8545 // Arguments to kernel functions in a program cannot be declared with the 8546 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8547 // uintptr_t or a struct and/or union that contain fields declared to be one 8548 // of these built-in scalar types. 8549 if (isOpenCLSizeDependentType(S.getASTContext(), PT)) 8550 return InvalidKernelParam; 8551 8552 if (PT->isImageType()) 8553 return PtrKernelParam; 8554 8555 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT()) 8556 return InvalidKernelParam; 8557 8558 // OpenCL extension spec v1.2 s9.5: 8559 // This extension adds support for half scalar and vector types as built-in 8560 // types that can be used for arithmetic operations, conversions etc. 8561 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType()) 8562 return InvalidKernelParam; 8563 8564 if (PT->isRecordType()) 8565 return RecordKernelParam; 8566 8567 // Look into an array argument to check if it has a forbidden type. 8568 if (PT->isArrayType()) { 8569 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType(); 8570 // Call ourself to check an underlying type of an array. Since the 8571 // getPointeeOrArrayElementType returns an innermost type which is not an 8572 // array, this recursive call only happens once. 8573 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0)); 8574 } 8575 8576 return ValidKernelParam; 8577 } 8578 8579 static void checkIsValidOpenCLKernelParameter( 8580 Sema &S, 8581 Declarator &D, 8582 ParmVarDecl *Param, 8583 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 8584 QualType PT = Param->getType(); 8585 8586 // Cache the valid types we encounter to avoid rechecking structs that are 8587 // used again 8588 if (ValidTypes.count(PT.getTypePtr())) 8589 return; 8590 8591 switch (getOpenCLKernelParameterType(S, PT)) { 8592 case PtrPtrKernelParam: 8593 // OpenCL v1.2 s6.9.a: 8594 // A kernel function argument cannot be declared as a 8595 // pointer to a pointer type. 8596 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 8597 D.setInvalidType(); 8598 return; 8599 8600 case InvalidAddrSpacePtrKernelParam: 8601 // OpenCL v1.0 s6.5: 8602 // __kernel function arguments declared to be a pointer of a type can point 8603 // to one of the following address spaces only : __global, __local or 8604 // __constant. 8605 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space); 8606 D.setInvalidType(); 8607 return; 8608 8609 // OpenCL v1.2 s6.9.k: 8610 // Arguments to kernel functions in a program cannot be declared with the 8611 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 8612 // uintptr_t or a struct and/or union that contain fields declared to be 8613 // one of these built-in scalar types. 8614 8615 case InvalidKernelParam: 8616 // OpenCL v1.2 s6.8 n: 8617 // A kernel function argument cannot be declared 8618 // of event_t type. 8619 // Do not diagnose half type since it is diagnosed as invalid argument 8620 // type for any function elsewhere. 8621 if (!PT->isHalfType()) { 8622 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8623 8624 // Explain what typedefs are involved. 8625 const TypedefType *Typedef = nullptr; 8626 while ((Typedef = PT->getAs<TypedefType>())) { 8627 SourceLocation Loc = Typedef->getDecl()->getLocation(); 8628 // SourceLocation may be invalid for a built-in type. 8629 if (Loc.isValid()) 8630 S.Diag(Loc, diag::note_entity_declared_at) << PT; 8631 PT = Typedef->desugar(); 8632 } 8633 } 8634 8635 D.setInvalidType(); 8636 return; 8637 8638 case PtrKernelParam: 8639 case ValidKernelParam: 8640 ValidTypes.insert(PT.getTypePtr()); 8641 return; 8642 8643 case RecordKernelParam: 8644 break; 8645 } 8646 8647 // Track nested structs we will inspect 8648 SmallVector<const Decl *, 4> VisitStack; 8649 8650 // Track where we are in the nested structs. Items will migrate from 8651 // VisitStack to HistoryStack as we do the DFS for bad field. 8652 SmallVector<const FieldDecl *, 4> HistoryStack; 8653 HistoryStack.push_back(nullptr); 8654 8655 // At this point we already handled everything except of a RecordType or 8656 // an ArrayType of a RecordType. 8657 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type."); 8658 const RecordType *RecTy = 8659 PT->getPointeeOrArrayElementType()->getAs<RecordType>(); 8660 const RecordDecl *OrigRecDecl = RecTy->getDecl(); 8661 8662 VisitStack.push_back(RecTy->getDecl()); 8663 assert(VisitStack.back() && "First decl null?"); 8664 8665 do { 8666 const Decl *Next = VisitStack.pop_back_val(); 8667 if (!Next) { 8668 assert(!HistoryStack.empty()); 8669 // Found a marker, we have gone up a level 8670 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 8671 ValidTypes.insert(Hist->getType().getTypePtr()); 8672 8673 continue; 8674 } 8675 8676 // Adds everything except the original parameter declaration (which is not a 8677 // field itself) to the history stack. 8678 const RecordDecl *RD; 8679 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 8680 HistoryStack.push_back(Field); 8681 8682 QualType FieldTy = Field->getType(); 8683 // Other field types (known to be valid or invalid) are handled while we 8684 // walk around RecordDecl::fields(). 8685 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) && 8686 "Unexpected type."); 8687 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType(); 8688 8689 RD = FieldRecTy->castAs<RecordType>()->getDecl(); 8690 } else { 8691 RD = cast<RecordDecl>(Next); 8692 } 8693 8694 // Add a null marker so we know when we've gone back up a level 8695 VisitStack.push_back(nullptr); 8696 8697 for (const auto *FD : RD->fields()) { 8698 QualType QT = FD->getType(); 8699 8700 if (ValidTypes.count(QT.getTypePtr())) 8701 continue; 8702 8703 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT); 8704 if (ParamType == ValidKernelParam) 8705 continue; 8706 8707 if (ParamType == RecordKernelParam) { 8708 VisitStack.push_back(FD); 8709 continue; 8710 } 8711 8712 // OpenCL v1.2 s6.9.p: 8713 // Arguments to kernel functions that are declared to be a struct or union 8714 // do not allow OpenCL objects to be passed as elements of the struct or 8715 // union. 8716 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 8717 ParamType == InvalidAddrSpacePtrKernelParam) { 8718 S.Diag(Param->getLocation(), 8719 diag::err_record_with_pointers_kernel_param) 8720 << PT->isUnionType() 8721 << PT; 8722 } else { 8723 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 8724 } 8725 8726 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type) 8727 << OrigRecDecl->getDeclName(); 8728 8729 // We have an error, now let's go back up through history and show where 8730 // the offending field came from 8731 for (ArrayRef<const FieldDecl *>::const_iterator 8732 I = HistoryStack.begin() + 1, 8733 E = HistoryStack.end(); 8734 I != E; ++I) { 8735 const FieldDecl *OuterField = *I; 8736 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 8737 << OuterField->getType(); 8738 } 8739 8740 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 8741 << QT->isPointerType() 8742 << QT; 8743 D.setInvalidType(); 8744 return; 8745 } 8746 } while (!VisitStack.empty()); 8747 } 8748 8749 /// Find the DeclContext in which a tag is implicitly declared if we see an 8750 /// elaborated type specifier in the specified context, and lookup finds 8751 /// nothing. 8752 static DeclContext *getTagInjectionContext(DeclContext *DC) { 8753 while (!DC->isFileContext() && !DC->isFunctionOrMethod()) 8754 DC = DC->getParent(); 8755 return DC; 8756 } 8757 8758 /// Find the Scope in which a tag is implicitly declared if we see an 8759 /// elaborated type specifier in the specified context, and lookup finds 8760 /// nothing. 8761 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) { 8762 while (S->isClassScope() || 8763 (LangOpts.CPlusPlus && 8764 S->isFunctionPrototypeScope()) || 8765 ((S->getFlags() & Scope::DeclScope) == 0) || 8766 (S->getEntity() && S->getEntity()->isTransparentContext())) 8767 S = S->getParent(); 8768 return S; 8769 } 8770 8771 NamedDecl* 8772 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 8773 TypeSourceInfo *TInfo, LookupResult &Previous, 8774 MultiTemplateParamsArg TemplateParamListsRef, 8775 bool &AddToScope) { 8776 QualType R = TInfo->getType(); 8777 8778 assert(R->isFunctionType()); 8779 SmallVector<TemplateParameterList *, 4> TemplateParamLists; 8780 for (TemplateParameterList *TPL : TemplateParamListsRef) 8781 TemplateParamLists.push_back(TPL); 8782 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) { 8783 if (!TemplateParamLists.empty() && 8784 Invented->getDepth() == TemplateParamLists.back()->getDepth()) 8785 TemplateParamLists.back() = Invented; 8786 else 8787 TemplateParamLists.push_back(Invented); 8788 } 8789 8790 // TODO: consider using NameInfo for diagnostic. 8791 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 8792 DeclarationName Name = NameInfo.getName(); 8793 StorageClass SC = getFunctionStorageClass(*this, D); 8794 8795 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 8796 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 8797 diag::err_invalid_thread) 8798 << DeclSpec::getSpecifierName(TSCS); 8799 8800 if (D.isFirstDeclarationOfMember()) 8801 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 8802 D.getIdentifierLoc()); 8803 8804 bool isFriend = false; 8805 FunctionTemplateDecl *FunctionTemplate = nullptr; 8806 bool isMemberSpecialization = false; 8807 bool isFunctionTemplateSpecialization = false; 8808 8809 bool isDependentClassScopeExplicitSpecialization = false; 8810 bool HasExplicitTemplateArgs = false; 8811 TemplateArgumentListInfo TemplateArgs; 8812 8813 bool isVirtualOkay = false; 8814 8815 DeclContext *OriginalDC = DC; 8816 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 8817 8818 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 8819 isVirtualOkay); 8820 if (!NewFD) return nullptr; 8821 8822 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 8823 NewFD->setTopLevelDeclInObjCContainer(); 8824 8825 // Set the lexical context. If this is a function-scope declaration, or has a 8826 // C++ scope specifier, or is the object of a friend declaration, the lexical 8827 // context will be different from the semantic context. 8828 NewFD->setLexicalDeclContext(CurContext); 8829 8830 if (IsLocalExternDecl) 8831 NewFD->setLocalExternDecl(); 8832 8833 if (getLangOpts().CPlusPlus) { 8834 bool isInline = D.getDeclSpec().isInlineSpecified(); 8835 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 8836 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier(); 8837 isFriend = D.getDeclSpec().isFriendSpecified(); 8838 if (isFriend && !isInline && D.isFunctionDefinition()) { 8839 // C++ [class.friend]p5 8840 // A function can be defined in a friend declaration of a 8841 // class . . . . Such a function is implicitly inline. 8842 NewFD->setImplicitlyInline(); 8843 } 8844 8845 // If this is a method defined in an __interface, and is not a constructor 8846 // or an overloaded operator, then set the pure flag (isVirtual will already 8847 // return true). 8848 if (const CXXRecordDecl *Parent = 8849 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 8850 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 8851 NewFD->setPure(true); 8852 8853 // C++ [class.union]p2 8854 // A union can have member functions, but not virtual functions. 8855 if (isVirtual && Parent->isUnion()) 8856 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 8857 } 8858 8859 SetNestedNameSpecifier(*this, NewFD, D); 8860 isMemberSpecialization = false; 8861 isFunctionTemplateSpecialization = false; 8862 if (D.isInvalidType()) 8863 NewFD->setInvalidDecl(); 8864 8865 // Match up the template parameter lists with the scope specifier, then 8866 // determine whether we have a template or a template specialization. 8867 bool Invalid = false; 8868 TemplateParameterList *TemplateParams = 8869 MatchTemplateParametersToScopeSpecifier( 8870 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(), 8871 D.getCXXScopeSpec(), 8872 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId 8873 ? D.getName().TemplateId 8874 : nullptr, 8875 TemplateParamLists, isFriend, isMemberSpecialization, 8876 Invalid); 8877 if (TemplateParams) { 8878 if (TemplateParams->size() > 0) { 8879 // This is a function template 8880 8881 // Check that we can declare a template here. 8882 if (CheckTemplateDeclScope(S, TemplateParams)) 8883 NewFD->setInvalidDecl(); 8884 8885 // A destructor cannot be a template. 8886 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 8887 Diag(NewFD->getLocation(), diag::err_destructor_template); 8888 NewFD->setInvalidDecl(); 8889 } 8890 8891 // If we're adding a template to a dependent context, we may need to 8892 // rebuilding some of the types used within the template parameter list, 8893 // now that we know what the current instantiation is. 8894 if (DC->isDependentContext()) { 8895 ContextRAII SavedContext(*this, DC); 8896 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 8897 Invalid = true; 8898 } 8899 8900 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 8901 NewFD->getLocation(), 8902 Name, TemplateParams, 8903 NewFD); 8904 FunctionTemplate->setLexicalDeclContext(CurContext); 8905 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 8906 8907 // For source fidelity, store the other template param lists. 8908 if (TemplateParamLists.size() > 1) { 8909 NewFD->setTemplateParameterListsInfo(Context, 8910 ArrayRef<TemplateParameterList *>(TemplateParamLists) 8911 .drop_back(1)); 8912 } 8913 } else { 8914 // This is a function template specialization. 8915 isFunctionTemplateSpecialization = true; 8916 // For source fidelity, store all the template param lists. 8917 if (TemplateParamLists.size() > 0) 8918 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8919 8920 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 8921 if (isFriend) { 8922 // We want to remove the "template<>", found here. 8923 SourceRange RemoveRange = TemplateParams->getSourceRange(); 8924 8925 // If we remove the template<> and the name is not a 8926 // template-id, we're actually silently creating a problem: 8927 // the friend declaration will refer to an untemplated decl, 8928 // and clearly the user wants a template specialization. So 8929 // we need to insert '<>' after the name. 8930 SourceLocation InsertLoc; 8931 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) { 8932 InsertLoc = D.getName().getSourceRange().getEnd(); 8933 InsertLoc = getLocForEndOfToken(InsertLoc); 8934 } 8935 8936 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 8937 << Name << RemoveRange 8938 << FixItHint::CreateRemoval(RemoveRange) 8939 << FixItHint::CreateInsertion(InsertLoc, "<>"); 8940 } 8941 } 8942 } else { 8943 // All template param lists were matched against the scope specifier: 8944 // this is NOT (an explicit specialization of) a template. 8945 if (TemplateParamLists.size() > 0) 8946 // For source fidelity, store all the template param lists. 8947 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 8948 } 8949 8950 if (Invalid) { 8951 NewFD->setInvalidDecl(); 8952 if (FunctionTemplate) 8953 FunctionTemplate->setInvalidDecl(); 8954 } 8955 8956 // C++ [dcl.fct.spec]p5: 8957 // The virtual specifier shall only be used in declarations of 8958 // nonstatic class member functions that appear within a 8959 // member-specification of a class declaration; see 10.3. 8960 // 8961 if (isVirtual && !NewFD->isInvalidDecl()) { 8962 if (!isVirtualOkay) { 8963 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8964 diag::err_virtual_non_function); 8965 } else if (!CurContext->isRecord()) { 8966 // 'virtual' was specified outside of the class. 8967 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8968 diag::err_virtual_out_of_class) 8969 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8970 } else if (NewFD->getDescribedFunctionTemplate()) { 8971 // C++ [temp.mem]p3: 8972 // A member function template shall not be virtual. 8973 Diag(D.getDeclSpec().getVirtualSpecLoc(), 8974 diag::err_virtual_member_function_template) 8975 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 8976 } else { 8977 // Okay: Add virtual to the method. 8978 NewFD->setVirtualAsWritten(true); 8979 } 8980 8981 if (getLangOpts().CPlusPlus14 && 8982 NewFD->getReturnType()->isUndeducedType()) 8983 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 8984 } 8985 8986 if (getLangOpts().CPlusPlus14 && 8987 (NewFD->isDependentContext() || 8988 (isFriend && CurContext->isDependentContext())) && 8989 NewFD->getReturnType()->isUndeducedType()) { 8990 // If the function template is referenced directly (for instance, as a 8991 // member of the current instantiation), pretend it has a dependent type. 8992 // This is not really justified by the standard, but is the only sane 8993 // thing to do. 8994 // FIXME: For a friend function, we have not marked the function as being 8995 // a friend yet, so 'isDependentContext' on the FD doesn't work. 8996 const FunctionProtoType *FPT = 8997 NewFD->getType()->castAs<FunctionProtoType>(); 8998 QualType Result = 8999 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 9000 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 9001 FPT->getExtProtoInfo())); 9002 } 9003 9004 // C++ [dcl.fct.spec]p3: 9005 // The inline specifier shall not appear on a block scope function 9006 // declaration. 9007 if (isInline && !NewFD->isInvalidDecl()) { 9008 if (CurContext->isFunctionOrMethod()) { 9009 // 'inline' is not allowed on block scope function declaration. 9010 Diag(D.getDeclSpec().getInlineSpecLoc(), 9011 diag::err_inline_declaration_block_scope) << Name 9012 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 9013 } 9014 } 9015 9016 // C++ [dcl.fct.spec]p6: 9017 // The explicit specifier shall be used only in the declaration of a 9018 // constructor or conversion function within its class definition; 9019 // see 12.3.1 and 12.3.2. 9020 if (hasExplicit && !NewFD->isInvalidDecl() && 9021 !isa<CXXDeductionGuideDecl>(NewFD)) { 9022 if (!CurContext->isRecord()) { 9023 // 'explicit' was specified outside of the class. 9024 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9025 diag::err_explicit_out_of_class) 9026 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9027 } else if (!isa<CXXConstructorDecl>(NewFD) && 9028 !isa<CXXConversionDecl>(NewFD)) { 9029 // 'explicit' was specified on a function that wasn't a constructor 9030 // or conversion function. 9031 Diag(D.getDeclSpec().getExplicitSpecLoc(), 9032 diag::err_explicit_non_ctor_or_conv_function) 9033 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange()); 9034 } 9035 } 9036 9037 if (ConstexprSpecKind ConstexprKind = 9038 D.getDeclSpec().getConstexprSpecifier()) { 9039 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 9040 // are implicitly inline. 9041 NewFD->setImplicitlyInline(); 9042 9043 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 9044 // be either constructors or to return a literal type. Therefore, 9045 // destructors cannot be declared constexpr. 9046 if (isa<CXXDestructorDecl>(NewFD) && 9047 (!getLangOpts().CPlusPlus2a || ConstexprKind == CSK_consteval)) { 9048 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor) 9049 << ConstexprKind; 9050 NewFD->setConstexprKind(getLangOpts().CPlusPlus2a ? CSK_unspecified : CSK_constexpr); 9051 } 9052 // C++20 [dcl.constexpr]p2: An allocation function, or a 9053 // deallocation function shall not be declared with the consteval 9054 // specifier. 9055 if (ConstexprKind == CSK_consteval && 9056 (NewFD->getOverloadedOperator() == OO_New || 9057 NewFD->getOverloadedOperator() == OO_Array_New || 9058 NewFD->getOverloadedOperator() == OO_Delete || 9059 NewFD->getOverloadedOperator() == OO_Array_Delete)) { 9060 Diag(D.getDeclSpec().getConstexprSpecLoc(), 9061 diag::err_invalid_consteval_decl_kind) 9062 << NewFD; 9063 NewFD->setConstexprKind(CSK_constexpr); 9064 } 9065 } 9066 9067 // If __module_private__ was specified, mark the function accordingly. 9068 if (D.getDeclSpec().isModulePrivateSpecified()) { 9069 if (isFunctionTemplateSpecialization) { 9070 SourceLocation ModulePrivateLoc 9071 = D.getDeclSpec().getModulePrivateSpecLoc(); 9072 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 9073 << 0 9074 << FixItHint::CreateRemoval(ModulePrivateLoc); 9075 } else { 9076 NewFD->setModulePrivate(); 9077 if (FunctionTemplate) 9078 FunctionTemplate->setModulePrivate(); 9079 } 9080 } 9081 9082 if (isFriend) { 9083 if (FunctionTemplate) { 9084 FunctionTemplate->setObjectOfFriendDecl(); 9085 FunctionTemplate->setAccess(AS_public); 9086 } 9087 NewFD->setObjectOfFriendDecl(); 9088 NewFD->setAccess(AS_public); 9089 } 9090 9091 // If a function is defined as defaulted or deleted, mark it as such now. 9092 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 9093 // definition kind to FDK_Definition. 9094 switch (D.getFunctionDefinitionKind()) { 9095 case FDK_Declaration: 9096 case FDK_Definition: 9097 break; 9098 9099 case FDK_Defaulted: 9100 NewFD->setDefaulted(); 9101 break; 9102 9103 case FDK_Deleted: 9104 NewFD->setDeletedAsWritten(); 9105 break; 9106 } 9107 9108 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 9109 D.isFunctionDefinition()) { 9110 // C++ [class.mfct]p2: 9111 // A member function may be defined (8.4) in its class definition, in 9112 // which case it is an inline member function (7.1.2) 9113 NewFD->setImplicitlyInline(); 9114 } 9115 9116 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 9117 !CurContext->isRecord()) { 9118 // C++ [class.static]p1: 9119 // A data or function member of a class may be declared static 9120 // in a class definition, in which case it is a static member of 9121 // the class. 9122 9123 // Complain about the 'static' specifier if it's on an out-of-line 9124 // member function definition. 9125 9126 // MSVC permits the use of a 'static' storage specifier on an out-of-line 9127 // member function template declaration and class member template 9128 // declaration (MSVC versions before 2015), warn about this. 9129 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 9130 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) && 9131 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) || 9132 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate())) 9133 ? diag::ext_static_out_of_line : diag::err_static_out_of_line) 9134 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 9135 } 9136 9137 // C++11 [except.spec]p15: 9138 // A deallocation function with no exception-specification is treated 9139 // as if it were specified with noexcept(true). 9140 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 9141 if ((Name.getCXXOverloadedOperator() == OO_Delete || 9142 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 9143 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 9144 NewFD->setType(Context.getFunctionType( 9145 FPT->getReturnType(), FPT->getParamTypes(), 9146 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 9147 } 9148 9149 // Filter out previous declarations that don't match the scope. 9150 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 9151 D.getCXXScopeSpec().isNotEmpty() || 9152 isMemberSpecialization || 9153 isFunctionTemplateSpecialization); 9154 9155 // Handle GNU asm-label extension (encoded as an attribute). 9156 if (Expr *E = (Expr*) D.getAsmLabel()) { 9157 // The parser guarantees this is a string. 9158 StringLiteral *SE = cast<StringLiteral>(E); 9159 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(), 9160 /*IsLiteralLabel=*/true, 9161 SE->getStrTokenLoc(0))); 9162 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 9163 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 9164 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 9165 if (I != ExtnameUndeclaredIdentifiers.end()) { 9166 if (isDeclExternC(NewFD)) { 9167 NewFD->addAttr(I->second); 9168 ExtnameUndeclaredIdentifiers.erase(I); 9169 } else 9170 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 9171 << /*Variable*/0 << NewFD; 9172 } 9173 } 9174 9175 // Copy the parameter declarations from the declarator D to the function 9176 // declaration NewFD, if they are available. First scavenge them into Params. 9177 SmallVector<ParmVarDecl*, 16> Params; 9178 unsigned FTIIdx; 9179 if (D.isFunctionDeclarator(FTIIdx)) { 9180 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun; 9181 9182 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 9183 // function that takes no arguments, not a function that takes a 9184 // single void argument. 9185 // We let through "const void" here because Sema::GetTypeForDeclarator 9186 // already checks for that case. 9187 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 9188 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 9189 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 9190 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 9191 Param->setDeclContext(NewFD); 9192 Params.push_back(Param); 9193 9194 if (Param->isInvalidDecl()) 9195 NewFD->setInvalidDecl(); 9196 } 9197 } 9198 9199 if (!getLangOpts().CPlusPlus) { 9200 // In C, find all the tag declarations from the prototype and move them 9201 // into the function DeclContext. Remove them from the surrounding tag 9202 // injection context of the function, which is typically but not always 9203 // the TU. 9204 DeclContext *PrototypeTagContext = 9205 getTagInjectionContext(NewFD->getLexicalDeclContext()); 9206 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) { 9207 auto *TD = dyn_cast<TagDecl>(NonParmDecl); 9208 9209 // We don't want to reparent enumerators. Look at their parent enum 9210 // instead. 9211 if (!TD) { 9212 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl)) 9213 TD = cast<EnumDecl>(ECD->getDeclContext()); 9214 } 9215 if (!TD) 9216 continue; 9217 DeclContext *TagDC = TD->getLexicalDeclContext(); 9218 if (!TagDC->containsDecl(TD)) 9219 continue; 9220 TagDC->removeDecl(TD); 9221 TD->setDeclContext(NewFD); 9222 NewFD->addDecl(TD); 9223 9224 // Preserve the lexical DeclContext if it is not the surrounding tag 9225 // injection context of the FD. In this example, the semantic context of 9226 // E will be f and the lexical context will be S, while both the 9227 // semantic and lexical contexts of S will be f: 9228 // void f(struct S { enum E { a } f; } s); 9229 if (TagDC != PrototypeTagContext) 9230 TD->setLexicalDeclContext(TagDC); 9231 } 9232 } 9233 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 9234 // When we're declaring a function with a typedef, typeof, etc as in the 9235 // following example, we'll need to synthesize (unnamed) 9236 // parameters for use in the declaration. 9237 // 9238 // @code 9239 // typedef void fn(int); 9240 // fn f; 9241 // @endcode 9242 9243 // Synthesize a parameter for each argument type. 9244 for (const auto &AI : FT->param_types()) { 9245 ParmVarDecl *Param = 9246 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 9247 Param->setScopeInfo(0, Params.size()); 9248 Params.push_back(Param); 9249 } 9250 } else { 9251 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 9252 "Should not need args for typedef of non-prototype fn"); 9253 } 9254 9255 // Finally, we know we have the right number of parameters, install them. 9256 NewFD->setParams(Params); 9257 9258 if (D.getDeclSpec().isNoreturnSpecified()) 9259 NewFD->addAttr(C11NoReturnAttr::Create(Context, 9260 D.getDeclSpec().getNoreturnSpecLoc(), 9261 AttributeCommonInfo::AS_Keyword)); 9262 9263 // Functions returning a variably modified type violate C99 6.7.5.2p2 9264 // because all functions have linkage. 9265 if (!NewFD->isInvalidDecl() && 9266 NewFD->getReturnType()->isVariablyModifiedType()) { 9267 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 9268 NewFD->setInvalidDecl(); 9269 } 9270 9271 // Apply an implicit SectionAttr if '#pragma clang section text' is active 9272 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() && 9273 !NewFD->hasAttr<SectionAttr>()) 9274 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit( 9275 Context, PragmaClangTextSection.SectionName, 9276 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma)); 9277 9278 // Apply an implicit SectionAttr if #pragma code_seg is active. 9279 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 9280 !NewFD->hasAttr<SectionAttr>()) { 9281 NewFD->addAttr(SectionAttr::CreateImplicit( 9282 Context, CodeSegStack.CurrentValue->getString(), 9283 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9284 SectionAttr::Declspec_allocate)); 9285 if (UnifySection(CodeSegStack.CurrentValue->getString(), 9286 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 9287 ASTContext::PSF_Read, 9288 NewFD)) 9289 NewFD->dropAttr<SectionAttr>(); 9290 } 9291 9292 // Apply an implicit CodeSegAttr from class declspec or 9293 // apply an implicit SectionAttr from #pragma code_seg if active. 9294 if (!NewFD->hasAttr<CodeSegAttr>()) { 9295 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD, 9296 D.isFunctionDefinition())) { 9297 NewFD->addAttr(SAttr); 9298 } 9299 } 9300 9301 // Handle attributes. 9302 ProcessDeclAttributes(S, NewFD, D); 9303 9304 if (getLangOpts().OpenCL) { 9305 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 9306 // type declaration will generate a compilation error. 9307 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace(); 9308 if (AddressSpace != LangAS::Default) { 9309 Diag(NewFD->getLocation(), 9310 diag::err_opencl_return_value_with_address_space); 9311 NewFD->setInvalidDecl(); 9312 } 9313 } 9314 9315 if (!getLangOpts().CPlusPlus) { 9316 // Perform semantic checking on the function declaration. 9317 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9318 CheckMain(NewFD, D.getDeclSpec()); 9319 9320 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9321 CheckMSVCRTEntryPoint(NewFD); 9322 9323 if (!NewFD->isInvalidDecl()) 9324 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9325 isMemberSpecialization)); 9326 else if (!Previous.empty()) 9327 // Recover gracefully from an invalid redeclaration. 9328 D.setRedeclaration(true); 9329 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9330 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9331 "previous declaration set still overloaded"); 9332 9333 // Diagnose no-prototype function declarations with calling conventions that 9334 // don't support variadic calls. Only do this in C and do it after merging 9335 // possibly prototyped redeclarations. 9336 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 9337 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 9338 CallingConv CC = FT->getExtInfo().getCC(); 9339 if (!supportsVariadicCall(CC)) { 9340 // Windows system headers sometimes accidentally use stdcall without 9341 // (void) parameters, so we relax this to a warning. 9342 int DiagID = 9343 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 9344 Diag(NewFD->getLocation(), DiagID) 9345 << FunctionType::getNameForCallConv(CC); 9346 } 9347 } 9348 9349 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() || 9350 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion()) 9351 checkNonTrivialCUnion(NewFD->getReturnType(), 9352 NewFD->getReturnTypeSourceRange().getBegin(), 9353 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy); 9354 } else { 9355 // C++11 [replacement.functions]p3: 9356 // The program's definitions shall not be specified as inline. 9357 // 9358 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 9359 // 9360 // Suppress the diagnostic if the function is __attribute__((used)), since 9361 // that forces an external definition to be emitted. 9362 if (D.getDeclSpec().isInlineSpecified() && 9363 NewFD->isReplaceableGlobalAllocationFunction() && 9364 !NewFD->hasAttr<UsedAttr>()) 9365 Diag(D.getDeclSpec().getInlineSpecLoc(), 9366 diag::ext_operator_new_delete_declared_inline) 9367 << NewFD->getDeclName(); 9368 9369 // If the declarator is a template-id, translate the parser's template 9370 // argument list into our AST format. 9371 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) { 9372 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 9373 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 9374 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 9375 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 9376 TemplateId->NumArgs); 9377 translateTemplateArguments(TemplateArgsPtr, 9378 TemplateArgs); 9379 9380 HasExplicitTemplateArgs = true; 9381 9382 if (NewFD->isInvalidDecl()) { 9383 HasExplicitTemplateArgs = false; 9384 } else if (FunctionTemplate) { 9385 // Function template with explicit template arguments. 9386 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 9387 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 9388 9389 HasExplicitTemplateArgs = false; 9390 } else { 9391 assert((isFunctionTemplateSpecialization || 9392 D.getDeclSpec().isFriendSpecified()) && 9393 "should have a 'template<>' for this decl"); 9394 // "friend void foo<>(int);" is an implicit specialization decl. 9395 isFunctionTemplateSpecialization = true; 9396 } 9397 } else if (isFriend && isFunctionTemplateSpecialization) { 9398 // This combination is only possible in a recovery case; the user 9399 // wrote something like: 9400 // template <> friend void foo(int); 9401 // which we're recovering from as if the user had written: 9402 // friend void foo<>(int); 9403 // Go ahead and fake up a template id. 9404 HasExplicitTemplateArgs = true; 9405 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 9406 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 9407 } 9408 9409 // We do not add HD attributes to specializations here because 9410 // they may have different constexpr-ness compared to their 9411 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied, 9412 // may end up with different effective targets. Instead, a 9413 // specialization inherits its target attributes from its template 9414 // in the CheckFunctionTemplateSpecialization() call below. 9415 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization) 9416 maybeAddCUDAHostDeviceAttrs(NewFD, Previous); 9417 9418 // If it's a friend (and only if it's a friend), it's possible 9419 // that either the specialized function type or the specialized 9420 // template is dependent, and therefore matching will fail. In 9421 // this case, don't check the specialization yet. 9422 bool InstantiationDependent = false; 9423 if (isFunctionTemplateSpecialization && isFriend && 9424 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 9425 TemplateSpecializationType::anyDependentTemplateArguments( 9426 TemplateArgs, 9427 InstantiationDependent))) { 9428 assert(HasExplicitTemplateArgs && 9429 "friend function specialization without template args"); 9430 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 9431 Previous)) 9432 NewFD->setInvalidDecl(); 9433 } else if (isFunctionTemplateSpecialization) { 9434 if (CurContext->isDependentContext() && CurContext->isRecord() 9435 && !isFriend) { 9436 isDependentClassScopeExplicitSpecialization = true; 9437 } else if (!NewFD->isInvalidDecl() && 9438 CheckFunctionTemplateSpecialization( 9439 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr), 9440 Previous)) 9441 NewFD->setInvalidDecl(); 9442 9443 // C++ [dcl.stc]p1: 9444 // A storage-class-specifier shall not be specified in an explicit 9445 // specialization (14.7.3) 9446 FunctionTemplateSpecializationInfo *Info = 9447 NewFD->getTemplateSpecializationInfo(); 9448 if (Info && SC != SC_None) { 9449 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 9450 Diag(NewFD->getLocation(), 9451 diag::err_explicit_specialization_inconsistent_storage_class) 9452 << SC 9453 << FixItHint::CreateRemoval( 9454 D.getDeclSpec().getStorageClassSpecLoc()); 9455 9456 else 9457 Diag(NewFD->getLocation(), 9458 diag::ext_explicit_specialization_storage_class) 9459 << FixItHint::CreateRemoval( 9460 D.getDeclSpec().getStorageClassSpecLoc()); 9461 } 9462 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) { 9463 if (CheckMemberSpecialization(NewFD, Previous)) 9464 NewFD->setInvalidDecl(); 9465 } 9466 9467 // Perform semantic checking on the function declaration. 9468 if (!isDependentClassScopeExplicitSpecialization) { 9469 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 9470 CheckMain(NewFD, D.getDeclSpec()); 9471 9472 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 9473 CheckMSVCRTEntryPoint(NewFD); 9474 9475 if (!NewFD->isInvalidDecl()) 9476 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 9477 isMemberSpecialization)); 9478 else if (!Previous.empty()) 9479 // Recover gracefully from an invalid redeclaration. 9480 D.setRedeclaration(true); 9481 } 9482 9483 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 9484 Previous.getResultKind() != LookupResult::FoundOverloaded) && 9485 "previous declaration set still overloaded"); 9486 9487 NamedDecl *PrincipalDecl = (FunctionTemplate 9488 ? cast<NamedDecl>(FunctionTemplate) 9489 : NewFD); 9490 9491 if (isFriend && NewFD->getPreviousDecl()) { 9492 AccessSpecifier Access = AS_public; 9493 if (!NewFD->isInvalidDecl()) 9494 Access = NewFD->getPreviousDecl()->getAccess(); 9495 9496 NewFD->setAccess(Access); 9497 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 9498 } 9499 9500 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 9501 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 9502 PrincipalDecl->setNonMemberOperator(); 9503 9504 // If we have a function template, check the template parameter 9505 // list. This will check and merge default template arguments. 9506 if (FunctionTemplate) { 9507 FunctionTemplateDecl *PrevTemplate = 9508 FunctionTemplate->getPreviousDecl(); 9509 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 9510 PrevTemplate ? PrevTemplate->getTemplateParameters() 9511 : nullptr, 9512 D.getDeclSpec().isFriendSpecified() 9513 ? (D.isFunctionDefinition() 9514 ? TPC_FriendFunctionTemplateDefinition 9515 : TPC_FriendFunctionTemplate) 9516 : (D.getCXXScopeSpec().isSet() && 9517 DC && DC->isRecord() && 9518 DC->isDependentContext()) 9519 ? TPC_ClassTemplateMember 9520 : TPC_FunctionTemplate); 9521 } 9522 9523 if (NewFD->isInvalidDecl()) { 9524 // Ignore all the rest of this. 9525 } else if (!D.isRedeclaration()) { 9526 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 9527 AddToScope }; 9528 // Fake up an access specifier if it's supposed to be a class member. 9529 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 9530 NewFD->setAccess(AS_public); 9531 9532 // Qualified decls generally require a previous declaration. 9533 if (D.getCXXScopeSpec().isSet()) { 9534 // ...with the major exception of templated-scope or 9535 // dependent-scope friend declarations. 9536 9537 // TODO: we currently also suppress this check in dependent 9538 // contexts because (1) the parameter depth will be off when 9539 // matching friend templates and (2) we might actually be 9540 // selecting a friend based on a dependent factor. But there 9541 // are situations where these conditions don't apply and we 9542 // can actually do this check immediately. 9543 // 9544 // Unless the scope is dependent, it's always an error if qualified 9545 // redeclaration lookup found nothing at all. Diagnose that now; 9546 // nothing will diagnose that error later. 9547 if (isFriend && 9548 (D.getCXXScopeSpec().getScopeRep()->isDependent() || 9549 (!Previous.empty() && CurContext->isDependentContext()))) { 9550 // ignore these 9551 } else { 9552 // The user tried to provide an out-of-line definition for a 9553 // function that is a member of a class or namespace, but there 9554 // was no such member function declared (C++ [class.mfct]p2, 9555 // C++ [namespace.memdef]p2). For example: 9556 // 9557 // class X { 9558 // void f() const; 9559 // }; 9560 // 9561 // void X::f() { } // ill-formed 9562 // 9563 // Complain about this problem, and attempt to suggest close 9564 // matches (e.g., those that differ only in cv-qualifiers and 9565 // whether the parameter types are references). 9566 9567 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9568 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 9569 AddToScope = ExtraArgs.AddToScope; 9570 return Result; 9571 } 9572 } 9573 9574 // Unqualified local friend declarations are required to resolve 9575 // to something. 9576 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 9577 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 9578 *this, Previous, NewFD, ExtraArgs, true, S)) { 9579 AddToScope = ExtraArgs.AddToScope; 9580 return Result; 9581 } 9582 } 9583 } else if (!D.isFunctionDefinition() && 9584 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 9585 !isFriend && !isFunctionTemplateSpecialization && 9586 !isMemberSpecialization) { 9587 // An out-of-line member function declaration must also be a 9588 // definition (C++ [class.mfct]p2). 9589 // Note that this is not the case for explicit specializations of 9590 // function templates or member functions of class templates, per 9591 // C++ [temp.expl.spec]p2. We also allow these declarations as an 9592 // extension for compatibility with old SWIG code which likes to 9593 // generate them. 9594 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 9595 << D.getCXXScopeSpec().getRange(); 9596 } 9597 } 9598 9599 ProcessPragmaWeak(S, NewFD); 9600 checkAttributesAfterMerging(*this, *NewFD); 9601 9602 AddKnownFunctionAttributes(NewFD); 9603 9604 if (NewFD->hasAttr<OverloadableAttr>() && 9605 !NewFD->getType()->getAs<FunctionProtoType>()) { 9606 Diag(NewFD->getLocation(), 9607 diag::err_attribute_overloadable_no_prototype) 9608 << NewFD; 9609 9610 // Turn this into a variadic function with no parameters. 9611 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 9612 FunctionProtoType::ExtProtoInfo EPI( 9613 Context.getDefaultCallingConvention(true, false)); 9614 EPI.Variadic = true; 9615 EPI.ExtInfo = FT->getExtInfo(); 9616 9617 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 9618 NewFD->setType(R); 9619 } 9620 9621 // If there's a #pragma GCC visibility in scope, and this isn't a class 9622 // member, set the visibility of this function. 9623 if (!DC->isRecord() && NewFD->isExternallyVisible()) 9624 AddPushedVisibilityAttribute(NewFD); 9625 9626 // If there's a #pragma clang arc_cf_code_audited in scope, consider 9627 // marking the function. 9628 AddCFAuditedAttribute(NewFD); 9629 9630 // If this is a function definition, check if we have to apply optnone due to 9631 // a pragma. 9632 if(D.isFunctionDefinition()) 9633 AddRangeBasedOptnone(NewFD); 9634 9635 // If this is the first declaration of an extern C variable, update 9636 // the map of such variables. 9637 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 9638 isIncompleteDeclExternC(*this, NewFD)) 9639 RegisterLocallyScopedExternCDecl(NewFD, S); 9640 9641 // Set this FunctionDecl's range up to the right paren. 9642 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 9643 9644 if (D.isRedeclaration() && !Previous.empty()) { 9645 NamedDecl *Prev = Previous.getRepresentativeDecl(); 9646 checkDLLAttributeRedeclaration(*this, Prev, NewFD, 9647 isMemberSpecialization || 9648 isFunctionTemplateSpecialization, 9649 D.isFunctionDefinition()); 9650 } 9651 9652 if (getLangOpts().CUDA) { 9653 IdentifierInfo *II = NewFD->getIdentifier(); 9654 if (II && II->isStr(getCudaConfigureFuncName()) && 9655 !NewFD->isInvalidDecl() && 9656 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 9657 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 9658 Diag(NewFD->getLocation(), diag::err_config_scalar_return) 9659 << getCudaConfigureFuncName(); 9660 Context.setcudaConfigureCallDecl(NewFD); 9661 } 9662 9663 // Variadic functions, other than a *declaration* of printf, are not allowed 9664 // in device-side CUDA code, unless someone passed 9665 // -fcuda-allow-variadic-functions. 9666 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() && 9667 (NewFD->hasAttr<CUDADeviceAttr>() || 9668 NewFD->hasAttr<CUDAGlobalAttr>()) && 9669 !(II && II->isStr("printf") && NewFD->isExternC() && 9670 !D.isFunctionDefinition())) { 9671 Diag(NewFD->getLocation(), diag::err_variadic_device_fn); 9672 } 9673 } 9674 9675 MarkUnusedFileScopedDecl(NewFD); 9676 9677 9678 9679 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) { 9680 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 9681 if ((getLangOpts().OpenCLVersion >= 120) 9682 && (SC == SC_Static)) { 9683 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 9684 D.setInvalidType(); 9685 } 9686 9687 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 9688 if (!NewFD->getReturnType()->isVoidType()) { 9689 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 9690 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 9691 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 9692 : FixItHint()); 9693 D.setInvalidType(); 9694 } 9695 9696 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 9697 for (auto Param : NewFD->parameters()) 9698 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 9699 9700 if (getLangOpts().OpenCLCPlusPlus) { 9701 if (DC->isRecord()) { 9702 Diag(D.getIdentifierLoc(), diag::err_method_kernel); 9703 D.setInvalidType(); 9704 } 9705 if (FunctionTemplate) { 9706 Diag(D.getIdentifierLoc(), diag::err_template_kernel); 9707 D.setInvalidType(); 9708 } 9709 } 9710 } 9711 9712 if (getLangOpts().CPlusPlus) { 9713 if (FunctionTemplate) { 9714 if (NewFD->isInvalidDecl()) 9715 FunctionTemplate->setInvalidDecl(); 9716 return FunctionTemplate; 9717 } 9718 9719 if (isMemberSpecialization && !NewFD->isInvalidDecl()) 9720 CompleteMemberSpecialization(NewFD, Previous); 9721 } 9722 9723 for (const ParmVarDecl *Param : NewFD->parameters()) { 9724 QualType PT = Param->getType(); 9725 9726 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value 9727 // types. 9728 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) { 9729 if(const PipeType *PipeTy = PT->getAs<PipeType>()) { 9730 QualType ElemTy = PipeTy->getElementType(); 9731 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) { 9732 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type ); 9733 D.setInvalidType(); 9734 } 9735 } 9736 } 9737 } 9738 9739 // Here we have an function template explicit specialization at class scope. 9740 // The actual specialization will be postponed to template instatiation 9741 // time via the ClassScopeFunctionSpecializationDecl node. 9742 if (isDependentClassScopeExplicitSpecialization) { 9743 ClassScopeFunctionSpecializationDecl *NewSpec = 9744 ClassScopeFunctionSpecializationDecl::Create( 9745 Context, CurContext, NewFD->getLocation(), 9746 cast<CXXMethodDecl>(NewFD), 9747 HasExplicitTemplateArgs, TemplateArgs); 9748 CurContext->addDecl(NewSpec); 9749 AddToScope = false; 9750 } 9751 9752 // Diagnose availability attributes. Availability cannot be used on functions 9753 // that are run during load/unload. 9754 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) { 9755 if (NewFD->hasAttr<ConstructorAttr>()) { 9756 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9757 << 1; 9758 NewFD->dropAttr<AvailabilityAttr>(); 9759 } 9760 if (NewFD->hasAttr<DestructorAttr>()) { 9761 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer) 9762 << 2; 9763 NewFD->dropAttr<AvailabilityAttr>(); 9764 } 9765 } 9766 9767 // Diagnose no_builtin attribute on function declaration that are not a 9768 // definition. 9769 // FIXME: We should really be doing this in 9770 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to 9771 // the FunctionDecl and at this point of the code 9772 // FunctionDecl::isThisDeclarationADefinition() which always returns `false` 9773 // because Sema::ActOnStartOfFunctionDef has not been called yet. 9774 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>()) 9775 switch (D.getFunctionDefinitionKind()) { 9776 case FDK_Defaulted: 9777 case FDK_Deleted: 9778 Diag(NBA->getLocation(), 9779 diag::err_attribute_no_builtin_on_defaulted_deleted_function) 9780 << NBA->getSpelling(); 9781 break; 9782 case FDK_Declaration: 9783 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition) 9784 << NBA->getSpelling(); 9785 break; 9786 case FDK_Definition: 9787 break; 9788 } 9789 9790 return NewFD; 9791 } 9792 9793 /// Return a CodeSegAttr from a containing class. The Microsoft docs say 9794 /// when __declspec(code_seg) "is applied to a class, all member functions of 9795 /// the class and nested classes -- this includes compiler-generated special 9796 /// member functions -- are put in the specified segment." 9797 /// The actual behavior is a little more complicated. The Microsoft compiler 9798 /// won't check outer classes if there is an active value from #pragma code_seg. 9799 /// The CodeSeg is always applied from the direct parent but only from outer 9800 /// classes when the #pragma code_seg stack is empty. See: 9801 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer 9802 /// available since MS has removed the page. 9803 static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) { 9804 const auto *Method = dyn_cast<CXXMethodDecl>(FD); 9805 if (!Method) 9806 return nullptr; 9807 const CXXRecordDecl *Parent = Method->getParent(); 9808 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9809 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9810 NewAttr->setImplicit(true); 9811 return NewAttr; 9812 } 9813 9814 // The Microsoft compiler won't check outer classes for the CodeSeg 9815 // when the #pragma code_seg stack is active. 9816 if (S.CodeSegStack.CurrentValue) 9817 return nullptr; 9818 9819 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) { 9820 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) { 9821 Attr *NewAttr = SAttr->clone(S.getASTContext()); 9822 NewAttr->setImplicit(true); 9823 return NewAttr; 9824 } 9825 } 9826 return nullptr; 9827 } 9828 9829 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a 9830 /// containing class. Otherwise it will return implicit SectionAttr if the 9831 /// function is a definition and there is an active value on CodeSegStack 9832 /// (from the current #pragma code-seg value). 9833 /// 9834 /// \param FD Function being declared. 9835 /// \param IsDefinition Whether it is a definition or just a declarartion. 9836 /// \returns A CodeSegAttr or SectionAttr to apply to the function or 9837 /// nullptr if no attribute should be added. 9838 Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, 9839 bool IsDefinition) { 9840 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD)) 9841 return A; 9842 if (!FD->hasAttr<SectionAttr>() && IsDefinition && 9843 CodeSegStack.CurrentValue) 9844 return SectionAttr::CreateImplicit( 9845 getASTContext(), CodeSegStack.CurrentValue->getString(), 9846 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 9847 SectionAttr::Declspec_allocate); 9848 return nullptr; 9849 } 9850 9851 /// Determines if we can perform a correct type check for \p D as a 9852 /// redeclaration of \p PrevDecl. If not, we can generally still perform a 9853 /// best-effort check. 9854 /// 9855 /// \param NewD The new declaration. 9856 /// \param OldD The old declaration. 9857 /// \param NewT The portion of the type of the new declaration to check. 9858 /// \param OldT The portion of the type of the old declaration to check. 9859 bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, 9860 QualType NewT, QualType OldT) { 9861 if (!NewD->getLexicalDeclContext()->isDependentContext()) 9862 return true; 9863 9864 // For dependently-typed local extern declarations and friends, we can't 9865 // perform a correct type check in general until instantiation: 9866 // 9867 // int f(); 9868 // template<typename T> void g() { T f(); } 9869 // 9870 // (valid if g() is only instantiated with T = int). 9871 if (NewT->isDependentType() && 9872 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind())) 9873 return false; 9874 9875 // Similarly, if the previous declaration was a dependent local extern 9876 // declaration, we don't really know its type yet. 9877 if (OldT->isDependentType() && OldD->isLocalExternDecl()) 9878 return false; 9879 9880 return true; 9881 } 9882 9883 /// Checks if the new declaration declared in dependent context must be 9884 /// put in the same redeclaration chain as the specified declaration. 9885 /// 9886 /// \param D Declaration that is checked. 9887 /// \param PrevDecl Previous declaration found with proper lookup method for the 9888 /// same declaration name. 9889 /// \returns True if D must be added to the redeclaration chain which PrevDecl 9890 /// belongs to. 9891 /// 9892 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) { 9893 if (!D->getLexicalDeclContext()->isDependentContext()) 9894 return true; 9895 9896 // Don't chain dependent friend function definitions until instantiation, to 9897 // permit cases like 9898 // 9899 // void func(); 9900 // template<typename T> class C1 { friend void func() {} }; 9901 // template<typename T> class C2 { friend void func() {} }; 9902 // 9903 // ... which is valid if only one of C1 and C2 is ever instantiated. 9904 // 9905 // FIXME: This need only apply to function definitions. For now, we proxy 9906 // this by checking for a file-scope function. We do not want this to apply 9907 // to friend declarations nominating member functions, because that gets in 9908 // the way of access checks. 9909 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext()) 9910 return false; 9911 9912 auto *VD = dyn_cast<ValueDecl>(D); 9913 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl); 9914 return !VD || !PrevVD || 9915 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(), 9916 PrevVD->getType()); 9917 } 9918 9919 /// Check the target attribute of the function for MultiVersion 9920 /// validity. 9921 /// 9922 /// Returns true if there was an error, false otherwise. 9923 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) { 9924 const auto *TA = FD->getAttr<TargetAttr>(); 9925 assert(TA && "MultiVersion Candidate requires a target attribute"); 9926 ParsedTargetAttr ParseInfo = TA->parse(); 9927 const TargetInfo &TargetInfo = S.Context.getTargetInfo(); 9928 enum ErrType { Feature = 0, Architecture = 1 }; 9929 9930 if (!ParseInfo.Architecture.empty() && 9931 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) { 9932 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9933 << Architecture << ParseInfo.Architecture; 9934 return true; 9935 } 9936 9937 for (const auto &Feat : ParseInfo.Features) { 9938 auto BareFeat = StringRef{Feat}.substr(1); 9939 if (Feat[0] == '-') { 9940 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9941 << Feature << ("no-" + BareFeat).str(); 9942 return true; 9943 } 9944 9945 if (!TargetInfo.validateCpuSupports(BareFeat) || 9946 !TargetInfo.isValidFeatureName(BareFeat)) { 9947 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option) 9948 << Feature << BareFeat; 9949 return true; 9950 } 9951 } 9952 return false; 9953 } 9954 9955 static bool HasNonMultiVersionAttributes(const FunctionDecl *FD, 9956 MultiVersionKind MVType) { 9957 for (const Attr *A : FD->attrs()) { 9958 switch (A->getKind()) { 9959 case attr::CPUDispatch: 9960 case attr::CPUSpecific: 9961 if (MVType != MultiVersionKind::CPUDispatch && 9962 MVType != MultiVersionKind::CPUSpecific) 9963 return true; 9964 break; 9965 case attr::Target: 9966 if (MVType != MultiVersionKind::Target) 9967 return true; 9968 break; 9969 default: 9970 return true; 9971 } 9972 } 9973 return false; 9974 } 9975 9976 bool Sema::areMultiversionVariantFunctionsCompatible( 9977 const FunctionDecl *OldFD, const FunctionDecl *NewFD, 9978 const PartialDiagnostic &NoProtoDiagID, 9979 const PartialDiagnosticAt &NoteCausedDiagIDAt, 9980 const PartialDiagnosticAt &NoSupportDiagIDAt, 9981 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, 9982 bool ConstexprSupported, bool CLinkageMayDiffer) { 9983 enum DoesntSupport { 9984 FuncTemplates = 0, 9985 VirtFuncs = 1, 9986 DeducedReturn = 2, 9987 Constructors = 3, 9988 Destructors = 4, 9989 DeletedFuncs = 5, 9990 DefaultedFuncs = 6, 9991 ConstexprFuncs = 7, 9992 ConstevalFuncs = 8, 9993 }; 9994 enum Different { 9995 CallingConv = 0, 9996 ReturnType = 1, 9997 ConstexprSpec = 2, 9998 InlineSpec = 3, 9999 StorageClass = 4, 10000 Linkage = 5, 10001 }; 10002 10003 if (NoProtoDiagID.getDiagID() != 0 && OldFD && 10004 !OldFD->getType()->getAs<FunctionProtoType>()) { 10005 Diag(OldFD->getLocation(), NoProtoDiagID); 10006 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second); 10007 return true; 10008 } 10009 10010 if (NoProtoDiagID.getDiagID() != 0 && 10011 !NewFD->getType()->getAs<FunctionProtoType>()) 10012 return Diag(NewFD->getLocation(), NoProtoDiagID); 10013 10014 if (!TemplatesSupported && 10015 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 10016 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10017 << FuncTemplates; 10018 10019 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) { 10020 if (NewCXXFD->isVirtual()) 10021 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10022 << VirtFuncs; 10023 10024 if (isa<CXXConstructorDecl>(NewCXXFD)) 10025 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10026 << Constructors; 10027 10028 if (isa<CXXDestructorDecl>(NewCXXFD)) 10029 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10030 << Destructors; 10031 } 10032 10033 if (NewFD->isDeleted()) 10034 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10035 << DeletedFuncs; 10036 10037 if (NewFD->isDefaulted()) 10038 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10039 << DefaultedFuncs; 10040 10041 if (!ConstexprSupported && NewFD->isConstexpr()) 10042 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10043 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 10044 10045 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 10046 const auto *NewType = cast<FunctionType>(NewQType); 10047 QualType NewReturnType = NewType->getReturnType(); 10048 10049 if (NewReturnType->isUndeducedType()) 10050 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second) 10051 << DeducedReturn; 10052 10053 // Ensure the return type is identical. 10054 if (OldFD) { 10055 QualType OldQType = Context.getCanonicalType(OldFD->getType()); 10056 const auto *OldType = cast<FunctionType>(OldQType); 10057 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 10058 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 10059 10060 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) 10061 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv; 10062 10063 QualType OldReturnType = OldType->getReturnType(); 10064 10065 if (OldReturnType != NewReturnType) 10066 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType; 10067 10068 if (OldFD->getConstexprKind() != NewFD->getConstexprKind()) 10069 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec; 10070 10071 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified()) 10072 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec; 10073 10074 if (OldFD->getStorageClass() != NewFD->getStorageClass()) 10075 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass; 10076 10077 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC()) 10078 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage; 10079 10080 if (CheckEquivalentExceptionSpec( 10081 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(), 10082 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation())) 10083 return true; 10084 } 10085 return false; 10086 } 10087 10088 static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, 10089 const FunctionDecl *NewFD, 10090 bool CausesMV, 10091 MultiVersionKind MVType) { 10092 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10093 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10094 if (OldFD) 10095 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10096 return true; 10097 } 10098 10099 bool IsCPUSpecificCPUDispatchMVType = 10100 MVType == MultiVersionKind::CPUDispatch || 10101 MVType == MultiVersionKind::CPUSpecific; 10102 10103 // For now, disallow all other attributes. These should be opt-in, but 10104 // an analysis of all of them is a future FIXME. 10105 if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFD, MVType)) { 10106 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs) 10107 << IsCPUSpecificCPUDispatchMVType; 10108 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10109 return true; 10110 } 10111 10112 if (HasNonMultiVersionAttributes(NewFD, MVType)) 10113 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs) 10114 << IsCPUSpecificCPUDispatchMVType; 10115 10116 // Only allow transition to MultiVersion if it hasn't been used. 10117 if (OldFD && CausesMV && OldFD->isUsed(false)) 10118 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used); 10119 10120 return S.areMultiversionVariantFunctionsCompatible( 10121 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto), 10122 PartialDiagnosticAt(NewFD->getLocation(), 10123 S.PDiag(diag::note_multiversioning_caused_here)), 10124 PartialDiagnosticAt(NewFD->getLocation(), 10125 S.PDiag(diag::err_multiversion_doesnt_support) 10126 << IsCPUSpecificCPUDispatchMVType), 10127 PartialDiagnosticAt(NewFD->getLocation(), 10128 S.PDiag(diag::err_multiversion_diff)), 10129 /*TemplatesSupported=*/false, 10130 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType, 10131 /*CLinkageMayDiffer=*/false); 10132 } 10133 10134 /// Check the validity of a multiversion function declaration that is the 10135 /// first of its kind. Also sets the multiversion'ness' of the function itself. 10136 /// 10137 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10138 /// 10139 /// Returns true if there was an error, false otherwise. 10140 static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, 10141 MultiVersionKind MVType, 10142 const TargetAttr *TA) { 10143 assert(MVType != MultiVersionKind::None && 10144 "Function lacks multiversion attribute"); 10145 10146 // Target only causes MV if it is default, otherwise this is a normal 10147 // function. 10148 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion()) 10149 return false; 10150 10151 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) { 10152 FD->setInvalidDecl(); 10153 return true; 10154 } 10155 10156 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) { 10157 FD->setInvalidDecl(); 10158 return true; 10159 } 10160 10161 FD->setIsMultiVersion(); 10162 return false; 10163 } 10164 10165 static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) { 10166 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) { 10167 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None) 10168 return true; 10169 } 10170 10171 return false; 10172 } 10173 10174 static bool CheckTargetCausesMultiVersioning( 10175 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, 10176 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10177 LookupResult &Previous) { 10178 const auto *OldTA = OldFD->getAttr<TargetAttr>(); 10179 ParsedTargetAttr NewParsed = NewTA->parse(); 10180 // Sort order doesn't matter, it just needs to be consistent. 10181 llvm::sort(NewParsed.Features); 10182 10183 // If the old decl is NOT MultiVersioned yet, and we don't cause that 10184 // to change, this is a simple redeclaration. 10185 if (!NewTA->isDefaultVersion() && 10186 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())) 10187 return false; 10188 10189 // Otherwise, this decl causes MultiVersioning. 10190 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) { 10191 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported); 10192 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10193 NewFD->setInvalidDecl(); 10194 return true; 10195 } 10196 10197 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true, 10198 MultiVersionKind::Target)) { 10199 NewFD->setInvalidDecl(); 10200 return true; 10201 } 10202 10203 if (CheckMultiVersionValue(S, NewFD)) { 10204 NewFD->setInvalidDecl(); 10205 return true; 10206 } 10207 10208 // If this is 'default', permit the forward declaration. 10209 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) { 10210 Redeclaration = true; 10211 OldDecl = OldFD; 10212 OldFD->setIsMultiVersion(); 10213 NewFD->setIsMultiVersion(); 10214 return false; 10215 } 10216 10217 if (CheckMultiVersionValue(S, OldFD)) { 10218 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10219 NewFD->setInvalidDecl(); 10220 return true; 10221 } 10222 10223 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>()); 10224 10225 if (OldParsed == NewParsed) { 10226 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10227 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10228 NewFD->setInvalidDecl(); 10229 return true; 10230 } 10231 10232 for (const auto *FD : OldFD->redecls()) { 10233 const auto *CurTA = FD->getAttr<TargetAttr>(); 10234 // We allow forward declarations before ANY multiversioning attributes, but 10235 // nothing after the fact. 10236 if (PreviousDeclsHaveMultiVersionAttribute(FD) && 10237 (!CurTA || CurTA->isInherited())) { 10238 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl) 10239 << 0; 10240 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here); 10241 NewFD->setInvalidDecl(); 10242 return true; 10243 } 10244 } 10245 10246 OldFD->setIsMultiVersion(); 10247 NewFD->setIsMultiVersion(); 10248 Redeclaration = false; 10249 MergeTypeWithPrevious = false; 10250 OldDecl = nullptr; 10251 Previous.clear(); 10252 return false; 10253 } 10254 10255 /// Check the validity of a new function declaration being added to an existing 10256 /// multiversioned declaration collection. 10257 static bool CheckMultiVersionAdditionalDecl( 10258 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, 10259 MultiVersionKind NewMVType, const TargetAttr *NewTA, 10260 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, 10261 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious, 10262 LookupResult &Previous) { 10263 10264 MultiVersionKind OldMVType = OldFD->getMultiVersionKind(); 10265 // Disallow mixing of multiversioning types. 10266 if ((OldMVType == MultiVersionKind::Target && 10267 NewMVType != MultiVersionKind::Target) || 10268 (NewMVType == MultiVersionKind::Target && 10269 OldMVType != MultiVersionKind::Target)) { 10270 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10271 S.Diag(OldFD->getLocation(), diag::note_previous_declaration); 10272 NewFD->setInvalidDecl(); 10273 return true; 10274 } 10275 10276 ParsedTargetAttr NewParsed; 10277 if (NewTA) { 10278 NewParsed = NewTA->parse(); 10279 llvm::sort(NewParsed.Features); 10280 } 10281 10282 bool UseMemberUsingDeclRules = 10283 S.CurContext->isRecord() && !NewFD->getFriendObjectKind(); 10284 10285 // Next, check ALL non-overloads to see if this is a redeclaration of a 10286 // previous member of the MultiVersion set. 10287 for (NamedDecl *ND : Previous) { 10288 FunctionDecl *CurFD = ND->getAsFunction(); 10289 if (!CurFD) 10290 continue; 10291 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules)) 10292 continue; 10293 10294 if (NewMVType == MultiVersionKind::Target) { 10295 const auto *CurTA = CurFD->getAttr<TargetAttr>(); 10296 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) { 10297 NewFD->setIsMultiVersion(); 10298 Redeclaration = true; 10299 OldDecl = ND; 10300 return false; 10301 } 10302 10303 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>()); 10304 if (CurParsed == NewParsed) { 10305 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate); 10306 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10307 NewFD->setInvalidDecl(); 10308 return true; 10309 } 10310 } else { 10311 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>(); 10312 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>(); 10313 // Handle CPUDispatch/CPUSpecific versions. 10314 // Only 1 CPUDispatch function is allowed, this will make it go through 10315 // the redeclaration errors. 10316 if (NewMVType == MultiVersionKind::CPUDispatch && 10317 CurFD->hasAttr<CPUDispatchAttr>()) { 10318 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() && 10319 std::equal( 10320 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(), 10321 NewCPUDisp->cpus_begin(), 10322 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10323 return Cur->getName() == New->getName(); 10324 })) { 10325 NewFD->setIsMultiVersion(); 10326 Redeclaration = true; 10327 OldDecl = ND; 10328 return false; 10329 } 10330 10331 // If the declarations don't match, this is an error condition. 10332 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch); 10333 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10334 NewFD->setInvalidDecl(); 10335 return true; 10336 } 10337 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) { 10338 10339 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() && 10340 std::equal( 10341 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(), 10342 NewCPUSpec->cpus_begin(), 10343 [](const IdentifierInfo *Cur, const IdentifierInfo *New) { 10344 return Cur->getName() == New->getName(); 10345 })) { 10346 NewFD->setIsMultiVersion(); 10347 Redeclaration = true; 10348 OldDecl = ND; 10349 return false; 10350 } 10351 10352 // Only 1 version of CPUSpecific is allowed for each CPU. 10353 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) { 10354 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) { 10355 if (CurII == NewII) { 10356 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs) 10357 << NewII; 10358 S.Diag(CurFD->getLocation(), diag::note_previous_declaration); 10359 NewFD->setInvalidDecl(); 10360 return true; 10361 } 10362 } 10363 } 10364 } 10365 // If the two decls aren't the same MVType, there is no possible error 10366 // condition. 10367 } 10368 } 10369 10370 // Else, this is simply a non-redecl case. Checking the 'value' is only 10371 // necessary in the Target case, since The CPUSpecific/Dispatch cases are 10372 // handled in the attribute adding step. 10373 if (NewMVType == MultiVersionKind::Target && 10374 CheckMultiVersionValue(S, NewFD)) { 10375 NewFD->setInvalidDecl(); 10376 return true; 10377 } 10378 10379 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, 10380 !OldFD->isMultiVersion(), NewMVType)) { 10381 NewFD->setInvalidDecl(); 10382 return true; 10383 } 10384 10385 // Permit forward declarations in the case where these two are compatible. 10386 if (!OldFD->isMultiVersion()) { 10387 OldFD->setIsMultiVersion(); 10388 NewFD->setIsMultiVersion(); 10389 Redeclaration = true; 10390 OldDecl = OldFD; 10391 return false; 10392 } 10393 10394 NewFD->setIsMultiVersion(); 10395 Redeclaration = false; 10396 MergeTypeWithPrevious = false; 10397 OldDecl = nullptr; 10398 Previous.clear(); 10399 return false; 10400 } 10401 10402 10403 /// Check the validity of a mulitversion function declaration. 10404 /// Also sets the multiversion'ness' of the function itself. 10405 /// 10406 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10407 /// 10408 /// Returns true if there was an error, false otherwise. 10409 static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, 10410 bool &Redeclaration, NamedDecl *&OldDecl, 10411 bool &MergeTypeWithPrevious, 10412 LookupResult &Previous) { 10413 const auto *NewTA = NewFD->getAttr<TargetAttr>(); 10414 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>(); 10415 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>(); 10416 10417 // Mixing Multiversioning types is prohibited. 10418 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) || 10419 (NewCPUDisp && NewCPUSpec)) { 10420 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed); 10421 NewFD->setInvalidDecl(); 10422 return true; 10423 } 10424 10425 MultiVersionKind MVType = NewFD->getMultiVersionKind(); 10426 10427 // Main isn't allowed to become a multiversion function, however it IS 10428 // permitted to have 'main' be marked with the 'target' optimization hint. 10429 if (NewFD->isMain()) { 10430 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) || 10431 MVType == MultiVersionKind::CPUDispatch || 10432 MVType == MultiVersionKind::CPUSpecific) { 10433 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main); 10434 NewFD->setInvalidDecl(); 10435 return true; 10436 } 10437 return false; 10438 } 10439 10440 if (!OldDecl || !OldDecl->getAsFunction() || 10441 OldDecl->getDeclContext()->getRedeclContext() != 10442 NewFD->getDeclContext()->getRedeclContext()) { 10443 // If there's no previous declaration, AND this isn't attempting to cause 10444 // multiversioning, this isn't an error condition. 10445 if (MVType == MultiVersionKind::None) 10446 return false; 10447 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA); 10448 } 10449 10450 FunctionDecl *OldFD = OldDecl->getAsFunction(); 10451 10452 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None) 10453 return false; 10454 10455 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) { 10456 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl) 10457 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target); 10458 NewFD->setInvalidDecl(); 10459 return true; 10460 } 10461 10462 // Handle the target potentially causes multiversioning case. 10463 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target) 10464 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA, 10465 Redeclaration, OldDecl, 10466 MergeTypeWithPrevious, Previous); 10467 10468 // At this point, we have a multiversion function decl (in OldFD) AND an 10469 // appropriate attribute in the current function decl. Resolve that these are 10470 // still compatible with previous declarations. 10471 return CheckMultiVersionAdditionalDecl( 10472 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration, 10473 OldDecl, MergeTypeWithPrevious, Previous); 10474 } 10475 10476 /// Perform semantic checking of a new function declaration. 10477 /// 10478 /// Performs semantic analysis of the new function declaration 10479 /// NewFD. This routine performs all semantic checking that does not 10480 /// require the actual declarator involved in the declaration, and is 10481 /// used both for the declaration of functions as they are parsed 10482 /// (called via ActOnDeclarator) and for the declaration of functions 10483 /// that have been instantiated via C++ template instantiation (called 10484 /// via InstantiateDecl). 10485 /// 10486 /// \param IsMemberSpecialization whether this new function declaration is 10487 /// a member specialization (that replaces any definition provided by the 10488 /// previous declaration). 10489 /// 10490 /// This sets NewFD->isInvalidDecl() to true if there was an error. 10491 /// 10492 /// \returns true if the function declaration is a redeclaration. 10493 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 10494 LookupResult &Previous, 10495 bool IsMemberSpecialization) { 10496 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 10497 "Variably modified return types are not handled here"); 10498 10499 // Determine whether the type of this function should be merged with 10500 // a previous visible declaration. This never happens for functions in C++, 10501 // and always happens in C if the previous declaration was visible. 10502 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 10503 !Previous.isShadowed(); 10504 10505 bool Redeclaration = false; 10506 NamedDecl *OldDecl = nullptr; 10507 bool MayNeedOverloadableChecks = false; 10508 10509 // Merge or overload the declaration with an existing declaration of 10510 // the same name, if appropriate. 10511 if (!Previous.empty()) { 10512 // Determine whether NewFD is an overload of PrevDecl or 10513 // a declaration that requires merging. If it's an overload, 10514 // there's no more work to do here; we'll just add the new 10515 // function to the scope. 10516 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) { 10517 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 10518 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 10519 Redeclaration = true; 10520 OldDecl = Candidate; 10521 } 10522 } else { 10523 MayNeedOverloadableChecks = true; 10524 switch (CheckOverload(S, NewFD, Previous, OldDecl, 10525 /*NewIsUsingDecl*/ false)) { 10526 case Ovl_Match: 10527 Redeclaration = true; 10528 break; 10529 10530 case Ovl_NonFunction: 10531 Redeclaration = true; 10532 break; 10533 10534 case Ovl_Overload: 10535 Redeclaration = false; 10536 break; 10537 } 10538 } 10539 } 10540 10541 // Check for a previous extern "C" declaration with this name. 10542 if (!Redeclaration && 10543 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 10544 if (!Previous.empty()) { 10545 // This is an extern "C" declaration with the same name as a previous 10546 // declaration, and thus redeclares that entity... 10547 Redeclaration = true; 10548 OldDecl = Previous.getFoundDecl(); 10549 MergeTypeWithPrevious = false; 10550 10551 // ... except in the presence of __attribute__((overloadable)). 10552 if (OldDecl->hasAttr<OverloadableAttr>() || 10553 NewFD->hasAttr<OverloadableAttr>()) { 10554 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 10555 MayNeedOverloadableChecks = true; 10556 Redeclaration = false; 10557 OldDecl = nullptr; 10558 } 10559 } 10560 } 10561 } 10562 10563 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, 10564 MergeTypeWithPrevious, Previous)) 10565 return Redeclaration; 10566 10567 // C++11 [dcl.constexpr]p8: 10568 // A constexpr specifier for a non-static member function that is not 10569 // a constructor declares that member function to be const. 10570 // 10571 // This needs to be delayed until we know whether this is an out-of-line 10572 // definition of a static member function. 10573 // 10574 // This rule is not present in C++1y, so we produce a backwards 10575 // compatibility warning whenever it happens in C++11. 10576 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 10577 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 10578 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 10579 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) { 10580 CXXMethodDecl *OldMD = nullptr; 10581 if (OldDecl) 10582 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 10583 if (!OldMD || !OldMD->isStatic()) { 10584 const FunctionProtoType *FPT = 10585 MD->getType()->castAs<FunctionProtoType>(); 10586 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 10587 EPI.TypeQuals.addConst(); 10588 MD->setType(Context.getFunctionType(FPT->getReturnType(), 10589 FPT->getParamTypes(), EPI)); 10590 10591 // Warn that we did this, if we're not performing template instantiation. 10592 // In that case, we'll have warned already when the template was defined. 10593 if (!inTemplateInstantiation()) { 10594 SourceLocation AddConstLoc; 10595 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 10596 .IgnoreParens().getAs<FunctionTypeLoc>()) 10597 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 10598 10599 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 10600 << FixItHint::CreateInsertion(AddConstLoc, " const"); 10601 } 10602 } 10603 } 10604 10605 if (Redeclaration) { 10606 // NewFD and OldDecl represent declarations that need to be 10607 // merged. 10608 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 10609 NewFD->setInvalidDecl(); 10610 return Redeclaration; 10611 } 10612 10613 Previous.clear(); 10614 Previous.addDecl(OldDecl); 10615 10616 if (FunctionTemplateDecl *OldTemplateDecl = 10617 dyn_cast<FunctionTemplateDecl>(OldDecl)) { 10618 auto *OldFD = OldTemplateDecl->getTemplatedDecl(); 10619 FunctionTemplateDecl *NewTemplateDecl 10620 = NewFD->getDescribedFunctionTemplate(); 10621 assert(NewTemplateDecl && "Template/non-template mismatch"); 10622 10623 // The call to MergeFunctionDecl above may have created some state in 10624 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we 10625 // can add it as a redeclaration. 10626 NewTemplateDecl->mergePrevDecl(OldTemplateDecl); 10627 10628 NewFD->setPreviousDeclaration(OldFD); 10629 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10630 if (NewFD->isCXXClassMember()) { 10631 NewFD->setAccess(OldTemplateDecl->getAccess()); 10632 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 10633 } 10634 10635 // If this is an explicit specialization of a member that is a function 10636 // template, mark it as a member specialization. 10637 if (IsMemberSpecialization && 10638 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 10639 NewTemplateDecl->setMemberSpecialization(); 10640 assert(OldTemplateDecl->isMemberSpecialization()); 10641 // Explicit specializations of a member template do not inherit deleted 10642 // status from the parent member template that they are specializing. 10643 if (OldFD->isDeleted()) { 10644 // FIXME: This assert will not hold in the presence of modules. 10645 assert(OldFD->getCanonicalDecl() == OldFD); 10646 // FIXME: We need an update record for this AST mutation. 10647 OldFD->setDeletedAsWritten(false); 10648 } 10649 } 10650 10651 } else { 10652 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) { 10653 auto *OldFD = cast<FunctionDecl>(OldDecl); 10654 // This needs to happen first so that 'inline' propagates. 10655 NewFD->setPreviousDeclaration(OldFD); 10656 adjustDeclContextForDeclaratorDecl(NewFD, OldFD); 10657 if (NewFD->isCXXClassMember()) 10658 NewFD->setAccess(OldFD->getAccess()); 10659 } 10660 } 10661 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks && 10662 !NewFD->getAttr<OverloadableAttr>()) { 10663 assert((Previous.empty() || 10664 llvm::any_of(Previous, 10665 [](const NamedDecl *ND) { 10666 return ND->hasAttr<OverloadableAttr>(); 10667 })) && 10668 "Non-redecls shouldn't happen without overloadable present"); 10669 10670 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) { 10671 const auto *FD = dyn_cast<FunctionDecl>(ND); 10672 return FD && !FD->hasAttr<OverloadableAttr>(); 10673 }); 10674 10675 if (OtherUnmarkedIter != Previous.end()) { 10676 Diag(NewFD->getLocation(), 10677 diag::err_attribute_overloadable_multiple_unmarked_overloads); 10678 Diag((*OtherUnmarkedIter)->getLocation(), 10679 diag::note_attribute_overloadable_prev_overload) 10680 << false; 10681 10682 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 10683 } 10684 } 10685 10686 // Semantic checking for this function declaration (in isolation). 10687 10688 if (getLangOpts().CPlusPlus) { 10689 // C++-specific checks. 10690 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 10691 CheckConstructor(Constructor); 10692 } else if (CXXDestructorDecl *Destructor = 10693 dyn_cast<CXXDestructorDecl>(NewFD)) { 10694 CXXRecordDecl *Record = Destructor->getParent(); 10695 QualType ClassType = Context.getTypeDeclType(Record); 10696 10697 // FIXME: Shouldn't we be able to perform this check even when the class 10698 // type is dependent? Both gcc and edg can handle that. 10699 if (!ClassType->isDependentType()) { 10700 DeclarationName Name 10701 = Context.DeclarationNames.getCXXDestructorName( 10702 Context.getCanonicalType(ClassType)); 10703 if (NewFD->getDeclName() != Name) { 10704 Diag(NewFD->getLocation(), diag::err_destructor_name); 10705 NewFD->setInvalidDecl(); 10706 return Redeclaration; 10707 } 10708 } 10709 } else if (CXXConversionDecl *Conversion 10710 = dyn_cast<CXXConversionDecl>(NewFD)) { 10711 ActOnConversionDeclarator(Conversion); 10712 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) { 10713 if (auto *TD = Guide->getDescribedFunctionTemplate()) 10714 CheckDeductionGuideTemplate(TD); 10715 10716 // A deduction guide is not on the list of entities that can be 10717 // explicitly specialized. 10718 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 10719 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized) 10720 << /*explicit specialization*/ 1; 10721 } 10722 10723 // Find any virtual functions that this function overrides. 10724 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 10725 if (!Method->isFunctionTemplateSpecialization() && 10726 !Method->getDescribedFunctionTemplate() && 10727 Method->isCanonicalDecl()) { 10728 if (AddOverriddenMethods(Method->getParent(), Method)) { 10729 // If the function was marked as "static", we have a problem. 10730 if (NewFD->getStorageClass() == SC_Static) { 10731 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 10732 } 10733 } 10734 } 10735 if (Method->isVirtual() && NewFD->getTrailingRequiresClause()) 10736 // C++2a [class.virtual]p6 10737 // A virtual method shall not have a requires-clause. 10738 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(), 10739 diag::err_constrained_virtual_method); 10740 10741 if (Method->isStatic()) 10742 checkThisInStaticMemberFunctionType(Method); 10743 } 10744 10745 // Extra checking for C++ overloaded operators (C++ [over.oper]). 10746 if (NewFD->isOverloadedOperator() && 10747 CheckOverloadedOperatorDeclaration(NewFD)) { 10748 NewFD->setInvalidDecl(); 10749 return Redeclaration; 10750 } 10751 10752 // Extra checking for C++0x literal operators (C++0x [over.literal]). 10753 if (NewFD->getLiteralIdentifier() && 10754 CheckLiteralOperatorDeclaration(NewFD)) { 10755 NewFD->setInvalidDecl(); 10756 return Redeclaration; 10757 } 10758 10759 // In C++, check default arguments now that we have merged decls. Unless 10760 // the lexical context is the class, because in this case this is done 10761 // during delayed parsing anyway. 10762 if (!CurContext->isRecord()) 10763 CheckCXXDefaultArguments(NewFD); 10764 10765 // If this function declares a builtin function, check the type of this 10766 // declaration against the expected type for the builtin. 10767 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 10768 ASTContext::GetBuiltinTypeError Error; 10769 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 10770 QualType T = Context.GetBuiltinType(BuiltinID, Error); 10771 // If the type of the builtin differs only in its exception 10772 // specification, that's OK. 10773 // FIXME: If the types do differ in this way, it would be better to 10774 // retain the 'noexcept' form of the type. 10775 if (!T.isNull() && 10776 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T, 10777 NewFD->getType())) 10778 // The type of this function differs from the type of the builtin, 10779 // so forget about the builtin entirely. 10780 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 10781 } 10782 10783 // If this function is declared as being extern "C", then check to see if 10784 // the function returns a UDT (class, struct, or union type) that is not C 10785 // compatible, and if it does, warn the user. 10786 // But, issue any diagnostic on the first declaration only. 10787 if (Previous.empty() && NewFD->isExternC()) { 10788 QualType R = NewFD->getReturnType(); 10789 if (R->isIncompleteType() && !R->isVoidType()) 10790 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 10791 << NewFD << R; 10792 else if (!R.isPODType(Context) && !R->isVoidType() && 10793 !R->isObjCObjectPointerType()) 10794 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 10795 } 10796 10797 // C++1z [dcl.fct]p6: 10798 // [...] whether the function has a non-throwing exception-specification 10799 // [is] part of the function type 10800 // 10801 // This results in an ABI break between C++14 and C++17 for functions whose 10802 // declared type includes an exception-specification in a parameter or 10803 // return type. (Exception specifications on the function itself are OK in 10804 // most cases, and exception specifications are not permitted in most other 10805 // contexts where they could make it into a mangling.) 10806 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) { 10807 auto HasNoexcept = [&](QualType T) -> bool { 10808 // Strip off declarator chunks that could be between us and a function 10809 // type. We don't need to look far, exception specifications are very 10810 // restricted prior to C++17. 10811 if (auto *RT = T->getAs<ReferenceType>()) 10812 T = RT->getPointeeType(); 10813 else if (T->isAnyPointerType()) 10814 T = T->getPointeeType(); 10815 else if (auto *MPT = T->getAs<MemberPointerType>()) 10816 T = MPT->getPointeeType(); 10817 if (auto *FPT = T->getAs<FunctionProtoType>()) 10818 if (FPT->isNothrow()) 10819 return true; 10820 return false; 10821 }; 10822 10823 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>(); 10824 bool AnyNoexcept = HasNoexcept(FPT->getReturnType()); 10825 for (QualType T : FPT->param_types()) 10826 AnyNoexcept |= HasNoexcept(T); 10827 if (AnyNoexcept) 10828 Diag(NewFD->getLocation(), 10829 diag::warn_cxx17_compat_exception_spec_in_signature) 10830 << NewFD; 10831 } 10832 10833 if (!Redeclaration && LangOpts.CUDA) 10834 checkCUDATargetOverload(NewFD, Previous); 10835 } 10836 return Redeclaration; 10837 } 10838 10839 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 10840 // C++11 [basic.start.main]p3: 10841 // A program that [...] declares main to be inline, static or 10842 // constexpr is ill-formed. 10843 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 10844 // appear in a declaration of main. 10845 // static main is not an error under C99, but we should warn about it. 10846 // We accept _Noreturn main as an extension. 10847 if (FD->getStorageClass() == SC_Static) 10848 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 10849 ? diag::err_static_main : diag::warn_static_main) 10850 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 10851 if (FD->isInlineSpecified()) 10852 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 10853 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 10854 if (DS.isNoreturnSpecified()) { 10855 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 10856 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 10857 Diag(NoreturnLoc, diag::ext_noreturn_main); 10858 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 10859 << FixItHint::CreateRemoval(NoreturnRange); 10860 } 10861 if (FD->isConstexpr()) { 10862 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 10863 << FD->isConsteval() 10864 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 10865 FD->setConstexprKind(CSK_unspecified); 10866 } 10867 10868 if (getLangOpts().OpenCL) { 10869 Diag(FD->getLocation(), diag::err_opencl_no_main) 10870 << FD->hasAttr<OpenCLKernelAttr>(); 10871 FD->setInvalidDecl(); 10872 return; 10873 } 10874 10875 QualType T = FD->getType(); 10876 assert(T->isFunctionType() && "function decl is not of function type"); 10877 const FunctionType* FT = T->castAs<FunctionType>(); 10878 10879 // Set default calling convention for main() 10880 if (FT->getCallConv() != CC_C) { 10881 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C)); 10882 FD->setType(QualType(FT, 0)); 10883 T = Context.getCanonicalType(FD->getType()); 10884 } 10885 10886 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 10887 // In C with GNU extensions we allow main() to have non-integer return 10888 // type, but we should warn about the extension, and we disable the 10889 // implicit-return-zero rule. 10890 10891 // GCC in C mode accepts qualified 'int'. 10892 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 10893 FD->setHasImplicitReturnZero(true); 10894 else { 10895 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 10896 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10897 if (RTRange.isValid()) 10898 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 10899 << FixItHint::CreateReplacement(RTRange, "int"); 10900 } 10901 } else { 10902 // In C and C++, main magically returns 0 if you fall off the end; 10903 // set the flag which tells us that. 10904 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 10905 10906 // All the standards say that main() should return 'int'. 10907 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 10908 FD->setHasImplicitReturnZero(true); 10909 else { 10910 // Otherwise, this is just a flat-out error. 10911 SourceRange RTRange = FD->getReturnTypeSourceRange(); 10912 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 10913 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 10914 : FixItHint()); 10915 FD->setInvalidDecl(true); 10916 } 10917 } 10918 10919 // Treat protoless main() as nullary. 10920 if (isa<FunctionNoProtoType>(FT)) return; 10921 10922 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 10923 unsigned nparams = FTP->getNumParams(); 10924 assert(FD->getNumParams() == nparams); 10925 10926 bool HasExtraParameters = (nparams > 3); 10927 10928 if (FTP->isVariadic()) { 10929 Diag(FD->getLocation(), diag::ext_variadic_main); 10930 // FIXME: if we had information about the location of the ellipsis, we 10931 // could add a FixIt hint to remove it as a parameter. 10932 } 10933 10934 // Darwin passes an undocumented fourth argument of type char**. If 10935 // other platforms start sprouting these, the logic below will start 10936 // getting shifty. 10937 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 10938 HasExtraParameters = false; 10939 10940 if (HasExtraParameters) { 10941 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 10942 FD->setInvalidDecl(true); 10943 nparams = 3; 10944 } 10945 10946 // FIXME: a lot of the following diagnostics would be improved 10947 // if we had some location information about types. 10948 10949 QualType CharPP = 10950 Context.getPointerType(Context.getPointerType(Context.CharTy)); 10951 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 10952 10953 for (unsigned i = 0; i < nparams; ++i) { 10954 QualType AT = FTP->getParamType(i); 10955 10956 bool mismatch = true; 10957 10958 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 10959 mismatch = false; 10960 else if (Expected[i] == CharPP) { 10961 // As an extension, the following forms are okay: 10962 // char const ** 10963 // char const * const * 10964 // char * const * 10965 10966 QualifierCollector qs; 10967 const PointerType* PT; 10968 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 10969 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 10970 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 10971 Context.CharTy)) { 10972 qs.removeConst(); 10973 mismatch = !qs.empty(); 10974 } 10975 } 10976 10977 if (mismatch) { 10978 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 10979 // TODO: suggest replacing given type with expected type 10980 FD->setInvalidDecl(true); 10981 } 10982 } 10983 10984 if (nparams == 1 && !FD->isInvalidDecl()) { 10985 Diag(FD->getLocation(), diag::warn_main_one_arg); 10986 } 10987 10988 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 10989 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 10990 FD->setInvalidDecl(); 10991 } 10992 } 10993 10994 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 10995 QualType T = FD->getType(); 10996 assert(T->isFunctionType() && "function decl is not of function type"); 10997 const FunctionType *FT = T->castAs<FunctionType>(); 10998 10999 // Set an implicit return of 'zero' if the function can return some integral, 11000 // enumeration, pointer or nullptr type. 11001 if (FT->getReturnType()->isIntegralOrEnumerationType() || 11002 FT->getReturnType()->isAnyPointerType() || 11003 FT->getReturnType()->isNullPtrType()) 11004 // DllMain is exempt because a return value of zero means it failed. 11005 if (FD->getName() != "DllMain") 11006 FD->setHasImplicitReturnZero(true); 11007 11008 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 11009 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 11010 FD->setInvalidDecl(); 11011 } 11012 } 11013 11014 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 11015 // FIXME: Need strict checking. In C89, we need to check for 11016 // any assignment, increment, decrement, function-calls, or 11017 // commas outside of a sizeof. In C99, it's the same list, 11018 // except that the aforementioned are allowed in unevaluated 11019 // expressions. Everything else falls under the 11020 // "may accept other forms of constant expressions" exception. 11021 // (We never end up here for C++, so the constant expression 11022 // rules there don't matter.) 11023 const Expr *Culprit; 11024 if (Init->isConstantInitializer(Context, false, &Culprit)) 11025 return false; 11026 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 11027 << Culprit->getSourceRange(); 11028 return true; 11029 } 11030 11031 namespace { 11032 // Visits an initialization expression to see if OrigDecl is evaluated in 11033 // its own initialization and throws a warning if it does. 11034 class SelfReferenceChecker 11035 : public EvaluatedExprVisitor<SelfReferenceChecker> { 11036 Sema &S; 11037 Decl *OrigDecl; 11038 bool isRecordType; 11039 bool isPODType; 11040 bool isReferenceType; 11041 11042 bool isInitList; 11043 llvm::SmallVector<unsigned, 4> InitFieldIndex; 11044 11045 public: 11046 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 11047 11048 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 11049 S(S), OrigDecl(OrigDecl) { 11050 isPODType = false; 11051 isRecordType = false; 11052 isReferenceType = false; 11053 isInitList = false; 11054 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 11055 isPODType = VD->getType().isPODType(S.Context); 11056 isRecordType = VD->getType()->isRecordType(); 11057 isReferenceType = VD->getType()->isReferenceType(); 11058 } 11059 } 11060 11061 // For most expressions, just call the visitor. For initializer lists, 11062 // track the index of the field being initialized since fields are 11063 // initialized in order allowing use of previously initialized fields. 11064 void CheckExpr(Expr *E) { 11065 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 11066 if (!InitList) { 11067 Visit(E); 11068 return; 11069 } 11070 11071 // Track and increment the index here. 11072 isInitList = true; 11073 InitFieldIndex.push_back(0); 11074 for (auto Child : InitList->children()) { 11075 CheckExpr(cast<Expr>(Child)); 11076 ++InitFieldIndex.back(); 11077 } 11078 InitFieldIndex.pop_back(); 11079 } 11080 11081 // Returns true if MemberExpr is checked and no further checking is needed. 11082 // Returns false if additional checking is required. 11083 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 11084 llvm::SmallVector<FieldDecl*, 4> Fields; 11085 Expr *Base = E; 11086 bool ReferenceField = false; 11087 11088 // Get the field members used. 11089 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11090 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 11091 if (!FD) 11092 return false; 11093 Fields.push_back(FD); 11094 if (FD->getType()->isReferenceType()) 11095 ReferenceField = true; 11096 Base = ME->getBase()->IgnoreParenImpCasts(); 11097 } 11098 11099 // Keep checking only if the base Decl is the same. 11100 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 11101 if (!DRE || DRE->getDecl() != OrigDecl) 11102 return false; 11103 11104 // A reference field can be bound to an unininitialized field. 11105 if (CheckReference && !ReferenceField) 11106 return true; 11107 11108 // Convert FieldDecls to their index number. 11109 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 11110 for (const FieldDecl *I : llvm::reverse(Fields)) 11111 UsedFieldIndex.push_back(I->getFieldIndex()); 11112 11113 // See if a warning is needed by checking the first difference in index 11114 // numbers. If field being used has index less than the field being 11115 // initialized, then the use is safe. 11116 for (auto UsedIter = UsedFieldIndex.begin(), 11117 UsedEnd = UsedFieldIndex.end(), 11118 OrigIter = InitFieldIndex.begin(), 11119 OrigEnd = InitFieldIndex.end(); 11120 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 11121 if (*UsedIter < *OrigIter) 11122 return true; 11123 if (*UsedIter > *OrigIter) 11124 break; 11125 } 11126 11127 // TODO: Add a different warning which will print the field names. 11128 HandleDeclRefExpr(DRE); 11129 return true; 11130 } 11131 11132 // For most expressions, the cast is directly above the DeclRefExpr. 11133 // For conditional operators, the cast can be outside the conditional 11134 // operator if both expressions are DeclRefExpr's. 11135 void HandleValue(Expr *E) { 11136 E = E->IgnoreParens(); 11137 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 11138 HandleDeclRefExpr(DRE); 11139 return; 11140 } 11141 11142 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 11143 Visit(CO->getCond()); 11144 HandleValue(CO->getTrueExpr()); 11145 HandleValue(CO->getFalseExpr()); 11146 return; 11147 } 11148 11149 if (BinaryConditionalOperator *BCO = 11150 dyn_cast<BinaryConditionalOperator>(E)) { 11151 Visit(BCO->getCond()); 11152 HandleValue(BCO->getFalseExpr()); 11153 return; 11154 } 11155 11156 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 11157 HandleValue(OVE->getSourceExpr()); 11158 return; 11159 } 11160 11161 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11162 if (BO->getOpcode() == BO_Comma) { 11163 Visit(BO->getLHS()); 11164 HandleValue(BO->getRHS()); 11165 return; 11166 } 11167 } 11168 11169 if (isa<MemberExpr>(E)) { 11170 if (isInitList) { 11171 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 11172 false /*CheckReference*/)) 11173 return; 11174 } 11175 11176 Expr *Base = E->IgnoreParenImpCasts(); 11177 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11178 // Check for static member variables and don't warn on them. 11179 if (!isa<FieldDecl>(ME->getMemberDecl())) 11180 return; 11181 Base = ME->getBase()->IgnoreParenImpCasts(); 11182 } 11183 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 11184 HandleDeclRefExpr(DRE); 11185 return; 11186 } 11187 11188 Visit(E); 11189 } 11190 11191 // Reference types not handled in HandleValue are handled here since all 11192 // uses of references are bad, not just r-value uses. 11193 void VisitDeclRefExpr(DeclRefExpr *E) { 11194 if (isReferenceType) 11195 HandleDeclRefExpr(E); 11196 } 11197 11198 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 11199 if (E->getCastKind() == CK_LValueToRValue) { 11200 HandleValue(E->getSubExpr()); 11201 return; 11202 } 11203 11204 Inherited::VisitImplicitCastExpr(E); 11205 } 11206 11207 void VisitMemberExpr(MemberExpr *E) { 11208 if (isInitList) { 11209 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 11210 return; 11211 } 11212 11213 // Don't warn on arrays since they can be treated as pointers. 11214 if (E->getType()->canDecayToPointerType()) return; 11215 11216 // Warn when a non-static method call is followed by non-static member 11217 // field accesses, which is followed by a DeclRefExpr. 11218 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 11219 bool Warn = (MD && !MD->isStatic()); 11220 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 11221 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 11222 if (!isa<FieldDecl>(ME->getMemberDecl())) 11223 Warn = false; 11224 Base = ME->getBase()->IgnoreParenImpCasts(); 11225 } 11226 11227 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 11228 if (Warn) 11229 HandleDeclRefExpr(DRE); 11230 return; 11231 } 11232 11233 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 11234 // Visit that expression. 11235 Visit(Base); 11236 } 11237 11238 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 11239 Expr *Callee = E->getCallee(); 11240 11241 if (isa<UnresolvedLookupExpr>(Callee)) 11242 return Inherited::VisitCXXOperatorCallExpr(E); 11243 11244 Visit(Callee); 11245 for (auto Arg: E->arguments()) 11246 HandleValue(Arg->IgnoreParenImpCasts()); 11247 } 11248 11249 void VisitUnaryOperator(UnaryOperator *E) { 11250 // For POD record types, addresses of its own members are well-defined. 11251 if (E->getOpcode() == UO_AddrOf && isRecordType && 11252 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 11253 if (!isPODType) 11254 HandleValue(E->getSubExpr()); 11255 return; 11256 } 11257 11258 if (E->isIncrementDecrementOp()) { 11259 HandleValue(E->getSubExpr()); 11260 return; 11261 } 11262 11263 Inherited::VisitUnaryOperator(E); 11264 } 11265 11266 void VisitObjCMessageExpr(ObjCMessageExpr *E) {} 11267 11268 void VisitCXXConstructExpr(CXXConstructExpr *E) { 11269 if (E->getConstructor()->isCopyConstructor()) { 11270 Expr *ArgExpr = E->getArg(0); 11271 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 11272 if (ILE->getNumInits() == 1) 11273 ArgExpr = ILE->getInit(0); 11274 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 11275 if (ICE->getCastKind() == CK_NoOp) 11276 ArgExpr = ICE->getSubExpr(); 11277 HandleValue(ArgExpr); 11278 return; 11279 } 11280 Inherited::VisitCXXConstructExpr(E); 11281 } 11282 11283 void VisitCallExpr(CallExpr *E) { 11284 // Treat std::move as a use. 11285 if (E->isCallToStdMove()) { 11286 HandleValue(E->getArg(0)); 11287 return; 11288 } 11289 11290 Inherited::VisitCallExpr(E); 11291 } 11292 11293 void VisitBinaryOperator(BinaryOperator *E) { 11294 if (E->isCompoundAssignmentOp()) { 11295 HandleValue(E->getLHS()); 11296 Visit(E->getRHS()); 11297 return; 11298 } 11299 11300 Inherited::VisitBinaryOperator(E); 11301 } 11302 11303 // A custom visitor for BinaryConditionalOperator is needed because the 11304 // regular visitor would check the condition and true expression separately 11305 // but both point to the same place giving duplicate diagnostics. 11306 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 11307 Visit(E->getCond()); 11308 Visit(E->getFalseExpr()); 11309 } 11310 11311 void HandleDeclRefExpr(DeclRefExpr *DRE) { 11312 Decl* ReferenceDecl = DRE->getDecl(); 11313 if (OrigDecl != ReferenceDecl) return; 11314 unsigned diag; 11315 if (isReferenceType) { 11316 diag = diag::warn_uninit_self_reference_in_reference_init; 11317 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 11318 diag = diag::warn_static_self_reference_in_init; 11319 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 11320 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 11321 DRE->getDecl()->getType()->isRecordType()) { 11322 diag = diag::warn_uninit_self_reference_in_init; 11323 } else { 11324 // Local variables will be handled by the CFG analysis. 11325 return; 11326 } 11327 11328 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE, 11329 S.PDiag(diag) 11330 << DRE->getDecl() << OrigDecl->getLocation() 11331 << DRE->getSourceRange()); 11332 } 11333 }; 11334 11335 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 11336 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 11337 bool DirectInit) { 11338 // Parameters arguments are occassionially constructed with itself, 11339 // for instance, in recursive functions. Skip them. 11340 if (isa<ParmVarDecl>(OrigDecl)) 11341 return; 11342 11343 E = E->IgnoreParens(); 11344 11345 // Skip checking T a = a where T is not a record or reference type. 11346 // Doing so is a way to silence uninitialized warnings. 11347 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 11348 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 11349 if (ICE->getCastKind() == CK_LValueToRValue) 11350 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 11351 if (DRE->getDecl() == OrigDecl) 11352 return; 11353 11354 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 11355 } 11356 } // end anonymous namespace 11357 11358 namespace { 11359 // Simple wrapper to add the name of a variable or (if no variable is 11360 // available) a DeclarationName into a diagnostic. 11361 struct VarDeclOrName { 11362 VarDecl *VDecl; 11363 DeclarationName Name; 11364 11365 friend const Sema::SemaDiagnosticBuilder & 11366 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) { 11367 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name; 11368 } 11369 }; 11370 } // end anonymous namespace 11371 11372 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 11373 DeclarationName Name, QualType Type, 11374 TypeSourceInfo *TSI, 11375 SourceRange Range, bool DirectInit, 11376 Expr *Init) { 11377 bool IsInitCapture = !VDecl; 11378 assert((!VDecl || !VDecl->isInitCapture()) && 11379 "init captures are expected to be deduced prior to initialization"); 11380 11381 VarDeclOrName VN{VDecl, Name}; 11382 11383 DeducedType *Deduced = Type->getContainedDeducedType(); 11384 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type"); 11385 11386 // C++11 [dcl.spec.auto]p3 11387 if (!Init) { 11388 assert(VDecl && "no init for init capture deduction?"); 11389 11390 // Except for class argument deduction, and then for an initializing 11391 // declaration only, i.e. no static at class scope or extern. 11392 if (!isa<DeducedTemplateSpecializationType>(Deduced) || 11393 VDecl->hasExternalStorage() || 11394 VDecl->isStaticDataMember()) { 11395 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init) 11396 << VDecl->getDeclName() << Type; 11397 return QualType(); 11398 } 11399 } 11400 11401 ArrayRef<Expr*> DeduceInits; 11402 if (Init) 11403 DeduceInits = Init; 11404 11405 if (DirectInit) { 11406 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init)) 11407 DeduceInits = PL->exprs(); 11408 } 11409 11410 if (isa<DeducedTemplateSpecializationType>(Deduced)) { 11411 assert(VDecl && "non-auto type for init capture deduction?"); 11412 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11413 InitializationKind Kind = InitializationKind::CreateForInit( 11414 VDecl->getLocation(), DirectInit, Init); 11415 // FIXME: Initialization should not be taking a mutable list of inits. 11416 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end()); 11417 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind, 11418 InitsCopy); 11419 } 11420 11421 if (DirectInit) { 11422 if (auto *IL = dyn_cast<InitListExpr>(Init)) 11423 DeduceInits = IL->inits(); 11424 } 11425 11426 // Deduction only works if we have exactly one source expression. 11427 if (DeduceInits.empty()) { 11428 // It isn't possible to write this directly, but it is possible to 11429 // end up in this situation with "auto x(some_pack...);" 11430 Diag(Init->getBeginLoc(), IsInitCapture 11431 ? diag::err_init_capture_no_expression 11432 : diag::err_auto_var_init_no_expression) 11433 << VN << Type << Range; 11434 return QualType(); 11435 } 11436 11437 if (DeduceInits.size() > 1) { 11438 Diag(DeduceInits[1]->getBeginLoc(), 11439 IsInitCapture ? diag::err_init_capture_multiple_expressions 11440 : diag::err_auto_var_init_multiple_expressions) 11441 << VN << Type << Range; 11442 return QualType(); 11443 } 11444 11445 Expr *DeduceInit = DeduceInits[0]; 11446 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 11447 Diag(Init->getBeginLoc(), IsInitCapture 11448 ? diag::err_init_capture_paren_braces 11449 : diag::err_auto_var_init_paren_braces) 11450 << isa<InitListExpr>(Init) << VN << Type << Range; 11451 return QualType(); 11452 } 11453 11454 // Expressions default to 'id' when we're in a debugger. 11455 bool DefaultedAnyToId = false; 11456 if (getLangOpts().DebuggerCastResultToId && 11457 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 11458 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11459 if (Result.isInvalid()) { 11460 return QualType(); 11461 } 11462 Init = Result.get(); 11463 DefaultedAnyToId = true; 11464 } 11465 11466 // C++ [dcl.decomp]p1: 11467 // If the assignment-expression [...] has array type A and no ref-qualifier 11468 // is present, e has type cv A 11469 if (VDecl && isa<DecompositionDecl>(VDecl) && 11470 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) && 11471 DeduceInit->getType()->isConstantArrayType()) 11472 return Context.getQualifiedType(DeduceInit->getType(), 11473 Type.getQualifiers()); 11474 11475 QualType DeducedType; 11476 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 11477 if (!IsInitCapture) 11478 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 11479 else if (isa<InitListExpr>(Init)) 11480 Diag(Range.getBegin(), 11481 diag::err_init_capture_deduction_failure_from_init_list) 11482 << VN 11483 << (DeduceInit->getType().isNull() ? TSI->getType() 11484 : DeduceInit->getType()) 11485 << DeduceInit->getSourceRange(); 11486 else 11487 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 11488 << VN << TSI->getType() 11489 << (DeduceInit->getType().isNull() ? TSI->getType() 11490 : DeduceInit->getType()) 11491 << DeduceInit->getSourceRange(); 11492 } 11493 11494 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 11495 // 'id' instead of a specific object type prevents most of our usual 11496 // checks. 11497 // We only want to warn outside of template instantiations, though: 11498 // inside a template, the 'id' could have come from a parameter. 11499 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture && 11500 !DeducedType.isNull() && DeducedType->isObjCIdType()) { 11501 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 11502 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range; 11503 } 11504 11505 return DeducedType; 11506 } 11507 11508 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, 11509 Expr *Init) { 11510 QualType DeducedType = deduceVarTypeFromInitializer( 11511 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(), 11512 VDecl->getSourceRange(), DirectInit, Init); 11513 if (DeducedType.isNull()) { 11514 VDecl->setInvalidDecl(); 11515 return true; 11516 } 11517 11518 VDecl->setType(DeducedType); 11519 assert(VDecl->isLinkageValid()); 11520 11521 // In ARC, infer lifetime. 11522 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 11523 VDecl->setInvalidDecl(); 11524 11525 if (getLangOpts().OpenCL) 11526 deduceOpenCLAddressSpace(VDecl); 11527 11528 // If this is a redeclaration, check that the type we just deduced matches 11529 // the previously declared type. 11530 if (VarDecl *Old = VDecl->getPreviousDecl()) { 11531 // We never need to merge the type, because we cannot form an incomplete 11532 // array of auto, nor deduce such a type. 11533 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 11534 } 11535 11536 // Check the deduced type is valid for a variable declaration. 11537 CheckVariableDeclarationType(VDecl); 11538 return VDecl->isInvalidDecl(); 11539 } 11540 11541 void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init, 11542 SourceLocation Loc) { 11543 if (auto *CE = dyn_cast<ConstantExpr>(Init)) 11544 Init = CE->getSubExpr(); 11545 11546 QualType InitType = Init->getType(); 11547 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11548 InitType.hasNonTrivialToPrimitiveCopyCUnion()) && 11549 "shouldn't be called if type doesn't have a non-trivial C struct"); 11550 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 11551 for (auto I : ILE->inits()) { 11552 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() && 11553 !I->getType().hasNonTrivialToPrimitiveCopyCUnion()) 11554 continue; 11555 SourceLocation SL = I->getExprLoc(); 11556 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc); 11557 } 11558 return; 11559 } 11560 11561 if (isa<ImplicitValueInitExpr>(Init)) { 11562 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11563 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject, 11564 NTCUK_Init); 11565 } else { 11566 // Assume all other explicit initializers involving copying some existing 11567 // object. 11568 // TODO: ignore any explicit initializers where we can guarantee 11569 // copy-elision. 11570 if (InitType.hasNonTrivialToPrimitiveCopyCUnion()) 11571 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy); 11572 } 11573 } 11574 11575 namespace { 11576 11577 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) { 11578 // Ignore unavailable fields. A field can be marked as unavailable explicitly 11579 // in the source code or implicitly by the compiler if it is in a union 11580 // defined in a system header and has non-trivial ObjC ownership 11581 // qualifications. We don't want those fields to participate in determining 11582 // whether the containing union is non-trivial. 11583 return FD->hasAttr<UnavailableAttr>(); 11584 } 11585 11586 struct DiagNonTrivalCUnionDefaultInitializeVisitor 11587 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11588 void> { 11589 using Super = 11590 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor, 11591 void>; 11592 11593 DiagNonTrivalCUnionDefaultInitializeVisitor( 11594 QualType OrigTy, SourceLocation OrigLoc, 11595 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11596 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11597 11598 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT, 11599 const FieldDecl *FD, bool InNonTrivialUnion) { 11600 if (const auto *AT = S.Context.getAsArrayType(QT)) 11601 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11602 InNonTrivialUnion); 11603 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion); 11604 } 11605 11606 void visitARCStrong(QualType QT, const FieldDecl *FD, 11607 bool InNonTrivialUnion) { 11608 if (InNonTrivialUnion) 11609 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11610 << 1 << 0 << QT << FD->getName(); 11611 } 11612 11613 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11614 if (InNonTrivialUnion) 11615 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11616 << 1 << 0 << QT << FD->getName(); 11617 } 11618 11619 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11620 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11621 if (RD->isUnion()) { 11622 if (OrigLoc.isValid()) { 11623 bool IsUnion = false; 11624 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11625 IsUnion = OrigRD->isUnion(); 11626 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11627 << 0 << OrigTy << IsUnion << UseContext; 11628 // Reset OrigLoc so that this diagnostic is emitted only once. 11629 OrigLoc = SourceLocation(); 11630 } 11631 InNonTrivialUnion = true; 11632 } 11633 11634 if (InNonTrivialUnion) 11635 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11636 << 0 << 0 << QT.getUnqualifiedType() << ""; 11637 11638 for (const FieldDecl *FD : RD->fields()) 11639 if (!shouldIgnoreForRecordTriviality(FD)) 11640 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11641 } 11642 11643 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11644 11645 // The non-trivial C union type or the struct/union type that contains a 11646 // non-trivial C union. 11647 QualType OrigTy; 11648 SourceLocation OrigLoc; 11649 Sema::NonTrivialCUnionContext UseContext; 11650 Sema &S; 11651 }; 11652 11653 struct DiagNonTrivalCUnionDestructedTypeVisitor 11654 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> { 11655 using Super = 11656 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>; 11657 11658 DiagNonTrivalCUnionDestructedTypeVisitor( 11659 QualType OrigTy, SourceLocation OrigLoc, 11660 Sema::NonTrivialCUnionContext UseContext, Sema &S) 11661 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11662 11663 void visitWithKind(QualType::DestructionKind DK, QualType QT, 11664 const FieldDecl *FD, bool InNonTrivialUnion) { 11665 if (const auto *AT = S.Context.getAsArrayType(QT)) 11666 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11667 InNonTrivialUnion); 11668 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion); 11669 } 11670 11671 void visitARCStrong(QualType QT, const FieldDecl *FD, 11672 bool InNonTrivialUnion) { 11673 if (InNonTrivialUnion) 11674 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11675 << 1 << 1 << QT << FD->getName(); 11676 } 11677 11678 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11679 if (InNonTrivialUnion) 11680 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11681 << 1 << 1 << QT << FD->getName(); 11682 } 11683 11684 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11685 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11686 if (RD->isUnion()) { 11687 if (OrigLoc.isValid()) { 11688 bool IsUnion = false; 11689 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11690 IsUnion = OrigRD->isUnion(); 11691 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11692 << 1 << OrigTy << IsUnion << UseContext; 11693 // Reset OrigLoc so that this diagnostic is emitted only once. 11694 OrigLoc = SourceLocation(); 11695 } 11696 InNonTrivialUnion = true; 11697 } 11698 11699 if (InNonTrivialUnion) 11700 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11701 << 0 << 1 << QT.getUnqualifiedType() << ""; 11702 11703 for (const FieldDecl *FD : RD->fields()) 11704 if (!shouldIgnoreForRecordTriviality(FD)) 11705 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11706 } 11707 11708 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11709 void visitCXXDestructor(QualType QT, const FieldDecl *FD, 11710 bool InNonTrivialUnion) {} 11711 11712 // The non-trivial C union type or the struct/union type that contains a 11713 // non-trivial C union. 11714 QualType OrigTy; 11715 SourceLocation OrigLoc; 11716 Sema::NonTrivialCUnionContext UseContext; 11717 Sema &S; 11718 }; 11719 11720 struct DiagNonTrivalCUnionCopyVisitor 11721 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> { 11722 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>; 11723 11724 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc, 11725 Sema::NonTrivialCUnionContext UseContext, 11726 Sema &S) 11727 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {} 11728 11729 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT, 11730 const FieldDecl *FD, bool InNonTrivialUnion) { 11731 if (const auto *AT = S.Context.getAsArrayType(QT)) 11732 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD, 11733 InNonTrivialUnion); 11734 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion); 11735 } 11736 11737 void visitARCStrong(QualType QT, const FieldDecl *FD, 11738 bool InNonTrivialUnion) { 11739 if (InNonTrivialUnion) 11740 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11741 << 1 << 2 << QT << FD->getName(); 11742 } 11743 11744 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11745 if (InNonTrivialUnion) 11746 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union) 11747 << 1 << 2 << QT << FD->getName(); 11748 } 11749 11750 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) { 11751 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl(); 11752 if (RD->isUnion()) { 11753 if (OrigLoc.isValid()) { 11754 bool IsUnion = false; 11755 if (auto *OrigRD = OrigTy->getAsRecordDecl()) 11756 IsUnion = OrigRD->isUnion(); 11757 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context) 11758 << 2 << OrigTy << IsUnion << UseContext; 11759 // Reset OrigLoc so that this diagnostic is emitted only once. 11760 OrigLoc = SourceLocation(); 11761 } 11762 InNonTrivialUnion = true; 11763 } 11764 11765 if (InNonTrivialUnion) 11766 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union) 11767 << 0 << 2 << QT.getUnqualifiedType() << ""; 11768 11769 for (const FieldDecl *FD : RD->fields()) 11770 if (!shouldIgnoreForRecordTriviality(FD)) 11771 asDerived().visit(FD->getType(), FD, InNonTrivialUnion); 11772 } 11773 11774 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT, 11775 const FieldDecl *FD, bool InNonTrivialUnion) {} 11776 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {} 11777 void visitVolatileTrivial(QualType QT, const FieldDecl *FD, 11778 bool InNonTrivialUnion) {} 11779 11780 // The non-trivial C union type or the struct/union type that contains a 11781 // non-trivial C union. 11782 QualType OrigTy; 11783 SourceLocation OrigLoc; 11784 Sema::NonTrivialCUnionContext UseContext; 11785 Sema &S; 11786 }; 11787 11788 } // namespace 11789 11790 void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc, 11791 NonTrivialCUnionContext UseContext, 11792 unsigned NonTrivialKind) { 11793 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 11794 QT.hasNonTrivialToPrimitiveDestructCUnion() || 11795 QT.hasNonTrivialToPrimitiveCopyCUnion()) && 11796 "shouldn't be called if type doesn't have a non-trivial C union"); 11797 11798 if ((NonTrivialKind & NTCUK_Init) && 11799 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 11800 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this) 11801 .visit(QT, nullptr, false); 11802 if ((NonTrivialKind & NTCUK_Destruct) && 11803 QT.hasNonTrivialToPrimitiveDestructCUnion()) 11804 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this) 11805 .visit(QT, nullptr, false); 11806 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion()) 11807 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this) 11808 .visit(QT, nullptr, false); 11809 } 11810 11811 /// AddInitializerToDecl - Adds the initializer Init to the 11812 /// declaration dcl. If DirectInit is true, this is C++ direct 11813 /// initialization rather than copy initialization. 11814 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) { 11815 // If there is no declaration, there was an error parsing it. Just ignore 11816 // the initializer. 11817 if (!RealDecl || RealDecl->isInvalidDecl()) { 11818 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 11819 return; 11820 } 11821 11822 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 11823 // Pure-specifiers are handled in ActOnPureSpecifier. 11824 Diag(Method->getLocation(), diag::err_member_function_initialization) 11825 << Method->getDeclName() << Init->getSourceRange(); 11826 Method->setInvalidDecl(); 11827 return; 11828 } 11829 11830 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 11831 if (!VDecl) { 11832 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 11833 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 11834 RealDecl->setInvalidDecl(); 11835 return; 11836 } 11837 11838 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 11839 if (VDecl->getType()->isUndeducedType()) { 11840 // Attempt typo correction early so that the type of the init expression can 11841 // be deduced based on the chosen correction if the original init contains a 11842 // TypoExpr. 11843 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 11844 if (!Res.isUsable()) { 11845 RealDecl->setInvalidDecl(); 11846 return; 11847 } 11848 Init = Res.get(); 11849 11850 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init)) 11851 return; 11852 } 11853 11854 // dllimport cannot be used on variable definitions. 11855 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 11856 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 11857 VDecl->setInvalidDecl(); 11858 return; 11859 } 11860 11861 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 11862 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 11863 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 11864 VDecl->setInvalidDecl(); 11865 return; 11866 } 11867 11868 if (!VDecl->getType()->isDependentType()) { 11869 // A definition must end up with a complete type, which means it must be 11870 // complete with the restriction that an array type might be completed by 11871 // the initializer; note that later code assumes this restriction. 11872 QualType BaseDeclType = VDecl->getType(); 11873 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 11874 BaseDeclType = Array->getElementType(); 11875 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 11876 diag::err_typecheck_decl_incomplete_type)) { 11877 RealDecl->setInvalidDecl(); 11878 return; 11879 } 11880 11881 // The variable can not have an abstract class type. 11882 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 11883 diag::err_abstract_type_in_decl, 11884 AbstractVariableType)) 11885 VDecl->setInvalidDecl(); 11886 } 11887 11888 // If adding the initializer will turn this declaration into a definition, 11889 // and we already have a definition for this variable, diagnose or otherwise 11890 // handle the situation. 11891 VarDecl *Def; 11892 if ((Def = VDecl->getDefinition()) && Def != VDecl && 11893 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) && 11894 !VDecl->isThisDeclarationADemotedDefinition() && 11895 checkVarDeclRedefinition(Def, VDecl)) 11896 return; 11897 11898 if (getLangOpts().CPlusPlus) { 11899 // C++ [class.static.data]p4 11900 // If a static data member is of const integral or const 11901 // enumeration type, its declaration in the class definition can 11902 // specify a constant-initializer which shall be an integral 11903 // constant expression (5.19). In that case, the member can appear 11904 // in integral constant expressions. The member shall still be 11905 // defined in a namespace scope if it is used in the program and the 11906 // namespace scope definition shall not contain an initializer. 11907 // 11908 // We already performed a redefinition check above, but for static 11909 // data members we also need to check whether there was an in-class 11910 // declaration with an initializer. 11911 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 11912 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 11913 << VDecl->getDeclName(); 11914 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 11915 diag::note_previous_initializer) 11916 << 0; 11917 return; 11918 } 11919 11920 if (VDecl->hasLocalStorage()) 11921 setFunctionHasBranchProtectedScope(); 11922 11923 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 11924 VDecl->setInvalidDecl(); 11925 return; 11926 } 11927 } 11928 11929 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 11930 // a kernel function cannot be initialized." 11931 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 11932 Diag(VDecl->getLocation(), diag::err_local_cant_init); 11933 VDecl->setInvalidDecl(); 11934 return; 11935 } 11936 11937 // Get the decls type and save a reference for later, since 11938 // CheckInitializerTypes may change it. 11939 QualType DclT = VDecl->getType(), SavT = DclT; 11940 11941 // Expressions default to 'id' when we're in a debugger 11942 // and we are assigning it to a variable of Objective-C pointer type. 11943 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 11944 Init->getType() == Context.UnknownAnyTy) { 11945 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 11946 if (Result.isInvalid()) { 11947 VDecl->setInvalidDecl(); 11948 return; 11949 } 11950 Init = Result.get(); 11951 } 11952 11953 // Perform the initialization. 11954 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 11955 if (!VDecl->isInvalidDecl()) { 11956 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 11957 InitializationKind Kind = InitializationKind::CreateForInit( 11958 VDecl->getLocation(), DirectInit, Init); 11959 11960 MultiExprArg Args = Init; 11961 if (CXXDirectInit) 11962 Args = MultiExprArg(CXXDirectInit->getExprs(), 11963 CXXDirectInit->getNumExprs()); 11964 11965 // Try to correct any TypoExprs in the initialization arguments. 11966 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 11967 ExprResult Res = CorrectDelayedTyposInExpr( 11968 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 11969 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 11970 return Init.Failed() ? ExprError() : E; 11971 }); 11972 if (Res.isInvalid()) { 11973 VDecl->setInvalidDecl(); 11974 } else if (Res.get() != Args[Idx]) { 11975 Args[Idx] = Res.get(); 11976 } 11977 } 11978 if (VDecl->isInvalidDecl()) 11979 return; 11980 11981 InitializationSequence InitSeq(*this, Entity, Kind, Args, 11982 /*TopLevelOfInitList=*/false, 11983 /*TreatUnavailableAsInvalid=*/false); 11984 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 11985 if (Result.isInvalid()) { 11986 VDecl->setInvalidDecl(); 11987 return; 11988 } 11989 11990 Init = Result.getAs<Expr>(); 11991 } 11992 11993 // Check for self-references within variable initializers. 11994 // Variables declared within a function/method body (except for references) 11995 // are handled by a dataflow analysis. 11996 // This is undefined behavior in C++, but valid in C. 11997 if (getLangOpts().CPlusPlus) { 11998 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 11999 VDecl->getType()->isReferenceType()) { 12000 CheckSelfReference(*this, RealDecl, Init, DirectInit); 12001 } 12002 } 12003 12004 // If the type changed, it means we had an incomplete type that was 12005 // completed by the initializer. For example: 12006 // int ary[] = { 1, 3, 5 }; 12007 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 12008 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 12009 VDecl->setType(DclT); 12010 12011 if (!VDecl->isInvalidDecl()) { 12012 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 12013 12014 if (VDecl->hasAttr<BlocksAttr>()) 12015 checkRetainCycles(VDecl, Init); 12016 12017 // It is safe to assign a weak reference into a strong variable. 12018 // Although this code can still have problems: 12019 // id x = self.weakProp; 12020 // id y = self.weakProp; 12021 // we do not warn to warn spuriously when 'x' and 'y' are on separate 12022 // paths through the function. This should be revisited if 12023 // -Wrepeated-use-of-weak is made flow-sensitive. 12024 if (FunctionScopeInfo *FSI = getCurFunction()) 12025 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong || 12026 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) && 12027 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 12028 Init->getBeginLoc())) 12029 FSI->markSafeWeakUse(Init); 12030 } 12031 12032 // The initialization is usually a full-expression. 12033 // 12034 // FIXME: If this is a braced initialization of an aggregate, it is not 12035 // an expression, and each individual field initializer is a separate 12036 // full-expression. For instance, in: 12037 // 12038 // struct Temp { ~Temp(); }; 12039 // struct S { S(Temp); }; 12040 // struct T { S a, b; } t = { Temp(), Temp() } 12041 // 12042 // we should destroy the first Temp before constructing the second. 12043 ExprResult Result = 12044 ActOnFinishFullExpr(Init, VDecl->getLocation(), 12045 /*DiscardedValue*/ false, VDecl->isConstexpr()); 12046 if (Result.isInvalid()) { 12047 VDecl->setInvalidDecl(); 12048 return; 12049 } 12050 Init = Result.get(); 12051 12052 // Attach the initializer to the decl. 12053 VDecl->setInit(Init); 12054 12055 if (VDecl->isLocalVarDecl()) { 12056 // Don't check the initializer if the declaration is malformed. 12057 if (VDecl->isInvalidDecl()) { 12058 // do nothing 12059 12060 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized. 12061 // This is true even in C++ for OpenCL. 12062 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) { 12063 CheckForConstantInitializer(Init, DclT); 12064 12065 // Otherwise, C++ does not restrict the initializer. 12066 } else if (getLangOpts().CPlusPlus) { 12067 // do nothing 12068 12069 // C99 6.7.8p4: All the expressions in an initializer for an object that has 12070 // static storage duration shall be constant expressions or string literals. 12071 } else if (VDecl->getStorageClass() == SC_Static) { 12072 CheckForConstantInitializer(Init, DclT); 12073 12074 // C89 is stricter than C99 for aggregate initializers. 12075 // C89 6.5.7p3: All the expressions [...] in an initializer list 12076 // for an object that has aggregate or union type shall be 12077 // constant expressions. 12078 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 12079 isa<InitListExpr>(Init)) { 12080 const Expr *Culprit; 12081 if (!Init->isConstantInitializer(Context, false, &Culprit)) { 12082 Diag(Culprit->getExprLoc(), 12083 diag::ext_aggregate_init_not_constant) 12084 << Culprit->getSourceRange(); 12085 } 12086 } 12087 12088 if (auto *E = dyn_cast<ExprWithCleanups>(Init)) 12089 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens())) 12090 if (VDecl->hasLocalStorage()) 12091 BE->getBlockDecl()->setCanAvoidCopyToHeap(); 12092 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() && 12093 VDecl->getLexicalDeclContext()->isRecord()) { 12094 // This is an in-class initialization for a static data member, e.g., 12095 // 12096 // struct S { 12097 // static const int value = 17; 12098 // }; 12099 12100 // C++ [class.mem]p4: 12101 // A member-declarator can contain a constant-initializer only 12102 // if it declares a static member (9.4) of const integral or 12103 // const enumeration type, see 9.4.2. 12104 // 12105 // C++11 [class.static.data]p3: 12106 // If a non-volatile non-inline const static data member is of integral 12107 // or enumeration type, its declaration in the class definition can 12108 // specify a brace-or-equal-initializer in which every initializer-clause 12109 // that is an assignment-expression is a constant expression. A static 12110 // data member of literal type can be declared in the class definition 12111 // with the constexpr specifier; if so, its declaration shall specify a 12112 // brace-or-equal-initializer in which every initializer-clause that is 12113 // an assignment-expression is a constant expression. 12114 12115 // Do nothing on dependent types. 12116 if (DclT->isDependentType()) { 12117 12118 // Allow any 'static constexpr' members, whether or not they are of literal 12119 // type. We separately check that every constexpr variable is of literal 12120 // type. 12121 } else if (VDecl->isConstexpr()) { 12122 12123 // Require constness. 12124 } else if (!DclT.isConstQualified()) { 12125 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 12126 << Init->getSourceRange(); 12127 VDecl->setInvalidDecl(); 12128 12129 // We allow integer constant expressions in all cases. 12130 } else if (DclT->isIntegralOrEnumerationType()) { 12131 // Check whether the expression is a constant expression. 12132 SourceLocation Loc; 12133 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 12134 // In C++11, a non-constexpr const static data member with an 12135 // in-class initializer cannot be volatile. 12136 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 12137 else if (Init->isValueDependent()) 12138 ; // Nothing to check. 12139 else if (Init->isIntegerConstantExpr(Context, &Loc)) 12140 ; // Ok, it's an ICE! 12141 else if (Init->getType()->isScopedEnumeralType() && 12142 Init->isCXX11ConstantExpr(Context)) 12143 ; // Ok, it is a scoped-enum constant expression. 12144 else if (Init->isEvaluatable(Context)) { 12145 // If we can constant fold the initializer through heroics, accept it, 12146 // but report this as a use of an extension for -pedantic. 12147 Diag(Loc, diag::ext_in_class_initializer_non_constant) 12148 << Init->getSourceRange(); 12149 } else { 12150 // Otherwise, this is some crazy unknown case. Report the issue at the 12151 // location provided by the isIntegerConstantExpr failed check. 12152 Diag(Loc, diag::err_in_class_initializer_non_constant) 12153 << Init->getSourceRange(); 12154 VDecl->setInvalidDecl(); 12155 } 12156 12157 // We allow foldable floating-point constants as an extension. 12158 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 12159 // In C++98, this is a GNU extension. In C++11, it is not, but we support 12160 // it anyway and provide a fixit to add the 'constexpr'. 12161 if (getLangOpts().CPlusPlus11) { 12162 Diag(VDecl->getLocation(), 12163 diag::ext_in_class_initializer_float_type_cxx11) 12164 << DclT << Init->getSourceRange(); 12165 Diag(VDecl->getBeginLoc(), 12166 diag::note_in_class_initializer_float_type_cxx11) 12167 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12168 } else { 12169 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 12170 << DclT << Init->getSourceRange(); 12171 12172 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 12173 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 12174 << Init->getSourceRange(); 12175 VDecl->setInvalidDecl(); 12176 } 12177 } 12178 12179 // Suggest adding 'constexpr' in C++11 for literal types. 12180 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 12181 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 12182 << DclT << Init->getSourceRange() 12183 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr "); 12184 VDecl->setConstexpr(true); 12185 12186 } else { 12187 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 12188 << DclT << Init->getSourceRange(); 12189 VDecl->setInvalidDecl(); 12190 } 12191 } else if (VDecl->isFileVarDecl()) { 12192 // In C, extern is typically used to avoid tentative definitions when 12193 // declaring variables in headers, but adding an intializer makes it a 12194 // definition. This is somewhat confusing, so GCC and Clang both warn on it. 12195 // In C++, extern is often used to give implictly static const variables 12196 // external linkage, so don't warn in that case. If selectany is present, 12197 // this might be header code intended for C and C++ inclusion, so apply the 12198 // C++ rules. 12199 if (VDecl->getStorageClass() == SC_Extern && 12200 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) || 12201 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) && 12202 !(getLangOpts().CPlusPlus && VDecl->isExternC()) && 12203 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 12204 Diag(VDecl->getLocation(), diag::warn_extern_init); 12205 12206 // In Microsoft C++ mode, a const variable defined in namespace scope has 12207 // external linkage by default if the variable is declared with 12208 // __declspec(dllexport). 12209 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && 12210 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() && 12211 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition()) 12212 VDecl->setStorageClass(SC_Extern); 12213 12214 // C99 6.7.8p4. All file scoped initializers need to be constant. 12215 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 12216 CheckForConstantInitializer(Init, DclT); 12217 } 12218 12219 QualType InitType = Init->getType(); 12220 if (!InitType.isNull() && 12221 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 12222 InitType.hasNonTrivialToPrimitiveCopyCUnion())) 12223 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc()); 12224 12225 // We will represent direct-initialization similarly to copy-initialization: 12226 // int x(1); -as-> int x = 1; 12227 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 12228 // 12229 // Clients that want to distinguish between the two forms, can check for 12230 // direct initializer using VarDecl::getInitStyle(). 12231 // A major benefit is that clients that don't particularly care about which 12232 // exactly form was it (like the CodeGen) can handle both cases without 12233 // special case code. 12234 12235 // C++ 8.5p11: 12236 // The form of initialization (using parentheses or '=') is generally 12237 // insignificant, but does matter when the entity being initialized has a 12238 // class type. 12239 if (CXXDirectInit) { 12240 assert(DirectInit && "Call-style initializer must be direct init."); 12241 VDecl->setInitStyle(VarDecl::CallInit); 12242 } else if (DirectInit) { 12243 // This must be list-initialization. No other way is direct-initialization. 12244 VDecl->setInitStyle(VarDecl::ListInit); 12245 } 12246 12247 CheckCompleteVariableDeclaration(VDecl); 12248 } 12249 12250 /// ActOnInitializerError - Given that there was an error parsing an 12251 /// initializer for the given declaration, try to return to some form 12252 /// of sanity. 12253 void Sema::ActOnInitializerError(Decl *D) { 12254 // Our main concern here is re-establishing invariants like "a 12255 // variable's type is either dependent or complete". 12256 if (!D || D->isInvalidDecl()) return; 12257 12258 VarDecl *VD = dyn_cast<VarDecl>(D); 12259 if (!VD) return; 12260 12261 // Bindings are not usable if we can't make sense of the initializer. 12262 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 12263 for (auto *BD : DD->bindings()) 12264 BD->setInvalidDecl(); 12265 12266 // Auto types are meaningless if we can't make sense of the initializer. 12267 if (ParsingInitForAutoVars.count(D)) { 12268 D->setInvalidDecl(); 12269 return; 12270 } 12271 12272 QualType Ty = VD->getType(); 12273 if (Ty->isDependentType()) return; 12274 12275 // Require a complete type. 12276 if (RequireCompleteType(VD->getLocation(), 12277 Context.getBaseElementType(Ty), 12278 diag::err_typecheck_decl_incomplete_type)) { 12279 VD->setInvalidDecl(); 12280 return; 12281 } 12282 12283 // Require a non-abstract type. 12284 if (RequireNonAbstractType(VD->getLocation(), Ty, 12285 diag::err_abstract_type_in_decl, 12286 AbstractVariableType)) { 12287 VD->setInvalidDecl(); 12288 return; 12289 } 12290 12291 // Don't bother complaining about constructors or destructors, 12292 // though. 12293 } 12294 12295 void Sema::ActOnUninitializedDecl(Decl *RealDecl) { 12296 // If there is no declaration, there was an error parsing it. Just ignore it. 12297 if (!RealDecl) 12298 return; 12299 12300 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 12301 QualType Type = Var->getType(); 12302 12303 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. 12304 if (isa<DecompositionDecl>(RealDecl)) { 12305 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; 12306 Var->setInvalidDecl(); 12307 return; 12308 } 12309 12310 if (Type->isUndeducedType() && 12311 DeduceVariableDeclarationType(Var, false, nullptr)) 12312 return; 12313 12314 // C++11 [class.static.data]p3: A static data member can be declared with 12315 // the constexpr specifier; if so, its declaration shall specify 12316 // a brace-or-equal-initializer. 12317 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 12318 // the definition of a variable [...] or the declaration of a static data 12319 // member. 12320 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() && 12321 !Var->isThisDeclarationADemotedDefinition()) { 12322 if (Var->isStaticDataMember()) { 12323 // C++1z removes the relevant rule; the in-class declaration is always 12324 // a definition there. 12325 if (!getLangOpts().CPlusPlus17 && 12326 !Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12327 Diag(Var->getLocation(), 12328 diag::err_constexpr_static_mem_var_requires_init) 12329 << Var->getDeclName(); 12330 Var->setInvalidDecl(); 12331 return; 12332 } 12333 } else { 12334 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 12335 Var->setInvalidDecl(); 12336 return; 12337 } 12338 } 12339 12340 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 12341 // be initialized. 12342 if (!Var->isInvalidDecl() && 12343 Var->getType().getAddressSpace() == LangAS::opencl_constant && 12344 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 12345 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 12346 Var->setInvalidDecl(); 12347 return; 12348 } 12349 12350 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition(); 12351 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly && 12352 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion()) 12353 checkNonTrivialCUnion(Var->getType(), Var->getLocation(), 12354 NTCUC_DefaultInitializedObject, NTCUK_Init); 12355 12356 12357 switch (DefKind) { 12358 case VarDecl::Definition: 12359 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 12360 break; 12361 12362 // We have an out-of-line definition of a static data member 12363 // that has an in-class initializer, so we type-check this like 12364 // a declaration. 12365 // 12366 LLVM_FALLTHROUGH; 12367 12368 case VarDecl::DeclarationOnly: 12369 // It's only a declaration. 12370 12371 // Block scope. C99 6.7p7: If an identifier for an object is 12372 // declared with no linkage (C99 6.2.2p6), the type for the 12373 // object shall be complete. 12374 if (!Type->isDependentType() && Var->isLocalVarDecl() && 12375 !Var->hasLinkage() && !Var->isInvalidDecl() && 12376 RequireCompleteType(Var->getLocation(), Type, 12377 diag::err_typecheck_decl_incomplete_type)) 12378 Var->setInvalidDecl(); 12379 12380 // Make sure that the type is not abstract. 12381 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12382 RequireNonAbstractType(Var->getLocation(), Type, 12383 diag::err_abstract_type_in_decl, 12384 AbstractVariableType)) 12385 Var->setInvalidDecl(); 12386 if (!Type->isDependentType() && !Var->isInvalidDecl() && 12387 Var->getStorageClass() == SC_PrivateExtern) { 12388 Diag(Var->getLocation(), diag::warn_private_extern); 12389 Diag(Var->getLocation(), diag::note_private_extern); 12390 } 12391 12392 if (Context.getTargetInfo().allowDebugInfoForExternalVar() && 12393 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus) 12394 ExternalDeclarations.push_back(Var); 12395 12396 return; 12397 12398 case VarDecl::TentativeDefinition: 12399 // File scope. C99 6.9.2p2: A declaration of an identifier for an 12400 // object that has file scope without an initializer, and without a 12401 // storage-class specifier or with the storage-class specifier "static", 12402 // constitutes a tentative definition. Note: A tentative definition with 12403 // external linkage is valid (C99 6.2.2p5). 12404 if (!Var->isInvalidDecl()) { 12405 if (const IncompleteArrayType *ArrayT 12406 = Context.getAsIncompleteArrayType(Type)) { 12407 if (RequireCompleteType(Var->getLocation(), 12408 ArrayT->getElementType(), 12409 diag::err_illegal_decl_array_incomplete_type)) 12410 Var->setInvalidDecl(); 12411 } else if (Var->getStorageClass() == SC_Static) { 12412 // C99 6.9.2p3: If the declaration of an identifier for an object is 12413 // a tentative definition and has internal linkage (C99 6.2.2p3), the 12414 // declared type shall not be an incomplete type. 12415 // NOTE: code such as the following 12416 // static struct s; 12417 // struct s { int a; }; 12418 // is accepted by gcc. Hence here we issue a warning instead of 12419 // an error and we do not invalidate the static declaration. 12420 // NOTE: to avoid multiple warnings, only check the first declaration. 12421 if (Var->isFirstDecl()) 12422 RequireCompleteType(Var->getLocation(), Type, 12423 diag::ext_typecheck_decl_incomplete_type); 12424 } 12425 } 12426 12427 // Record the tentative definition; we're done. 12428 if (!Var->isInvalidDecl()) 12429 TentativeDefinitions.push_back(Var); 12430 return; 12431 } 12432 12433 // Provide a specific diagnostic for uninitialized variable 12434 // definitions with incomplete array type. 12435 if (Type->isIncompleteArrayType()) { 12436 Diag(Var->getLocation(), 12437 diag::err_typecheck_incomplete_array_needs_initializer); 12438 Var->setInvalidDecl(); 12439 return; 12440 } 12441 12442 // Provide a specific diagnostic for uninitialized variable 12443 // definitions with reference type. 12444 if (Type->isReferenceType()) { 12445 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 12446 << Var->getDeclName() 12447 << SourceRange(Var->getLocation(), Var->getLocation()); 12448 Var->setInvalidDecl(); 12449 return; 12450 } 12451 12452 // Do not attempt to type-check the default initializer for a 12453 // variable with dependent type. 12454 if (Type->isDependentType()) 12455 return; 12456 12457 if (Var->isInvalidDecl()) 12458 return; 12459 12460 if (!Var->hasAttr<AliasAttr>()) { 12461 if (RequireCompleteType(Var->getLocation(), 12462 Context.getBaseElementType(Type), 12463 diag::err_typecheck_decl_incomplete_type)) { 12464 Var->setInvalidDecl(); 12465 return; 12466 } 12467 } else { 12468 return; 12469 } 12470 12471 // The variable can not have an abstract class type. 12472 if (RequireNonAbstractType(Var->getLocation(), Type, 12473 diag::err_abstract_type_in_decl, 12474 AbstractVariableType)) { 12475 Var->setInvalidDecl(); 12476 return; 12477 } 12478 12479 // Check for jumps past the implicit initializer. C++0x 12480 // clarifies that this applies to a "variable with automatic 12481 // storage duration", not a "local variable". 12482 // C++11 [stmt.dcl]p3 12483 // A program that jumps from a point where a variable with automatic 12484 // storage duration is not in scope to a point where it is in scope is 12485 // ill-formed unless the variable has scalar type, class type with a 12486 // trivial default constructor and a trivial destructor, a cv-qualified 12487 // version of one of these types, or an array of one of the preceding 12488 // types and is declared without an initializer. 12489 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 12490 if (const RecordType *Record 12491 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 12492 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 12493 // Mark the function (if we're in one) for further checking even if the 12494 // looser rules of C++11 do not require such checks, so that we can 12495 // diagnose incompatibilities with C++98. 12496 if (!CXXRecord->isPOD()) 12497 setFunctionHasBranchProtectedScope(); 12498 } 12499 } 12500 // In OpenCL, we can't initialize objects in the __local address space, 12501 // even implicitly, so don't synthesize an implicit initializer. 12502 if (getLangOpts().OpenCL && 12503 Var->getType().getAddressSpace() == LangAS::opencl_local) 12504 return; 12505 // C++03 [dcl.init]p9: 12506 // If no initializer is specified for an object, and the 12507 // object is of (possibly cv-qualified) non-POD class type (or 12508 // array thereof), the object shall be default-initialized; if 12509 // the object is of const-qualified type, the underlying class 12510 // type shall have a user-declared default 12511 // constructor. Otherwise, if no initializer is specified for 12512 // a non- static object, the object and its subobjects, if 12513 // any, have an indeterminate initial value); if the object 12514 // or any of its subobjects are of const-qualified type, the 12515 // program is ill-formed. 12516 // C++0x [dcl.init]p11: 12517 // If no initializer is specified for an object, the object is 12518 // default-initialized; [...]. 12519 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 12520 InitializationKind Kind 12521 = InitializationKind::CreateDefault(Var->getLocation()); 12522 12523 InitializationSequence InitSeq(*this, Entity, Kind, None); 12524 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 12525 if (Init.isInvalid()) 12526 Var->setInvalidDecl(); 12527 else if (Init.get()) { 12528 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 12529 // This is important for template substitution. 12530 Var->setInitStyle(VarDecl::CallInit); 12531 } 12532 12533 CheckCompleteVariableDeclaration(Var); 12534 } 12535 } 12536 12537 void Sema::ActOnCXXForRangeDecl(Decl *D) { 12538 // If there is no declaration, there was an error parsing it. Ignore it. 12539 if (!D) 12540 return; 12541 12542 VarDecl *VD = dyn_cast<VarDecl>(D); 12543 if (!VD) { 12544 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 12545 D->setInvalidDecl(); 12546 return; 12547 } 12548 12549 VD->setCXXForRangeDecl(true); 12550 12551 // for-range-declaration cannot be given a storage class specifier. 12552 int Error = -1; 12553 switch (VD->getStorageClass()) { 12554 case SC_None: 12555 break; 12556 case SC_Extern: 12557 Error = 0; 12558 break; 12559 case SC_Static: 12560 Error = 1; 12561 break; 12562 case SC_PrivateExtern: 12563 Error = 2; 12564 break; 12565 case SC_Auto: 12566 Error = 3; 12567 break; 12568 case SC_Register: 12569 Error = 4; 12570 break; 12571 } 12572 if (Error != -1) { 12573 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 12574 << VD->getDeclName() << Error; 12575 D->setInvalidDecl(); 12576 } 12577 } 12578 12579 StmtResult 12580 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 12581 IdentifierInfo *Ident, 12582 ParsedAttributes &Attrs, 12583 SourceLocation AttrEnd) { 12584 // C++1y [stmt.iter]p1: 12585 // A range-based for statement of the form 12586 // for ( for-range-identifier : for-range-initializer ) statement 12587 // is equivalent to 12588 // for ( auto&& for-range-identifier : for-range-initializer ) statement 12589 DeclSpec DS(Attrs.getPool().getFactory()); 12590 12591 const char *PrevSpec; 12592 unsigned DiagID; 12593 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 12594 getPrintingPolicy()); 12595 12596 Declarator D(DS, DeclaratorContext::ForContext); 12597 D.SetIdentifier(Ident, IdentLoc); 12598 D.takeAttributes(Attrs, AttrEnd); 12599 12600 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false), 12601 IdentLoc); 12602 Decl *Var = ActOnDeclarator(S, D); 12603 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 12604 FinalizeDeclaration(Var); 12605 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 12606 AttrEnd.isValid() ? AttrEnd : IdentLoc); 12607 } 12608 12609 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 12610 if (var->isInvalidDecl()) return; 12611 12612 if (getLangOpts().OpenCL) { 12613 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an 12614 // initialiser 12615 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() && 12616 !var->hasInit()) { 12617 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration) 12618 << 1 /*Init*/; 12619 var->setInvalidDecl(); 12620 return; 12621 } 12622 } 12623 12624 // In Objective-C, don't allow jumps past the implicit initialization of a 12625 // local retaining variable. 12626 if (getLangOpts().ObjC && 12627 var->hasLocalStorage()) { 12628 switch (var->getType().getObjCLifetime()) { 12629 case Qualifiers::OCL_None: 12630 case Qualifiers::OCL_ExplicitNone: 12631 case Qualifiers::OCL_Autoreleasing: 12632 break; 12633 12634 case Qualifiers::OCL_Weak: 12635 case Qualifiers::OCL_Strong: 12636 setFunctionHasBranchProtectedScope(); 12637 break; 12638 } 12639 } 12640 12641 if (var->hasLocalStorage() && 12642 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) 12643 setFunctionHasBranchProtectedScope(); 12644 12645 // Warn about externally-visible variables being defined without a 12646 // prior declaration. We only want to do this for global 12647 // declarations, but we also specifically need to avoid doing it for 12648 // class members because the linkage of an anonymous class can 12649 // change if it's later given a typedef name. 12650 if (var->isThisDeclarationADefinition() && 12651 var->getDeclContext()->getRedeclContext()->isFileContext() && 12652 var->isExternallyVisible() && var->hasLinkage() && 12653 !var->isInline() && !var->getDescribedVarTemplate() && 12654 !isa<VarTemplatePartialSpecializationDecl>(var) && 12655 !isTemplateInstantiation(var->getTemplateSpecializationKind()) && 12656 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 12657 var->getLocation())) { 12658 // Find a previous declaration that's not a definition. 12659 VarDecl *prev = var->getPreviousDecl(); 12660 while (prev && prev->isThisDeclarationADefinition()) 12661 prev = prev->getPreviousDecl(); 12662 12663 if (!prev) { 12664 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 12665 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 12666 << /* variable */ 0; 12667 } 12668 } 12669 12670 // Cache the result of checking for constant initialization. 12671 Optional<bool> CacheHasConstInit; 12672 const Expr *CacheCulprit = nullptr; 12673 auto checkConstInit = [&]() mutable { 12674 if (!CacheHasConstInit) 12675 CacheHasConstInit = var->getInit()->isConstantInitializer( 12676 Context, var->getType()->isReferenceType(), &CacheCulprit); 12677 return *CacheHasConstInit; 12678 }; 12679 12680 if (var->getTLSKind() == VarDecl::TLS_Static) { 12681 if (var->getType().isDestructedType()) { 12682 // GNU C++98 edits for __thread, [basic.start.term]p3: 12683 // The type of an object with thread storage duration shall not 12684 // have a non-trivial destructor. 12685 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 12686 if (getLangOpts().CPlusPlus11) 12687 Diag(var->getLocation(), diag::note_use_thread_local); 12688 } else if (getLangOpts().CPlusPlus && var->hasInit()) { 12689 if (!checkConstInit()) { 12690 // GNU C++98 edits for __thread, [basic.start.init]p4: 12691 // An object of thread storage duration shall not require dynamic 12692 // initialization. 12693 // FIXME: Need strict checking here. 12694 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init) 12695 << CacheCulprit->getSourceRange(); 12696 if (getLangOpts().CPlusPlus11) 12697 Diag(var->getLocation(), diag::note_use_thread_local); 12698 } 12699 } 12700 } 12701 12702 // Apply section attributes and pragmas to global variables. 12703 bool GlobalStorage = var->hasGlobalStorage(); 12704 if (GlobalStorage && var->isThisDeclarationADefinition() && 12705 !inTemplateInstantiation()) { 12706 PragmaStack<StringLiteral *> *Stack = nullptr; 12707 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 12708 if (var->getType().isConstQualified()) 12709 Stack = &ConstSegStack; 12710 else if (!var->getInit()) { 12711 Stack = &BSSSegStack; 12712 SectionFlags |= ASTContext::PSF_Write; 12713 } else { 12714 Stack = &DataSegStack; 12715 SectionFlags |= ASTContext::PSF_Write; 12716 } 12717 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) 12718 var->addAttr(SectionAttr::CreateImplicit( 12719 Context, Stack->CurrentValue->getString(), 12720 Stack->CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma, 12721 SectionAttr::Declspec_allocate)); 12722 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 12723 if (UnifySection(SA->getName(), SectionFlags, var)) 12724 var->dropAttr<SectionAttr>(); 12725 12726 // Apply the init_seg attribute if this has an initializer. If the 12727 // initializer turns out to not be dynamic, we'll end up ignoring this 12728 // attribute. 12729 if (CurInitSeg && var->getInit()) 12730 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 12731 CurInitSegLoc, 12732 AttributeCommonInfo::AS_Pragma)); 12733 } 12734 12735 // All the following checks are C++ only. 12736 if (!getLangOpts().CPlusPlus) { 12737 // If this variable must be emitted, add it as an initializer for the 12738 // current module. 12739 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12740 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12741 return; 12742 } 12743 12744 if (auto *DD = dyn_cast<DecompositionDecl>(var)) 12745 CheckCompleteDecompositionDeclaration(DD); 12746 12747 QualType type = var->getType(); 12748 if (type->isDependentType()) return; 12749 12750 if (var->hasAttr<BlocksAttr>()) 12751 getCurFunction()->addByrefBlockVar(var); 12752 12753 Expr *Init = var->getInit(); 12754 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 12755 QualType baseType = Context.getBaseElementType(type); 12756 12757 if (Init && !Init->isValueDependent()) { 12758 if (var->isConstexpr()) { 12759 SmallVector<PartialDiagnosticAt, 8> Notes; 12760 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 12761 SourceLocation DiagLoc = var->getLocation(); 12762 // If the note doesn't add any useful information other than a source 12763 // location, fold it into the primary diagnostic. 12764 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 12765 diag::note_invalid_subexpr_in_const_expr) { 12766 DiagLoc = Notes[0].first; 12767 Notes.clear(); 12768 } 12769 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 12770 << var << Init->getSourceRange(); 12771 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 12772 Diag(Notes[I].first, Notes[I].second); 12773 } 12774 } else if (var->mightBeUsableInConstantExpressions(Context)) { 12775 // Check whether the initializer of a const variable of integral or 12776 // enumeration type is an ICE now, since we can't tell whether it was 12777 // initialized by a constant expression if we check later. 12778 var->checkInitIsICE(); 12779 } 12780 12781 // Don't emit further diagnostics about constexpr globals since they 12782 // were just diagnosed. 12783 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) { 12784 // FIXME: Need strict checking in C++03 here. 12785 bool DiagErr = getLangOpts().CPlusPlus11 12786 ? !var->checkInitIsICE() : !checkConstInit(); 12787 if (DiagErr) { 12788 auto *Attr = var->getAttr<ConstInitAttr>(); 12789 Diag(var->getLocation(), diag::err_require_constant_init_failed) 12790 << Init->getSourceRange(); 12791 Diag(Attr->getLocation(), 12792 diag::note_declared_required_constant_init_here) 12793 << Attr->getRange() << Attr->isConstinit(); 12794 if (getLangOpts().CPlusPlus11) { 12795 APValue Value; 12796 SmallVector<PartialDiagnosticAt, 8> Notes; 12797 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes); 12798 for (auto &it : Notes) 12799 Diag(it.first, it.second); 12800 } else { 12801 Diag(CacheCulprit->getExprLoc(), 12802 diag::note_invalid_subexpr_in_const_expr) 12803 << CacheCulprit->getSourceRange(); 12804 } 12805 } 12806 } 12807 else if (!var->isConstexpr() && IsGlobal && 12808 !getDiagnostics().isIgnored(diag::warn_global_constructor, 12809 var->getLocation())) { 12810 // Warn about globals which don't have a constant initializer. Don't 12811 // warn about globals with a non-trivial destructor because we already 12812 // warned about them. 12813 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 12814 if (!(RD && !RD->hasTrivialDestructor())) { 12815 if (!checkConstInit()) 12816 Diag(var->getLocation(), diag::warn_global_constructor) 12817 << Init->getSourceRange(); 12818 } 12819 } 12820 } 12821 12822 // Require the destructor. 12823 if (const RecordType *recordType = baseType->getAs<RecordType>()) 12824 FinalizeVarWithDestructor(var, recordType); 12825 12826 // If this variable must be emitted, add it as an initializer for the current 12827 // module. 12828 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty()) 12829 Context.addModuleInitializer(ModuleScopes.back().Module, var); 12830 } 12831 12832 /// Determines if a variable's alignment is dependent. 12833 static bool hasDependentAlignment(VarDecl *VD) { 12834 if (VD->getType()->isDependentType()) 12835 return true; 12836 for (auto *I : VD->specific_attrs<AlignedAttr>()) 12837 if (I->isAlignmentDependent()) 12838 return true; 12839 return false; 12840 } 12841 12842 /// Check if VD needs to be dllexport/dllimport due to being in a 12843 /// dllexport/import function. 12844 void Sema::CheckStaticLocalForDllExport(VarDecl *VD) { 12845 assert(VD->isStaticLocal()); 12846 12847 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 12848 12849 // Find outermost function when VD is in lambda function. 12850 while (FD && !getDLLAttr(FD) && 12851 !FD->hasAttr<DLLExportStaticLocalAttr>() && 12852 !FD->hasAttr<DLLImportStaticLocalAttr>()) { 12853 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod()); 12854 } 12855 12856 if (!FD) 12857 return; 12858 12859 // Static locals inherit dll attributes from their function. 12860 if (Attr *A = getDLLAttr(FD)) { 12861 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 12862 NewAttr->setInherited(true); 12863 VD->addAttr(NewAttr); 12864 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) { 12865 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A); 12866 NewAttr->setInherited(true); 12867 VD->addAttr(NewAttr); 12868 12869 // Export this function to enforce exporting this static variable even 12870 // if it is not used in this compilation unit. 12871 if (!FD->hasAttr<DLLExportAttr>()) 12872 FD->addAttr(NewAttr); 12873 12874 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) { 12875 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A); 12876 NewAttr->setInherited(true); 12877 VD->addAttr(NewAttr); 12878 } 12879 } 12880 12881 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 12882 /// any semantic actions necessary after any initializer has been attached. 12883 void Sema::FinalizeDeclaration(Decl *ThisDecl) { 12884 // Note that we are no longer parsing the initializer for this declaration. 12885 ParsingInitForAutoVars.erase(ThisDecl); 12886 12887 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 12888 if (!VD) 12889 return; 12890 12891 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active 12892 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() && 12893 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) { 12894 if (PragmaClangBSSSection.Valid) 12895 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit( 12896 Context, PragmaClangBSSSection.SectionName, 12897 PragmaClangBSSSection.PragmaLocation, 12898 AttributeCommonInfo::AS_Pragma)); 12899 if (PragmaClangDataSection.Valid) 12900 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit( 12901 Context, PragmaClangDataSection.SectionName, 12902 PragmaClangDataSection.PragmaLocation, 12903 AttributeCommonInfo::AS_Pragma)); 12904 if (PragmaClangRodataSection.Valid) 12905 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit( 12906 Context, PragmaClangRodataSection.SectionName, 12907 PragmaClangRodataSection.PragmaLocation, 12908 AttributeCommonInfo::AS_Pragma)); 12909 if (PragmaClangRelroSection.Valid) 12910 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit( 12911 Context, PragmaClangRelroSection.SectionName, 12912 PragmaClangRelroSection.PragmaLocation, 12913 AttributeCommonInfo::AS_Pragma)); 12914 } 12915 12916 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) { 12917 for (auto *BD : DD->bindings()) { 12918 FinalizeDeclaration(BD); 12919 } 12920 } 12921 12922 checkAttributesAfterMerging(*this, *VD); 12923 12924 // Perform TLS alignment check here after attributes attached to the variable 12925 // which may affect the alignment have been processed. Only perform the check 12926 // if the target has a maximum TLS alignment (zero means no constraints). 12927 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 12928 // Protect the check so that it's not performed on dependent types and 12929 // dependent alignments (we can't determine the alignment in that case). 12930 if (VD->getTLSKind() && !hasDependentAlignment(VD) && 12931 !VD->isInvalidDecl()) { 12932 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 12933 if (Context.getDeclAlign(VD) > MaxAlignChars) { 12934 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 12935 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 12936 << (unsigned)MaxAlignChars.getQuantity(); 12937 } 12938 } 12939 } 12940 12941 if (VD->isStaticLocal()) { 12942 CheckStaticLocalForDllExport(VD); 12943 12944 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 12945 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__ 12946 // function, only __shared__ variables or variables without any device 12947 // memory qualifiers may be declared with static storage class. 12948 // Note: It is unclear how a function-scope non-const static variable 12949 // without device memory qualifier is implemented, therefore only static 12950 // const variable without device memory qualifier is allowed. 12951 [&]() { 12952 if (!getLangOpts().CUDA) 12953 return; 12954 if (VD->hasAttr<CUDASharedAttr>()) 12955 return; 12956 if (VD->getType().isConstQualified() && 12957 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>())) 12958 return; 12959 if (CUDADiagIfDeviceCode(VD->getLocation(), 12960 diag::err_device_static_local_var) 12961 << CurrentCUDATarget()) 12962 VD->setInvalidDecl(); 12963 }(); 12964 } 12965 } 12966 12967 // Perform check for initializers of device-side global variables. 12968 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA 12969 // 7.5). We must also apply the same checks to all __shared__ 12970 // variables whether they are local or not. CUDA also allows 12971 // constant initializers for __constant__ and __device__ variables. 12972 if (getLangOpts().CUDA) 12973 checkAllowedCUDAInitializer(VD); 12974 12975 // Grab the dllimport or dllexport attribute off of the VarDecl. 12976 const InheritableAttr *DLLAttr = getDLLAttr(VD); 12977 12978 // Imported static data members cannot be defined out-of-line. 12979 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 12980 if (VD->isStaticDataMember() && VD->isOutOfLine() && 12981 VD->isThisDeclarationADefinition()) { 12982 // We allow definitions of dllimport class template static data members 12983 // with a warning. 12984 CXXRecordDecl *Context = 12985 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 12986 bool IsClassTemplateMember = 12987 isa<ClassTemplatePartialSpecializationDecl>(Context) || 12988 Context->getDescribedClassTemplate(); 12989 12990 Diag(VD->getLocation(), 12991 IsClassTemplateMember 12992 ? diag::warn_attribute_dllimport_static_field_definition 12993 : diag::err_attribute_dllimport_static_field_definition); 12994 Diag(IA->getLocation(), diag::note_attribute); 12995 if (!IsClassTemplateMember) 12996 VD->setInvalidDecl(); 12997 } 12998 } 12999 13000 // dllimport/dllexport variables cannot be thread local, their TLS index 13001 // isn't exported with the variable. 13002 if (DLLAttr && VD->getTLSKind()) { 13003 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 13004 if (F && getDLLAttr(F)) { 13005 assert(VD->isStaticLocal()); 13006 // But if this is a static local in a dlimport/dllexport function, the 13007 // function will never be inlined, which means the var would never be 13008 // imported, so having it marked import/export is safe. 13009 } else { 13010 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 13011 << DLLAttr; 13012 VD->setInvalidDecl(); 13013 } 13014 } 13015 13016 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 13017 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 13018 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 13019 VD->dropAttr<UsedAttr>(); 13020 } 13021 } 13022 13023 const DeclContext *DC = VD->getDeclContext(); 13024 // If there's a #pragma GCC visibility in scope, and this isn't a class 13025 // member, set the visibility of this variable. 13026 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 13027 AddPushedVisibilityAttribute(VD); 13028 13029 // FIXME: Warn on unused var template partial specializations. 13030 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD)) 13031 MarkUnusedFileScopedDecl(VD); 13032 13033 // Now we have parsed the initializer and can update the table of magic 13034 // tag values. 13035 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 13036 !VD->getType()->isIntegralOrEnumerationType()) 13037 return; 13038 13039 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 13040 const Expr *MagicValueExpr = VD->getInit(); 13041 if (!MagicValueExpr) { 13042 continue; 13043 } 13044 llvm::APSInt MagicValueInt; 13045 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 13046 Diag(I->getRange().getBegin(), 13047 diag::err_type_tag_for_datatype_not_ice) 13048 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13049 continue; 13050 } 13051 if (MagicValueInt.getActiveBits() > 64) { 13052 Diag(I->getRange().getBegin(), 13053 diag::err_type_tag_for_datatype_too_large) 13054 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 13055 continue; 13056 } 13057 uint64_t MagicValue = MagicValueInt.getZExtValue(); 13058 RegisterTypeTagForDatatype(I->getArgumentKind(), 13059 MagicValue, 13060 I->getMatchingCType(), 13061 I->getLayoutCompatible(), 13062 I->getMustBeNull()); 13063 } 13064 } 13065 13066 static bool hasDeducedAuto(DeclaratorDecl *DD) { 13067 auto *VD = dyn_cast<VarDecl>(DD); 13068 return VD && !VD->getType()->hasAutoForTrailingReturnType(); 13069 } 13070 13071 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 13072 ArrayRef<Decl *> Group) { 13073 SmallVector<Decl*, 8> Decls; 13074 13075 if (DS.isTypeSpecOwned()) 13076 Decls.push_back(DS.getRepAsDecl()); 13077 13078 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 13079 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr; 13080 bool DiagnosedMultipleDecomps = false; 13081 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr; 13082 bool DiagnosedNonDeducedAuto = false; 13083 13084 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13085 if (Decl *D = Group[i]) { 13086 // For declarators, there are some additional syntactic-ish checks we need 13087 // to perform. 13088 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) { 13089 if (!FirstDeclaratorInGroup) 13090 FirstDeclaratorInGroup = DD; 13091 if (!FirstDecompDeclaratorInGroup) 13092 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D); 13093 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() && 13094 !hasDeducedAuto(DD)) 13095 FirstNonDeducedAutoInGroup = DD; 13096 13097 if (FirstDeclaratorInGroup != DD) { 13098 // A decomposition declaration cannot be combined with any other 13099 // declaration in the same group. 13100 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) { 13101 Diag(FirstDecompDeclaratorInGroup->getLocation(), 13102 diag::err_decomp_decl_not_alone) 13103 << FirstDeclaratorInGroup->getSourceRange() 13104 << DD->getSourceRange(); 13105 DiagnosedMultipleDecomps = true; 13106 } 13107 13108 // A declarator that uses 'auto' in any way other than to declare a 13109 // variable with a deduced type cannot be combined with any other 13110 // declarator in the same group. 13111 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) { 13112 Diag(FirstNonDeducedAutoInGroup->getLocation(), 13113 diag::err_auto_non_deduced_not_alone) 13114 << FirstNonDeducedAutoInGroup->getType() 13115 ->hasAutoForTrailingReturnType() 13116 << FirstDeclaratorInGroup->getSourceRange() 13117 << DD->getSourceRange(); 13118 DiagnosedNonDeducedAuto = true; 13119 } 13120 } 13121 } 13122 13123 Decls.push_back(D); 13124 } 13125 } 13126 13127 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 13128 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 13129 handleTagNumbering(Tag, S); 13130 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 13131 getLangOpts().CPlusPlus) 13132 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 13133 } 13134 } 13135 13136 return BuildDeclaratorGroup(Decls); 13137 } 13138 13139 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 13140 /// group, performing any necessary semantic checking. 13141 Sema::DeclGroupPtrTy 13142 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) { 13143 // C++14 [dcl.spec.auto]p7: (DR1347) 13144 // If the type that replaces the placeholder type is not the same in each 13145 // deduction, the program is ill-formed. 13146 if (Group.size() > 1) { 13147 QualType Deduced; 13148 VarDecl *DeducedDecl = nullptr; 13149 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 13150 VarDecl *D = dyn_cast<VarDecl>(Group[i]); 13151 if (!D || D->isInvalidDecl()) 13152 break; 13153 DeducedType *DT = D->getType()->getContainedDeducedType(); 13154 if (!DT || DT->getDeducedType().isNull()) 13155 continue; 13156 if (Deduced.isNull()) { 13157 Deduced = DT->getDeducedType(); 13158 DeducedDecl = D; 13159 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) { 13160 auto *AT = dyn_cast<AutoType>(DT); 13161 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 13162 diag::err_auto_different_deductions) 13163 << (AT ? (unsigned)AT->getKeyword() : 3) 13164 << Deduced << DeducedDecl->getDeclName() 13165 << DT->getDeducedType() << D->getDeclName() 13166 << DeducedDecl->getInit()->getSourceRange() 13167 << D->getInit()->getSourceRange(); 13168 D->setInvalidDecl(); 13169 break; 13170 } 13171 } 13172 } 13173 13174 ActOnDocumentableDecls(Group); 13175 13176 return DeclGroupPtrTy::make( 13177 DeclGroupRef::Create(Context, Group.data(), Group.size())); 13178 } 13179 13180 void Sema::ActOnDocumentableDecl(Decl *D) { 13181 ActOnDocumentableDecls(D); 13182 } 13183 13184 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 13185 // Don't parse the comment if Doxygen diagnostics are ignored. 13186 if (Group.empty() || !Group[0]) 13187 return; 13188 13189 if (Diags.isIgnored(diag::warn_doc_param_not_found, 13190 Group[0]->getLocation()) && 13191 Diags.isIgnored(diag::warn_unknown_comment_command_name, 13192 Group[0]->getLocation())) 13193 return; 13194 13195 if (Group.size() >= 2) { 13196 // This is a decl group. Normally it will contain only declarations 13197 // produced from declarator list. But in case we have any definitions or 13198 // additional declaration references: 13199 // 'typedef struct S {} S;' 13200 // 'typedef struct S *S;' 13201 // 'struct S *pS;' 13202 // FinalizeDeclaratorGroup adds these as separate declarations. 13203 Decl *MaybeTagDecl = Group[0]; 13204 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 13205 Group = Group.slice(1); 13206 } 13207 } 13208 13209 // FIMXE: We assume every Decl in the group is in the same file. 13210 // This is false when preprocessor constructs the group from decls in 13211 // different files (e. g. macros or #include). 13212 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor()); 13213 } 13214 13215 /// Common checks for a parameter-declaration that should apply to both function 13216 /// parameters and non-type template parameters. 13217 void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) { 13218 // Check that there are no default arguments inside the type of this 13219 // parameter. 13220 if (getLangOpts().CPlusPlus) 13221 CheckExtraCXXDefaultArguments(D); 13222 13223 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 13224 if (D.getCXXScopeSpec().isSet()) { 13225 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 13226 << D.getCXXScopeSpec().getRange(); 13227 } 13228 13229 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a 13230 // simple identifier except [...irrelevant cases...]. 13231 switch (D.getName().getKind()) { 13232 case UnqualifiedIdKind::IK_Identifier: 13233 break; 13234 13235 case UnqualifiedIdKind::IK_OperatorFunctionId: 13236 case UnqualifiedIdKind::IK_ConversionFunctionId: 13237 case UnqualifiedIdKind::IK_LiteralOperatorId: 13238 case UnqualifiedIdKind::IK_ConstructorName: 13239 case UnqualifiedIdKind::IK_DestructorName: 13240 case UnqualifiedIdKind::IK_ImplicitSelfParam: 13241 case UnqualifiedIdKind::IK_DeductionGuideName: 13242 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 13243 << GetNameForDeclarator(D).getName(); 13244 break; 13245 13246 case UnqualifiedIdKind::IK_TemplateId: 13247 case UnqualifiedIdKind::IK_ConstructorTemplateId: 13248 // GetNameForDeclarator would not produce a useful name in this case. 13249 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id); 13250 break; 13251 } 13252 } 13253 13254 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 13255 /// to introduce parameters into function prototype scope. 13256 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 13257 const DeclSpec &DS = D.getDeclSpec(); 13258 13259 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 13260 13261 // C++03 [dcl.stc]p2 also permits 'auto'. 13262 StorageClass SC = SC_None; 13263 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 13264 SC = SC_Register; 13265 // In C++11, the 'register' storage class specifier is deprecated. 13266 // In C++17, it is not allowed, but we tolerate it as an extension. 13267 if (getLangOpts().CPlusPlus11) { 13268 Diag(DS.getStorageClassSpecLoc(), 13269 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class 13270 : diag::warn_deprecated_register) 13271 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 13272 } 13273 } else if (getLangOpts().CPlusPlus && 13274 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 13275 SC = SC_Auto; 13276 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 13277 Diag(DS.getStorageClassSpecLoc(), 13278 diag::err_invalid_storage_class_in_func_decl); 13279 D.getMutableDeclSpec().ClearStorageClassSpecs(); 13280 } 13281 13282 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 13283 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 13284 << DeclSpec::getSpecifierName(TSCS); 13285 if (DS.isInlineSpecified()) 13286 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function) 13287 << getLangOpts().CPlusPlus17; 13288 if (DS.hasConstexprSpecifier()) 13289 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 13290 << 0 << D.getDeclSpec().getConstexprSpecifier(); 13291 13292 DiagnoseFunctionSpecifiers(DS); 13293 13294 CheckFunctionOrTemplateParamDeclarator(S, D); 13295 13296 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13297 QualType parmDeclType = TInfo->getType(); 13298 13299 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 13300 IdentifierInfo *II = D.getIdentifier(); 13301 if (II) { 13302 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 13303 ForVisibleRedeclaration); 13304 LookupName(R, S); 13305 if (R.isSingleResult()) { 13306 NamedDecl *PrevDecl = R.getFoundDecl(); 13307 if (PrevDecl->isTemplateParameter()) { 13308 // Maybe we will complain about the shadowed template parameter. 13309 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 13310 // Just pretend that we didn't see the previous declaration. 13311 PrevDecl = nullptr; 13312 } else if (S->isDeclScope(PrevDecl)) { 13313 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 13314 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13315 13316 // Recover by removing the name 13317 II = nullptr; 13318 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 13319 D.setInvalidType(true); 13320 } 13321 } 13322 } 13323 13324 // Temporarily put parameter variables in the translation unit, not 13325 // the enclosing context. This prevents them from accidentally 13326 // looking like class members in C++. 13327 ParmVarDecl *New = 13328 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(), 13329 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC); 13330 13331 if (D.isInvalidType()) 13332 New->setInvalidDecl(); 13333 13334 assert(S->isFunctionPrototypeScope()); 13335 assert(S->getFunctionPrototypeDepth() >= 1); 13336 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 13337 S->getNextFunctionPrototypeIndex()); 13338 13339 // Add the parameter declaration into this scope. 13340 S->AddDecl(New); 13341 if (II) 13342 IdResolver.AddDecl(New); 13343 13344 ProcessDeclAttributes(S, New, D); 13345 13346 if (D.getDeclSpec().isModulePrivateSpecified()) 13347 Diag(New->getLocation(), diag::err_module_private_local) 13348 << 1 << New->getDeclName() 13349 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 13350 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 13351 13352 if (New->hasAttr<BlocksAttr>()) { 13353 Diag(New->getLocation(), diag::err_block_on_nonlocal); 13354 } 13355 13356 if (getLangOpts().OpenCL) 13357 deduceOpenCLAddressSpace(New); 13358 13359 return New; 13360 } 13361 13362 /// Synthesizes a variable for a parameter arising from a 13363 /// typedef. 13364 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 13365 SourceLocation Loc, 13366 QualType T) { 13367 /* FIXME: setting StartLoc == Loc. 13368 Would it be worth to modify callers so as to provide proper source 13369 location for the unnamed parameters, embedding the parameter's type? */ 13370 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 13371 T, Context.getTrivialTypeSourceInfo(T, Loc), 13372 SC_None, nullptr); 13373 Param->setImplicit(); 13374 return Param; 13375 } 13376 13377 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) { 13378 // Don't diagnose unused-parameter errors in template instantiations; we 13379 // will already have done so in the template itself. 13380 if (inTemplateInstantiation()) 13381 return; 13382 13383 for (const ParmVarDecl *Parameter : Parameters) { 13384 if (!Parameter->isReferenced() && Parameter->getDeclName() && 13385 !Parameter->hasAttr<UnusedAttr>()) { 13386 Diag(Parameter->getLocation(), diag::warn_unused_parameter) 13387 << Parameter->getDeclName(); 13388 } 13389 } 13390 } 13391 13392 void Sema::DiagnoseSizeOfParametersAndReturnValue( 13393 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) { 13394 if (LangOpts.NumLargeByValueCopy == 0) // No check. 13395 return; 13396 13397 // Warn if the return value is pass-by-value and larger than the specified 13398 // threshold. 13399 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 13400 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 13401 if (Size > LangOpts.NumLargeByValueCopy) 13402 Diag(D->getLocation(), diag::warn_return_value_size) 13403 << D->getDeclName() << Size; 13404 } 13405 13406 // Warn if any parameter is pass-by-value and larger than the specified 13407 // threshold. 13408 for (const ParmVarDecl *Parameter : Parameters) { 13409 QualType T = Parameter->getType(); 13410 if (T->isDependentType() || !T.isPODType(Context)) 13411 continue; 13412 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 13413 if (Size > LangOpts.NumLargeByValueCopy) 13414 Diag(Parameter->getLocation(), diag::warn_parameter_size) 13415 << Parameter->getDeclName() << Size; 13416 } 13417 } 13418 13419 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 13420 SourceLocation NameLoc, IdentifierInfo *Name, 13421 QualType T, TypeSourceInfo *TSInfo, 13422 StorageClass SC) { 13423 // In ARC, infer a lifetime qualifier for appropriate parameter types. 13424 if (getLangOpts().ObjCAutoRefCount && 13425 T.getObjCLifetime() == Qualifiers::OCL_None && 13426 T->isObjCLifetimeType()) { 13427 13428 Qualifiers::ObjCLifetime lifetime; 13429 13430 // Special cases for arrays: 13431 // - if it's const, use __unsafe_unretained 13432 // - otherwise, it's an error 13433 if (T->isArrayType()) { 13434 if (!T.isConstQualified()) { 13435 if (DelayedDiagnostics.shouldDelayDiagnostics()) 13436 DelayedDiagnostics.add( 13437 sema::DelayedDiagnostic::makeForbiddenType( 13438 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 13439 else 13440 Diag(NameLoc, diag::err_arc_array_param_no_ownership) 13441 << TSInfo->getTypeLoc().getSourceRange(); 13442 } 13443 lifetime = Qualifiers::OCL_ExplicitNone; 13444 } else { 13445 lifetime = T->getObjCARCImplicitLifetime(); 13446 } 13447 T = Context.getLifetimeQualifiedType(T, lifetime); 13448 } 13449 13450 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 13451 Context.getAdjustedParameterType(T), 13452 TSInfo, SC, nullptr); 13453 13454 // Make a note if we created a new pack in the scope of a lambda, so that 13455 // we know that references to that pack must also be expanded within the 13456 // lambda scope. 13457 if (New->isParameterPack()) 13458 if (auto *LSI = getEnclosingLambda()) 13459 LSI->LocalPacks.push_back(New); 13460 13461 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() || 13462 New->getType().hasNonTrivialToPrimitiveCopyCUnion()) 13463 checkNonTrivialCUnion(New->getType(), New->getLocation(), 13464 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy); 13465 13466 // Parameters can not be abstract class types. 13467 // For record types, this is done by the AbstractClassUsageDiagnoser once 13468 // the class has been completely parsed. 13469 if (!CurContext->isRecord() && 13470 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 13471 AbstractParamType)) 13472 New->setInvalidDecl(); 13473 13474 // Parameter declarators cannot be interface types. All ObjC objects are 13475 // passed by reference. 13476 if (T->isObjCObjectType()) { 13477 SourceLocation TypeEndLoc = 13478 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc()); 13479 Diag(NameLoc, 13480 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 13481 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 13482 T = Context.getObjCObjectPointerType(T); 13483 New->setType(T); 13484 } 13485 13486 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 13487 // duration shall not be qualified by an address-space qualifier." 13488 // Since all parameters have automatic store duration, they can not have 13489 // an address space. 13490 if (T.getAddressSpace() != LangAS::Default && 13491 // OpenCL allows function arguments declared to be an array of a type 13492 // to be qualified with an address space. 13493 !(getLangOpts().OpenCL && 13494 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) { 13495 Diag(NameLoc, diag::err_arg_with_address_space); 13496 New->setInvalidDecl(); 13497 } 13498 13499 return New; 13500 } 13501 13502 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 13503 SourceLocation LocAfterDecls) { 13504 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 13505 13506 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 13507 // for a K&R function. 13508 if (!FTI.hasPrototype) { 13509 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 13510 --i; 13511 if (FTI.Params[i].Param == nullptr) { 13512 SmallString<256> Code; 13513 llvm::raw_svector_ostream(Code) 13514 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 13515 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 13516 << FTI.Params[i].Ident 13517 << FixItHint::CreateInsertion(LocAfterDecls, Code); 13518 13519 // Implicitly declare the argument as type 'int' for lack of a better 13520 // type. 13521 AttributeFactory attrs; 13522 DeclSpec DS(attrs); 13523 const char* PrevSpec; // unused 13524 unsigned DiagID; // unused 13525 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 13526 DiagID, Context.getPrintingPolicy()); 13527 // Use the identifier location for the type source range. 13528 DS.SetRangeStart(FTI.Params[i].IdentLoc); 13529 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 13530 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext); 13531 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 13532 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 13533 } 13534 } 13535 } 13536 } 13537 13538 Decl * 13539 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 13540 MultiTemplateParamsArg TemplateParameterLists, 13541 SkipBodyInfo *SkipBody) { 13542 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 13543 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 13544 Scope *ParentScope = FnBodyScope->getParent(); 13545 13546 D.setFunctionDefinitionKind(FDK_Definition); 13547 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 13548 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 13549 } 13550 13551 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) { 13552 Consumer.HandleInlineFunctionDefinition(D); 13553 } 13554 13555 static bool 13556 ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 13557 const FunctionDecl *&PossiblePrototype) { 13558 // Don't warn about invalid declarations. 13559 if (FD->isInvalidDecl()) 13560 return false; 13561 13562 // Or declarations that aren't global. 13563 if (!FD->isGlobal()) 13564 return false; 13565 13566 // Don't warn about C++ member functions. 13567 if (isa<CXXMethodDecl>(FD)) 13568 return false; 13569 13570 // Don't warn about 'main'. 13571 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext())) 13572 if (IdentifierInfo *II = FD->getIdentifier()) 13573 if (II->isStr("main")) 13574 return false; 13575 13576 // Don't warn about inline functions. 13577 if (FD->isInlined()) 13578 return false; 13579 13580 // Don't warn about function templates. 13581 if (FD->getDescribedFunctionTemplate()) 13582 return false; 13583 13584 // Don't warn about function template specializations. 13585 if (FD->isFunctionTemplateSpecialization()) 13586 return false; 13587 13588 // Don't warn for OpenCL kernels. 13589 if (FD->hasAttr<OpenCLKernelAttr>()) 13590 return false; 13591 13592 // Don't warn on explicitly deleted functions. 13593 if (FD->isDeleted()) 13594 return false; 13595 13596 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 13597 Prev; Prev = Prev->getPreviousDecl()) { 13598 // Ignore any declarations that occur in function or method 13599 // scope, because they aren't visible from the header. 13600 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 13601 continue; 13602 13603 PossiblePrototype = Prev; 13604 return Prev->getType()->isFunctionNoProtoType(); 13605 } 13606 13607 return true; 13608 } 13609 13610 void 13611 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 13612 const FunctionDecl *EffectiveDefinition, 13613 SkipBodyInfo *SkipBody) { 13614 const FunctionDecl *Definition = EffectiveDefinition; 13615 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) { 13616 // If this is a friend function defined in a class template, it does not 13617 // have a body until it is used, nevertheless it is a definition, see 13618 // [temp.inst]p2: 13619 // 13620 // ... for the purpose of determining whether an instantiated redeclaration 13621 // is valid according to [basic.def.odr] and [class.mem], a declaration that 13622 // corresponds to a definition in the template is considered to be a 13623 // definition. 13624 // 13625 // The following code must produce redefinition error: 13626 // 13627 // template<typename T> struct C20 { friend void func_20() {} }; 13628 // C20<int> c20i; 13629 // void func_20() {} 13630 // 13631 for (auto I : FD->redecls()) { 13632 if (I != FD && !I->isInvalidDecl() && 13633 I->getFriendObjectKind() != Decl::FOK_None) { 13634 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) { 13635 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) { 13636 // A merged copy of the same function, instantiated as a member of 13637 // the same class, is OK. 13638 if (declaresSameEntity(OrigFD, Original) && 13639 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()), 13640 cast<Decl>(FD->getLexicalDeclContext()))) 13641 continue; 13642 } 13643 13644 if (Original->isThisDeclarationADefinition()) { 13645 Definition = I; 13646 break; 13647 } 13648 } 13649 } 13650 } 13651 } 13652 13653 if (!Definition) 13654 // Similar to friend functions a friend function template may be a 13655 // definition and do not have a body if it is instantiated in a class 13656 // template. 13657 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) { 13658 for (auto I : FTD->redecls()) { 13659 auto D = cast<FunctionTemplateDecl>(I); 13660 if (D != FTD) { 13661 assert(!D->isThisDeclarationADefinition() && 13662 "More than one definition in redeclaration chain"); 13663 if (D->getFriendObjectKind() != Decl::FOK_None) 13664 if (FunctionTemplateDecl *FT = 13665 D->getInstantiatedFromMemberTemplate()) { 13666 if (FT->isThisDeclarationADefinition()) { 13667 Definition = D->getTemplatedDecl(); 13668 break; 13669 } 13670 } 13671 } 13672 } 13673 } 13674 13675 if (!Definition) 13676 return; 13677 13678 if (canRedefineFunction(Definition, getLangOpts())) 13679 return; 13680 13681 // Don't emit an error when this is redefinition of a typo-corrected 13682 // definition. 13683 if (TypoCorrectedFunctionDefinitions.count(Definition)) 13684 return; 13685 13686 // If we don't have a visible definition of the function, and it's inline or 13687 // a template, skip the new definition. 13688 if (SkipBody && !hasVisibleDefinition(Definition) && 13689 (Definition->getFormalLinkage() == InternalLinkage || 13690 Definition->isInlined() || 13691 Definition->getDescribedFunctionTemplate() || 13692 Definition->getNumTemplateParameterLists())) { 13693 SkipBody->ShouldSkip = true; 13694 SkipBody->Previous = const_cast<FunctionDecl*>(Definition); 13695 if (auto *TD = Definition->getDescribedFunctionTemplate()) 13696 makeMergedDefinitionVisible(TD); 13697 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition)); 13698 return; 13699 } 13700 13701 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 13702 Definition->getStorageClass() == SC_Extern) 13703 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 13704 << FD->getDeclName() << getLangOpts().CPlusPlus; 13705 else 13706 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 13707 13708 Diag(Definition->getLocation(), diag::note_previous_definition); 13709 FD->setInvalidDecl(); 13710 } 13711 13712 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 13713 Sema &S) { 13714 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 13715 13716 LambdaScopeInfo *LSI = S.PushLambdaScope(); 13717 LSI->CallOperator = CallOperator; 13718 LSI->Lambda = LambdaClass; 13719 LSI->ReturnType = CallOperator->getReturnType(); 13720 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 13721 13722 if (LCD == LCD_None) 13723 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 13724 else if (LCD == LCD_ByCopy) 13725 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 13726 else if (LCD == LCD_ByRef) 13727 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 13728 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 13729 13730 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 13731 LSI->Mutable = !CallOperator->isConst(); 13732 13733 // Add the captures to the LSI so they can be noted as already 13734 // captured within tryCaptureVar. 13735 auto I = LambdaClass->field_begin(); 13736 for (const auto &C : LambdaClass->captures()) { 13737 if (C.capturesVariable()) { 13738 VarDecl *VD = C.getCapturedVar(); 13739 if (VD->isInitCapture()) 13740 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 13741 QualType CaptureType = VD->getType(); 13742 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 13743 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 13744 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 13745 /*EllipsisLoc*/C.isPackExpansion() 13746 ? C.getEllipsisLoc() : SourceLocation(), 13747 CaptureType, /*Invalid*/false); 13748 13749 } else if (C.capturesThis()) { 13750 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(), 13751 C.getCaptureKind() == LCK_StarThis); 13752 } else { 13753 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(), 13754 I->getType()); 13755 } 13756 ++I; 13757 } 13758 } 13759 13760 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 13761 SkipBodyInfo *SkipBody) { 13762 if (!D) { 13763 // Parsing the function declaration failed in some way. Push on a fake scope 13764 // anyway so we can try to parse the function body. 13765 PushFunctionScope(); 13766 PushExpressionEvaluationContext(ExprEvalContexts.back().Context); 13767 return D; 13768 } 13769 13770 FunctionDecl *FD = nullptr; 13771 13772 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 13773 FD = FunTmpl->getTemplatedDecl(); 13774 else 13775 FD = cast<FunctionDecl>(D); 13776 13777 // Do not push if it is a lambda because one is already pushed when building 13778 // the lambda in ActOnStartOfLambdaDefinition(). 13779 if (!isLambdaCallOperator(FD)) 13780 PushExpressionEvaluationContext( 13781 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated 13782 : ExprEvalContexts.back().Context); 13783 13784 // Check for defining attributes before the check for redefinition. 13785 if (const auto *Attr = FD->getAttr<AliasAttr>()) { 13786 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0; 13787 FD->dropAttr<AliasAttr>(); 13788 FD->setInvalidDecl(); 13789 } 13790 if (const auto *Attr = FD->getAttr<IFuncAttr>()) { 13791 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1; 13792 FD->dropAttr<IFuncAttr>(); 13793 FD->setInvalidDecl(); 13794 } 13795 13796 // See if this is a redefinition. If 'will have body' is already set, then 13797 // these checks were already performed when it was set. 13798 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) { 13799 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 13800 13801 // If we're skipping the body, we're done. Don't enter the scope. 13802 if (SkipBody && SkipBody->ShouldSkip) 13803 return D; 13804 } 13805 13806 // Mark this function as "will have a body eventually". This lets users to 13807 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing 13808 // this function. 13809 FD->setWillHaveBody(); 13810 13811 // If we are instantiating a generic lambda call operator, push 13812 // a LambdaScopeInfo onto the function stack. But use the information 13813 // that's already been calculated (ActOnLambdaExpr) to prime the current 13814 // LambdaScopeInfo. 13815 // When the template operator is being specialized, the LambdaScopeInfo, 13816 // has to be properly restored so that tryCaptureVariable doesn't try 13817 // and capture any new variables. In addition when calculating potential 13818 // captures during transformation of nested lambdas, it is necessary to 13819 // have the LSI properly restored. 13820 if (isGenericLambdaCallOperatorSpecialization(FD)) { 13821 assert(inTemplateInstantiation() && 13822 "There should be an active template instantiation on the stack " 13823 "when instantiating a generic lambda!"); 13824 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 13825 } else { 13826 // Enter a new function scope 13827 PushFunctionScope(); 13828 } 13829 13830 // Builtin functions cannot be defined. 13831 if (unsigned BuiltinID = FD->getBuiltinID()) { 13832 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 13833 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 13834 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 13835 FD->setInvalidDecl(); 13836 } 13837 } 13838 13839 // The return type of a function definition must be complete 13840 // (C99 6.9.1p3, C++ [dcl.fct]p6). 13841 QualType ResultType = FD->getReturnType(); 13842 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 13843 !FD->isInvalidDecl() && 13844 RequireCompleteType(FD->getLocation(), ResultType, 13845 diag::err_func_def_incomplete_result)) 13846 FD->setInvalidDecl(); 13847 13848 if (FnBodyScope) 13849 PushDeclContext(FnBodyScope, FD); 13850 13851 // Check the validity of our function parameters 13852 CheckParmsForFunctionDef(FD->parameters(), 13853 /*CheckParameterNames=*/true); 13854 13855 // Add non-parameter declarations already in the function to the current 13856 // scope. 13857 if (FnBodyScope) { 13858 for (Decl *NPD : FD->decls()) { 13859 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD); 13860 if (!NonParmDecl) 13861 continue; 13862 assert(!isa<ParmVarDecl>(NonParmDecl) && 13863 "parameters should not be in newly created FD yet"); 13864 13865 // If the decl has a name, make it accessible in the current scope. 13866 if (NonParmDecl->getDeclName()) 13867 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false); 13868 13869 // Similarly, dive into enums and fish their constants out, making them 13870 // accessible in this scope. 13871 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) { 13872 for (auto *EI : ED->enumerators()) 13873 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 13874 } 13875 } 13876 } 13877 13878 // Introduce our parameters into the function scope 13879 for (auto Param : FD->parameters()) { 13880 Param->setOwningFunction(FD); 13881 13882 // If this has an identifier, add it to the scope stack. 13883 if (Param->getIdentifier() && FnBodyScope) { 13884 CheckShadow(FnBodyScope, Param); 13885 13886 PushOnScopeChains(Param, FnBodyScope); 13887 } 13888 } 13889 13890 // Ensure that the function's exception specification is instantiated. 13891 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 13892 ResolveExceptionSpec(D->getLocation(), FPT); 13893 13894 // dllimport cannot be applied to non-inline function definitions. 13895 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 13896 !FD->isTemplateInstantiation()) { 13897 assert(!FD->hasAttr<DLLExportAttr>()); 13898 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 13899 FD->setInvalidDecl(); 13900 return D; 13901 } 13902 // We want to attach documentation to original Decl (which might be 13903 // a function template). 13904 ActOnDocumentableDecl(D); 13905 if (getCurLexicalContext()->isObjCContainer() && 13906 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 13907 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 13908 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 13909 13910 return D; 13911 } 13912 13913 /// Given the set of return statements within a function body, 13914 /// compute the variables that are subject to the named return value 13915 /// optimization. 13916 /// 13917 /// Each of the variables that is subject to the named return value 13918 /// optimization will be marked as NRVO variables in the AST, and any 13919 /// return statement that has a marked NRVO variable as its NRVO candidate can 13920 /// use the named return value optimization. 13921 /// 13922 /// This function applies a very simplistic algorithm for NRVO: if every return 13923 /// statement in the scope of a variable has the same NRVO candidate, that 13924 /// candidate is an NRVO variable. 13925 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 13926 ReturnStmt **Returns = Scope->Returns.data(); 13927 13928 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 13929 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 13930 if (!NRVOCandidate->isNRVOVariable()) 13931 Returns[I]->setNRVOCandidate(nullptr); 13932 } 13933 } 13934 } 13935 13936 bool Sema::canDelayFunctionBody(const Declarator &D) { 13937 // We can't delay parsing the body of a constexpr function template (yet). 13938 if (D.getDeclSpec().hasConstexprSpecifier()) 13939 return false; 13940 13941 // We can't delay parsing the body of a function template with a deduced 13942 // return type (yet). 13943 if (D.getDeclSpec().hasAutoTypeSpec()) { 13944 // If the placeholder introduces a non-deduced trailing return type, 13945 // we can still delay parsing it. 13946 if (D.getNumTypeObjects()) { 13947 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 13948 if (Outer.Kind == DeclaratorChunk::Function && 13949 Outer.Fun.hasTrailingReturnType()) { 13950 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 13951 return Ty.isNull() || !Ty->isUndeducedType(); 13952 } 13953 } 13954 return false; 13955 } 13956 13957 return true; 13958 } 13959 13960 bool Sema::canSkipFunctionBody(Decl *D) { 13961 // We cannot skip the body of a function (or function template) which is 13962 // constexpr, since we may need to evaluate its body in order to parse the 13963 // rest of the file. 13964 // We cannot skip the body of a function with an undeduced return type, 13965 // because any callers of that function need to know the type. 13966 if (const FunctionDecl *FD = D->getAsFunction()) { 13967 if (FD->isConstexpr()) 13968 return false; 13969 // We can't simply call Type::isUndeducedType here, because inside template 13970 // auto can be deduced to a dependent type, which is not considered 13971 // "undeduced". 13972 if (FD->getReturnType()->getContainedDeducedType()) 13973 return false; 13974 } 13975 return Consumer.shouldSkipFunctionBody(D); 13976 } 13977 13978 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 13979 if (!Decl) 13980 return nullptr; 13981 if (FunctionDecl *FD = Decl->getAsFunction()) 13982 FD->setHasSkippedBody(); 13983 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl)) 13984 MD->setHasSkippedBody(); 13985 return Decl; 13986 } 13987 13988 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 13989 return ActOnFinishFunctionBody(D, BodyArg, false); 13990 } 13991 13992 /// RAII object that pops an ExpressionEvaluationContext when exiting a function 13993 /// body. 13994 class ExitFunctionBodyRAII { 13995 public: 13996 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {} 13997 ~ExitFunctionBodyRAII() { 13998 if (!IsLambda) 13999 S.PopExpressionEvaluationContext(); 14000 } 14001 14002 private: 14003 Sema &S; 14004 bool IsLambda = false; 14005 }; 14006 14007 static void diagnoseImplicitlyRetainedSelf(Sema &S) { 14008 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo; 14009 14010 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) { 14011 if (EscapeInfo.count(BD)) 14012 return EscapeInfo[BD]; 14013 14014 bool R = false; 14015 const BlockDecl *CurBD = BD; 14016 14017 do { 14018 R = !CurBD->doesNotEscape(); 14019 if (R) 14020 break; 14021 CurBD = CurBD->getParent()->getInnermostBlockDecl(); 14022 } while (CurBD); 14023 14024 return EscapeInfo[BD] = R; 14025 }; 14026 14027 // If the location where 'self' is implicitly retained is inside a escaping 14028 // block, emit a diagnostic. 14029 for (const std::pair<SourceLocation, const BlockDecl *> &P : 14030 S.ImplicitlyRetainedSelfLocs) 14031 if (IsOrNestedInEscapingBlock(P.second)) 14032 S.Diag(P.first, diag::warn_implicitly_retains_self) 14033 << FixItHint::CreateInsertion(P.first, "self->"); 14034 } 14035 14036 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 14037 bool IsInstantiation) { 14038 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 14039 14040 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 14041 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 14042 14043 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine()) 14044 CheckCompletedCoroutineBody(FD, Body); 14045 14046 // Do not call PopExpressionEvaluationContext() if it is a lambda because one 14047 // is already popped when finishing the lambda in BuildLambdaExpr(). This is 14048 // meant to pop the context added in ActOnStartOfFunctionDef(). 14049 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD)); 14050 14051 if (FD) { 14052 FD->setBody(Body); 14053 FD->setWillHaveBody(false); 14054 14055 if (getLangOpts().CPlusPlus14) { 14056 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() && 14057 FD->getReturnType()->isUndeducedType()) { 14058 // If the function has a deduced result type but contains no 'return' 14059 // statements, the result type as written must be exactly 'auto', and 14060 // the deduced result type is 'void'. 14061 if (!FD->getReturnType()->getAs<AutoType>()) { 14062 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 14063 << FD->getReturnType(); 14064 FD->setInvalidDecl(); 14065 } else { 14066 // Substitute 'void' for the 'auto' in the type. 14067 TypeLoc ResultType = getReturnTypeLoc(FD); 14068 Context.adjustDeducedFunctionResultType( 14069 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 14070 } 14071 } 14072 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 14073 // In C++11, we don't use 'auto' deduction rules for lambda call 14074 // operators because we don't support return type deduction. 14075 auto *LSI = getCurLambda(); 14076 if (LSI->HasImplicitReturnType) { 14077 deduceClosureReturnType(*LSI); 14078 14079 // C++11 [expr.prim.lambda]p4: 14080 // [...] if there are no return statements in the compound-statement 14081 // [the deduced type is] the type void 14082 QualType RetType = 14083 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 14084 14085 // Update the return type to the deduced type. 14086 const auto *Proto = FD->getType()->castAs<FunctionProtoType>(); 14087 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 14088 Proto->getExtProtoInfo())); 14089 } 14090 } 14091 14092 // If the function implicitly returns zero (like 'main') or is naked, 14093 // don't complain about missing return statements. 14094 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 14095 WP.disableCheckFallThrough(); 14096 14097 // MSVC permits the use of pure specifier (=0) on function definition, 14098 // defined at class scope, warn about this non-standard construct. 14099 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine()) 14100 Diag(FD->getLocation(), diag::ext_pure_function_definition); 14101 14102 if (!FD->isInvalidDecl()) { 14103 // Don't diagnose unused parameters of defaulted or deleted functions. 14104 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody()) 14105 DiagnoseUnusedParameters(FD->parameters()); 14106 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(), 14107 FD->getReturnType(), FD); 14108 14109 // If this is a structor, we need a vtable. 14110 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 14111 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 14112 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 14113 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 14114 14115 // Try to apply the named return value optimization. We have to check 14116 // if we can do this here because lambdas keep return statements around 14117 // to deduce an implicit return type. 14118 if (FD->getReturnType()->isRecordType() && 14119 (!getLangOpts().CPlusPlus || !FD->isDependentContext())) 14120 computeNRVO(Body, getCurFunction()); 14121 } 14122 14123 // GNU warning -Wmissing-prototypes: 14124 // Warn if a global function is defined without a previous 14125 // prototype declaration. This warning is issued even if the 14126 // definition itself provides a prototype. The aim is to detect 14127 // global functions that fail to be declared in header files. 14128 const FunctionDecl *PossiblePrototype = nullptr; 14129 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) { 14130 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 14131 14132 if (PossiblePrototype) { 14133 // We found a declaration that is not a prototype, 14134 // but that could be a zero-parameter prototype 14135 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) { 14136 TypeLoc TL = TI->getTypeLoc(); 14137 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 14138 Diag(PossiblePrototype->getLocation(), 14139 diag::note_declaration_not_a_prototype) 14140 << (FD->getNumParams() != 0) 14141 << (FD->getNumParams() == 0 14142 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void") 14143 : FixItHint{}); 14144 } 14145 } else { 14146 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage) 14147 << /* function */ 1 14148 << (FD->getStorageClass() == SC_None 14149 ? FixItHint::CreateInsertion(FD->getTypeSpecStartLoc(), 14150 "static ") 14151 : FixItHint{}); 14152 } 14153 14154 // GNU warning -Wstrict-prototypes 14155 // Warn if K&R function is defined without a previous declaration. 14156 // This warning is issued only if the definition itself does not provide 14157 // a prototype. Only K&R definitions do not provide a prototype. 14158 if (!FD->hasWrittenPrototype()) { 14159 TypeSourceInfo *TI = FD->getTypeSourceInfo(); 14160 TypeLoc TL = TI->getTypeLoc(); 14161 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>(); 14162 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2; 14163 } 14164 } 14165 14166 // Warn on CPUDispatch with an actual body. 14167 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body) 14168 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body)) 14169 if (!CmpndBody->body_empty()) 14170 Diag(CmpndBody->body_front()->getBeginLoc(), 14171 diag::warn_dispatch_body_ignored); 14172 14173 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 14174 const CXXMethodDecl *KeyFunction; 14175 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 14176 MD->isVirtual() && 14177 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 14178 MD == KeyFunction->getCanonicalDecl()) { 14179 // Update the key-function state if necessary for this ABI. 14180 if (FD->isInlined() && 14181 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 14182 Context.setNonKeyFunction(MD); 14183 14184 // If the newly-chosen key function is already defined, then we 14185 // need to mark the vtable as used retroactively. 14186 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 14187 const FunctionDecl *Definition; 14188 if (KeyFunction && KeyFunction->isDefined(Definition)) 14189 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 14190 } else { 14191 // We just defined they key function; mark the vtable as used. 14192 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 14193 } 14194 } 14195 } 14196 14197 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 14198 "Function parsing confused"); 14199 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 14200 assert(MD == getCurMethodDecl() && "Method parsing confused"); 14201 MD->setBody(Body); 14202 if (!MD->isInvalidDecl()) { 14203 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(), 14204 MD->getReturnType(), MD); 14205 14206 if (Body) 14207 computeNRVO(Body, getCurFunction()); 14208 } 14209 if (getCurFunction()->ObjCShouldCallSuper) { 14210 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call) 14211 << MD->getSelector().getAsString(); 14212 getCurFunction()->ObjCShouldCallSuper = false; 14213 } 14214 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 14215 const ObjCMethodDecl *InitMethod = nullptr; 14216 bool isDesignated = 14217 MD->isDesignatedInitializerForTheInterface(&InitMethod); 14218 assert(isDesignated && InitMethod); 14219 (void)isDesignated; 14220 14221 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 14222 auto IFace = MD->getClassInterface(); 14223 if (!IFace) 14224 return false; 14225 auto SuperD = IFace->getSuperClass(); 14226 if (!SuperD) 14227 return false; 14228 return SuperD->getIdentifier() == 14229 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 14230 }; 14231 // Don't issue this warning for unavailable inits or direct subclasses 14232 // of NSObject. 14233 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 14234 Diag(MD->getLocation(), 14235 diag::warn_objc_designated_init_missing_super_call); 14236 Diag(InitMethod->getLocation(), 14237 diag::note_objc_designated_init_marked_here); 14238 } 14239 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 14240 } 14241 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 14242 // Don't issue this warning for unavaialable inits. 14243 if (!MD->isUnavailable()) 14244 Diag(MD->getLocation(), 14245 diag::warn_objc_secondary_init_missing_init_call); 14246 getCurFunction()->ObjCWarnForNoInitDelegation = false; 14247 } 14248 14249 diagnoseImplicitlyRetainedSelf(*this); 14250 } else { 14251 // Parsing the function declaration failed in some way. Pop the fake scope 14252 // we pushed on. 14253 PopFunctionScopeInfo(ActivePolicy, dcl); 14254 return nullptr; 14255 } 14256 14257 if (Body && getCurFunction()->HasPotentialAvailabilityViolations) 14258 DiagnoseUnguardedAvailabilityViolations(dcl); 14259 14260 assert(!getCurFunction()->ObjCShouldCallSuper && 14261 "This should only be set for ObjC methods, which should have been " 14262 "handled in the block above."); 14263 14264 // Verify and clean out per-function state. 14265 if (Body && (!FD || !FD->isDefaulted())) { 14266 // C++ constructors that have function-try-blocks can't have return 14267 // statements in the handlers of that block. (C++ [except.handle]p14) 14268 // Verify this. 14269 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 14270 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 14271 14272 // Verify that gotos and switch cases don't jump into scopes illegally. 14273 if (getCurFunction()->NeedsScopeChecking() && 14274 !PP.isCodeCompletionEnabled()) 14275 DiagnoseInvalidJumps(Body); 14276 14277 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 14278 if (!Destructor->getParent()->isDependentType()) 14279 CheckDestructor(Destructor); 14280 14281 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 14282 Destructor->getParent()); 14283 } 14284 14285 // If any errors have occurred, clear out any temporaries that may have 14286 // been leftover. This ensures that these temporaries won't be picked up for 14287 // deletion in some later function. 14288 if (getDiagnostics().hasErrorOccurred() || 14289 getDiagnostics().getSuppressAllDiagnostics()) { 14290 DiscardCleanupsInEvaluationContext(); 14291 } 14292 if (!getDiagnostics().hasUncompilableErrorOccurred() && 14293 !isa<FunctionTemplateDecl>(dcl)) { 14294 // Since the body is valid, issue any analysis-based warnings that are 14295 // enabled. 14296 ActivePolicy = &WP; 14297 } 14298 14299 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 14300 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose)) 14301 FD->setInvalidDecl(); 14302 14303 if (FD && FD->hasAttr<NakedAttr>()) { 14304 for (const Stmt *S : Body->children()) { 14305 // Allow local register variables without initializer as they don't 14306 // require prologue. 14307 bool RegisterVariables = false; 14308 if (auto *DS = dyn_cast<DeclStmt>(S)) { 14309 for (const auto *Decl : DS->decls()) { 14310 if (const auto *Var = dyn_cast<VarDecl>(Decl)) { 14311 RegisterVariables = 14312 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit(); 14313 if (!RegisterVariables) 14314 break; 14315 } 14316 } 14317 } 14318 if (RegisterVariables) 14319 continue; 14320 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 14321 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function); 14322 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 14323 FD->setInvalidDecl(); 14324 break; 14325 } 14326 } 14327 } 14328 14329 assert(ExprCleanupObjects.size() == 14330 ExprEvalContexts.back().NumCleanupObjects && 14331 "Leftover temporaries in function"); 14332 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function"); 14333 assert(MaybeODRUseExprs.empty() && 14334 "Leftover expressions for odr-use checking"); 14335 } 14336 14337 if (!IsInstantiation) 14338 PopDeclContext(); 14339 14340 PopFunctionScopeInfo(ActivePolicy, dcl); 14341 // If any errors have occurred, clear out any temporaries that may have 14342 // been leftover. This ensures that these temporaries won't be picked up for 14343 // deletion in some later function. 14344 if (getDiagnostics().hasErrorOccurred()) { 14345 DiscardCleanupsInEvaluationContext(); 14346 } 14347 14348 return dcl; 14349 } 14350 14351 /// When we finish delayed parsing of an attribute, we must attach it to the 14352 /// relevant Decl. 14353 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 14354 ParsedAttributes &Attrs) { 14355 // Always attach attributes to the underlying decl. 14356 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 14357 D = TD->getTemplatedDecl(); 14358 ProcessDeclAttributeList(S, D, Attrs); 14359 14360 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 14361 if (Method->isStatic()) 14362 checkThisInStaticMemberFunctionAttributes(Method); 14363 } 14364 14365 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 14366 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 14367 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 14368 IdentifierInfo &II, Scope *S) { 14369 // Find the scope in which the identifier is injected and the corresponding 14370 // DeclContext. 14371 // FIXME: C89 does not say what happens if there is no enclosing block scope. 14372 // In that case, we inject the declaration into the translation unit scope 14373 // instead. 14374 Scope *BlockScope = S; 14375 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent()) 14376 BlockScope = BlockScope->getParent(); 14377 14378 Scope *ContextScope = BlockScope; 14379 while (!ContextScope->getEntity()) 14380 ContextScope = ContextScope->getParent(); 14381 ContextRAII SavedContext(*this, ContextScope->getEntity()); 14382 14383 // Before we produce a declaration for an implicitly defined 14384 // function, see whether there was a locally-scoped declaration of 14385 // this name as a function or variable. If so, use that 14386 // (non-visible) declaration, and complain about it. 14387 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II); 14388 if (ExternCPrev) { 14389 // We still need to inject the function into the enclosing block scope so 14390 // that later (non-call) uses can see it. 14391 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false); 14392 14393 // C89 footnote 38: 14394 // If in fact it is not defined as having type "function returning int", 14395 // the behavior is undefined. 14396 if (!isa<FunctionDecl>(ExternCPrev) || 14397 !Context.typesAreCompatible( 14398 cast<FunctionDecl>(ExternCPrev)->getType(), 14399 Context.getFunctionNoProtoType(Context.IntTy))) { 14400 Diag(Loc, diag::ext_use_out_of_scope_declaration) 14401 << ExternCPrev << !getLangOpts().C99; 14402 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 14403 return ExternCPrev; 14404 } 14405 } 14406 14407 // Extension in C99. Legal in C90, but warn about it. 14408 unsigned diag_id; 14409 if (II.getName().startswith("__builtin_")) 14410 diag_id = diag::warn_builtin_unknown; 14411 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported. 14412 else if (getLangOpts().OpenCL) 14413 diag_id = diag::err_opencl_implicit_function_decl; 14414 else if (getLangOpts().C99) 14415 diag_id = diag::ext_implicit_function_decl; 14416 else 14417 diag_id = diag::warn_implicit_function_decl; 14418 Diag(Loc, diag_id) << &II; 14419 14420 // If we found a prior declaration of this function, don't bother building 14421 // another one. We've already pushed that one into scope, so there's nothing 14422 // more to do. 14423 if (ExternCPrev) 14424 return ExternCPrev; 14425 14426 // Because typo correction is expensive, only do it if the implicit 14427 // function declaration is going to be treated as an error. 14428 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 14429 TypoCorrection Corrected; 14430 DeclFilterCCC<FunctionDecl> CCC{}; 14431 if (S && (Corrected = 14432 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName, 14433 S, nullptr, CCC, CTK_NonError))) 14434 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 14435 /*ErrorRecovery*/false); 14436 } 14437 14438 // Set a Declarator for the implicit definition: int foo(); 14439 const char *Dummy; 14440 AttributeFactory attrFactory; 14441 DeclSpec DS(attrFactory); 14442 unsigned DiagID; 14443 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 14444 Context.getPrintingPolicy()); 14445 (void)Error; // Silence warning. 14446 assert(!Error && "Error setting up implicit decl!"); 14447 SourceLocation NoLoc; 14448 Declarator D(DS, DeclaratorContext::BlockContext); 14449 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 14450 /*IsAmbiguous=*/false, 14451 /*LParenLoc=*/NoLoc, 14452 /*Params=*/nullptr, 14453 /*NumParams=*/0, 14454 /*EllipsisLoc=*/NoLoc, 14455 /*RParenLoc=*/NoLoc, 14456 /*RefQualifierIsLvalueRef=*/true, 14457 /*RefQualifierLoc=*/NoLoc, 14458 /*MutableLoc=*/NoLoc, EST_None, 14459 /*ESpecRange=*/SourceRange(), 14460 /*Exceptions=*/nullptr, 14461 /*ExceptionRanges=*/nullptr, 14462 /*NumExceptions=*/0, 14463 /*NoexceptExpr=*/nullptr, 14464 /*ExceptionSpecTokens=*/nullptr, 14465 /*DeclsInPrototype=*/None, Loc, 14466 Loc, D), 14467 std::move(DS.getAttributes()), SourceLocation()); 14468 D.SetIdentifier(&II, Loc); 14469 14470 // Insert this function into the enclosing block scope. 14471 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D)); 14472 FD->setImplicit(); 14473 14474 AddKnownFunctionAttributes(FD); 14475 14476 return FD; 14477 } 14478 14479 /// If this function is a C++ replaceable global allocation function 14480 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]), 14481 /// adds any function attributes that we know a priori based on the standard. 14482 /// 14483 /// We need to check for duplicate attributes both here and where user-written 14484 /// attributes are applied to declarations. 14485 void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( 14486 FunctionDecl *FD) { 14487 if (FD->isInvalidDecl()) 14488 return; 14489 14490 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New && 14491 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New) 14492 return; 14493 14494 Optional<unsigned> AlignmentParam; 14495 bool IsNothrow = false; 14496 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow)) 14497 return; 14498 14499 // C++2a [basic.stc.dynamic.allocation]p4: 14500 // An allocation function that has a non-throwing exception specification 14501 // indicates failure by returning a null pointer value. Any other allocation 14502 // function never returns a null pointer value and indicates failure only by 14503 // throwing an exception [...] 14504 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>()) 14505 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation())); 14506 14507 // C++2a [basic.stc.dynamic.allocation]p2: 14508 // An allocation function attempts to allocate the requested amount of 14509 // storage. [...] If the request succeeds, the value returned by a 14510 // replaceable allocation function is a [...] pointer value p0 different 14511 // from any previously returned value p1 [...] 14512 // 14513 // However, this particular information is being added in codegen, 14514 // because there is an opt-out switch for it (-fno-assume-sane-operator-new) 14515 14516 // C++2a [basic.stc.dynamic.allocation]p2: 14517 // An allocation function attempts to allocate the requested amount of 14518 // storage. If it is successful, it returns the address of the start of a 14519 // block of storage whose length in bytes is at least as large as the 14520 // requested size. 14521 if (!FD->hasAttr<AllocSizeAttr>()) { 14522 FD->addAttr(AllocSizeAttr::CreateImplicit( 14523 Context, /*ElemSizeParam=*/ParamIdx(1, FD), 14524 /*NumElemsParam=*/ParamIdx(), FD->getLocation())); 14525 } 14526 14527 // C++2a [basic.stc.dynamic.allocation]p3: 14528 // For an allocation function [...], the pointer returned on a successful 14529 // call shall represent the address of storage that is aligned as follows: 14530 // (3.1) If the allocation function takes an argument of type 14531 // std::align_val_t, the storage will have the alignment 14532 // specified by the value of this argument. 14533 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) { 14534 FD->addAttr(AllocAlignAttr::CreateImplicit( 14535 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation())); 14536 } 14537 14538 // FIXME: 14539 // C++2a [basic.stc.dynamic.allocation]p3: 14540 // For an allocation function [...], the pointer returned on a successful 14541 // call shall represent the address of storage that is aligned as follows: 14542 // (3.2) Otherwise, if the allocation function is named operator new[], 14543 // the storage is aligned for any object that does not have 14544 // new-extended alignment ([basic.align]) and is no larger than the 14545 // requested size. 14546 // (3.3) Otherwise, the storage is aligned for any object that does not 14547 // have new-extended alignment and is of the requested size. 14548 } 14549 14550 /// Adds any function attributes that we know a priori based on 14551 /// the declaration of this function. 14552 /// 14553 /// These attributes can apply both to implicitly-declared builtins 14554 /// (like __builtin___printf_chk) or to library-declared functions 14555 /// like NSLog or printf. 14556 /// 14557 /// We need to check for duplicate attributes both here and where user-written 14558 /// attributes are applied to declarations. 14559 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 14560 if (FD->isInvalidDecl()) 14561 return; 14562 14563 // If this is a built-in function, map its builtin attributes to 14564 // actual attributes. 14565 if (unsigned BuiltinID = FD->getBuiltinID()) { 14566 // Handle printf-formatting attributes. 14567 unsigned FormatIdx; 14568 bool HasVAListArg; 14569 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 14570 if (!FD->hasAttr<FormatAttr>()) { 14571 const char *fmt = "printf"; 14572 unsigned int NumParams = FD->getNumParams(); 14573 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 14574 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 14575 fmt = "NSString"; 14576 FD->addAttr(FormatAttr::CreateImplicit(Context, 14577 &Context.Idents.get(fmt), 14578 FormatIdx+1, 14579 HasVAListArg ? 0 : FormatIdx+2, 14580 FD->getLocation())); 14581 } 14582 } 14583 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 14584 HasVAListArg)) { 14585 if (!FD->hasAttr<FormatAttr>()) 14586 FD->addAttr(FormatAttr::CreateImplicit(Context, 14587 &Context.Idents.get("scanf"), 14588 FormatIdx+1, 14589 HasVAListArg ? 0 : FormatIdx+2, 14590 FD->getLocation())); 14591 } 14592 14593 // Handle automatically recognized callbacks. 14594 SmallVector<int, 4> Encoding; 14595 if (!FD->hasAttr<CallbackAttr>() && 14596 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding)) 14597 FD->addAttr(CallbackAttr::CreateImplicit( 14598 Context, Encoding.data(), Encoding.size(), FD->getLocation())); 14599 14600 // Mark const if we don't care about errno and that is the only thing 14601 // preventing the function from being const. This allows IRgen to use LLVM 14602 // intrinsics for such functions. 14603 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() && 14604 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) 14605 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14606 14607 // We make "fma" on some platforms const because we know it does not set 14608 // errno in those environments even though it could set errno based on the 14609 // C standard. 14610 const llvm::Triple &Trip = Context.getTargetInfo().getTriple(); 14611 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) && 14612 !FD->hasAttr<ConstAttr>()) { 14613 switch (BuiltinID) { 14614 case Builtin::BI__builtin_fma: 14615 case Builtin::BI__builtin_fmaf: 14616 case Builtin::BI__builtin_fmal: 14617 case Builtin::BIfma: 14618 case Builtin::BIfmaf: 14619 case Builtin::BIfmal: 14620 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14621 break; 14622 default: 14623 break; 14624 } 14625 } 14626 14627 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 14628 !FD->hasAttr<ReturnsTwiceAttr>()) 14629 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 14630 FD->getLocation())); 14631 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 14632 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14633 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>()) 14634 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation())); 14635 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 14636 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 14637 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 14638 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 14639 // Add the appropriate attribute, depending on the CUDA compilation mode 14640 // and which target the builtin belongs to. For example, during host 14641 // compilation, aux builtins are __device__, while the rest are __host__. 14642 if (getLangOpts().CUDAIsDevice != 14643 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 14644 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 14645 else 14646 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 14647 } 14648 } 14649 14650 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD); 14651 14652 // If C++ exceptions are enabled but we are told extern "C" functions cannot 14653 // throw, add an implicit nothrow attribute to any extern "C" function we come 14654 // across. 14655 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind && 14656 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) { 14657 const auto *FPT = FD->getType()->getAs<FunctionProtoType>(); 14658 if (!FPT || FPT->getExceptionSpecType() == EST_None) 14659 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 14660 } 14661 14662 IdentifierInfo *Name = FD->getIdentifier(); 14663 if (!Name) 14664 return; 14665 if ((!getLangOpts().CPlusPlus && 14666 FD->getDeclContext()->isTranslationUnit()) || 14667 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 14668 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 14669 LinkageSpecDecl::lang_c)) { 14670 // Okay: this could be a libc/libm/Objective-C function we know 14671 // about. 14672 } else 14673 return; 14674 14675 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 14676 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 14677 // target-specific builtins, perhaps? 14678 if (!FD->hasAttr<FormatAttr>()) 14679 FD->addAttr(FormatAttr::CreateImplicit(Context, 14680 &Context.Idents.get("printf"), 2, 14681 Name->isStr("vasprintf") ? 0 : 3, 14682 FD->getLocation())); 14683 } 14684 14685 if (Name->isStr("__CFStringMakeConstantString")) { 14686 // We already have a __builtin___CFStringMakeConstantString, 14687 // but builds that use -fno-constant-cfstrings don't go through that. 14688 if (!FD->hasAttr<FormatArgAttr>()) 14689 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD), 14690 FD->getLocation())); 14691 } 14692 } 14693 14694 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 14695 TypeSourceInfo *TInfo) { 14696 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 14697 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 14698 14699 if (!TInfo) { 14700 assert(D.isInvalidType() && "no declarator info for valid type"); 14701 TInfo = Context.getTrivialTypeSourceInfo(T); 14702 } 14703 14704 // Scope manipulation handled by caller. 14705 TypedefDecl *NewTD = 14706 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(), 14707 D.getIdentifierLoc(), D.getIdentifier(), TInfo); 14708 14709 // Bail out immediately if we have an invalid declaration. 14710 if (D.isInvalidType()) { 14711 NewTD->setInvalidDecl(); 14712 return NewTD; 14713 } 14714 14715 if (D.getDeclSpec().isModulePrivateSpecified()) { 14716 if (CurContext->isFunctionOrMethod()) 14717 Diag(NewTD->getLocation(), diag::err_module_private_local) 14718 << 2 << NewTD->getDeclName() 14719 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 14720 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 14721 else 14722 NewTD->setModulePrivate(); 14723 } 14724 14725 // C++ [dcl.typedef]p8: 14726 // If the typedef declaration defines an unnamed class (or 14727 // enum), the first typedef-name declared by the declaration 14728 // to be that class type (or enum type) is used to denote the 14729 // class type (or enum type) for linkage purposes only. 14730 // We need to check whether the type was declared in the declaration. 14731 switch (D.getDeclSpec().getTypeSpecType()) { 14732 case TST_enum: 14733 case TST_struct: 14734 case TST_interface: 14735 case TST_union: 14736 case TST_class: { 14737 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 14738 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 14739 break; 14740 } 14741 14742 default: 14743 break; 14744 } 14745 14746 return NewTD; 14747 } 14748 14749 /// Check that this is a valid underlying type for an enum declaration. 14750 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 14751 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 14752 QualType T = TI->getType(); 14753 14754 if (T->isDependentType()) 14755 return false; 14756 14757 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 14758 if (BT->isInteger()) 14759 return false; 14760 14761 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 14762 return true; 14763 } 14764 14765 /// Check whether this is a valid redeclaration of a previous enumeration. 14766 /// \return true if the redeclaration was invalid. 14767 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 14768 QualType EnumUnderlyingTy, bool IsFixed, 14769 const EnumDecl *Prev) { 14770 if (IsScoped != Prev->isScoped()) { 14771 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 14772 << Prev->isScoped(); 14773 Diag(Prev->getLocation(), diag::note_previous_declaration); 14774 return true; 14775 } 14776 14777 if (IsFixed && Prev->isFixed()) { 14778 if (!EnumUnderlyingTy->isDependentType() && 14779 !Prev->getIntegerType()->isDependentType() && 14780 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 14781 Prev->getIntegerType())) { 14782 // TODO: Highlight the underlying type of the redeclaration. 14783 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 14784 << EnumUnderlyingTy << Prev->getIntegerType(); 14785 Diag(Prev->getLocation(), diag::note_previous_declaration) 14786 << Prev->getIntegerTypeRange(); 14787 return true; 14788 } 14789 } else if (IsFixed != Prev->isFixed()) { 14790 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 14791 << Prev->isFixed(); 14792 Diag(Prev->getLocation(), diag::note_previous_declaration); 14793 return true; 14794 } 14795 14796 return false; 14797 } 14798 14799 /// Get diagnostic %select index for tag kind for 14800 /// redeclaration diagnostic message. 14801 /// WARNING: Indexes apply to particular diagnostics only! 14802 /// 14803 /// \returns diagnostic %select index. 14804 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 14805 switch (Tag) { 14806 case TTK_Struct: return 0; 14807 case TTK_Interface: return 1; 14808 case TTK_Class: return 2; 14809 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 14810 } 14811 } 14812 14813 /// Determine if tag kind is a class-key compatible with 14814 /// class for redeclaration (class, struct, or __interface). 14815 /// 14816 /// \returns true iff the tag kind is compatible. 14817 static bool isClassCompatTagKind(TagTypeKind Tag) 14818 { 14819 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 14820 } 14821 14822 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl, 14823 TagTypeKind TTK) { 14824 if (isa<TypedefDecl>(PrevDecl)) 14825 return NTK_Typedef; 14826 else if (isa<TypeAliasDecl>(PrevDecl)) 14827 return NTK_TypeAlias; 14828 else if (isa<ClassTemplateDecl>(PrevDecl)) 14829 return NTK_Template; 14830 else if (isa<TypeAliasTemplateDecl>(PrevDecl)) 14831 return NTK_TypeAliasTemplate; 14832 else if (isa<TemplateTemplateParmDecl>(PrevDecl)) 14833 return NTK_TemplateTemplateArgument; 14834 switch (TTK) { 14835 case TTK_Struct: 14836 case TTK_Interface: 14837 case TTK_Class: 14838 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct; 14839 case TTK_Union: 14840 return NTK_NonUnion; 14841 case TTK_Enum: 14842 return NTK_NonEnum; 14843 } 14844 llvm_unreachable("invalid TTK"); 14845 } 14846 14847 /// Determine whether a tag with a given kind is acceptable 14848 /// as a redeclaration of the given tag declaration. 14849 /// 14850 /// \returns true if the new tag kind is acceptable, false otherwise. 14851 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 14852 TagTypeKind NewTag, bool isDefinition, 14853 SourceLocation NewTagLoc, 14854 const IdentifierInfo *Name) { 14855 // C++ [dcl.type.elab]p3: 14856 // The class-key or enum keyword present in the 14857 // elaborated-type-specifier shall agree in kind with the 14858 // declaration to which the name in the elaborated-type-specifier 14859 // refers. This rule also applies to the form of 14860 // elaborated-type-specifier that declares a class-name or 14861 // friend class since it can be construed as referring to the 14862 // definition of the class. Thus, in any 14863 // elaborated-type-specifier, the enum keyword shall be used to 14864 // refer to an enumeration (7.2), the union class-key shall be 14865 // used to refer to a union (clause 9), and either the class or 14866 // struct class-key shall be used to refer to a class (clause 9) 14867 // declared using the class or struct class-key. 14868 TagTypeKind OldTag = Previous->getTagKind(); 14869 if (OldTag != NewTag && 14870 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag))) 14871 return false; 14872 14873 // Tags are compatible, but we might still want to warn on mismatched tags. 14874 // Non-class tags can't be mismatched at this point. 14875 if (!isClassCompatTagKind(NewTag)) 14876 return true; 14877 14878 // Declarations for which -Wmismatched-tags is disabled are entirely ignored 14879 // by our warning analysis. We don't want to warn about mismatches with (eg) 14880 // declarations in system headers that are designed to be specialized, but if 14881 // a user asks us to warn, we should warn if their code contains mismatched 14882 // declarations. 14883 auto IsIgnoredLoc = [&](SourceLocation Loc) { 14884 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch, 14885 Loc); 14886 }; 14887 if (IsIgnoredLoc(NewTagLoc)) 14888 return true; 14889 14890 auto IsIgnored = [&](const TagDecl *Tag) { 14891 return IsIgnoredLoc(Tag->getLocation()); 14892 }; 14893 while (IsIgnored(Previous)) { 14894 Previous = Previous->getPreviousDecl(); 14895 if (!Previous) 14896 return true; 14897 OldTag = Previous->getTagKind(); 14898 } 14899 14900 bool isTemplate = false; 14901 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 14902 isTemplate = Record->getDescribedClassTemplate(); 14903 14904 if (inTemplateInstantiation()) { 14905 if (OldTag != NewTag) { 14906 // In a template instantiation, do not offer fix-its for tag mismatches 14907 // since they usually mess up the template instead of fixing the problem. 14908 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14909 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14910 << getRedeclDiagFromTagKind(OldTag); 14911 // FIXME: Note previous location? 14912 } 14913 return true; 14914 } 14915 14916 if (isDefinition) { 14917 // On definitions, check all previous tags and issue a fix-it for each 14918 // one that doesn't match the current tag. 14919 if (Previous->getDefinition()) { 14920 // Don't suggest fix-its for redefinitions. 14921 return true; 14922 } 14923 14924 bool previousMismatch = false; 14925 for (const TagDecl *I : Previous->redecls()) { 14926 if (I->getTagKind() != NewTag) { 14927 // Ignore previous declarations for which the warning was disabled. 14928 if (IsIgnored(I)) 14929 continue; 14930 14931 if (!previousMismatch) { 14932 previousMismatch = true; 14933 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 14934 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14935 << getRedeclDiagFromTagKind(I->getTagKind()); 14936 } 14937 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 14938 << getRedeclDiagFromTagKind(NewTag) 14939 << FixItHint::CreateReplacement(I->getInnerLocStart(), 14940 TypeWithKeyword::getTagTypeKindName(NewTag)); 14941 } 14942 } 14943 return true; 14944 } 14945 14946 // Identify the prevailing tag kind: this is the kind of the definition (if 14947 // there is a non-ignored definition), or otherwise the kind of the prior 14948 // (non-ignored) declaration. 14949 const TagDecl *PrevDef = Previous->getDefinition(); 14950 if (PrevDef && IsIgnored(PrevDef)) 14951 PrevDef = nullptr; 14952 const TagDecl *Redecl = PrevDef ? PrevDef : Previous; 14953 if (Redecl->getTagKind() != NewTag) { 14954 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 14955 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 14956 << getRedeclDiagFromTagKind(OldTag); 14957 Diag(Redecl->getLocation(), diag::note_previous_use); 14958 14959 // If there is a previous definition, suggest a fix-it. 14960 if (PrevDef) { 14961 Diag(NewTagLoc, diag::note_struct_class_suggestion) 14962 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 14963 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 14964 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 14965 } 14966 } 14967 14968 return true; 14969 } 14970 14971 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 14972 /// from an outer enclosing namespace or file scope inside a friend declaration. 14973 /// This should provide the commented out code in the following snippet: 14974 /// namespace N { 14975 /// struct X; 14976 /// namespace M { 14977 /// struct Y { friend struct /*N::*/ X; }; 14978 /// } 14979 /// } 14980 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 14981 SourceLocation NameLoc) { 14982 // While the decl is in a namespace, do repeated lookup of that name and see 14983 // if we get the same namespace back. If we do not, continue until 14984 // translation unit scope, at which point we have a fully qualified NNS. 14985 SmallVector<IdentifierInfo *, 4> Namespaces; 14986 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 14987 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 14988 // This tag should be declared in a namespace, which can only be enclosed by 14989 // other namespaces. Bail if there's an anonymous namespace in the chain. 14990 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 14991 if (!Namespace || Namespace->isAnonymousNamespace()) 14992 return FixItHint(); 14993 IdentifierInfo *II = Namespace->getIdentifier(); 14994 Namespaces.push_back(II); 14995 NamedDecl *Lookup = SemaRef.LookupSingleName( 14996 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 14997 if (Lookup == Namespace) 14998 break; 14999 } 15000 15001 // Once we have all the namespaces, reverse them to go outermost first, and 15002 // build an NNS. 15003 SmallString<64> Insertion; 15004 llvm::raw_svector_ostream OS(Insertion); 15005 if (DC->isTranslationUnit()) 15006 OS << "::"; 15007 std::reverse(Namespaces.begin(), Namespaces.end()); 15008 for (auto *II : Namespaces) 15009 OS << II->getName() << "::"; 15010 return FixItHint::CreateInsertion(NameLoc, Insertion); 15011 } 15012 15013 /// Determine whether a tag originally declared in context \p OldDC can 15014 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup 15015 /// found a declaration in \p OldDC as a previous decl, perhaps through a 15016 /// using-declaration). 15017 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 15018 DeclContext *NewDC) { 15019 OldDC = OldDC->getRedeclContext(); 15020 NewDC = NewDC->getRedeclContext(); 15021 15022 if (OldDC->Equals(NewDC)) 15023 return true; 15024 15025 // In MSVC mode, we allow a redeclaration if the contexts are related (either 15026 // encloses the other). 15027 if (S.getLangOpts().MSVCCompat && 15028 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 15029 return true; 15030 15031 return false; 15032 } 15033 15034 /// This is invoked when we see 'struct foo' or 'struct {'. In the 15035 /// former case, Name will be non-null. In the later case, Name will be null. 15036 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 15037 /// reference/declaration/definition of a tag. 15038 /// 15039 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 15040 /// trailing-type-specifier) other than one in an alias-declaration. 15041 /// 15042 /// \param SkipBody If non-null, will be set to indicate if the caller should 15043 /// skip the definition of this tag and treat it as if it were a declaration. 15044 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 15045 SourceLocation KWLoc, CXXScopeSpec &SS, 15046 IdentifierInfo *Name, SourceLocation NameLoc, 15047 const ParsedAttributesView &Attrs, AccessSpecifier AS, 15048 SourceLocation ModulePrivateLoc, 15049 MultiTemplateParamsArg TemplateParameterLists, 15050 bool &OwnedDecl, bool &IsDependent, 15051 SourceLocation ScopedEnumKWLoc, 15052 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, 15053 bool IsTypeSpecifier, bool IsTemplateParamOrArg, 15054 SkipBodyInfo *SkipBody) { 15055 // If this is not a definition, it must have a name. 15056 IdentifierInfo *OrigName = Name; 15057 assert((Name != nullptr || TUK == TUK_Definition) && 15058 "Nameless record must be a definition!"); 15059 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 15060 15061 OwnedDecl = false; 15062 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 15063 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 15064 15065 // FIXME: Check member specializations more carefully. 15066 bool isMemberSpecialization = false; 15067 bool Invalid = false; 15068 15069 // We only need to do this matching if we have template parameters 15070 // or a scope specifier, which also conveniently avoids this work 15071 // for non-C++ cases. 15072 if (TemplateParameterLists.size() > 0 || 15073 (SS.isNotEmpty() && TUK != TUK_Reference)) { 15074 if (TemplateParameterList *TemplateParams = 15075 MatchTemplateParametersToScopeSpecifier( 15076 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 15077 TUK == TUK_Friend, isMemberSpecialization, Invalid)) { 15078 if (Kind == TTK_Enum) { 15079 Diag(KWLoc, diag::err_enum_template); 15080 return nullptr; 15081 } 15082 15083 if (TemplateParams->size() > 0) { 15084 // This is a declaration or definition of a class template (which may 15085 // be a member of another template). 15086 15087 if (Invalid) 15088 return nullptr; 15089 15090 OwnedDecl = false; 15091 DeclResult Result = CheckClassTemplate( 15092 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams, 15093 AS, ModulePrivateLoc, 15094 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1, 15095 TemplateParameterLists.data(), SkipBody); 15096 return Result.get(); 15097 } else { 15098 // The "template<>" header is extraneous. 15099 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 15100 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 15101 isMemberSpecialization = true; 15102 } 15103 } 15104 } 15105 15106 // Figure out the underlying type if this a enum declaration. We need to do 15107 // this early, because it's needed to detect if this is an incompatible 15108 // redeclaration. 15109 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 15110 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum; 15111 15112 if (Kind == TTK_Enum) { 15113 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) { 15114 // No underlying type explicitly specified, or we failed to parse the 15115 // type, default to int. 15116 EnumUnderlying = Context.IntTy.getTypePtr(); 15117 } else if (UnderlyingType.get()) { 15118 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 15119 // integral type; any cv-qualification is ignored. 15120 TypeSourceInfo *TI = nullptr; 15121 GetTypeFromParser(UnderlyingType.get(), &TI); 15122 EnumUnderlying = TI; 15123 15124 if (CheckEnumUnderlyingType(TI)) 15125 // Recover by falling back to int. 15126 EnumUnderlying = Context.IntTy.getTypePtr(); 15127 15128 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 15129 UPPC_FixedUnderlyingType)) 15130 EnumUnderlying = Context.IntTy.getTypePtr(); 15131 15132 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) { 15133 // For MSVC ABI compatibility, unfixed enums must use an underlying type 15134 // of 'int'. However, if this is an unfixed forward declaration, don't set 15135 // the underlying type unless the user enables -fms-compatibility. This 15136 // makes unfixed forward declared enums incomplete and is more conforming. 15137 if (TUK == TUK_Definition || getLangOpts().MSVCCompat) 15138 EnumUnderlying = Context.IntTy.getTypePtr(); 15139 } 15140 } 15141 15142 DeclContext *SearchDC = CurContext; 15143 DeclContext *DC = CurContext; 15144 bool isStdBadAlloc = false; 15145 bool isStdAlignValT = false; 15146 15147 RedeclarationKind Redecl = forRedeclarationInCurContext(); 15148 if (TUK == TUK_Friend || TUK == TUK_Reference) 15149 Redecl = NotForRedeclaration; 15150 15151 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C 15152 /// implemented asks for structural equivalence checking, the returned decl 15153 /// here is passed back to the parser, allowing the tag body to be parsed. 15154 auto createTagFromNewDecl = [&]() -> TagDecl * { 15155 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage"); 15156 // If there is an identifier, use the location of the identifier as the 15157 // location of the decl, otherwise use the location of the struct/union 15158 // keyword. 15159 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15160 TagDecl *New = nullptr; 15161 15162 if (Kind == TTK_Enum) { 15163 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr, 15164 ScopedEnum, ScopedEnumUsesClassTag, IsFixed); 15165 // If this is an undefined enum, bail. 15166 if (TUK != TUK_Definition && !Invalid) 15167 return nullptr; 15168 if (EnumUnderlying) { 15169 EnumDecl *ED = cast<EnumDecl>(New); 15170 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>()) 15171 ED->setIntegerTypeSourceInfo(TI); 15172 else 15173 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0)); 15174 ED->setPromotionType(ED->getIntegerType()); 15175 } 15176 } else { // struct/union 15177 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15178 nullptr); 15179 } 15180 15181 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15182 // Add alignment attributes if necessary; these attributes are checked 15183 // when the ASTContext lays out the structure. 15184 // 15185 // It is important for implementing the correct semantics that this 15186 // happen here (in ActOnTag). The #pragma pack stack is 15187 // maintained as a result of parser callbacks which can occur at 15188 // many points during the parsing of a struct declaration (because 15189 // the #pragma tokens are effectively skipped over during the 15190 // parsing of the struct). 15191 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15192 AddAlignmentAttributesForRecord(RD); 15193 AddMsStructLayoutForRecord(RD); 15194 } 15195 } 15196 New->setLexicalDeclContext(CurContext); 15197 return New; 15198 }; 15199 15200 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 15201 if (Name && SS.isNotEmpty()) { 15202 // We have a nested-name tag ('struct foo::bar'). 15203 15204 // Check for invalid 'foo::'. 15205 if (SS.isInvalid()) { 15206 Name = nullptr; 15207 goto CreateNewDecl; 15208 } 15209 15210 // If this is a friend or a reference to a class in a dependent 15211 // context, don't try to make a decl for it. 15212 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15213 DC = computeDeclContext(SS, false); 15214 if (!DC) { 15215 IsDependent = true; 15216 return nullptr; 15217 } 15218 } else { 15219 DC = computeDeclContext(SS, true); 15220 if (!DC) { 15221 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 15222 << SS.getRange(); 15223 return nullptr; 15224 } 15225 } 15226 15227 if (RequireCompleteDeclContext(SS, DC)) 15228 return nullptr; 15229 15230 SearchDC = DC; 15231 // Look-up name inside 'foo::'. 15232 LookupQualifiedName(Previous, DC); 15233 15234 if (Previous.isAmbiguous()) 15235 return nullptr; 15236 15237 if (Previous.empty()) { 15238 // Name lookup did not find anything. However, if the 15239 // nested-name-specifier refers to the current instantiation, 15240 // and that current instantiation has any dependent base 15241 // classes, we might find something at instantiation time: treat 15242 // this as a dependent elaborated-type-specifier. 15243 // But this only makes any sense for reference-like lookups. 15244 if (Previous.wasNotFoundInCurrentInstantiation() && 15245 (TUK == TUK_Reference || TUK == TUK_Friend)) { 15246 IsDependent = true; 15247 return nullptr; 15248 } 15249 15250 // A tag 'foo::bar' must already exist. 15251 Diag(NameLoc, diag::err_not_tag_in_scope) 15252 << Kind << Name << DC << SS.getRange(); 15253 Name = nullptr; 15254 Invalid = true; 15255 goto CreateNewDecl; 15256 } 15257 } else if (Name) { 15258 // C++14 [class.mem]p14: 15259 // If T is the name of a class, then each of the following shall have a 15260 // name different from T: 15261 // -- every member of class T that is itself a type 15262 if (TUK != TUK_Reference && TUK != TUK_Friend && 15263 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 15264 return nullptr; 15265 15266 // If this is a named struct, check to see if there was a previous forward 15267 // declaration or definition. 15268 // FIXME: We're looking into outer scopes here, even when we 15269 // shouldn't be. Doing so can result in ambiguities that we 15270 // shouldn't be diagnosing. 15271 LookupName(Previous, S); 15272 15273 // When declaring or defining a tag, ignore ambiguities introduced 15274 // by types using'ed into this scope. 15275 if (Previous.isAmbiguous() && 15276 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 15277 LookupResult::Filter F = Previous.makeFilter(); 15278 while (F.hasNext()) { 15279 NamedDecl *ND = F.next(); 15280 if (!ND->getDeclContext()->getRedeclContext()->Equals( 15281 SearchDC->getRedeclContext())) 15282 F.erase(); 15283 } 15284 F.done(); 15285 } 15286 15287 // C++11 [namespace.memdef]p3: 15288 // If the name in a friend declaration is neither qualified nor 15289 // a template-id and the declaration is a function or an 15290 // elaborated-type-specifier, the lookup to determine whether 15291 // the entity has been previously declared shall not consider 15292 // any scopes outside the innermost enclosing namespace. 15293 // 15294 // MSVC doesn't implement the above rule for types, so a friend tag 15295 // declaration may be a redeclaration of a type declared in an enclosing 15296 // scope. They do implement this rule for friend functions. 15297 // 15298 // Does it matter that this should be by scope instead of by 15299 // semantic context? 15300 if (!Previous.empty() && TUK == TUK_Friend) { 15301 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 15302 LookupResult::Filter F = Previous.makeFilter(); 15303 bool FriendSawTagOutsideEnclosingNamespace = false; 15304 while (F.hasNext()) { 15305 NamedDecl *ND = F.next(); 15306 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 15307 if (DC->isFileContext() && 15308 !EnclosingNS->Encloses(ND->getDeclContext())) { 15309 if (getLangOpts().MSVCCompat) 15310 FriendSawTagOutsideEnclosingNamespace = true; 15311 else 15312 F.erase(); 15313 } 15314 } 15315 F.done(); 15316 15317 // Diagnose this MSVC extension in the easy case where lookup would have 15318 // unambiguously found something outside the enclosing namespace. 15319 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 15320 NamedDecl *ND = Previous.getFoundDecl(); 15321 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 15322 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 15323 } 15324 } 15325 15326 // Note: there used to be some attempt at recovery here. 15327 if (Previous.isAmbiguous()) 15328 return nullptr; 15329 15330 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 15331 // FIXME: This makes sure that we ignore the contexts associated 15332 // with C structs, unions, and enums when looking for a matching 15333 // tag declaration or definition. See the similar lookup tweak 15334 // in Sema::LookupName; is there a better way to deal with this? 15335 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 15336 SearchDC = SearchDC->getParent(); 15337 } 15338 } 15339 15340 if (Previous.isSingleResult() && 15341 Previous.getFoundDecl()->isTemplateParameter()) { 15342 // Maybe we will complain about the shadowed template parameter. 15343 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 15344 // Just pretend that we didn't see the previous declaration. 15345 Previous.clear(); 15346 } 15347 15348 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 15349 DC->Equals(getStdNamespace())) { 15350 if (Name->isStr("bad_alloc")) { 15351 // This is a declaration of or a reference to "std::bad_alloc". 15352 isStdBadAlloc = true; 15353 15354 // If std::bad_alloc has been implicitly declared (but made invisible to 15355 // name lookup), fill in this implicit declaration as the previous 15356 // declaration, so that the declarations get chained appropriately. 15357 if (Previous.empty() && StdBadAlloc) 15358 Previous.addDecl(getStdBadAlloc()); 15359 } else if (Name->isStr("align_val_t")) { 15360 isStdAlignValT = true; 15361 if (Previous.empty() && StdAlignValT) 15362 Previous.addDecl(getStdAlignValT()); 15363 } 15364 } 15365 15366 // If we didn't find a previous declaration, and this is a reference 15367 // (or friend reference), move to the correct scope. In C++, we 15368 // also need to do a redeclaration lookup there, just in case 15369 // there's a shadow friend decl. 15370 if (Name && Previous.empty() && 15371 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) { 15372 if (Invalid) goto CreateNewDecl; 15373 assert(SS.isEmpty()); 15374 15375 if (TUK == TUK_Reference || IsTemplateParamOrArg) { 15376 // C++ [basic.scope.pdecl]p5: 15377 // -- for an elaborated-type-specifier of the form 15378 // 15379 // class-key identifier 15380 // 15381 // if the elaborated-type-specifier is used in the 15382 // decl-specifier-seq or parameter-declaration-clause of a 15383 // function defined in namespace scope, the identifier is 15384 // declared as a class-name in the namespace that contains 15385 // the declaration; otherwise, except as a friend 15386 // declaration, the identifier is declared in the smallest 15387 // non-class, non-function-prototype scope that contains the 15388 // declaration. 15389 // 15390 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 15391 // C structs and unions. 15392 // 15393 // It is an error in C++ to declare (rather than define) an enum 15394 // type, including via an elaborated type specifier. We'll 15395 // diagnose that later; for now, declare the enum in the same 15396 // scope as we would have picked for any other tag type. 15397 // 15398 // GNU C also supports this behavior as part of its incomplete 15399 // enum types extension, while GNU C++ does not. 15400 // 15401 // Find the context where we'll be declaring the tag. 15402 // FIXME: We would like to maintain the current DeclContext as the 15403 // lexical context, 15404 SearchDC = getTagInjectionContext(SearchDC); 15405 15406 // Find the scope where we'll be declaring the tag. 15407 S = getTagInjectionScope(S, getLangOpts()); 15408 } else { 15409 assert(TUK == TUK_Friend); 15410 // C++ [namespace.memdef]p3: 15411 // If a friend declaration in a non-local class first declares a 15412 // class or function, the friend class or function is a member of 15413 // the innermost enclosing namespace. 15414 SearchDC = SearchDC->getEnclosingNamespaceContext(); 15415 } 15416 15417 // In C++, we need to do a redeclaration lookup to properly 15418 // diagnose some problems. 15419 // FIXME: redeclaration lookup is also used (with and without C++) to find a 15420 // hidden declaration so that we don't get ambiguity errors when using a 15421 // type declared by an elaborated-type-specifier. In C that is not correct 15422 // and we should instead merge compatible types found by lookup. 15423 if (getLangOpts().CPlusPlus) { 15424 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15425 LookupQualifiedName(Previous, SearchDC); 15426 } else { 15427 Previous.setRedeclarationKind(forRedeclarationInCurContext()); 15428 LookupName(Previous, S); 15429 } 15430 } 15431 15432 // If we have a known previous declaration to use, then use it. 15433 if (Previous.empty() && SkipBody && SkipBody->Previous) 15434 Previous.addDecl(SkipBody->Previous); 15435 15436 if (!Previous.empty()) { 15437 NamedDecl *PrevDecl = Previous.getFoundDecl(); 15438 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 15439 15440 // It's okay to have a tag decl in the same scope as a typedef 15441 // which hides a tag decl in the same scope. Finding this 15442 // insanity with a redeclaration lookup can only actually happen 15443 // in C++. 15444 // 15445 // This is also okay for elaborated-type-specifiers, which is 15446 // technically forbidden by the current standard but which is 15447 // okay according to the likely resolution of an open issue; 15448 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 15449 if (getLangOpts().CPlusPlus) { 15450 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15451 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 15452 TagDecl *Tag = TT->getDecl(); 15453 if (Tag->getDeclName() == Name && 15454 Tag->getDeclContext()->getRedeclContext() 15455 ->Equals(TD->getDeclContext()->getRedeclContext())) { 15456 PrevDecl = Tag; 15457 Previous.clear(); 15458 Previous.addDecl(Tag); 15459 Previous.resolveKind(); 15460 } 15461 } 15462 } 15463 } 15464 15465 // If this is a redeclaration of a using shadow declaration, it must 15466 // declare a tag in the same context. In MSVC mode, we allow a 15467 // redefinition if either context is within the other. 15468 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 15469 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 15470 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 15471 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) && 15472 !(OldTag && isAcceptableTagRedeclContext( 15473 *this, OldTag->getDeclContext(), SearchDC))) { 15474 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 15475 Diag(Shadow->getTargetDecl()->getLocation(), 15476 diag::note_using_decl_target); 15477 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 15478 << 0; 15479 // Recover by ignoring the old declaration. 15480 Previous.clear(); 15481 goto CreateNewDecl; 15482 } 15483 } 15484 15485 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 15486 // If this is a use of a previous tag, or if the tag is already declared 15487 // in the same scope (so that the definition/declaration completes or 15488 // rementions the tag), reuse the decl. 15489 if (TUK == TUK_Reference || TUK == TUK_Friend || 15490 isDeclInScope(DirectPrevDecl, SearchDC, S, 15491 SS.isNotEmpty() || isMemberSpecialization)) { 15492 // Make sure that this wasn't declared as an enum and now used as a 15493 // struct or something similar. 15494 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 15495 TUK == TUK_Definition, KWLoc, 15496 Name)) { 15497 bool SafeToContinue 15498 = (PrevTagDecl->getTagKind() != TTK_Enum && 15499 Kind != TTK_Enum); 15500 if (SafeToContinue) 15501 Diag(KWLoc, diag::err_use_with_wrong_tag) 15502 << Name 15503 << FixItHint::CreateReplacement(SourceRange(KWLoc), 15504 PrevTagDecl->getKindName()); 15505 else 15506 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 15507 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 15508 15509 if (SafeToContinue) 15510 Kind = PrevTagDecl->getTagKind(); 15511 else { 15512 // Recover by making this an anonymous redefinition. 15513 Name = nullptr; 15514 Previous.clear(); 15515 Invalid = true; 15516 } 15517 } 15518 15519 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 15520 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 15521 15522 // If this is an elaborated-type-specifier for a scoped enumeration, 15523 // the 'class' keyword is not necessary and not permitted. 15524 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15525 if (ScopedEnum) 15526 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 15527 << PrevEnum->isScoped() 15528 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 15529 return PrevTagDecl; 15530 } 15531 15532 QualType EnumUnderlyingTy; 15533 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15534 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 15535 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 15536 EnumUnderlyingTy = QualType(T, 0); 15537 15538 // All conflicts with previous declarations are recovered by 15539 // returning the previous declaration, unless this is a definition, 15540 // in which case we want the caller to bail out. 15541 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 15542 ScopedEnum, EnumUnderlyingTy, 15543 IsFixed, PrevEnum)) 15544 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 15545 } 15546 15547 // C++11 [class.mem]p1: 15548 // A member shall not be declared twice in the member-specification, 15549 // except that a nested class or member class template can be declared 15550 // and then later defined. 15551 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 15552 S->isDeclScope(PrevDecl)) { 15553 Diag(NameLoc, diag::ext_member_redeclared); 15554 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 15555 } 15556 15557 if (!Invalid) { 15558 // If this is a use, just return the declaration we found, unless 15559 // we have attributes. 15560 if (TUK == TUK_Reference || TUK == TUK_Friend) { 15561 if (!Attrs.empty()) { 15562 // FIXME: Diagnose these attributes. For now, we create a new 15563 // declaration to hold them. 15564 } else if (TUK == TUK_Reference && 15565 (PrevTagDecl->getFriendObjectKind() == 15566 Decl::FOK_Undeclared || 15567 PrevDecl->getOwningModule() != getCurrentModule()) && 15568 SS.isEmpty()) { 15569 // This declaration is a reference to an existing entity, but 15570 // has different visibility from that entity: it either makes 15571 // a friend visible or it makes a type visible in a new module. 15572 // In either case, create a new declaration. We only do this if 15573 // the declaration would have meant the same thing if no prior 15574 // declaration were found, that is, if it was found in the same 15575 // scope where we would have injected a declaration. 15576 if (!getTagInjectionContext(CurContext)->getRedeclContext() 15577 ->Equals(PrevDecl->getDeclContext()->getRedeclContext())) 15578 return PrevTagDecl; 15579 // This is in the injected scope, create a new declaration in 15580 // that scope. 15581 S = getTagInjectionScope(S, getLangOpts()); 15582 } else { 15583 return PrevTagDecl; 15584 } 15585 } 15586 15587 // Diagnose attempts to redefine a tag. 15588 if (TUK == TUK_Definition) { 15589 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 15590 // If we're defining a specialization and the previous definition 15591 // is from an implicit instantiation, don't emit an error 15592 // here; we'll catch this in the general case below. 15593 bool IsExplicitSpecializationAfterInstantiation = false; 15594 if (isMemberSpecialization) { 15595 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 15596 IsExplicitSpecializationAfterInstantiation = 15597 RD->getTemplateSpecializationKind() != 15598 TSK_ExplicitSpecialization; 15599 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 15600 IsExplicitSpecializationAfterInstantiation = 15601 ED->getTemplateSpecializationKind() != 15602 TSK_ExplicitSpecialization; 15603 } 15604 15605 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do 15606 // not keep more that one definition around (merge them). However, 15607 // ensure the decl passes the structural compatibility check in 15608 // C11 6.2.7/1 (or 6.1.2.6/1 in C89). 15609 NamedDecl *Hidden = nullptr; 15610 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) { 15611 // There is a definition of this tag, but it is not visible. We 15612 // explicitly make use of C++'s one definition rule here, and 15613 // assume that this definition is identical to the hidden one 15614 // we already have. Make the existing definition visible and 15615 // use it in place of this one. 15616 if (!getLangOpts().CPlusPlus) { 15617 // Postpone making the old definition visible until after we 15618 // complete parsing the new one and do the structural 15619 // comparison. 15620 SkipBody->CheckSameAsPrevious = true; 15621 SkipBody->New = createTagFromNewDecl(); 15622 SkipBody->Previous = Def; 15623 return Def; 15624 } else { 15625 SkipBody->ShouldSkip = true; 15626 SkipBody->Previous = Def; 15627 makeMergedDefinitionVisible(Hidden); 15628 // Carry on and handle it like a normal definition. We'll 15629 // skip starting the definitiion later. 15630 } 15631 } else if (!IsExplicitSpecializationAfterInstantiation) { 15632 // A redeclaration in function prototype scope in C isn't 15633 // visible elsewhere, so merely issue a warning. 15634 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 15635 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 15636 else 15637 Diag(NameLoc, diag::err_redefinition) << Name; 15638 notePreviousDefinition(Def, 15639 NameLoc.isValid() ? NameLoc : KWLoc); 15640 // If this is a redefinition, recover by making this 15641 // struct be anonymous, which will make any later 15642 // references get the previous definition. 15643 Name = nullptr; 15644 Previous.clear(); 15645 Invalid = true; 15646 } 15647 } else { 15648 // If the type is currently being defined, complain 15649 // about a nested redefinition. 15650 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 15651 if (TD->isBeingDefined()) { 15652 Diag(NameLoc, diag::err_nested_redefinition) << Name; 15653 Diag(PrevTagDecl->getLocation(), 15654 diag::note_previous_definition); 15655 Name = nullptr; 15656 Previous.clear(); 15657 Invalid = true; 15658 } 15659 } 15660 15661 // Okay, this is definition of a previously declared or referenced 15662 // tag. We're going to create a new Decl for it. 15663 } 15664 15665 // Okay, we're going to make a redeclaration. If this is some kind 15666 // of reference, make sure we build the redeclaration in the same DC 15667 // as the original, and ignore the current access specifier. 15668 if (TUK == TUK_Friend || TUK == TUK_Reference) { 15669 SearchDC = PrevTagDecl->getDeclContext(); 15670 AS = AS_none; 15671 } 15672 } 15673 // If we get here we have (another) forward declaration or we 15674 // have a definition. Just create a new decl. 15675 15676 } else { 15677 // If we get here, this is a definition of a new tag type in a nested 15678 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 15679 // new decl/type. We set PrevDecl to NULL so that the entities 15680 // have distinct types. 15681 Previous.clear(); 15682 } 15683 // If we get here, we're going to create a new Decl. If PrevDecl 15684 // is non-NULL, it's a definition of the tag declared by 15685 // PrevDecl. If it's NULL, we have a new definition. 15686 15687 // Otherwise, PrevDecl is not a tag, but was found with tag 15688 // lookup. This is only actually possible in C++, where a few 15689 // things like templates still live in the tag namespace. 15690 } else { 15691 // Use a better diagnostic if an elaborated-type-specifier 15692 // found the wrong kind of type on the first 15693 // (non-redeclaration) lookup. 15694 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 15695 !Previous.isForRedeclaration()) { 15696 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15697 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK 15698 << Kind; 15699 Diag(PrevDecl->getLocation(), diag::note_declared_at); 15700 Invalid = true; 15701 15702 // Otherwise, only diagnose if the declaration is in scope. 15703 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 15704 SS.isNotEmpty() || isMemberSpecialization)) { 15705 // do nothing 15706 15707 // Diagnose implicit declarations introduced by elaborated types. 15708 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 15709 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind); 15710 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK; 15711 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15712 Invalid = true; 15713 15714 // Otherwise it's a declaration. Call out a particularly common 15715 // case here. 15716 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 15717 unsigned Kind = 0; 15718 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 15719 Diag(NameLoc, diag::err_tag_definition_of_typedef) 15720 << Name << Kind << TND->getUnderlyingType(); 15721 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 15722 Invalid = true; 15723 15724 // Otherwise, diagnose. 15725 } else { 15726 // The tag name clashes with something else in the target scope, 15727 // issue an error and recover by making this tag be anonymous. 15728 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 15729 notePreviousDefinition(PrevDecl, NameLoc); 15730 Name = nullptr; 15731 Invalid = true; 15732 } 15733 15734 // The existing declaration isn't relevant to us; we're in a 15735 // new scope, so clear out the previous declaration. 15736 Previous.clear(); 15737 } 15738 } 15739 15740 CreateNewDecl: 15741 15742 TagDecl *PrevDecl = nullptr; 15743 if (Previous.isSingleResult()) 15744 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 15745 15746 // If there is an identifier, use the location of the identifier as the 15747 // location of the decl, otherwise use the location of the struct/union 15748 // keyword. 15749 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 15750 15751 // Otherwise, create a new declaration. If there is a previous 15752 // declaration of the same entity, the two will be linked via 15753 // PrevDecl. 15754 TagDecl *New; 15755 15756 if (Kind == TTK_Enum) { 15757 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15758 // enum X { A, B, C } D; D should chain to X. 15759 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 15760 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 15761 ScopedEnumUsesClassTag, IsFixed); 15762 15763 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit())) 15764 StdAlignValT = cast<EnumDecl>(New); 15765 15766 // If this is an undefined enum, warn. 15767 if (TUK != TUK_Definition && !Invalid) { 15768 TagDecl *Def; 15769 if (IsFixed && cast<EnumDecl>(New)->isFixed()) { 15770 // C++0x: 7.2p2: opaque-enum-declaration. 15771 // Conflicts are diagnosed above. Do nothing. 15772 } 15773 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 15774 Diag(Loc, diag::ext_forward_ref_enum_def) 15775 << New; 15776 Diag(Def->getLocation(), diag::note_previous_definition); 15777 } else { 15778 unsigned DiagID = diag::ext_forward_ref_enum; 15779 if (getLangOpts().MSVCCompat) 15780 DiagID = diag::ext_ms_forward_ref_enum; 15781 else if (getLangOpts().CPlusPlus) 15782 DiagID = diag::err_forward_ref_enum; 15783 Diag(Loc, DiagID); 15784 } 15785 } 15786 15787 if (EnumUnderlying) { 15788 EnumDecl *ED = cast<EnumDecl>(New); 15789 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 15790 ED->setIntegerTypeSourceInfo(TI); 15791 else 15792 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 15793 ED->setPromotionType(ED->getIntegerType()); 15794 assert(ED->isComplete() && "enum with type should be complete"); 15795 } 15796 } else { 15797 // struct/union/class 15798 15799 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 15800 // struct X { int A; } D; D should chain to X. 15801 if (getLangOpts().CPlusPlus) { 15802 // FIXME: Look for a way to use RecordDecl for simple structs. 15803 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15804 cast_or_null<CXXRecordDecl>(PrevDecl)); 15805 15806 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 15807 StdBadAlloc = cast<CXXRecordDecl>(New); 15808 } else 15809 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 15810 cast_or_null<RecordDecl>(PrevDecl)); 15811 } 15812 15813 // C++11 [dcl.type]p3: 15814 // A type-specifier-seq shall not define a class or enumeration [...]. 15815 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) && 15816 TUK == TUK_Definition) { 15817 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 15818 << Context.getTagDeclType(New); 15819 Invalid = true; 15820 } 15821 15822 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition && 15823 DC->getDeclKind() == Decl::Enum) { 15824 Diag(New->getLocation(), diag::err_type_defined_in_enum) 15825 << Context.getTagDeclType(New); 15826 Invalid = true; 15827 } 15828 15829 // Maybe add qualifier info. 15830 if (SS.isNotEmpty()) { 15831 if (SS.isSet()) { 15832 // If this is either a declaration or a definition, check the 15833 // nested-name-specifier against the current context. 15834 if ((TUK == TUK_Definition || TUK == TUK_Declaration) && 15835 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc, 15836 isMemberSpecialization)) 15837 Invalid = true; 15838 15839 New->setQualifierInfo(SS.getWithLocInContext(Context)); 15840 if (TemplateParameterLists.size() > 0) { 15841 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 15842 } 15843 } 15844 else 15845 Invalid = true; 15846 } 15847 15848 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 15849 // Add alignment attributes if necessary; these attributes are checked when 15850 // the ASTContext lays out the structure. 15851 // 15852 // It is important for implementing the correct semantics that this 15853 // happen here (in ActOnTag). The #pragma pack stack is 15854 // maintained as a result of parser callbacks which can occur at 15855 // many points during the parsing of a struct declaration (because 15856 // the #pragma tokens are effectively skipped over during the 15857 // parsing of the struct). 15858 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) { 15859 AddAlignmentAttributesForRecord(RD); 15860 AddMsStructLayoutForRecord(RD); 15861 } 15862 } 15863 15864 if (ModulePrivateLoc.isValid()) { 15865 if (isMemberSpecialization) 15866 Diag(New->getLocation(), diag::err_module_private_specialization) 15867 << 2 15868 << FixItHint::CreateRemoval(ModulePrivateLoc); 15869 // __module_private__ does not apply to local classes. However, we only 15870 // diagnose this as an error when the declaration specifiers are 15871 // freestanding. Here, we just ignore the __module_private__. 15872 else if (!SearchDC->isFunctionOrMethod()) 15873 New->setModulePrivate(); 15874 } 15875 15876 // If this is a specialization of a member class (of a class template), 15877 // check the specialization. 15878 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous)) 15879 Invalid = true; 15880 15881 // If we're declaring or defining a tag in function prototype scope in C, 15882 // note that this type can only be used within the function and add it to 15883 // the list of decls to inject into the function definition scope. 15884 if ((Name || Kind == TTK_Enum) && 15885 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 15886 if (getLangOpts().CPlusPlus) { 15887 // C++ [dcl.fct]p6: 15888 // Types shall not be defined in return or parameter types. 15889 if (TUK == TUK_Definition && !IsTypeSpecifier) { 15890 Diag(Loc, diag::err_type_defined_in_param_type) 15891 << Name; 15892 Invalid = true; 15893 } 15894 } else if (!PrevDecl) { 15895 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 15896 } 15897 } 15898 15899 if (Invalid) 15900 New->setInvalidDecl(); 15901 15902 // Set the lexical context. If the tag has a C++ scope specifier, the 15903 // lexical context will be different from the semantic context. 15904 New->setLexicalDeclContext(CurContext); 15905 15906 // Mark this as a friend decl if applicable. 15907 // In Microsoft mode, a friend declaration also acts as a forward 15908 // declaration so we always pass true to setObjectOfFriendDecl to make 15909 // the tag name visible. 15910 if (TUK == TUK_Friend) 15911 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 15912 15913 // Set the access specifier. 15914 if (!Invalid && SearchDC->isRecord()) 15915 SetMemberAccessSpecifier(New, PrevDecl, AS); 15916 15917 if (PrevDecl) 15918 CheckRedeclarationModuleOwnership(New, PrevDecl); 15919 15920 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) 15921 New->startDefinition(); 15922 15923 ProcessDeclAttributeList(S, New, Attrs); 15924 AddPragmaAttributes(S, New); 15925 15926 // If this has an identifier, add it to the scope stack. 15927 if (TUK == TUK_Friend) { 15928 // We might be replacing an existing declaration in the lookup tables; 15929 // if so, borrow its access specifier. 15930 if (PrevDecl) 15931 New->setAccess(PrevDecl->getAccess()); 15932 15933 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 15934 DC->makeDeclVisibleInContext(New); 15935 if (Name) // can be null along some error paths 15936 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 15937 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 15938 } else if (Name) { 15939 S = getNonFieldDeclScope(S); 15940 PushOnScopeChains(New, S, true); 15941 } else { 15942 CurContext->addDecl(New); 15943 } 15944 15945 // If this is the C FILE type, notify the AST context. 15946 if (IdentifierInfo *II = New->getIdentifier()) 15947 if (!New->isInvalidDecl() && 15948 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 15949 II->isStr("FILE")) 15950 Context.setFILEDecl(New); 15951 15952 if (PrevDecl) 15953 mergeDeclAttributes(New, PrevDecl); 15954 15955 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New)) 15956 inferGslOwnerPointerAttribute(CXXRD); 15957 15958 // If there's a #pragma GCC visibility in scope, set the visibility of this 15959 // record. 15960 AddPushedVisibilityAttribute(New); 15961 15962 if (isMemberSpecialization && !New->isInvalidDecl()) 15963 CompleteMemberSpecialization(New, Previous); 15964 15965 OwnedDecl = true; 15966 // In C++, don't return an invalid declaration. We can't recover well from 15967 // the cases where we make the type anonymous. 15968 if (Invalid && getLangOpts().CPlusPlus) { 15969 if (New->isBeingDefined()) 15970 if (auto RD = dyn_cast<RecordDecl>(New)) 15971 RD->completeDefinition(); 15972 return nullptr; 15973 } else if (SkipBody && SkipBody->ShouldSkip) { 15974 return SkipBody->Previous; 15975 } else { 15976 return New; 15977 } 15978 } 15979 15980 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 15981 AdjustDeclIfTemplate(TagD); 15982 TagDecl *Tag = cast<TagDecl>(TagD); 15983 15984 // Enter the tag context. 15985 PushDeclContext(S, Tag); 15986 15987 ActOnDocumentableDecl(TagD); 15988 15989 // If there's a #pragma GCC visibility in scope, set the visibility of this 15990 // record. 15991 AddPushedVisibilityAttribute(Tag); 15992 } 15993 15994 bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, 15995 SkipBodyInfo &SkipBody) { 15996 if (!hasStructuralCompatLayout(Prev, SkipBody.New)) 15997 return false; 15998 15999 // Make the previous decl visible. 16000 makeMergedDefinitionVisible(SkipBody.Previous); 16001 return true; 16002 } 16003 16004 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 16005 assert(isa<ObjCContainerDecl>(IDecl) && 16006 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 16007 DeclContext *OCD = cast<DeclContext>(IDecl); 16008 assert(getContainingDC(OCD) == CurContext && 16009 "The next DeclContext should be lexically contained in the current one."); 16010 CurContext = OCD; 16011 return IDecl; 16012 } 16013 16014 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 16015 SourceLocation FinalLoc, 16016 bool IsFinalSpelledSealed, 16017 SourceLocation LBraceLoc) { 16018 AdjustDeclIfTemplate(TagD); 16019 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 16020 16021 FieldCollector->StartClass(); 16022 16023 if (!Record->getIdentifier()) 16024 return; 16025 16026 if (FinalLoc.isValid()) 16027 Record->addAttr(FinalAttr::Create( 16028 Context, FinalLoc, AttributeCommonInfo::AS_Keyword, 16029 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed))); 16030 16031 // C++ [class]p2: 16032 // [...] The class-name is also inserted into the scope of the 16033 // class itself; this is known as the injected-class-name. For 16034 // purposes of access checking, the injected-class-name is treated 16035 // as if it were a public member name. 16036 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create( 16037 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(), 16038 Record->getLocation(), Record->getIdentifier(), 16039 /*PrevDecl=*/nullptr, 16040 /*DelayTypeCreation=*/true); 16041 Context.getTypeDeclType(InjectedClassName, Record); 16042 InjectedClassName->setImplicit(); 16043 InjectedClassName->setAccess(AS_public); 16044 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 16045 InjectedClassName->setDescribedClassTemplate(Template); 16046 PushOnScopeChains(InjectedClassName, S); 16047 assert(InjectedClassName->isInjectedClassName() && 16048 "Broken injected-class-name"); 16049 } 16050 16051 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 16052 SourceRange BraceRange) { 16053 AdjustDeclIfTemplate(TagD); 16054 TagDecl *Tag = cast<TagDecl>(TagD); 16055 Tag->setBraceRange(BraceRange); 16056 16057 // Make sure we "complete" the definition even it is invalid. 16058 if (Tag->isBeingDefined()) { 16059 assert(Tag->isInvalidDecl() && "We should already have completed it"); 16060 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16061 RD->completeDefinition(); 16062 } 16063 16064 if (isa<CXXRecordDecl>(Tag)) { 16065 FieldCollector->FinishClass(); 16066 } 16067 16068 // Exit this scope of this tag's definition. 16069 PopDeclContext(); 16070 16071 if (getCurLexicalContext()->isObjCContainer() && 16072 Tag->getDeclContext()->isFileContext()) 16073 Tag->setTopLevelDeclInObjCContainer(); 16074 16075 // Notify the consumer that we've defined a tag. 16076 if (!Tag->isInvalidDecl()) 16077 Consumer.HandleTagDeclDefinition(Tag); 16078 } 16079 16080 void Sema::ActOnObjCContainerFinishDefinition() { 16081 // Exit this scope of this interface definition. 16082 PopDeclContext(); 16083 } 16084 16085 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 16086 assert(DC == CurContext && "Mismatch of container contexts"); 16087 OriginalLexicalContext = DC; 16088 ActOnObjCContainerFinishDefinition(); 16089 } 16090 16091 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 16092 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 16093 OriginalLexicalContext = nullptr; 16094 } 16095 16096 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 16097 AdjustDeclIfTemplate(TagD); 16098 TagDecl *Tag = cast<TagDecl>(TagD); 16099 Tag->setInvalidDecl(); 16100 16101 // Make sure we "complete" the definition even it is invalid. 16102 if (Tag->isBeingDefined()) { 16103 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 16104 RD->completeDefinition(); 16105 } 16106 16107 // We're undoing ActOnTagStartDefinition here, not 16108 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 16109 // the FieldCollector. 16110 16111 PopDeclContext(); 16112 } 16113 16114 // Note that FieldName may be null for anonymous bitfields. 16115 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 16116 IdentifierInfo *FieldName, 16117 QualType FieldTy, bool IsMsStruct, 16118 Expr *BitWidth, bool *ZeroWidth) { 16119 // Default to true; that shouldn't confuse checks for emptiness 16120 if (ZeroWidth) 16121 *ZeroWidth = true; 16122 16123 // C99 6.7.2.1p4 - verify the field type. 16124 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 16125 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 16126 // Handle incomplete types with specific error. 16127 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 16128 return ExprError(); 16129 if (FieldName) 16130 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 16131 << FieldName << FieldTy << BitWidth->getSourceRange(); 16132 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 16133 << FieldTy << BitWidth->getSourceRange(); 16134 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 16135 UPPC_BitFieldWidth)) 16136 return ExprError(); 16137 16138 // If the bit-width is type- or value-dependent, don't try to check 16139 // it now. 16140 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 16141 return BitWidth; 16142 16143 llvm::APSInt Value; 16144 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 16145 if (ICE.isInvalid()) 16146 return ICE; 16147 BitWidth = ICE.get(); 16148 16149 if (Value != 0 && ZeroWidth) 16150 *ZeroWidth = false; 16151 16152 // Zero-width bitfield is ok for anonymous field. 16153 if (Value == 0 && FieldName) 16154 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 16155 16156 if (Value.isSigned() && Value.isNegative()) { 16157 if (FieldName) 16158 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 16159 << FieldName << Value.toString(10); 16160 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 16161 << Value.toString(10); 16162 } 16163 16164 if (!FieldTy->isDependentType()) { 16165 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 16166 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 16167 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 16168 16169 // Over-wide bitfields are an error in C or when using the MSVC bitfield 16170 // ABI. 16171 bool CStdConstraintViolation = 16172 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 16173 bool MSBitfieldViolation = 16174 Value.ugt(TypeStorageSize) && 16175 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 16176 if (CStdConstraintViolation || MSBitfieldViolation) { 16177 unsigned DiagWidth = 16178 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 16179 if (FieldName) 16180 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 16181 << FieldName << (unsigned)Value.getZExtValue() 16182 << !CStdConstraintViolation << DiagWidth; 16183 16184 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 16185 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 16186 << DiagWidth; 16187 } 16188 16189 // Warn on types where the user might conceivably expect to get all 16190 // specified bits as value bits: that's all integral types other than 16191 // 'bool'. 16192 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 16193 if (FieldName) 16194 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 16195 << FieldName << (unsigned)Value.getZExtValue() 16196 << (unsigned)TypeWidth; 16197 else 16198 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 16199 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 16200 } 16201 } 16202 16203 return BitWidth; 16204 } 16205 16206 /// ActOnField - Each field of a C struct/union is passed into this in order 16207 /// to create a FieldDecl object for it. 16208 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 16209 Declarator &D, Expr *BitfieldWidth) { 16210 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 16211 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 16212 /*InitStyle=*/ICIS_NoInit, AS_public); 16213 return Res; 16214 } 16215 16216 /// HandleField - Analyze a field of a C struct or a C++ data member. 16217 /// 16218 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 16219 SourceLocation DeclStart, 16220 Declarator &D, Expr *BitWidth, 16221 InClassInitStyle InitStyle, 16222 AccessSpecifier AS) { 16223 if (D.isDecompositionDeclarator()) { 16224 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator(); 16225 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context) 16226 << Decomp.getSourceRange(); 16227 return nullptr; 16228 } 16229 16230 IdentifierInfo *II = D.getIdentifier(); 16231 SourceLocation Loc = DeclStart; 16232 if (II) Loc = D.getIdentifierLoc(); 16233 16234 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16235 QualType T = TInfo->getType(); 16236 if (getLangOpts().CPlusPlus) { 16237 CheckExtraCXXDefaultArguments(D); 16238 16239 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 16240 UPPC_DataMemberType)) { 16241 D.setInvalidType(); 16242 T = Context.IntTy; 16243 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 16244 } 16245 } 16246 16247 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 16248 16249 if (D.getDeclSpec().isInlineSpecified()) 16250 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function) 16251 << getLangOpts().CPlusPlus17; 16252 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 16253 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 16254 diag::err_invalid_thread) 16255 << DeclSpec::getSpecifierName(TSCS); 16256 16257 // Check to see if this name was declared as a member previously 16258 NamedDecl *PrevDecl = nullptr; 16259 LookupResult Previous(*this, II, Loc, LookupMemberName, 16260 ForVisibleRedeclaration); 16261 LookupName(Previous, S); 16262 switch (Previous.getResultKind()) { 16263 case LookupResult::Found: 16264 case LookupResult::FoundUnresolvedValue: 16265 PrevDecl = Previous.getAsSingle<NamedDecl>(); 16266 break; 16267 16268 case LookupResult::FoundOverloaded: 16269 PrevDecl = Previous.getRepresentativeDecl(); 16270 break; 16271 16272 case LookupResult::NotFound: 16273 case LookupResult::NotFoundInCurrentInstantiation: 16274 case LookupResult::Ambiguous: 16275 break; 16276 } 16277 Previous.suppressDiagnostics(); 16278 16279 if (PrevDecl && PrevDecl->isTemplateParameter()) { 16280 // Maybe we will complain about the shadowed template parameter. 16281 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 16282 // Just pretend that we didn't see the previous declaration. 16283 PrevDecl = nullptr; 16284 } 16285 16286 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 16287 PrevDecl = nullptr; 16288 16289 bool Mutable 16290 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 16291 SourceLocation TSSL = D.getBeginLoc(); 16292 FieldDecl *NewFD 16293 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 16294 TSSL, AS, PrevDecl, &D); 16295 16296 if (NewFD->isInvalidDecl()) 16297 Record->setInvalidDecl(); 16298 16299 if (D.getDeclSpec().isModulePrivateSpecified()) 16300 NewFD->setModulePrivate(); 16301 16302 if (NewFD->isInvalidDecl() && PrevDecl) { 16303 // Don't introduce NewFD into scope; there's already something 16304 // with the same name in the same scope. 16305 } else if (II) { 16306 PushOnScopeChains(NewFD, S); 16307 } else 16308 Record->addDecl(NewFD); 16309 16310 return NewFD; 16311 } 16312 16313 /// Build a new FieldDecl and check its well-formedness. 16314 /// 16315 /// This routine builds a new FieldDecl given the fields name, type, 16316 /// record, etc. \p PrevDecl should refer to any previous declaration 16317 /// with the same name and in the same scope as the field to be 16318 /// created. 16319 /// 16320 /// \returns a new FieldDecl. 16321 /// 16322 /// \todo The Declarator argument is a hack. It will be removed once 16323 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 16324 TypeSourceInfo *TInfo, 16325 RecordDecl *Record, SourceLocation Loc, 16326 bool Mutable, Expr *BitWidth, 16327 InClassInitStyle InitStyle, 16328 SourceLocation TSSL, 16329 AccessSpecifier AS, NamedDecl *PrevDecl, 16330 Declarator *D) { 16331 IdentifierInfo *II = Name.getAsIdentifierInfo(); 16332 bool InvalidDecl = false; 16333 if (D) InvalidDecl = D->isInvalidType(); 16334 16335 // If we receive a broken type, recover by assuming 'int' and 16336 // marking this declaration as invalid. 16337 if (T.isNull()) { 16338 InvalidDecl = true; 16339 T = Context.IntTy; 16340 } 16341 16342 QualType EltTy = Context.getBaseElementType(T); 16343 if (!EltTy->isDependentType()) { 16344 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 16345 // Fields of incomplete type force their record to be invalid. 16346 Record->setInvalidDecl(); 16347 InvalidDecl = true; 16348 } else { 16349 NamedDecl *Def; 16350 EltTy->isIncompleteType(&Def); 16351 if (Def && Def->isInvalidDecl()) { 16352 Record->setInvalidDecl(); 16353 InvalidDecl = true; 16354 } 16355 } 16356 } 16357 16358 // TR 18037 does not allow fields to be declared with address space 16359 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() || 16360 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) { 16361 Diag(Loc, diag::err_field_with_address_space); 16362 Record->setInvalidDecl(); 16363 InvalidDecl = true; 16364 } 16365 16366 if (LangOpts.OpenCL) { 16367 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be 16368 // used as structure or union field: image, sampler, event or block types. 16369 if (T->isEventT() || T->isImageType() || T->isSamplerT() || 16370 T->isBlockPointerType()) { 16371 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T; 16372 Record->setInvalidDecl(); 16373 InvalidDecl = true; 16374 } 16375 // OpenCL v1.2 s6.9.c: bitfields are not supported. 16376 if (BitWidth) { 16377 Diag(Loc, diag::err_opencl_bitfields); 16378 InvalidDecl = true; 16379 } 16380 } 16381 16382 // Anonymous bit-fields cannot be cv-qualified (CWG 2229). 16383 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth && 16384 T.hasQualifiers()) { 16385 InvalidDecl = true; 16386 Diag(Loc, diag::err_anon_bitfield_qualifiers); 16387 } 16388 16389 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16390 // than a variably modified type. 16391 if (!InvalidDecl && T->isVariablyModifiedType()) { 16392 bool SizeIsNegative; 16393 llvm::APSInt Oversized; 16394 16395 TypeSourceInfo *FixedTInfo = 16396 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 16397 SizeIsNegative, 16398 Oversized); 16399 if (FixedTInfo) { 16400 Diag(Loc, diag::warn_illegal_constant_array_size); 16401 TInfo = FixedTInfo; 16402 T = FixedTInfo->getType(); 16403 } else { 16404 if (SizeIsNegative) 16405 Diag(Loc, diag::err_typecheck_negative_array_size); 16406 else if (Oversized.getBoolValue()) 16407 Diag(Loc, diag::err_array_too_large) 16408 << Oversized.toString(10); 16409 else 16410 Diag(Loc, diag::err_typecheck_field_variable_size); 16411 InvalidDecl = true; 16412 } 16413 } 16414 16415 // Fields can not have abstract class types 16416 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 16417 diag::err_abstract_type_in_decl, 16418 AbstractFieldType)) 16419 InvalidDecl = true; 16420 16421 bool ZeroWidth = false; 16422 if (InvalidDecl) 16423 BitWidth = nullptr; 16424 // If this is declared as a bit-field, check the bit-field. 16425 if (BitWidth) { 16426 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 16427 &ZeroWidth).get(); 16428 if (!BitWidth) { 16429 InvalidDecl = true; 16430 BitWidth = nullptr; 16431 ZeroWidth = false; 16432 } 16433 } 16434 16435 // Check that 'mutable' is consistent with the type of the declaration. 16436 if (!InvalidDecl && Mutable) { 16437 unsigned DiagID = 0; 16438 if (T->isReferenceType()) 16439 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 16440 : diag::err_mutable_reference; 16441 else if (T.isConstQualified()) 16442 DiagID = diag::err_mutable_const; 16443 16444 if (DiagID) { 16445 SourceLocation ErrLoc = Loc; 16446 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 16447 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 16448 Diag(ErrLoc, DiagID); 16449 if (DiagID != diag::ext_mutable_reference) { 16450 Mutable = false; 16451 InvalidDecl = true; 16452 } 16453 } 16454 } 16455 16456 // C++11 [class.union]p8 (DR1460): 16457 // At most one variant member of a union may have a 16458 // brace-or-equal-initializer. 16459 if (InitStyle != ICIS_NoInit) 16460 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 16461 16462 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 16463 BitWidth, Mutable, InitStyle); 16464 if (InvalidDecl) 16465 NewFD->setInvalidDecl(); 16466 16467 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 16468 Diag(Loc, diag::err_duplicate_member) << II; 16469 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16470 NewFD->setInvalidDecl(); 16471 } 16472 16473 if (!InvalidDecl && getLangOpts().CPlusPlus) { 16474 if (Record->isUnion()) { 16475 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16476 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16477 if (RDecl->getDefinition()) { 16478 // C++ [class.union]p1: An object of a class with a non-trivial 16479 // constructor, a non-trivial copy constructor, a non-trivial 16480 // destructor, or a non-trivial copy assignment operator 16481 // cannot be a member of a union, nor can an array of such 16482 // objects. 16483 if (CheckNontrivialField(NewFD)) 16484 NewFD->setInvalidDecl(); 16485 } 16486 } 16487 16488 // C++ [class.union]p1: If a union contains a member of reference type, 16489 // the program is ill-formed, except when compiling with MSVC extensions 16490 // enabled. 16491 if (EltTy->isReferenceType()) { 16492 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 16493 diag::ext_union_member_of_reference_type : 16494 diag::err_union_member_of_reference_type) 16495 << NewFD->getDeclName() << EltTy; 16496 if (!getLangOpts().MicrosoftExt) 16497 NewFD->setInvalidDecl(); 16498 } 16499 } 16500 } 16501 16502 // FIXME: We need to pass in the attributes given an AST 16503 // representation, not a parser representation. 16504 if (D) { 16505 // FIXME: The current scope is almost... but not entirely... correct here. 16506 ProcessDeclAttributes(getCurScope(), NewFD, *D); 16507 16508 if (NewFD->hasAttrs()) 16509 CheckAlignasUnderalignment(NewFD); 16510 } 16511 16512 // In auto-retain/release, infer strong retension for fields of 16513 // retainable type. 16514 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 16515 NewFD->setInvalidDecl(); 16516 16517 if (T.isObjCGCWeak()) 16518 Diag(Loc, diag::warn_attribute_weak_on_field); 16519 16520 NewFD->setAccess(AS); 16521 return NewFD; 16522 } 16523 16524 bool Sema::CheckNontrivialField(FieldDecl *FD) { 16525 assert(FD); 16526 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 16527 16528 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 16529 return false; 16530 16531 QualType EltTy = Context.getBaseElementType(FD->getType()); 16532 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 16533 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 16534 if (RDecl->getDefinition()) { 16535 // We check for copy constructors before constructors 16536 // because otherwise we'll never get complaints about 16537 // copy constructors. 16538 16539 CXXSpecialMember member = CXXInvalid; 16540 // We're required to check for any non-trivial constructors. Since the 16541 // implicit default constructor is suppressed if there are any 16542 // user-declared constructors, we just need to check that there is a 16543 // trivial default constructor and a trivial copy constructor. (We don't 16544 // worry about move constructors here, since this is a C++98 check.) 16545 if (RDecl->hasNonTrivialCopyConstructor()) 16546 member = CXXCopyConstructor; 16547 else if (!RDecl->hasTrivialDefaultConstructor()) 16548 member = CXXDefaultConstructor; 16549 else if (RDecl->hasNonTrivialCopyAssignment()) 16550 member = CXXCopyAssignment; 16551 else if (RDecl->hasNonTrivialDestructor()) 16552 member = CXXDestructor; 16553 16554 if (member != CXXInvalid) { 16555 if (!getLangOpts().CPlusPlus11 && 16556 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 16557 // Objective-C++ ARC: it is an error to have a non-trivial field of 16558 // a union. However, system headers in Objective-C programs 16559 // occasionally have Objective-C lifetime objects within unions, 16560 // and rather than cause the program to fail, we make those 16561 // members unavailable. 16562 SourceLocation Loc = FD->getLocation(); 16563 if (getSourceManager().isInSystemHeader(Loc)) { 16564 if (!FD->hasAttr<UnavailableAttr>()) 16565 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 16566 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 16567 return false; 16568 } 16569 } 16570 16571 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 16572 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 16573 diag::err_illegal_union_or_anon_struct_member) 16574 << FD->getParent()->isUnion() << FD->getDeclName() << member; 16575 DiagnoseNontrivial(RDecl, member); 16576 return !getLangOpts().CPlusPlus11; 16577 } 16578 } 16579 } 16580 16581 return false; 16582 } 16583 16584 /// TranslateIvarVisibility - Translate visibility from a token ID to an 16585 /// AST enum value. 16586 static ObjCIvarDecl::AccessControl 16587 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 16588 switch (ivarVisibility) { 16589 default: llvm_unreachable("Unknown visitibility kind"); 16590 case tok::objc_private: return ObjCIvarDecl::Private; 16591 case tok::objc_public: return ObjCIvarDecl::Public; 16592 case tok::objc_protected: return ObjCIvarDecl::Protected; 16593 case tok::objc_package: return ObjCIvarDecl::Package; 16594 } 16595 } 16596 16597 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 16598 /// in order to create an IvarDecl object for it. 16599 Decl *Sema::ActOnIvar(Scope *S, 16600 SourceLocation DeclStart, 16601 Declarator &D, Expr *BitfieldWidth, 16602 tok::ObjCKeywordKind Visibility) { 16603 16604 IdentifierInfo *II = D.getIdentifier(); 16605 Expr *BitWidth = (Expr*)BitfieldWidth; 16606 SourceLocation Loc = DeclStart; 16607 if (II) Loc = D.getIdentifierLoc(); 16608 16609 // FIXME: Unnamed fields can be handled in various different ways, for 16610 // example, unnamed unions inject all members into the struct namespace! 16611 16612 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 16613 QualType T = TInfo->getType(); 16614 16615 if (BitWidth) { 16616 // 6.7.2.1p3, 6.7.2.1p4 16617 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 16618 if (!BitWidth) 16619 D.setInvalidType(); 16620 } else { 16621 // Not a bitfield. 16622 16623 // validate II. 16624 16625 } 16626 if (T->isReferenceType()) { 16627 Diag(Loc, diag::err_ivar_reference_type); 16628 D.setInvalidType(); 16629 } 16630 // C99 6.7.2.1p8: A member of a structure or union may have any type other 16631 // than a variably modified type. 16632 else if (T->isVariablyModifiedType()) { 16633 Diag(Loc, diag::err_typecheck_ivar_variable_size); 16634 D.setInvalidType(); 16635 } 16636 16637 // Get the visibility (access control) for this ivar. 16638 ObjCIvarDecl::AccessControl ac = 16639 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 16640 : ObjCIvarDecl::None; 16641 // Must set ivar's DeclContext to its enclosing interface. 16642 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 16643 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 16644 return nullptr; 16645 ObjCContainerDecl *EnclosingContext; 16646 if (ObjCImplementationDecl *IMPDecl = 16647 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 16648 if (LangOpts.ObjCRuntime.isFragile()) { 16649 // Case of ivar declared in an implementation. Context is that of its class. 16650 EnclosingContext = IMPDecl->getClassInterface(); 16651 assert(EnclosingContext && "Implementation has no class interface!"); 16652 } 16653 else 16654 EnclosingContext = EnclosingDecl; 16655 } else { 16656 if (ObjCCategoryDecl *CDecl = 16657 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 16658 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 16659 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 16660 return nullptr; 16661 } 16662 } 16663 EnclosingContext = EnclosingDecl; 16664 } 16665 16666 // Construct the decl. 16667 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 16668 DeclStart, Loc, II, T, 16669 TInfo, ac, (Expr *)BitfieldWidth); 16670 16671 if (II) { 16672 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 16673 ForVisibleRedeclaration); 16674 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 16675 && !isa<TagDecl>(PrevDecl)) { 16676 Diag(Loc, diag::err_duplicate_member) << II; 16677 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 16678 NewID->setInvalidDecl(); 16679 } 16680 } 16681 16682 // Process attributes attached to the ivar. 16683 ProcessDeclAttributes(S, NewID, D); 16684 16685 if (D.isInvalidType()) 16686 NewID->setInvalidDecl(); 16687 16688 // In ARC, infer 'retaining' for ivars of retainable type. 16689 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 16690 NewID->setInvalidDecl(); 16691 16692 if (D.getDeclSpec().isModulePrivateSpecified()) 16693 NewID->setModulePrivate(); 16694 16695 if (II) { 16696 // FIXME: When interfaces are DeclContexts, we'll need to add 16697 // these to the interface. 16698 S->AddDecl(NewID); 16699 IdResolver.AddDecl(NewID); 16700 } 16701 16702 if (LangOpts.ObjCRuntime.isNonFragile() && 16703 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 16704 Diag(Loc, diag::warn_ivars_in_interface); 16705 16706 return NewID; 16707 } 16708 16709 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 16710 /// class and class extensions. For every class \@interface and class 16711 /// extension \@interface, if the last ivar is a bitfield of any type, 16712 /// then add an implicit `char :0` ivar to the end of that interface. 16713 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 16714 SmallVectorImpl<Decl *> &AllIvarDecls) { 16715 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 16716 return; 16717 16718 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 16719 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 16720 16721 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context)) 16722 return; 16723 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 16724 if (!ID) { 16725 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 16726 if (!CD->IsClassExtension()) 16727 return; 16728 } 16729 // No need to add this to end of @implementation. 16730 else 16731 return; 16732 } 16733 // All conditions are met. Add a new bitfield to the tail end of ivars. 16734 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 16735 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 16736 16737 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 16738 DeclLoc, DeclLoc, nullptr, 16739 Context.CharTy, 16740 Context.getTrivialTypeSourceInfo(Context.CharTy, 16741 DeclLoc), 16742 ObjCIvarDecl::Private, BW, 16743 true); 16744 AllIvarDecls.push_back(Ivar); 16745 } 16746 16747 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 16748 ArrayRef<Decl *> Fields, SourceLocation LBrac, 16749 SourceLocation RBrac, 16750 const ParsedAttributesView &Attrs) { 16751 assert(EnclosingDecl && "missing record or interface decl"); 16752 16753 // If this is an Objective-C @implementation or category and we have 16754 // new fields here we should reset the layout of the interface since 16755 // it will now change. 16756 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 16757 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 16758 switch (DC->getKind()) { 16759 default: break; 16760 case Decl::ObjCCategory: 16761 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 16762 break; 16763 case Decl::ObjCImplementation: 16764 Context. 16765 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 16766 break; 16767 } 16768 } 16769 16770 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 16771 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl); 16772 16773 // Start counting up the number of named members; make sure to include 16774 // members of anonymous structs and unions in the total. 16775 unsigned NumNamedMembers = 0; 16776 if (Record) { 16777 for (const auto *I : Record->decls()) { 16778 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 16779 if (IFD->getDeclName()) 16780 ++NumNamedMembers; 16781 } 16782 } 16783 16784 // Verify that all the fields are okay. 16785 SmallVector<FieldDecl*, 32> RecFields; 16786 16787 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 16788 i != end; ++i) { 16789 FieldDecl *FD = cast<FieldDecl>(*i); 16790 16791 // Get the type for the field. 16792 const Type *FDTy = FD->getType().getTypePtr(); 16793 16794 if (!FD->isAnonymousStructOrUnion()) { 16795 // Remember all fields written by the user. 16796 RecFields.push_back(FD); 16797 } 16798 16799 // If the field is already invalid for some reason, don't emit more 16800 // diagnostics about it. 16801 if (FD->isInvalidDecl()) { 16802 EnclosingDecl->setInvalidDecl(); 16803 continue; 16804 } 16805 16806 // C99 6.7.2.1p2: 16807 // A structure or union shall not contain a member with 16808 // incomplete or function type (hence, a structure shall not 16809 // contain an instance of itself, but may contain a pointer to 16810 // an instance of itself), except that the last member of a 16811 // structure with more than one named member may have incomplete 16812 // array type; such a structure (and any union containing, 16813 // possibly recursively, a member that is such a structure) 16814 // shall not be a member of a structure or an element of an 16815 // array. 16816 bool IsLastField = (i + 1 == Fields.end()); 16817 if (FDTy->isFunctionType()) { 16818 // Field declared as a function. 16819 Diag(FD->getLocation(), diag::err_field_declared_as_function) 16820 << FD->getDeclName(); 16821 FD->setInvalidDecl(); 16822 EnclosingDecl->setInvalidDecl(); 16823 continue; 16824 } else if (FDTy->isIncompleteArrayType() && 16825 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) { 16826 if (Record) { 16827 // Flexible array member. 16828 // Microsoft and g++ is more permissive regarding flexible array. 16829 // It will accept flexible array in union and also 16830 // as the sole element of a struct/class. 16831 unsigned DiagID = 0; 16832 if (!Record->isUnion() && !IsLastField) { 16833 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end) 16834 << FD->getDeclName() << FD->getType() << Record->getTagKind(); 16835 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration); 16836 FD->setInvalidDecl(); 16837 EnclosingDecl->setInvalidDecl(); 16838 continue; 16839 } else if (Record->isUnion()) 16840 DiagID = getLangOpts().MicrosoftExt 16841 ? diag::ext_flexible_array_union_ms 16842 : getLangOpts().CPlusPlus 16843 ? diag::ext_flexible_array_union_gnu 16844 : diag::err_flexible_array_union; 16845 else if (NumNamedMembers < 1) 16846 DiagID = getLangOpts().MicrosoftExt 16847 ? diag::ext_flexible_array_empty_aggregate_ms 16848 : getLangOpts().CPlusPlus 16849 ? diag::ext_flexible_array_empty_aggregate_gnu 16850 : diag::err_flexible_array_empty_aggregate; 16851 16852 if (DiagID) 16853 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 16854 << Record->getTagKind(); 16855 // While the layout of types that contain virtual bases is not specified 16856 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 16857 // virtual bases after the derived members. This would make a flexible 16858 // array member declared at the end of an object not adjacent to the end 16859 // of the type. 16860 if (CXXRecord && CXXRecord->getNumVBases() != 0) 16861 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 16862 << FD->getDeclName() << Record->getTagKind(); 16863 if (!getLangOpts().C99) 16864 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 16865 << FD->getDeclName() << Record->getTagKind(); 16866 16867 // If the element type has a non-trivial destructor, we would not 16868 // implicitly destroy the elements, so disallow it for now. 16869 // 16870 // FIXME: GCC allows this. We should probably either implicitly delete 16871 // the destructor of the containing class, or just allow this. 16872 QualType BaseElem = Context.getBaseElementType(FD->getType()); 16873 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 16874 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 16875 << FD->getDeclName() << FD->getType(); 16876 FD->setInvalidDecl(); 16877 EnclosingDecl->setInvalidDecl(); 16878 continue; 16879 } 16880 // Okay, we have a legal flexible array member at the end of the struct. 16881 Record->setHasFlexibleArrayMember(true); 16882 } else { 16883 // In ObjCContainerDecl ivars with incomplete array type are accepted, 16884 // unless they are followed by another ivar. That check is done 16885 // elsewhere, after synthesized ivars are known. 16886 } 16887 } else if (!FDTy->isDependentType() && 16888 RequireCompleteType(FD->getLocation(), FD->getType(), 16889 diag::err_field_incomplete)) { 16890 // Incomplete type 16891 FD->setInvalidDecl(); 16892 EnclosingDecl->setInvalidDecl(); 16893 continue; 16894 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 16895 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 16896 // A type which contains a flexible array member is considered to be a 16897 // flexible array member. 16898 Record->setHasFlexibleArrayMember(true); 16899 if (!Record->isUnion()) { 16900 // If this is a struct/class and this is not the last element, reject 16901 // it. Note that GCC supports variable sized arrays in the middle of 16902 // structures. 16903 if (!IsLastField) 16904 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 16905 << FD->getDeclName() << FD->getType(); 16906 else { 16907 // We support flexible arrays at the end of structs in 16908 // other structs as an extension. 16909 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 16910 << FD->getDeclName(); 16911 } 16912 } 16913 } 16914 if (isa<ObjCContainerDecl>(EnclosingDecl) && 16915 RequireNonAbstractType(FD->getLocation(), FD->getType(), 16916 diag::err_abstract_type_in_decl, 16917 AbstractIvarType)) { 16918 // Ivars can not have abstract class types 16919 FD->setInvalidDecl(); 16920 } 16921 if (Record && FDTTy->getDecl()->hasObjectMember()) 16922 Record->setHasObjectMember(true); 16923 if (Record && FDTTy->getDecl()->hasVolatileMember()) 16924 Record->setHasVolatileMember(true); 16925 } else if (FDTy->isObjCObjectType()) { 16926 /// A field cannot be an Objective-c object 16927 Diag(FD->getLocation(), diag::err_statically_allocated_object) 16928 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 16929 QualType T = Context.getObjCObjectPointerType(FD->getType()); 16930 FD->setType(T); 16931 } else if (Record && Record->isUnion() && 16932 FD->getType().hasNonTrivialObjCLifetime() && 16933 getSourceManager().isInSystemHeader(FD->getLocation()) && 16934 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() && 16935 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong || 16936 !Context.hasDirectOwnershipQualifier(FD->getType()))) { 16937 // For backward compatibility, fields of C unions declared in system 16938 // headers that have non-trivial ObjC ownership qualifications are marked 16939 // as unavailable unless the qualifier is explicit and __strong. This can 16940 // break ABI compatibility between programs compiled with ARC and MRR, but 16941 // is a better option than rejecting programs using those unions under 16942 // ARC. 16943 FD->addAttr(UnavailableAttr::CreateImplicit( 16944 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership, 16945 FD->getLocation())); 16946 } else if (getLangOpts().ObjC && 16947 getLangOpts().getGC() != LangOptions::NonGC && 16948 Record && !Record->hasObjectMember()) { 16949 if (FD->getType()->isObjCObjectPointerType() || 16950 FD->getType().isObjCGCStrong()) 16951 Record->setHasObjectMember(true); 16952 else if (Context.getAsArrayType(FD->getType())) { 16953 QualType BaseType = Context.getBaseElementType(FD->getType()); 16954 if (BaseType->isRecordType() && 16955 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember()) 16956 Record->setHasObjectMember(true); 16957 else if (BaseType->isObjCObjectPointerType() || 16958 BaseType.isObjCGCStrong()) 16959 Record->setHasObjectMember(true); 16960 } 16961 } 16962 16963 if (Record && !getLangOpts().CPlusPlus && 16964 !shouldIgnoreForRecordTriviality(FD)) { 16965 QualType FT = FD->getType(); 16966 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) { 16967 Record->setNonTrivialToPrimitiveDefaultInitialize(true); 16968 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() || 16969 Record->isUnion()) 16970 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true); 16971 } 16972 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy(); 16973 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) { 16974 Record->setNonTrivialToPrimitiveCopy(true); 16975 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion()) 16976 Record->setHasNonTrivialToPrimitiveCopyCUnion(true); 16977 } 16978 if (FT.isDestructedType()) { 16979 Record->setNonTrivialToPrimitiveDestroy(true); 16980 Record->setParamDestroyedInCallee(true); 16981 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion()) 16982 Record->setHasNonTrivialToPrimitiveDestructCUnion(true); 16983 } 16984 16985 if (const auto *RT = FT->getAs<RecordType>()) { 16986 if (RT->getDecl()->getArgPassingRestrictions() == 16987 RecordDecl::APK_CanNeverPassInRegs) 16988 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16989 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak) 16990 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs); 16991 } 16992 16993 if (Record && FD->getType().isVolatileQualified()) 16994 Record->setHasVolatileMember(true); 16995 // Keep track of the number of named members. 16996 if (FD->getIdentifier()) 16997 ++NumNamedMembers; 16998 } 16999 17000 // Okay, we successfully defined 'Record'. 17001 if (Record) { 17002 bool Completed = false; 17003 if (CXXRecord) { 17004 if (!CXXRecord->isInvalidDecl()) { 17005 // Set access bits correctly on the directly-declared conversions. 17006 for (CXXRecordDecl::conversion_iterator 17007 I = CXXRecord->conversion_begin(), 17008 E = CXXRecord->conversion_end(); I != E; ++I) 17009 I.setAccess((*I)->getAccess()); 17010 } 17011 17012 if (!CXXRecord->isDependentType()) { 17013 // Add any implicitly-declared members to this class. 17014 AddImplicitlyDeclaredMembersToClass(CXXRecord); 17015 17016 if (!CXXRecord->isInvalidDecl()) { 17017 // If we have virtual base classes, we may end up finding multiple 17018 // final overriders for a given virtual function. Check for this 17019 // problem now. 17020 if (CXXRecord->getNumVBases()) { 17021 CXXFinalOverriderMap FinalOverriders; 17022 CXXRecord->getFinalOverriders(FinalOverriders); 17023 17024 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 17025 MEnd = FinalOverriders.end(); 17026 M != MEnd; ++M) { 17027 for (OverridingMethods::iterator SO = M->second.begin(), 17028 SOEnd = M->second.end(); 17029 SO != SOEnd; ++SO) { 17030 assert(SO->second.size() > 0 && 17031 "Virtual function without overriding functions?"); 17032 if (SO->second.size() == 1) 17033 continue; 17034 17035 // C++ [class.virtual]p2: 17036 // In a derived class, if a virtual member function of a base 17037 // class subobject has more than one final overrider the 17038 // program is ill-formed. 17039 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 17040 << (const NamedDecl *)M->first << Record; 17041 Diag(M->first->getLocation(), 17042 diag::note_overridden_virtual_function); 17043 for (OverridingMethods::overriding_iterator 17044 OM = SO->second.begin(), 17045 OMEnd = SO->second.end(); 17046 OM != OMEnd; ++OM) 17047 Diag(OM->Method->getLocation(), diag::note_final_overrider) 17048 << (const NamedDecl *)M->first << OM->Method->getParent(); 17049 17050 Record->setInvalidDecl(); 17051 } 17052 } 17053 CXXRecord->completeDefinition(&FinalOverriders); 17054 Completed = true; 17055 } 17056 } 17057 } 17058 } 17059 17060 if (!Completed) 17061 Record->completeDefinition(); 17062 17063 // Handle attributes before checking the layout. 17064 ProcessDeclAttributeList(S, Record, Attrs); 17065 17066 // We may have deferred checking for a deleted destructor. Check now. 17067 if (CXXRecord) { 17068 auto *Dtor = CXXRecord->getDestructor(); 17069 if (Dtor && Dtor->isImplicit() && 17070 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) { 17071 CXXRecord->setImplicitDestructorIsDeleted(); 17072 SetDeclDeleted(Dtor, CXXRecord->getLocation()); 17073 } 17074 } 17075 17076 if (Record->hasAttrs()) { 17077 CheckAlignasUnderalignment(Record); 17078 17079 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 17080 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 17081 IA->getRange(), IA->getBestCase(), 17082 IA->getInheritanceModel()); 17083 } 17084 17085 // Check if the structure/union declaration is a type that can have zero 17086 // size in C. For C this is a language extension, for C++ it may cause 17087 // compatibility problems. 17088 bool CheckForZeroSize; 17089 if (!getLangOpts().CPlusPlus) { 17090 CheckForZeroSize = true; 17091 } else { 17092 // For C++ filter out types that cannot be referenced in C code. 17093 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 17094 CheckForZeroSize = 17095 CXXRecord->getLexicalDeclContext()->isExternCContext() && 17096 !CXXRecord->isDependentType() && 17097 CXXRecord->isCLike(); 17098 } 17099 if (CheckForZeroSize) { 17100 bool ZeroSize = true; 17101 bool IsEmpty = true; 17102 unsigned NonBitFields = 0; 17103 for (RecordDecl::field_iterator I = Record->field_begin(), 17104 E = Record->field_end(); 17105 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 17106 IsEmpty = false; 17107 if (I->isUnnamedBitfield()) { 17108 if (!I->isZeroLengthBitField(Context)) 17109 ZeroSize = false; 17110 } else { 17111 ++NonBitFields; 17112 QualType FieldType = I->getType(); 17113 if (FieldType->isIncompleteType() || 17114 !Context.getTypeSizeInChars(FieldType).isZero()) 17115 ZeroSize = false; 17116 } 17117 } 17118 17119 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 17120 // allowed in C++, but warn if its declaration is inside 17121 // extern "C" block. 17122 if (ZeroSize) { 17123 Diag(RecLoc, getLangOpts().CPlusPlus ? 17124 diag::warn_zero_size_struct_union_in_extern_c : 17125 diag::warn_zero_size_struct_union_compat) 17126 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 17127 } 17128 17129 // Structs without named members are extension in C (C99 6.7.2.1p7), 17130 // but are accepted by GCC. 17131 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 17132 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 17133 diag::ext_no_named_members_in_struct_union) 17134 << Record->isUnion(); 17135 } 17136 } 17137 } else { 17138 ObjCIvarDecl **ClsFields = 17139 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 17140 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 17141 ID->setEndOfDefinitionLoc(RBrac); 17142 // Add ivar's to class's DeclContext. 17143 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17144 ClsFields[i]->setLexicalDeclContext(ID); 17145 ID->addDecl(ClsFields[i]); 17146 } 17147 // Must enforce the rule that ivars in the base classes may not be 17148 // duplicates. 17149 if (ID->getSuperClass()) 17150 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 17151 } else if (ObjCImplementationDecl *IMPDecl = 17152 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 17153 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 17154 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 17155 // Ivar declared in @implementation never belongs to the implementation. 17156 // Only it is in implementation's lexical context. 17157 ClsFields[I]->setLexicalDeclContext(IMPDecl); 17158 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 17159 IMPDecl->setIvarLBraceLoc(LBrac); 17160 IMPDecl->setIvarRBraceLoc(RBrac); 17161 } else if (ObjCCategoryDecl *CDecl = 17162 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 17163 // case of ivars in class extension; all other cases have been 17164 // reported as errors elsewhere. 17165 // FIXME. Class extension does not have a LocEnd field. 17166 // CDecl->setLocEnd(RBrac); 17167 // Add ivar's to class extension's DeclContext. 17168 // Diagnose redeclaration of private ivars. 17169 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 17170 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 17171 if (IDecl) { 17172 if (const ObjCIvarDecl *ClsIvar = 17173 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 17174 Diag(ClsFields[i]->getLocation(), 17175 diag::err_duplicate_ivar_declaration); 17176 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 17177 continue; 17178 } 17179 for (const auto *Ext : IDecl->known_extensions()) { 17180 if (const ObjCIvarDecl *ClsExtIvar 17181 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 17182 Diag(ClsFields[i]->getLocation(), 17183 diag::err_duplicate_ivar_declaration); 17184 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 17185 continue; 17186 } 17187 } 17188 } 17189 ClsFields[i]->setLexicalDeclContext(CDecl); 17190 CDecl->addDecl(ClsFields[i]); 17191 } 17192 CDecl->setIvarLBraceLoc(LBrac); 17193 CDecl->setIvarRBraceLoc(RBrac); 17194 } 17195 } 17196 } 17197 17198 /// Determine whether the given integral value is representable within 17199 /// the given type T. 17200 static bool isRepresentableIntegerValue(ASTContext &Context, 17201 llvm::APSInt &Value, 17202 QualType T) { 17203 assert((T->isIntegralType(Context) || T->isEnumeralType()) && 17204 "Integral type required!"); 17205 unsigned BitWidth = Context.getIntWidth(T); 17206 17207 if (Value.isUnsigned() || Value.isNonNegative()) { 17208 if (T->isSignedIntegerOrEnumerationType()) 17209 --BitWidth; 17210 return Value.getActiveBits() <= BitWidth; 17211 } 17212 return Value.getMinSignedBits() <= BitWidth; 17213 } 17214 17215 // Given an integral type, return the next larger integral type 17216 // (or a NULL type of no such type exists). 17217 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 17218 // FIXME: Int128/UInt128 support, which also needs to be introduced into 17219 // enum checking below. 17220 assert((T->isIntegralType(Context) || 17221 T->isEnumeralType()) && "Integral type required!"); 17222 const unsigned NumTypes = 4; 17223 QualType SignedIntegralTypes[NumTypes] = { 17224 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 17225 }; 17226 QualType UnsignedIntegralTypes[NumTypes] = { 17227 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 17228 Context.UnsignedLongLongTy 17229 }; 17230 17231 unsigned BitWidth = Context.getTypeSize(T); 17232 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 17233 : UnsignedIntegralTypes; 17234 for (unsigned I = 0; I != NumTypes; ++I) 17235 if (Context.getTypeSize(Types[I]) > BitWidth) 17236 return Types[I]; 17237 17238 return QualType(); 17239 } 17240 17241 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 17242 EnumConstantDecl *LastEnumConst, 17243 SourceLocation IdLoc, 17244 IdentifierInfo *Id, 17245 Expr *Val) { 17246 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17247 llvm::APSInt EnumVal(IntWidth); 17248 QualType EltTy; 17249 17250 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 17251 Val = nullptr; 17252 17253 if (Val) 17254 Val = DefaultLvalueConversion(Val).get(); 17255 17256 if (Val) { 17257 if (Enum->isDependentType() || Val->isTypeDependent()) 17258 EltTy = Context.DependentTy; 17259 else { 17260 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) { 17261 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 17262 // constant-expression in the enumerator-definition shall be a converted 17263 // constant expression of the underlying type. 17264 EltTy = Enum->getIntegerType(); 17265 ExprResult Converted = 17266 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 17267 CCEK_Enumerator); 17268 if (Converted.isInvalid()) 17269 Val = nullptr; 17270 else 17271 Val = Converted.get(); 17272 } else if (!Val->isValueDependent() && 17273 !(Val = VerifyIntegerConstantExpression(Val, 17274 &EnumVal).get())) { 17275 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 17276 } else { 17277 if (Enum->isComplete()) { 17278 EltTy = Enum->getIntegerType(); 17279 17280 // In Obj-C and Microsoft mode, require the enumeration value to be 17281 // representable in the underlying type of the enumeration. In C++11, 17282 // we perform a non-narrowing conversion as part of converted constant 17283 // expression checking. 17284 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17285 if (Context.getTargetInfo() 17286 .getTriple() 17287 .isWindowsMSVCEnvironment()) { 17288 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 17289 } else { 17290 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 17291 } 17292 } 17293 17294 // Cast to the underlying type. 17295 Val = ImpCastExprToType(Val, EltTy, 17296 EltTy->isBooleanType() ? CK_IntegralToBoolean 17297 : CK_IntegralCast) 17298 .get(); 17299 } else if (getLangOpts().CPlusPlus) { 17300 // C++11 [dcl.enum]p5: 17301 // If the underlying type is not fixed, the type of each enumerator 17302 // is the type of its initializing value: 17303 // - If an initializer is specified for an enumerator, the 17304 // initializing value has the same type as the expression. 17305 EltTy = Val->getType(); 17306 } else { 17307 // C99 6.7.2.2p2: 17308 // The expression that defines the value of an enumeration constant 17309 // shall be an integer constant expression that has a value 17310 // representable as an int. 17311 17312 // Complain if the value is not representable in an int. 17313 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 17314 Diag(IdLoc, diag::ext_enum_value_not_int) 17315 << EnumVal.toString(10) << Val->getSourceRange() 17316 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 17317 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 17318 // Force the type of the expression to 'int'. 17319 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 17320 } 17321 EltTy = Val->getType(); 17322 } 17323 } 17324 } 17325 } 17326 17327 if (!Val) { 17328 if (Enum->isDependentType()) 17329 EltTy = Context.DependentTy; 17330 else if (!LastEnumConst) { 17331 // C++0x [dcl.enum]p5: 17332 // If the underlying type is not fixed, the type of each enumerator 17333 // is the type of its initializing value: 17334 // - If no initializer is specified for the first enumerator, the 17335 // initializing value has an unspecified integral type. 17336 // 17337 // GCC uses 'int' for its unspecified integral type, as does 17338 // C99 6.7.2.2p3. 17339 if (Enum->isFixed()) { 17340 EltTy = Enum->getIntegerType(); 17341 } 17342 else { 17343 EltTy = Context.IntTy; 17344 } 17345 } else { 17346 // Assign the last value + 1. 17347 EnumVal = LastEnumConst->getInitVal(); 17348 ++EnumVal; 17349 EltTy = LastEnumConst->getType(); 17350 17351 // Check for overflow on increment. 17352 if (EnumVal < LastEnumConst->getInitVal()) { 17353 // C++0x [dcl.enum]p5: 17354 // If the underlying type is not fixed, the type of each enumerator 17355 // is the type of its initializing value: 17356 // 17357 // - Otherwise the type of the initializing value is the same as 17358 // the type of the initializing value of the preceding enumerator 17359 // unless the incremented value is not representable in that type, 17360 // in which case the type is an unspecified integral type 17361 // sufficient to contain the incremented value. If no such type 17362 // exists, the program is ill-formed. 17363 QualType T = getNextLargerIntegralType(Context, EltTy); 17364 if (T.isNull() || Enum->isFixed()) { 17365 // There is no integral type larger enough to represent this 17366 // value. Complain, then allow the value to wrap around. 17367 EnumVal = LastEnumConst->getInitVal(); 17368 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 17369 ++EnumVal; 17370 if (Enum->isFixed()) 17371 // When the underlying type is fixed, this is ill-formed. 17372 Diag(IdLoc, diag::err_enumerator_wrapped) 17373 << EnumVal.toString(10) 17374 << EltTy; 17375 else 17376 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 17377 << EnumVal.toString(10); 17378 } else { 17379 EltTy = T; 17380 } 17381 17382 // Retrieve the last enumerator's value, extent that type to the 17383 // type that is supposed to be large enough to represent the incremented 17384 // value, then increment. 17385 EnumVal = LastEnumConst->getInitVal(); 17386 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17387 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 17388 ++EnumVal; 17389 17390 // If we're not in C++, diagnose the overflow of enumerator values, 17391 // which in C99 means that the enumerator value is not representable in 17392 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 17393 // permits enumerator values that are representable in some larger 17394 // integral type. 17395 if (!getLangOpts().CPlusPlus && !T.isNull()) 17396 Diag(IdLoc, diag::warn_enum_value_overflow); 17397 } else if (!getLangOpts().CPlusPlus && 17398 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 17399 // Enforce C99 6.7.2.2p2 even when we compute the next value. 17400 Diag(IdLoc, diag::ext_enum_value_not_int) 17401 << EnumVal.toString(10) << 1; 17402 } 17403 } 17404 } 17405 17406 if (!EltTy->isDependentType()) { 17407 // Make the enumerator value match the signedness and size of the 17408 // enumerator's type. 17409 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 17410 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 17411 } 17412 17413 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 17414 Val, EnumVal); 17415 } 17416 17417 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 17418 SourceLocation IILoc) { 17419 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 17420 !getLangOpts().CPlusPlus) 17421 return SkipBodyInfo(); 17422 17423 // We have an anonymous enum definition. Look up the first enumerator to 17424 // determine if we should merge the definition with an existing one and 17425 // skip the body. 17426 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 17427 forRedeclarationInCurContext()); 17428 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 17429 if (!PrevECD) 17430 return SkipBodyInfo(); 17431 17432 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 17433 NamedDecl *Hidden; 17434 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 17435 SkipBodyInfo Skip; 17436 Skip.Previous = Hidden; 17437 return Skip; 17438 } 17439 17440 return SkipBodyInfo(); 17441 } 17442 17443 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 17444 SourceLocation IdLoc, IdentifierInfo *Id, 17445 const ParsedAttributesView &Attrs, 17446 SourceLocation EqualLoc, Expr *Val) { 17447 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 17448 EnumConstantDecl *LastEnumConst = 17449 cast_or_null<EnumConstantDecl>(lastEnumConst); 17450 17451 // The scope passed in may not be a decl scope. Zip up the scope tree until 17452 // we find one that is. 17453 S = getNonFieldDeclScope(S); 17454 17455 // Verify that there isn't already something declared with this name in this 17456 // scope. 17457 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration); 17458 LookupName(R, S); 17459 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>(); 17460 17461 if (PrevDecl && PrevDecl->isTemplateParameter()) { 17462 // Maybe we will complain about the shadowed template parameter. 17463 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 17464 // Just pretend that we didn't see the previous declaration. 17465 PrevDecl = nullptr; 17466 } 17467 17468 // C++ [class.mem]p15: 17469 // If T is the name of a class, then each of the following shall have a name 17470 // different from T: 17471 // - every enumerator of every member of class T that is an unscoped 17472 // enumerated type 17473 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped()) 17474 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 17475 DeclarationNameInfo(Id, IdLoc)); 17476 17477 EnumConstantDecl *New = 17478 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 17479 if (!New) 17480 return nullptr; 17481 17482 if (PrevDecl) { 17483 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) { 17484 // Check for other kinds of shadowing not already handled. 17485 CheckShadow(New, PrevDecl, R); 17486 } 17487 17488 // When in C++, we may get a TagDecl with the same name; in this case the 17489 // enum constant will 'hide' the tag. 17490 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 17491 "Received TagDecl when not in C++!"); 17492 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 17493 if (isa<EnumConstantDecl>(PrevDecl)) 17494 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 17495 else 17496 Diag(IdLoc, diag::err_redefinition) << Id; 17497 notePreviousDefinition(PrevDecl, IdLoc); 17498 return nullptr; 17499 } 17500 } 17501 17502 // Process attributes. 17503 ProcessDeclAttributeList(S, New, Attrs); 17504 AddPragmaAttributes(S, New); 17505 17506 // Register this decl in the current scope stack. 17507 New->setAccess(TheEnumDecl->getAccess()); 17508 PushOnScopeChains(New, S); 17509 17510 ActOnDocumentableDecl(New); 17511 17512 return New; 17513 } 17514 17515 // Returns true when the enum initial expression does not trigger the 17516 // duplicate enum warning. A few common cases are exempted as follows: 17517 // Element2 = Element1 17518 // Element2 = Element1 + 1 17519 // Element2 = Element1 - 1 17520 // Where Element2 and Element1 are from the same enum. 17521 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 17522 Expr *InitExpr = ECD->getInitExpr(); 17523 if (!InitExpr) 17524 return true; 17525 InitExpr = InitExpr->IgnoreImpCasts(); 17526 17527 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 17528 if (!BO->isAdditiveOp()) 17529 return true; 17530 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 17531 if (!IL) 17532 return true; 17533 if (IL->getValue() != 1) 17534 return true; 17535 17536 InitExpr = BO->getLHS(); 17537 } 17538 17539 // This checks if the elements are from the same enum. 17540 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 17541 if (!DRE) 17542 return true; 17543 17544 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 17545 if (!EnumConstant) 17546 return true; 17547 17548 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 17549 Enum) 17550 return true; 17551 17552 return false; 17553 } 17554 17555 // Emits a warning when an element is implicitly set a value that 17556 // a previous element has already been set to. 17557 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 17558 EnumDecl *Enum, QualType EnumType) { 17559 // Avoid anonymous enums 17560 if (!Enum->getIdentifier()) 17561 return; 17562 17563 // Only check for small enums. 17564 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 17565 return; 17566 17567 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 17568 return; 17569 17570 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 17571 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector; 17572 17573 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 17574 17575 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map. 17576 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap; 17577 17578 // Use int64_t as a key to avoid needing special handling for map keys. 17579 auto EnumConstantToKey = [](const EnumConstantDecl *D) { 17580 llvm::APSInt Val = D->getInitVal(); 17581 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(); 17582 }; 17583 17584 DuplicatesVector DupVector; 17585 ValueToVectorMap EnumMap; 17586 17587 // Populate the EnumMap with all values represented by enum constants without 17588 // an initializer. 17589 for (auto *Element : Elements) { 17590 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element); 17591 17592 // Null EnumConstantDecl means a previous diagnostic has been emitted for 17593 // this constant. Skip this enum since it may be ill-formed. 17594 if (!ECD) { 17595 return; 17596 } 17597 17598 // Constants with initalizers are handled in the next loop. 17599 if (ECD->getInitExpr()) 17600 continue; 17601 17602 // Duplicate values are handled in the next loop. 17603 EnumMap.insert({EnumConstantToKey(ECD), ECD}); 17604 } 17605 17606 if (EnumMap.size() == 0) 17607 return; 17608 17609 // Create vectors for any values that has duplicates. 17610 for (auto *Element : Elements) { 17611 // The last loop returned if any constant was null. 17612 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element); 17613 if (!ValidDuplicateEnum(ECD, Enum)) 17614 continue; 17615 17616 auto Iter = EnumMap.find(EnumConstantToKey(ECD)); 17617 if (Iter == EnumMap.end()) 17618 continue; 17619 17620 DeclOrVector& Entry = Iter->second; 17621 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 17622 // Ensure constants are different. 17623 if (D == ECD) 17624 continue; 17625 17626 // Create new vector and push values onto it. 17627 auto Vec = std::make_unique<ECDVector>(); 17628 Vec->push_back(D); 17629 Vec->push_back(ECD); 17630 17631 // Update entry to point to the duplicates vector. 17632 Entry = Vec.get(); 17633 17634 // Store the vector somewhere we can consult later for quick emission of 17635 // diagnostics. 17636 DupVector.emplace_back(std::move(Vec)); 17637 continue; 17638 } 17639 17640 ECDVector *Vec = Entry.get<ECDVector*>(); 17641 // Make sure constants are not added more than once. 17642 if (*Vec->begin() == ECD) 17643 continue; 17644 17645 Vec->push_back(ECD); 17646 } 17647 17648 // Emit diagnostics. 17649 for (const auto &Vec : DupVector) { 17650 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 17651 17652 // Emit warning for one enum constant. 17653 auto *FirstECD = Vec->front(); 17654 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values) 17655 << FirstECD << FirstECD->getInitVal().toString(10) 17656 << FirstECD->getSourceRange(); 17657 17658 // Emit one note for each of the remaining enum constants with 17659 // the same value. 17660 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end())) 17661 S.Diag(ECD->getLocation(), diag::note_duplicate_element) 17662 << ECD << ECD->getInitVal().toString(10) 17663 << ECD->getSourceRange(); 17664 } 17665 } 17666 17667 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 17668 bool AllowMask) const { 17669 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum"); 17670 assert(ED->isCompleteDefinition() && "expected enum definition"); 17671 17672 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 17673 llvm::APInt &FlagBits = R.first->second; 17674 17675 if (R.second) { 17676 for (auto *E : ED->enumerators()) { 17677 const auto &EVal = E->getInitVal(); 17678 // Only single-bit enumerators introduce new flag values. 17679 if (EVal.isPowerOf2()) 17680 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 17681 } 17682 } 17683 17684 // A value is in a flag enum if either its bits are a subset of the enum's 17685 // flag bits (the first condition) or we are allowing masks and the same is 17686 // true of its complement (the second condition). When masks are allowed, we 17687 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 17688 // 17689 // While it's true that any value could be used as a mask, the assumption is 17690 // that a mask will have all of the insignificant bits set. Anything else is 17691 // likely a logic error. 17692 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 17693 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 17694 } 17695 17696 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, 17697 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S, 17698 const ParsedAttributesView &Attrs) { 17699 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 17700 QualType EnumType = Context.getTypeDeclType(Enum); 17701 17702 ProcessDeclAttributeList(S, Enum, Attrs); 17703 17704 if (Enum->isDependentType()) { 17705 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17706 EnumConstantDecl *ECD = 17707 cast_or_null<EnumConstantDecl>(Elements[i]); 17708 if (!ECD) continue; 17709 17710 ECD->setType(EnumType); 17711 } 17712 17713 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 17714 return; 17715 } 17716 17717 // TODO: If the result value doesn't fit in an int, it must be a long or long 17718 // long value. ISO C does not support this, but GCC does as an extension, 17719 // emit a warning. 17720 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 17721 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 17722 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 17723 17724 // Verify that all the values are okay, compute the size of the values, and 17725 // reverse the list. 17726 unsigned NumNegativeBits = 0; 17727 unsigned NumPositiveBits = 0; 17728 17729 // Keep track of whether all elements have type int. 17730 bool AllElementsInt = true; 17731 17732 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 17733 EnumConstantDecl *ECD = 17734 cast_or_null<EnumConstantDecl>(Elements[i]); 17735 if (!ECD) continue; // Already issued a diagnostic. 17736 17737 const llvm::APSInt &InitVal = ECD->getInitVal(); 17738 17739 // Keep track of the size of positive and negative values. 17740 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 17741 NumPositiveBits = std::max(NumPositiveBits, 17742 (unsigned)InitVal.getActiveBits()); 17743 else 17744 NumNegativeBits = std::max(NumNegativeBits, 17745 (unsigned)InitVal.getMinSignedBits()); 17746 17747 // Keep track of whether every enum element has type int (very common). 17748 if (AllElementsInt) 17749 AllElementsInt = ECD->getType() == Context.IntTy; 17750 } 17751 17752 // Figure out the type that should be used for this enum. 17753 QualType BestType; 17754 unsigned BestWidth; 17755 17756 // C++0x N3000 [conv.prom]p3: 17757 // An rvalue of an unscoped enumeration type whose underlying 17758 // type is not fixed can be converted to an rvalue of the first 17759 // of the following types that can represent all the values of 17760 // the enumeration: int, unsigned int, long int, unsigned long 17761 // int, long long int, or unsigned long long int. 17762 // C99 6.4.4.3p2: 17763 // An identifier declared as an enumeration constant has type int. 17764 // The C99 rule is modified by a gcc extension 17765 QualType BestPromotionType; 17766 17767 bool Packed = Enum->hasAttr<PackedAttr>(); 17768 // -fshort-enums is the equivalent to specifying the packed attribute on all 17769 // enum definitions. 17770 if (LangOpts.ShortEnums) 17771 Packed = true; 17772 17773 // If the enum already has a type because it is fixed or dictated by the 17774 // target, promote that type instead of analyzing the enumerators. 17775 if (Enum->isComplete()) { 17776 BestType = Enum->getIntegerType(); 17777 if (BestType->isPromotableIntegerType()) 17778 BestPromotionType = Context.getPromotedIntegerType(BestType); 17779 else 17780 BestPromotionType = BestType; 17781 17782 BestWidth = Context.getIntWidth(BestType); 17783 } 17784 else if (NumNegativeBits) { 17785 // If there is a negative value, figure out the smallest integer type (of 17786 // int/long/longlong) that fits. 17787 // If it's packed, check also if it fits a char or a short. 17788 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 17789 BestType = Context.SignedCharTy; 17790 BestWidth = CharWidth; 17791 } else if (Packed && NumNegativeBits <= ShortWidth && 17792 NumPositiveBits < ShortWidth) { 17793 BestType = Context.ShortTy; 17794 BestWidth = ShortWidth; 17795 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 17796 BestType = Context.IntTy; 17797 BestWidth = IntWidth; 17798 } else { 17799 BestWidth = Context.getTargetInfo().getLongWidth(); 17800 17801 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 17802 BestType = Context.LongTy; 17803 } else { 17804 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17805 17806 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 17807 Diag(Enum->getLocation(), diag::ext_enum_too_large); 17808 BestType = Context.LongLongTy; 17809 } 17810 } 17811 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 17812 } else { 17813 // If there is no negative value, figure out the smallest type that fits 17814 // all of the enumerator values. 17815 // If it's packed, check also if it fits a char or a short. 17816 if (Packed && NumPositiveBits <= CharWidth) { 17817 BestType = Context.UnsignedCharTy; 17818 BestPromotionType = Context.IntTy; 17819 BestWidth = CharWidth; 17820 } else if (Packed && NumPositiveBits <= ShortWidth) { 17821 BestType = Context.UnsignedShortTy; 17822 BestPromotionType = Context.IntTy; 17823 BestWidth = ShortWidth; 17824 } else if (NumPositiveBits <= IntWidth) { 17825 BestType = Context.UnsignedIntTy; 17826 BestWidth = IntWidth; 17827 BestPromotionType 17828 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17829 ? Context.UnsignedIntTy : Context.IntTy; 17830 } else if (NumPositiveBits <= 17831 (BestWidth = Context.getTargetInfo().getLongWidth())) { 17832 BestType = Context.UnsignedLongTy; 17833 BestPromotionType 17834 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17835 ? Context.UnsignedLongTy : Context.LongTy; 17836 } else { 17837 BestWidth = Context.getTargetInfo().getLongLongWidth(); 17838 assert(NumPositiveBits <= BestWidth && 17839 "How could an initializer get larger than ULL?"); 17840 BestType = Context.UnsignedLongLongTy; 17841 BestPromotionType 17842 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 17843 ? Context.UnsignedLongLongTy : Context.LongLongTy; 17844 } 17845 } 17846 17847 // Loop over all of the enumerator constants, changing their types to match 17848 // the type of the enum if needed. 17849 for (auto *D : Elements) { 17850 auto *ECD = cast_or_null<EnumConstantDecl>(D); 17851 if (!ECD) continue; // Already issued a diagnostic. 17852 17853 // Standard C says the enumerators have int type, but we allow, as an 17854 // extension, the enumerators to be larger than int size. If each 17855 // enumerator value fits in an int, type it as an int, otherwise type it the 17856 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 17857 // that X has type 'int', not 'unsigned'. 17858 17859 // Determine whether the value fits into an int. 17860 llvm::APSInt InitVal = ECD->getInitVal(); 17861 17862 // If it fits into an integer type, force it. Otherwise force it to match 17863 // the enum decl type. 17864 QualType NewTy; 17865 unsigned NewWidth; 17866 bool NewSign; 17867 if (!getLangOpts().CPlusPlus && 17868 !Enum->isFixed() && 17869 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 17870 NewTy = Context.IntTy; 17871 NewWidth = IntWidth; 17872 NewSign = true; 17873 } else if (ECD->getType() == BestType) { 17874 // Already the right type! 17875 if (getLangOpts().CPlusPlus) 17876 // C++ [dcl.enum]p4: Following the closing brace of an 17877 // enum-specifier, each enumerator has the type of its 17878 // enumeration. 17879 ECD->setType(EnumType); 17880 continue; 17881 } else { 17882 NewTy = BestType; 17883 NewWidth = BestWidth; 17884 NewSign = BestType->isSignedIntegerOrEnumerationType(); 17885 } 17886 17887 // Adjust the APSInt value. 17888 InitVal = InitVal.extOrTrunc(NewWidth); 17889 InitVal.setIsSigned(NewSign); 17890 ECD->setInitVal(InitVal); 17891 17892 // Adjust the Expr initializer and type. 17893 if (ECD->getInitExpr() && 17894 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 17895 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 17896 CK_IntegralCast, 17897 ECD->getInitExpr(), 17898 /*base paths*/ nullptr, 17899 VK_RValue)); 17900 if (getLangOpts().CPlusPlus) 17901 // C++ [dcl.enum]p4: Following the closing brace of an 17902 // enum-specifier, each enumerator has the type of its 17903 // enumeration. 17904 ECD->setType(EnumType); 17905 else 17906 ECD->setType(NewTy); 17907 } 17908 17909 Enum->completeDefinition(BestType, BestPromotionType, 17910 NumPositiveBits, NumNegativeBits); 17911 17912 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 17913 17914 if (Enum->isClosedFlag()) { 17915 for (Decl *D : Elements) { 17916 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 17917 if (!ECD) continue; // Already issued a diagnostic. 17918 17919 llvm::APSInt InitVal = ECD->getInitVal(); 17920 if (InitVal != 0 && !InitVal.isPowerOf2() && 17921 !IsValueInFlagEnum(Enum, InitVal, true)) 17922 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 17923 << ECD << Enum; 17924 } 17925 } 17926 17927 // Now that the enum type is defined, ensure it's not been underaligned. 17928 if (Enum->hasAttrs()) 17929 CheckAlignasUnderalignment(Enum); 17930 } 17931 17932 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 17933 SourceLocation StartLoc, 17934 SourceLocation EndLoc) { 17935 StringLiteral *AsmString = cast<StringLiteral>(expr); 17936 17937 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 17938 AsmString, StartLoc, 17939 EndLoc); 17940 CurContext->addDecl(New); 17941 return New; 17942 } 17943 17944 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 17945 IdentifierInfo* AliasName, 17946 SourceLocation PragmaLoc, 17947 SourceLocation NameLoc, 17948 SourceLocation AliasNameLoc) { 17949 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 17950 LookupOrdinaryName); 17951 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc), 17952 AttributeCommonInfo::AS_Pragma); 17953 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit( 17954 Context, AliasName->getName(), /*LiteralLabel=*/true, Info); 17955 17956 // If a declaration that: 17957 // 1) declares a function or a variable 17958 // 2) has external linkage 17959 // already exists, add a label attribute to it. 17960 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17961 if (isDeclExternC(PrevDecl)) 17962 PrevDecl->addAttr(Attr); 17963 else 17964 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 17965 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 17966 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 17967 } else 17968 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 17969 } 17970 17971 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 17972 SourceLocation PragmaLoc, 17973 SourceLocation NameLoc) { 17974 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 17975 17976 if (PrevDecl) { 17977 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma)); 17978 } else { 17979 (void)WeakUndeclaredIdentifiers.insert( 17980 std::pair<IdentifierInfo*,WeakInfo> 17981 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 17982 } 17983 } 17984 17985 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 17986 IdentifierInfo* AliasName, 17987 SourceLocation PragmaLoc, 17988 SourceLocation NameLoc, 17989 SourceLocation AliasNameLoc) { 17990 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 17991 LookupOrdinaryName); 17992 WeakInfo W = WeakInfo(Name, NameLoc); 17993 17994 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 17995 if (!PrevDecl->hasAttr<AliasAttr>()) 17996 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 17997 DeclApplyPragmaWeak(TUScope, ND, W); 17998 } else { 17999 (void)WeakUndeclaredIdentifiers.insert( 18000 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 18001 } 18002 } 18003 18004 Decl *Sema::getObjCDeclContext() const { 18005 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 18006 } 18007 18008 Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD) { 18009 // Templates are emitted when they're instantiated. 18010 if (FD->isDependentContext()) 18011 return FunctionEmissionStatus::TemplateDiscarded; 18012 18013 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown; 18014 if (LangOpts.OpenMPIsDevice) { 18015 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18016 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18017 if (DevTy.hasValue()) { 18018 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host) 18019 OMPES = FunctionEmissionStatus::OMPDiscarded; 18020 else if (DeviceKnownEmittedFns.count(FD) > 0) 18021 OMPES = FunctionEmissionStatus::Emitted; 18022 } 18023 } else if (LangOpts.OpenMP) { 18024 // In OpenMP 4.5 all the functions are host functions. 18025 if (LangOpts.OpenMP <= 45) { 18026 OMPES = FunctionEmissionStatus::Emitted; 18027 } else { 18028 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 18029 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl()); 18030 // In OpenMP 5.0 or above, DevTy may be changed later by 18031 // #pragma omp declare target to(*) device_type(*). Therefore DevTy 18032 // having no value does not imply host. The emission status will be 18033 // checked again at the end of compilation unit. 18034 if (DevTy.hasValue()) { 18035 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 18036 OMPES = FunctionEmissionStatus::OMPDiscarded; 18037 } else if (DeviceKnownEmittedFns.count(FD) > 0) { 18038 OMPES = FunctionEmissionStatus::Emitted; 18039 } 18040 } 18041 } 18042 } 18043 if (OMPES == FunctionEmissionStatus::OMPDiscarded || 18044 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA)) 18045 return OMPES; 18046 18047 if (LangOpts.CUDA) { 18048 // When compiling for device, host functions are never emitted. Similarly, 18049 // when compiling for host, device and global functions are never emitted. 18050 // (Technically, we do emit a host-side stub for global functions, but this 18051 // doesn't count for our purposes here.) 18052 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD); 18053 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host) 18054 return FunctionEmissionStatus::CUDADiscarded; 18055 if (!LangOpts.CUDAIsDevice && 18056 (T == Sema::CFT_Device || T == Sema::CFT_Global)) 18057 return FunctionEmissionStatus::CUDADiscarded; 18058 18059 // Check whether this function is externally visible -- if so, it's 18060 // known-emitted. 18061 // 18062 // We have to check the GVA linkage of the function's *definition* -- if we 18063 // only have a declaration, we don't know whether or not the function will 18064 // be emitted, because (say) the definition could include "inline". 18065 FunctionDecl *Def = FD->getDefinition(); 18066 18067 if (Def && 18068 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)) 18069 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted)) 18070 return FunctionEmissionStatus::Emitted; 18071 } 18072 18073 // Otherwise, the function is known-emitted if it's in our set of 18074 // known-emitted functions. 18075 return (DeviceKnownEmittedFns.count(FD) > 0) 18076 ? FunctionEmissionStatus::Emitted 18077 : FunctionEmissionStatus::Unknown; 18078 } 18079 18080 bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) { 18081 // Host-side references to a __global__ function refer to the stub, so the 18082 // function itself is never emitted and therefore should not be marked. 18083 // If we have host fn calls kernel fn calls host+device, the HD function 18084 // does not get instantiated on the host. We model this by omitting at the 18085 // call to the kernel from the callgraph. This ensures that, when compiling 18086 // for host, only HD functions actually called from the host get marked as 18087 // known-emitted. 18088 return LangOpts.CUDA && !LangOpts.CUDAIsDevice && 18089 IdentifyCUDATarget(Callee) == CFT_Global; 18090 } 18091