1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for declarations. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "TypeLocBuilder.h" 16 #include "clang/AST/ASTConsumer.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/ASTLambda.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/CharUnits.h" 21 #include "clang/AST/CommentDiagnostic.h" 22 #include "clang/AST/DeclCXX.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclTemplate.h" 25 #include "clang/AST/EvaluatedExprVisitor.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/StmtCXX.h" 28 #include "clang/Basic/Builtins.h" 29 #include "clang/Basic/PartialDiagnostic.h" 30 #include "clang/Basic/SourceManager.h" 31 #include "clang/Basic/TargetInfo.h" 32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex 33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex 35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled() 36 #include "clang/Parse/ParseDiagnostic.h" 37 #include "clang/Sema/CXXFieldCollector.h" 38 #include "clang/Sema/DeclSpec.h" 39 #include "clang/Sema/DelayedDiagnostic.h" 40 #include "clang/Sema/Initialization.h" 41 #include "clang/Sema/Lookup.h" 42 #include "clang/Sema/ParsedTemplate.h" 43 #include "clang/Sema/Scope.h" 44 #include "clang/Sema/ScopeInfo.h" 45 #include "clang/Sema/Template.h" 46 #include "llvm/ADT/SmallString.h" 47 #include "llvm/ADT/Triple.h" 48 #include <algorithm> 49 #include <cstring> 50 #include <functional> 51 using namespace clang; 52 using namespace sema; 53 54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) { 55 if (OwnedType) { 56 Decl *Group[2] = { OwnedType, Ptr }; 57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2)); 58 } 59 60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr)); 61 } 62 63 namespace { 64 65 class TypeNameValidatorCCC : public CorrectionCandidateCallback { 66 public: 67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false, 68 bool AllowTemplates=false) 69 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass), 70 AllowClassTemplates(AllowTemplates) { 71 WantExpressionKeywords = false; 72 WantCXXNamedCasts = false; 73 WantRemainingKeywords = false; 74 } 75 76 bool ValidateCandidate(const TypoCorrection &candidate) override { 77 if (NamedDecl *ND = candidate.getCorrectionDecl()) { 78 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND); 79 bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND); 80 return (IsType || AllowedTemplate) && 81 (AllowInvalidDecl || !ND->isInvalidDecl()); 82 } 83 return !WantClassName && candidate.isKeyword(); 84 } 85 86 private: 87 bool AllowInvalidDecl; 88 bool WantClassName; 89 bool AllowClassTemplates; 90 }; 91 92 } // namespace 93 94 /// \brief Determine whether the token kind starts a simple-type-specifier. 95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const { 96 switch (Kind) { 97 // FIXME: Take into account the current language when deciding whether a 98 // token kind is a valid type specifier 99 case tok::kw_short: 100 case tok::kw_long: 101 case tok::kw___int64: 102 case tok::kw___int128: 103 case tok::kw_signed: 104 case tok::kw_unsigned: 105 case tok::kw_void: 106 case tok::kw_char: 107 case tok::kw_int: 108 case tok::kw_half: 109 case tok::kw_float: 110 case tok::kw_double: 111 case tok::kw_wchar_t: 112 case tok::kw_bool: 113 case tok::kw___underlying_type: 114 return true; 115 116 case tok::annot_typename: 117 case tok::kw_char16_t: 118 case tok::kw_char32_t: 119 case tok::kw_typeof: 120 case tok::annot_decltype: 121 case tok::kw_decltype: 122 return getLangOpts().CPlusPlus; 123 124 default: 125 break; 126 } 127 128 return false; 129 } 130 131 namespace { 132 enum class UnqualifiedTypeNameLookupResult { 133 NotFound, 134 FoundNonType, 135 FoundType 136 }; 137 } // namespace 138 139 /// \brief Tries to perform unqualified lookup of the type decls in bases for 140 /// dependent class. 141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 142 /// type decl, \a FoundType if only type decls are found. 143 static UnqualifiedTypeNameLookupResult 144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 145 SourceLocation NameLoc, 146 const CXXRecordDecl *RD) { 147 if (!RD->hasDefinition()) 148 return UnqualifiedTypeNameLookupResult::NotFound; 149 // Look for type decls in base classes. 150 UnqualifiedTypeNameLookupResult FoundTypeDecl = 151 UnqualifiedTypeNameLookupResult::NotFound; 152 for (const auto &Base : RD->bases()) { 153 const CXXRecordDecl *BaseRD = nullptr; 154 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 155 BaseRD = BaseTT->getAsCXXRecordDecl(); 156 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 157 // Look for type decls in dependent base classes that have known primary 158 // templates. 159 if (!TST || !TST->isDependentType()) 160 continue; 161 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 162 if (!TD) 163 continue; 164 auto *BasePrimaryTemplate = 165 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl()); 166 if (!BasePrimaryTemplate) 167 continue; 168 BaseRD = BasePrimaryTemplate; 169 } 170 if (BaseRD) { 171 for (NamedDecl *ND : BaseRD->lookup(&II)) { 172 if (!isa<TypeDecl>(ND)) 173 return UnqualifiedTypeNameLookupResult::FoundNonType; 174 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 175 } 176 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 177 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 178 case UnqualifiedTypeNameLookupResult::FoundNonType: 179 return UnqualifiedTypeNameLookupResult::FoundNonType; 180 case UnqualifiedTypeNameLookupResult::FoundType: 181 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 182 break; 183 case UnqualifiedTypeNameLookupResult::NotFound: 184 break; 185 } 186 } 187 } 188 } 189 190 return FoundTypeDecl; 191 } 192 193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 194 const IdentifierInfo &II, 195 SourceLocation NameLoc) { 196 // Lookup in the parent class template context, if any. 197 const CXXRecordDecl *RD = nullptr; 198 UnqualifiedTypeNameLookupResult FoundTypeDecl = 199 UnqualifiedTypeNameLookupResult::NotFound; 200 for (DeclContext *DC = S.CurContext; 201 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 202 DC = DC->getParent()) { 203 // Look for type decls in dependent base classes that have known primary 204 // templates. 205 RD = dyn_cast<CXXRecordDecl>(DC); 206 if (RD && RD->getDescribedClassTemplate()) 207 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 208 } 209 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 210 return ParsedType(); 211 212 // We found some types in dependent base classes. Recover as if the user 213 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 214 // lookup during template instantiation. 215 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 216 217 ASTContext &Context = S.Context; 218 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 219 cast<Type>(Context.getRecordType(RD))); 220 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 221 222 CXXScopeSpec SS; 223 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 224 225 TypeLocBuilder Builder; 226 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 227 DepTL.setNameLoc(NameLoc); 228 DepTL.setElaboratedKeywordLoc(SourceLocation()); 229 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 230 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 231 } 232 233 /// \brief If the identifier refers to a type name within this scope, 234 /// return the declaration of that type. 235 /// 236 /// This routine performs ordinary name lookup of the identifier II 237 /// within the given scope, with optional C++ scope specifier SS, to 238 /// determine whether the name refers to a type. If so, returns an 239 /// opaque pointer (actually a QualType) corresponding to that 240 /// type. Otherwise, returns NULL. 241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 242 Scope *S, CXXScopeSpec *SS, 243 bool isClassName, bool HasTrailingDot, 244 ParsedType ObjectTypePtr, 245 bool IsCtorOrDtorName, 246 bool WantNontrivialTypeSourceInfo, 247 IdentifierInfo **CorrectedII) { 248 // Determine where we will perform name lookup. 249 DeclContext *LookupCtx = nullptr; 250 if (ObjectTypePtr) { 251 QualType ObjectType = ObjectTypePtr.get(); 252 if (ObjectType->isRecordType()) 253 LookupCtx = computeDeclContext(ObjectType); 254 } else if (SS && SS->isNotEmpty()) { 255 LookupCtx = computeDeclContext(*SS, false); 256 257 if (!LookupCtx) { 258 if (isDependentScopeSpecifier(*SS)) { 259 // C++ [temp.res]p3: 260 // A qualified-id that refers to a type and in which the 261 // nested-name-specifier depends on a template-parameter (14.6.2) 262 // shall be prefixed by the keyword typename to indicate that the 263 // qualified-id denotes a type, forming an 264 // elaborated-type-specifier (7.1.5.3). 265 // 266 // We therefore do not perform any name lookup if the result would 267 // refer to a member of an unknown specialization. 268 if (!isClassName && !IsCtorOrDtorName) 269 return ParsedType(); 270 271 // We know from the grammar that this name refers to a type, 272 // so build a dependent node to describe the type. 273 if (WantNontrivialTypeSourceInfo) 274 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 275 276 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 277 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 278 II, NameLoc); 279 return ParsedType::make(T); 280 } 281 282 return ParsedType(); 283 } 284 285 if (!LookupCtx->isDependentContext() && 286 RequireCompleteDeclContext(*SS, LookupCtx)) 287 return ParsedType(); 288 } 289 290 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 291 // lookup for class-names. 292 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 293 LookupOrdinaryName; 294 LookupResult Result(*this, &II, NameLoc, Kind); 295 if (LookupCtx) { 296 // Perform "qualified" name lookup into the declaration context we 297 // computed, which is either the type of the base of a member access 298 // expression or the declaration context associated with a prior 299 // nested-name-specifier. 300 LookupQualifiedName(Result, LookupCtx); 301 302 if (ObjectTypePtr && Result.empty()) { 303 // C++ [basic.lookup.classref]p3: 304 // If the unqualified-id is ~type-name, the type-name is looked up 305 // in the context of the entire postfix-expression. If the type T of 306 // the object expression is of a class type C, the type-name is also 307 // looked up in the scope of class C. At least one of the lookups shall 308 // find a name that refers to (possibly cv-qualified) T. 309 LookupName(Result, S); 310 } 311 } else { 312 // Perform unqualified name lookup. 313 LookupName(Result, S); 314 315 // For unqualified lookup in a class template in MSVC mode, look into 316 // dependent base classes where the primary class template is known. 317 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 318 if (ParsedType TypeInBase = 319 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 320 return TypeInBase; 321 } 322 } 323 324 NamedDecl *IIDecl = nullptr; 325 switch (Result.getResultKind()) { 326 case LookupResult::NotFound: 327 case LookupResult::NotFoundInCurrentInstantiation: 328 if (CorrectedII) { 329 TypoCorrection Correction = CorrectTypo( 330 Result.getLookupNameInfo(), Kind, S, SS, 331 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName), 332 CTK_ErrorRecovery); 333 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 334 TemplateTy Template; 335 bool MemberOfUnknownSpecialization; 336 UnqualifiedId TemplateName; 337 TemplateName.setIdentifier(NewII, NameLoc); 338 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 339 CXXScopeSpec NewSS, *NewSSPtr = SS; 340 if (SS && NNS) { 341 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 342 NewSSPtr = &NewSS; 343 } 344 if (Correction && (NNS || NewII != &II) && 345 // Ignore a correction to a template type as the to-be-corrected 346 // identifier is not a template (typo correction for template names 347 // is handled elsewhere). 348 !(getLangOpts().CPlusPlus && NewSSPtr && 349 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 350 false, Template, MemberOfUnknownSpecialization))) { 351 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 352 isClassName, HasTrailingDot, ObjectTypePtr, 353 IsCtorOrDtorName, 354 WantNontrivialTypeSourceInfo); 355 if (Ty) { 356 diagnoseTypo(Correction, 357 PDiag(diag::err_unknown_type_or_class_name_suggest) 358 << Result.getLookupName() << isClassName); 359 if (SS && NNS) 360 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 361 *CorrectedII = NewII; 362 return Ty; 363 } 364 } 365 } 366 // If typo correction failed or was not performed, fall through 367 case LookupResult::FoundOverloaded: 368 case LookupResult::FoundUnresolvedValue: 369 Result.suppressDiagnostics(); 370 return ParsedType(); 371 372 case LookupResult::Ambiguous: 373 // Recover from type-hiding ambiguities by hiding the type. We'll 374 // do the lookup again when looking for an object, and we can 375 // diagnose the error then. If we don't do this, then the error 376 // about hiding the type will be immediately followed by an error 377 // that only makes sense if the identifier was treated like a type. 378 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 379 Result.suppressDiagnostics(); 380 return ParsedType(); 381 } 382 383 // Look to see if we have a type anywhere in the list of results. 384 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 385 Res != ResEnd; ++Res) { 386 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 387 if (!IIDecl || 388 (*Res)->getLocation().getRawEncoding() < 389 IIDecl->getLocation().getRawEncoding()) 390 IIDecl = *Res; 391 } 392 } 393 394 if (!IIDecl) { 395 // None of the entities we found is a type, so there is no way 396 // to even assume that the result is a type. In this case, don't 397 // complain about the ambiguity. The parser will either try to 398 // perform this lookup again (e.g., as an object name), which 399 // will produce the ambiguity, or will complain that it expected 400 // a type name. 401 Result.suppressDiagnostics(); 402 return ParsedType(); 403 } 404 405 // We found a type within the ambiguous lookup; diagnose the 406 // ambiguity and then return that type. This might be the right 407 // answer, or it might not be, but it suppresses any attempt to 408 // perform the name lookup again. 409 break; 410 411 case LookupResult::Found: 412 IIDecl = Result.getFoundDecl(); 413 break; 414 } 415 416 assert(IIDecl && "Didn't find decl"); 417 418 QualType T; 419 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 420 DiagnoseUseOfDecl(IIDecl, NameLoc); 421 422 T = Context.getTypeDeclType(TD); 423 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 424 425 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 426 // constructor or destructor name (in such a case, the scope specifier 427 // will be attached to the enclosing Expr or Decl node). 428 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 429 if (WantNontrivialTypeSourceInfo) { 430 // Construct a type with type-source information. 431 TypeLocBuilder Builder; 432 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 433 434 T = getElaboratedType(ETK_None, *SS, T); 435 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 436 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 437 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 438 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 439 } else { 440 T = getElaboratedType(ETK_None, *SS, T); 441 } 442 } 443 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 444 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 445 if (!HasTrailingDot) 446 T = Context.getObjCInterfaceType(IDecl); 447 } 448 449 if (T.isNull()) { 450 // If it's not plausibly a type, suppress diagnostics. 451 Result.suppressDiagnostics(); 452 return ParsedType(); 453 } 454 return ParsedType::make(T); 455 } 456 457 // Builds a fake NNS for the given decl context. 458 static NestedNameSpecifier * 459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 460 for (;; DC = DC->getLookupParent()) { 461 DC = DC->getPrimaryContext(); 462 auto *ND = dyn_cast<NamespaceDecl>(DC); 463 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 464 return NestedNameSpecifier::Create(Context, nullptr, ND); 465 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 466 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 467 RD->getTypeForDecl()); 468 else if (isa<TranslationUnitDecl>(DC)) 469 return NestedNameSpecifier::GlobalSpecifier(Context); 470 } 471 llvm_unreachable("something isn't in TU scope?"); 472 } 473 474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 475 SourceLocation NameLoc) { 476 // Accepting an undeclared identifier as a default argument for a template 477 // type parameter is a Microsoft extension. 478 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 479 480 // Build a fake DependentNameType that will perform lookup into CurContext at 481 // instantiation time. The name specifier isn't dependent, so template 482 // instantiation won't transform it. It will retry the lookup, however. 483 NestedNameSpecifier *NNS = 484 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 485 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 486 487 // Build type location information. We synthesized the qualifier, so we have 488 // to build a fake NestedNameSpecifierLoc. 489 NestedNameSpecifierLocBuilder NNSLocBuilder; 490 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 491 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 492 493 TypeLocBuilder Builder; 494 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 495 DepTL.setNameLoc(NameLoc); 496 DepTL.setElaboratedKeywordLoc(SourceLocation()); 497 DepTL.setQualifierLoc(QualifierLoc); 498 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 499 } 500 501 /// isTagName() - This method is called *for error recovery purposes only* 502 /// to determine if the specified name is a valid tag name ("struct foo"). If 503 /// so, this returns the TST for the tag corresponding to it (TST_enum, 504 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 505 /// cases in C where the user forgot to specify the tag. 506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 507 // Do a tag name lookup in this scope. 508 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 509 LookupName(R, S, false); 510 R.suppressDiagnostics(); 511 if (R.getResultKind() == LookupResult::Found) 512 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 513 switch (TD->getTagKind()) { 514 case TTK_Struct: return DeclSpec::TST_struct; 515 case TTK_Interface: return DeclSpec::TST_interface; 516 case TTK_Union: return DeclSpec::TST_union; 517 case TTK_Class: return DeclSpec::TST_class; 518 case TTK_Enum: return DeclSpec::TST_enum; 519 } 520 } 521 522 return DeclSpec::TST_unspecified; 523 } 524 525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 527 /// then downgrade the missing typename error to a warning. 528 /// This is needed for MSVC compatibility; Example: 529 /// @code 530 /// template<class T> class A { 531 /// public: 532 /// typedef int TYPE; 533 /// }; 534 /// template<class T> class B : public A<T> { 535 /// public: 536 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 537 /// }; 538 /// @endcode 539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 540 if (CurContext->isRecord()) { 541 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 542 return true; 543 544 const Type *Ty = SS->getScopeRep()->getAsType(); 545 546 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 547 for (const auto &Base : RD->bases()) 548 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 549 return true; 550 return S->isFunctionPrototypeScope(); 551 } 552 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 553 } 554 555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 556 SourceLocation IILoc, 557 Scope *S, 558 CXXScopeSpec *SS, 559 ParsedType &SuggestedType, 560 bool AllowClassTemplates) { 561 // We don't have anything to suggest (yet). 562 SuggestedType = ParsedType(); 563 564 // There may have been a typo in the name of the type. Look up typo 565 // results, in case we have something that we can suggest. 566 if (TypoCorrection Corrected = 567 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 568 llvm::make_unique<TypeNameValidatorCCC>( 569 false, false, AllowClassTemplates), 570 CTK_ErrorRecovery)) { 571 if (Corrected.isKeyword()) { 572 // We corrected to a keyword. 573 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 574 II = Corrected.getCorrectionAsIdentifierInfo(); 575 } else { 576 // We found a similarly-named type or interface; suggest that. 577 if (!SS || !SS->isSet()) { 578 diagnoseTypo(Corrected, 579 PDiag(diag::err_unknown_typename_suggest) << II); 580 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 581 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 582 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 583 II->getName().equals(CorrectedStr); 584 diagnoseTypo(Corrected, 585 PDiag(diag::err_unknown_nested_typename_suggest) 586 << II << DC << DroppedSpecifier << SS->getRange()); 587 } else { 588 llvm_unreachable("could not have corrected a typo here"); 589 } 590 591 CXXScopeSpec tmpSS; 592 if (Corrected.getCorrectionSpecifier()) 593 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 594 SourceRange(IILoc)); 595 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 596 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 597 false, ParsedType(), 598 /*IsCtorOrDtorName=*/false, 599 /*NonTrivialTypeSourceInfo=*/true); 600 } 601 return; 602 } 603 604 if (getLangOpts().CPlusPlus) { 605 // See if II is a class template that the user forgot to pass arguments to. 606 UnqualifiedId Name; 607 Name.setIdentifier(II, IILoc); 608 CXXScopeSpec EmptySS; 609 TemplateTy TemplateResult; 610 bool MemberOfUnknownSpecialization; 611 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 612 Name, ParsedType(), true, TemplateResult, 613 MemberOfUnknownSpecialization) == TNK_Type_template) { 614 TemplateName TplName = TemplateResult.get(); 615 Diag(IILoc, diag::err_template_missing_args) << TplName; 616 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 617 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 618 << TplDecl->getTemplateParameters()->getSourceRange(); 619 } 620 return; 621 } 622 } 623 624 // FIXME: Should we move the logic that tries to recover from a missing tag 625 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 626 627 if (!SS || (!SS->isSet() && !SS->isInvalid())) 628 Diag(IILoc, diag::err_unknown_typename) << II; 629 else if (DeclContext *DC = computeDeclContext(*SS, false)) 630 Diag(IILoc, diag::err_typename_nested_not_found) 631 << II << DC << SS->getRange(); 632 else if (isDependentScopeSpecifier(*SS)) { 633 unsigned DiagID = diag::err_typename_missing; 634 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 635 DiagID = diag::ext_typename_missing; 636 637 Diag(SS->getRange().getBegin(), DiagID) 638 << SS->getScopeRep() << II->getName() 639 << SourceRange(SS->getRange().getBegin(), IILoc) 640 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 641 SuggestedType = ActOnTypenameType(S, SourceLocation(), 642 *SS, *II, IILoc).get(); 643 } else { 644 assert(SS && SS->isInvalid() && 645 "Invalid scope specifier has already been diagnosed"); 646 } 647 } 648 649 /// \brief Determine whether the given result set contains either a type name 650 /// or 651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 652 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 653 NextToken.is(tok::less); 654 655 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 656 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 657 return true; 658 659 if (CheckTemplate && isa<TemplateDecl>(*I)) 660 return true; 661 } 662 663 return false; 664 } 665 666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 667 Scope *S, CXXScopeSpec &SS, 668 IdentifierInfo *&Name, 669 SourceLocation NameLoc) { 670 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 671 SemaRef.LookupParsedName(R, S, &SS); 672 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 673 StringRef FixItTagName; 674 switch (Tag->getTagKind()) { 675 case TTK_Class: 676 FixItTagName = "class "; 677 break; 678 679 case TTK_Enum: 680 FixItTagName = "enum "; 681 break; 682 683 case TTK_Struct: 684 FixItTagName = "struct "; 685 break; 686 687 case TTK_Interface: 688 FixItTagName = "__interface "; 689 break; 690 691 case TTK_Union: 692 FixItTagName = "union "; 693 break; 694 } 695 696 StringRef TagName = FixItTagName.drop_back(); 697 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 698 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 699 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 700 701 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 702 I != IEnd; ++I) 703 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 704 << Name << TagName; 705 706 // Replace lookup results with just the tag decl. 707 Result.clear(Sema::LookupTagName); 708 SemaRef.LookupParsedName(Result, S, &SS); 709 return true; 710 } 711 712 return false; 713 } 714 715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 717 QualType T, SourceLocation NameLoc) { 718 ASTContext &Context = S.Context; 719 720 TypeLocBuilder Builder; 721 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 722 723 T = S.getElaboratedType(ETK_None, SS, T); 724 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 725 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 726 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 727 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 728 } 729 730 Sema::NameClassification 731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 732 SourceLocation NameLoc, const Token &NextToken, 733 bool IsAddressOfOperand, 734 std::unique_ptr<CorrectionCandidateCallback> CCC) { 735 DeclarationNameInfo NameInfo(Name, NameLoc); 736 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 737 738 if (NextToken.is(tok::coloncolon)) { 739 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 740 QualType(), false, SS, nullptr, false); 741 } 742 743 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 744 LookupParsedName(Result, S, &SS, !CurMethod); 745 746 // For unqualified lookup in a class template in MSVC mode, look into 747 // dependent base classes where the primary class template is known. 748 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 749 if (ParsedType TypeInBase = 750 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 751 return TypeInBase; 752 } 753 754 // Perform lookup for Objective-C instance variables (including automatically 755 // synthesized instance variables), if we're in an Objective-C method. 756 // FIXME: This lookup really, really needs to be folded in to the normal 757 // unqualified lookup mechanism. 758 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 759 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 760 if (E.get() || E.isInvalid()) 761 return E; 762 } 763 764 bool SecondTry = false; 765 bool IsFilteredTemplateName = false; 766 767 Corrected: 768 switch (Result.getResultKind()) { 769 case LookupResult::NotFound: 770 // If an unqualified-id is followed by a '(', then we have a function 771 // call. 772 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 773 // In C++, this is an ADL-only call. 774 // FIXME: Reference? 775 if (getLangOpts().CPlusPlus) 776 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 777 778 // C90 6.3.2.2: 779 // If the expression that precedes the parenthesized argument list in a 780 // function call consists solely of an identifier, and if no 781 // declaration is visible for this identifier, the identifier is 782 // implicitly declared exactly as if, in the innermost block containing 783 // the function call, the declaration 784 // 785 // extern int identifier (); 786 // 787 // appeared. 788 // 789 // We also allow this in C99 as an extension. 790 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 791 Result.addDecl(D); 792 Result.resolveKind(); 793 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 794 } 795 } 796 797 // In C, we first see whether there is a tag type by the same name, in 798 // which case it's likely that the user just forget to write "enum", 799 // "struct", or "union". 800 if (!getLangOpts().CPlusPlus && !SecondTry && 801 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 802 break; 803 } 804 805 // Perform typo correction to determine if there is another name that is 806 // close to this name. 807 if (!SecondTry && CCC) { 808 SecondTry = true; 809 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 810 Result.getLookupKind(), S, 811 &SS, std::move(CCC), 812 CTK_ErrorRecovery)) { 813 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 814 unsigned QualifiedDiag = diag::err_no_member_suggest; 815 816 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 817 NamedDecl *UnderlyingFirstDecl 818 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr; 819 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 820 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 821 UnqualifiedDiag = diag::err_no_template_suggest; 822 QualifiedDiag = diag::err_no_member_template_suggest; 823 } else if (UnderlyingFirstDecl && 824 (isa<TypeDecl>(UnderlyingFirstDecl) || 825 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 826 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 827 UnqualifiedDiag = diag::err_unknown_typename_suggest; 828 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 829 } 830 831 if (SS.isEmpty()) { 832 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 833 } else {// FIXME: is this even reachable? Test it. 834 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 835 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 836 Name->getName().equals(CorrectedStr); 837 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 838 << Name << computeDeclContext(SS, false) 839 << DroppedSpecifier << SS.getRange()); 840 } 841 842 // Update the name, so that the caller has the new name. 843 Name = Corrected.getCorrectionAsIdentifierInfo(); 844 845 // Typo correction corrected to a keyword. 846 if (Corrected.isKeyword()) 847 return Name; 848 849 // Also update the LookupResult... 850 // FIXME: This should probably go away at some point 851 Result.clear(); 852 Result.setLookupName(Corrected.getCorrection()); 853 if (FirstDecl) 854 Result.addDecl(FirstDecl); 855 856 // If we found an Objective-C instance variable, let 857 // LookupInObjCMethod build the appropriate expression to 858 // reference the ivar. 859 // FIXME: This is a gross hack. 860 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 861 Result.clear(); 862 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 863 return E; 864 } 865 866 goto Corrected; 867 } 868 } 869 870 // We failed to correct; just fall through and let the parser deal with it. 871 Result.suppressDiagnostics(); 872 return NameClassification::Unknown(); 873 874 case LookupResult::NotFoundInCurrentInstantiation: { 875 // We performed name lookup into the current instantiation, and there were 876 // dependent bases, so we treat this result the same way as any other 877 // dependent nested-name-specifier. 878 879 // C++ [temp.res]p2: 880 // A name used in a template declaration or definition and that is 881 // dependent on a template-parameter is assumed not to name a type 882 // unless the applicable name lookup finds a type name or the name is 883 // qualified by the keyword typename. 884 // 885 // FIXME: If the next token is '<', we might want to ask the parser to 886 // perform some heroics to see if we actually have a 887 // template-argument-list, which would indicate a missing 'template' 888 // keyword here. 889 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 890 NameInfo, IsAddressOfOperand, 891 /*TemplateArgs=*/nullptr); 892 } 893 894 case LookupResult::Found: 895 case LookupResult::FoundOverloaded: 896 case LookupResult::FoundUnresolvedValue: 897 break; 898 899 case LookupResult::Ambiguous: 900 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 901 hasAnyAcceptableTemplateNames(Result)) { 902 // C++ [temp.local]p3: 903 // A lookup that finds an injected-class-name (10.2) can result in an 904 // ambiguity in certain cases (for example, if it is found in more than 905 // one base class). If all of the injected-class-names that are found 906 // refer to specializations of the same class template, and if the name 907 // is followed by a template-argument-list, the reference refers to the 908 // class template itself and not a specialization thereof, and is not 909 // ambiguous. 910 // 911 // This filtering can make an ambiguous result into an unambiguous one, 912 // so try again after filtering out template names. 913 FilterAcceptableTemplateNames(Result); 914 if (!Result.isAmbiguous()) { 915 IsFilteredTemplateName = true; 916 break; 917 } 918 } 919 920 // Diagnose the ambiguity and return an error. 921 return NameClassification::Error(); 922 } 923 924 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 925 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 926 // C++ [temp.names]p3: 927 // After name lookup (3.4) finds that a name is a template-name or that 928 // an operator-function-id or a literal- operator-id refers to a set of 929 // overloaded functions any member of which is a function template if 930 // this is followed by a <, the < is always taken as the delimiter of a 931 // template-argument-list and never as the less-than operator. 932 if (!IsFilteredTemplateName) 933 FilterAcceptableTemplateNames(Result); 934 935 if (!Result.empty()) { 936 bool IsFunctionTemplate; 937 bool IsVarTemplate; 938 TemplateName Template; 939 if (Result.end() - Result.begin() > 1) { 940 IsFunctionTemplate = true; 941 Template = Context.getOverloadedTemplateName(Result.begin(), 942 Result.end()); 943 } else { 944 TemplateDecl *TD 945 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 946 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 947 IsVarTemplate = isa<VarTemplateDecl>(TD); 948 949 if (SS.isSet() && !SS.isInvalid()) 950 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 951 /*TemplateKeyword=*/false, 952 TD); 953 else 954 Template = TemplateName(TD); 955 } 956 957 if (IsFunctionTemplate) { 958 // Function templates always go through overload resolution, at which 959 // point we'll perform the various checks (e.g., accessibility) we need 960 // to based on which function we selected. 961 Result.suppressDiagnostics(); 962 963 return NameClassification::FunctionTemplate(Template); 964 } 965 966 return IsVarTemplate ? NameClassification::VarTemplate(Template) 967 : NameClassification::TypeTemplate(Template); 968 } 969 } 970 971 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 972 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 973 DiagnoseUseOfDecl(Type, NameLoc); 974 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 975 QualType T = Context.getTypeDeclType(Type); 976 if (SS.isNotEmpty()) 977 return buildNestedType(*this, SS, T, NameLoc); 978 return ParsedType::make(T); 979 } 980 981 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 982 if (!Class) { 983 // FIXME: It's unfortunate that we don't have a Type node for handling this. 984 if (ObjCCompatibleAliasDecl *Alias = 985 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 986 Class = Alias->getClassInterface(); 987 } 988 989 if (Class) { 990 DiagnoseUseOfDecl(Class, NameLoc); 991 992 if (NextToken.is(tok::period)) { 993 // Interface. <something> is parsed as a property reference expression. 994 // Just return "unknown" as a fall-through for now. 995 Result.suppressDiagnostics(); 996 return NameClassification::Unknown(); 997 } 998 999 QualType T = Context.getObjCInterfaceType(Class); 1000 return ParsedType::make(T); 1001 } 1002 1003 // We can have a type template here if we're classifying a template argument. 1004 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 1005 return NameClassification::TypeTemplate( 1006 TemplateName(cast<TemplateDecl>(FirstDecl))); 1007 1008 // Check for a tag type hidden by a non-type decl in a few cases where it 1009 // seems likely a type is wanted instead of the non-type that was found. 1010 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1011 if ((NextToken.is(tok::identifier) || 1012 (NextIsOp && 1013 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1014 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1015 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1016 DiagnoseUseOfDecl(Type, NameLoc); 1017 QualType T = Context.getTypeDeclType(Type); 1018 if (SS.isNotEmpty()) 1019 return buildNestedType(*this, SS, T, NameLoc); 1020 return ParsedType::make(T); 1021 } 1022 1023 if (FirstDecl->isCXXClassMember()) 1024 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1025 nullptr); 1026 1027 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1028 return BuildDeclarationNameExpr(SS, Result, ADL); 1029 } 1030 1031 // Determines the context to return to after temporarily entering a 1032 // context. This depends in an unnecessarily complicated way on the 1033 // exact ordering of callbacks from the parser. 1034 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1035 1036 // Functions defined inline within classes aren't parsed until we've 1037 // finished parsing the top-level class, so the top-level class is 1038 // the context we'll need to return to. 1039 // A Lambda call operator whose parent is a class must not be treated 1040 // as an inline member function. A Lambda can be used legally 1041 // either as an in-class member initializer or a default argument. These 1042 // are parsed once the class has been marked complete and so the containing 1043 // context would be the nested class (when the lambda is defined in one); 1044 // If the class is not complete, then the lambda is being used in an 1045 // ill-formed fashion (such as to specify the width of a bit-field, or 1046 // in an array-bound) - in which case we still want to return the 1047 // lexically containing DC (which could be a nested class). 1048 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1049 DC = DC->getLexicalParent(); 1050 1051 // A function not defined within a class will always return to its 1052 // lexical context. 1053 if (!isa<CXXRecordDecl>(DC)) 1054 return DC; 1055 1056 // A C++ inline method/friend is parsed *after* the topmost class 1057 // it was declared in is fully parsed ("complete"); the topmost 1058 // class is the context we need to return to. 1059 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1060 DC = RD; 1061 1062 // Return the declaration context of the topmost class the inline method is 1063 // declared in. 1064 return DC; 1065 } 1066 1067 return DC->getLexicalParent(); 1068 } 1069 1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1071 assert(getContainingDC(DC) == CurContext && 1072 "The next DeclContext should be lexically contained in the current one."); 1073 CurContext = DC; 1074 S->setEntity(DC); 1075 } 1076 1077 void Sema::PopDeclContext() { 1078 assert(CurContext && "DeclContext imbalance!"); 1079 1080 CurContext = getContainingDC(CurContext); 1081 assert(CurContext && "Popped translation unit!"); 1082 } 1083 1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1085 Decl *D) { 1086 // Unlike PushDeclContext, the context to which we return is not necessarily 1087 // the containing DC of TD, because the new context will be some pre-existing 1088 // TagDecl definition instead of a fresh one. 1089 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1090 CurContext = cast<TagDecl>(D)->getDefinition(); 1091 assert(CurContext && "skipping definition of undefined tag"); 1092 S->setEntity(CurContext); 1093 return Result; 1094 } 1095 1096 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1097 CurContext = static_cast<decltype(CurContext)>(Context); 1098 } 1099 1100 /// EnterDeclaratorContext - Used when we must lookup names in the context 1101 /// of a declarator's nested name specifier. 1102 /// 1103 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1104 // C++0x [basic.lookup.unqual]p13: 1105 // A name used in the definition of a static data member of class 1106 // X (after the qualified-id of the static member) is looked up as 1107 // if the name was used in a member function of X. 1108 // C++0x [basic.lookup.unqual]p14: 1109 // If a variable member of a namespace is defined outside of the 1110 // scope of its namespace then any name used in the definition of 1111 // the variable member (after the declarator-id) is looked up as 1112 // if the definition of the variable member occurred in its 1113 // namespace. 1114 // Both of these imply that we should push a scope whose context 1115 // is the semantic context of the declaration. We can't use 1116 // PushDeclContext here because that context is not necessarily 1117 // lexically contained in the current context. Fortunately, 1118 // the containing scope should have the appropriate information. 1119 1120 assert(!S->getEntity() && "scope already has entity"); 1121 1122 #ifndef NDEBUG 1123 Scope *Ancestor = S->getParent(); 1124 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1125 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1126 #endif 1127 1128 CurContext = DC; 1129 S->setEntity(DC); 1130 } 1131 1132 void Sema::ExitDeclaratorContext(Scope *S) { 1133 assert(S->getEntity() == CurContext && "Context imbalance!"); 1134 1135 // Switch back to the lexical context. The safety of this is 1136 // enforced by an assert in EnterDeclaratorContext. 1137 Scope *Ancestor = S->getParent(); 1138 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1139 CurContext = Ancestor->getEntity(); 1140 1141 // We don't need to do anything with the scope, which is going to 1142 // disappear. 1143 } 1144 1145 1146 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1147 // We assume that the caller has already called 1148 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1149 FunctionDecl *FD = D->getAsFunction(); 1150 if (!FD) 1151 return; 1152 1153 // Same implementation as PushDeclContext, but enters the context 1154 // from the lexical parent, rather than the top-level class. 1155 assert(CurContext == FD->getLexicalParent() && 1156 "The next DeclContext should be lexically contained in the current one."); 1157 CurContext = FD; 1158 S->setEntity(CurContext); 1159 1160 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1161 ParmVarDecl *Param = FD->getParamDecl(P); 1162 // If the parameter has an identifier, then add it to the scope 1163 if (Param->getIdentifier()) { 1164 S->AddDecl(Param); 1165 IdResolver.AddDecl(Param); 1166 } 1167 } 1168 } 1169 1170 1171 void Sema::ActOnExitFunctionContext() { 1172 // Same implementation as PopDeclContext, but returns to the lexical parent, 1173 // rather than the top-level class. 1174 assert(CurContext && "DeclContext imbalance!"); 1175 CurContext = CurContext->getLexicalParent(); 1176 assert(CurContext && "Popped translation unit!"); 1177 } 1178 1179 1180 /// \brief Determine whether we allow overloading of the function 1181 /// PrevDecl with another declaration. 1182 /// 1183 /// This routine determines whether overloading is possible, not 1184 /// whether some new function is actually an overload. It will return 1185 /// true in C++ (where we can always provide overloads) or, as an 1186 /// extension, in C when the previous function is already an 1187 /// overloaded function declaration or has the "overloadable" 1188 /// attribute. 1189 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1190 ASTContext &Context) { 1191 if (Context.getLangOpts().CPlusPlus) 1192 return true; 1193 1194 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1195 return true; 1196 1197 return (Previous.getResultKind() == LookupResult::Found 1198 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1199 } 1200 1201 /// Add this decl to the scope shadowed decl chains. 1202 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1203 // Move up the scope chain until we find the nearest enclosing 1204 // non-transparent context. The declaration will be introduced into this 1205 // scope. 1206 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1207 S = S->getParent(); 1208 1209 // Add scoped declarations into their context, so that they can be 1210 // found later. Declarations without a context won't be inserted 1211 // into any context. 1212 if (AddToContext) 1213 CurContext->addDecl(D); 1214 1215 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1216 // are function-local declarations. 1217 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1218 !D->getDeclContext()->getRedeclContext()->Equals( 1219 D->getLexicalDeclContext()->getRedeclContext()) && 1220 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1221 return; 1222 1223 // Template instantiations should also not be pushed into scope. 1224 if (isa<FunctionDecl>(D) && 1225 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1226 return; 1227 1228 // If this replaces anything in the current scope, 1229 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1230 IEnd = IdResolver.end(); 1231 for (; I != IEnd; ++I) { 1232 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1233 S->RemoveDecl(*I); 1234 IdResolver.RemoveDecl(*I); 1235 1236 // Should only need to replace one decl. 1237 break; 1238 } 1239 } 1240 1241 S->AddDecl(D); 1242 1243 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1244 // Implicitly-generated labels may end up getting generated in an order that 1245 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1246 // the label at the appropriate place in the identifier chain. 1247 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1248 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1249 if (IDC == CurContext) { 1250 if (!S->isDeclScope(*I)) 1251 continue; 1252 } else if (IDC->Encloses(CurContext)) 1253 break; 1254 } 1255 1256 IdResolver.InsertDeclAfter(I, D); 1257 } else { 1258 IdResolver.AddDecl(D); 1259 } 1260 } 1261 1262 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1263 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1264 TUScope->AddDecl(D); 1265 } 1266 1267 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1268 bool AllowInlineNamespace) { 1269 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1270 } 1271 1272 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1273 DeclContext *TargetDC = DC->getPrimaryContext(); 1274 do { 1275 if (DeclContext *ScopeDC = S->getEntity()) 1276 if (ScopeDC->getPrimaryContext() == TargetDC) 1277 return S; 1278 } while ((S = S->getParent())); 1279 1280 return nullptr; 1281 } 1282 1283 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1284 DeclContext*, 1285 ASTContext&); 1286 1287 /// Filters out lookup results that don't fall within the given scope 1288 /// as determined by isDeclInScope. 1289 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1290 bool ConsiderLinkage, 1291 bool AllowInlineNamespace) { 1292 LookupResult::Filter F = R.makeFilter(); 1293 while (F.hasNext()) { 1294 NamedDecl *D = F.next(); 1295 1296 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1297 continue; 1298 1299 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1300 continue; 1301 1302 F.erase(); 1303 } 1304 1305 F.done(); 1306 } 1307 1308 static bool isUsingDecl(NamedDecl *D) { 1309 return isa<UsingShadowDecl>(D) || 1310 isa<UnresolvedUsingTypenameDecl>(D) || 1311 isa<UnresolvedUsingValueDecl>(D); 1312 } 1313 1314 /// Removes using shadow declarations from the lookup results. 1315 static void RemoveUsingDecls(LookupResult &R) { 1316 LookupResult::Filter F = R.makeFilter(); 1317 while (F.hasNext()) 1318 if (isUsingDecl(F.next())) 1319 F.erase(); 1320 1321 F.done(); 1322 } 1323 1324 /// \brief Check for this common pattern: 1325 /// @code 1326 /// class S { 1327 /// S(const S&); // DO NOT IMPLEMENT 1328 /// void operator=(const S&); // DO NOT IMPLEMENT 1329 /// }; 1330 /// @endcode 1331 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1332 // FIXME: Should check for private access too but access is set after we get 1333 // the decl here. 1334 if (D->doesThisDeclarationHaveABody()) 1335 return false; 1336 1337 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1338 return CD->isCopyConstructor(); 1339 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1340 return Method->isCopyAssignmentOperator(); 1341 return false; 1342 } 1343 1344 // We need this to handle 1345 // 1346 // typedef struct { 1347 // void *foo() { return 0; } 1348 // } A; 1349 // 1350 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1351 // for example. If 'A', foo will have external linkage. If we have '*A', 1352 // foo will have no linkage. Since we can't know until we get to the end 1353 // of the typedef, this function finds out if D might have non-external linkage. 1354 // Callers should verify at the end of the TU if it D has external linkage or 1355 // not. 1356 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1357 const DeclContext *DC = D->getDeclContext(); 1358 while (!DC->isTranslationUnit()) { 1359 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1360 if (!RD->hasNameForLinkage()) 1361 return true; 1362 } 1363 DC = DC->getParent(); 1364 } 1365 1366 return !D->isExternallyVisible(); 1367 } 1368 1369 // FIXME: This needs to be refactored; some other isInMainFile users want 1370 // these semantics. 1371 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1372 if (S.TUKind != TU_Complete) 1373 return false; 1374 return S.SourceMgr.isInMainFile(Loc); 1375 } 1376 1377 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1378 assert(D); 1379 1380 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1381 return false; 1382 1383 // Ignore all entities declared within templates, and out-of-line definitions 1384 // of members of class templates. 1385 if (D->getDeclContext()->isDependentContext() || 1386 D->getLexicalDeclContext()->isDependentContext()) 1387 return false; 1388 1389 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1390 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1391 return false; 1392 1393 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1394 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1395 return false; 1396 } else { 1397 // 'static inline' functions are defined in headers; don't warn. 1398 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1399 return false; 1400 } 1401 1402 if (FD->doesThisDeclarationHaveABody() && 1403 Context.DeclMustBeEmitted(FD)) 1404 return false; 1405 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1406 // Constants and utility variables are defined in headers with internal 1407 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1408 // like "inline".) 1409 if (!isMainFileLoc(*this, VD->getLocation())) 1410 return false; 1411 1412 if (Context.DeclMustBeEmitted(VD)) 1413 return false; 1414 1415 if (VD->isStaticDataMember() && 1416 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1417 return false; 1418 } else { 1419 return false; 1420 } 1421 1422 // Only warn for unused decls internal to the translation unit. 1423 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1424 // for inline functions defined in the main source file, for instance. 1425 return mightHaveNonExternalLinkage(D); 1426 } 1427 1428 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1429 if (!D) 1430 return; 1431 1432 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1433 const FunctionDecl *First = FD->getFirstDecl(); 1434 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1435 return; // First should already be in the vector. 1436 } 1437 1438 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1439 const VarDecl *First = VD->getFirstDecl(); 1440 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1441 return; // First should already be in the vector. 1442 } 1443 1444 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1445 UnusedFileScopedDecls.push_back(D); 1446 } 1447 1448 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1449 if (D->isInvalidDecl()) 1450 return false; 1451 1452 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1453 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1454 return false; 1455 1456 if (isa<LabelDecl>(D)) 1457 return true; 1458 1459 // Except for labels, we only care about unused decls that are local to 1460 // functions. 1461 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1462 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1463 // For dependent types, the diagnostic is deferred. 1464 WithinFunction = 1465 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1466 if (!WithinFunction) 1467 return false; 1468 1469 if (isa<TypedefNameDecl>(D)) 1470 return true; 1471 1472 // White-list anything that isn't a local variable. 1473 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1474 return false; 1475 1476 // Types of valid local variables should be complete, so this should succeed. 1477 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1478 1479 // White-list anything with an __attribute__((unused)) type. 1480 QualType Ty = VD->getType(); 1481 1482 // Only look at the outermost level of typedef. 1483 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1484 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1485 return false; 1486 } 1487 1488 // If we failed to complete the type for some reason, or if the type is 1489 // dependent, don't diagnose the variable. 1490 if (Ty->isIncompleteType() || Ty->isDependentType()) 1491 return false; 1492 1493 if (const TagType *TT = Ty->getAs<TagType>()) { 1494 const TagDecl *Tag = TT->getDecl(); 1495 if (Tag->hasAttr<UnusedAttr>()) 1496 return false; 1497 1498 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1499 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1500 return false; 1501 1502 if (const Expr *Init = VD->getInit()) { 1503 if (const ExprWithCleanups *Cleanups = 1504 dyn_cast<ExprWithCleanups>(Init)) 1505 Init = Cleanups->getSubExpr(); 1506 const CXXConstructExpr *Construct = 1507 dyn_cast<CXXConstructExpr>(Init); 1508 if (Construct && !Construct->isElidable()) { 1509 CXXConstructorDecl *CD = Construct->getConstructor(); 1510 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1511 return false; 1512 } 1513 } 1514 } 1515 } 1516 1517 // TODO: __attribute__((unused)) templates? 1518 } 1519 1520 return true; 1521 } 1522 1523 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1524 FixItHint &Hint) { 1525 if (isa<LabelDecl>(D)) { 1526 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1527 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1528 if (AfterColon.isInvalid()) 1529 return; 1530 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1531 getCharRange(D->getLocStart(), AfterColon)); 1532 } 1533 return; 1534 } 1535 1536 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1537 if (D->getTypeForDecl()->isDependentType()) 1538 return; 1539 1540 for (auto *TmpD : D->decls()) { 1541 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1542 DiagnoseUnusedDecl(T); 1543 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1544 DiagnoseUnusedNestedTypedefs(R); 1545 } 1546 } 1547 1548 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1549 /// unless they are marked attr(unused). 1550 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1551 if (!ShouldDiagnoseUnusedDecl(D)) 1552 return; 1553 1554 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1555 // typedefs can be referenced later on, so the diagnostics are emitted 1556 // at end-of-translation-unit. 1557 UnusedLocalTypedefNameCandidates.insert(TD); 1558 return; 1559 } 1560 1561 FixItHint Hint; 1562 GenerateFixForUnusedDecl(D, Context, Hint); 1563 1564 unsigned DiagID; 1565 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1566 DiagID = diag::warn_unused_exception_param; 1567 else if (isa<LabelDecl>(D)) 1568 DiagID = diag::warn_unused_label; 1569 else 1570 DiagID = diag::warn_unused_variable; 1571 1572 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1573 } 1574 1575 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1576 // Verify that we have no forward references left. If so, there was a goto 1577 // or address of a label taken, but no definition of it. Label fwd 1578 // definitions are indicated with a null substmt which is also not a resolved 1579 // MS inline assembly label name. 1580 bool Diagnose = false; 1581 if (L->isMSAsmLabel()) 1582 Diagnose = !L->isResolvedMSAsmLabel(); 1583 else 1584 Diagnose = L->getStmt() == nullptr; 1585 if (Diagnose) 1586 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1587 } 1588 1589 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1590 S->mergeNRVOIntoParent(); 1591 1592 if (S->decl_empty()) return; 1593 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1594 "Scope shouldn't contain decls!"); 1595 1596 for (auto *TmpD : S->decls()) { 1597 assert(TmpD && "This decl didn't get pushed??"); 1598 1599 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1600 NamedDecl *D = cast<NamedDecl>(TmpD); 1601 1602 if (!D->getDeclName()) continue; 1603 1604 // Diagnose unused variables in this scope. 1605 if (!S->hasUnrecoverableErrorOccurred()) { 1606 DiagnoseUnusedDecl(D); 1607 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1608 DiagnoseUnusedNestedTypedefs(RD); 1609 } 1610 1611 // If this was a forward reference to a label, verify it was defined. 1612 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1613 CheckPoppedLabel(LD, *this); 1614 1615 // Remove this name from our lexical scope. 1616 IdResolver.RemoveDecl(D); 1617 } 1618 } 1619 1620 /// \brief Look for an Objective-C class in the translation unit. 1621 /// 1622 /// \param Id The name of the Objective-C class we're looking for. If 1623 /// typo-correction fixes this name, the Id will be updated 1624 /// to the fixed name. 1625 /// 1626 /// \param IdLoc The location of the name in the translation unit. 1627 /// 1628 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1629 /// if there is no class with the given name. 1630 /// 1631 /// \returns The declaration of the named Objective-C class, or NULL if the 1632 /// class could not be found. 1633 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1634 SourceLocation IdLoc, 1635 bool DoTypoCorrection) { 1636 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1637 // creation from this context. 1638 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1639 1640 if (!IDecl && DoTypoCorrection) { 1641 // Perform typo correction at the given location, but only if we 1642 // find an Objective-C class name. 1643 if (TypoCorrection C = CorrectTypo( 1644 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1645 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1646 CTK_ErrorRecovery)) { 1647 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1648 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1649 Id = IDecl->getIdentifier(); 1650 } 1651 } 1652 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1653 // This routine must always return a class definition, if any. 1654 if (Def && Def->getDefinition()) 1655 Def = Def->getDefinition(); 1656 return Def; 1657 } 1658 1659 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1660 /// from S, where a non-field would be declared. This routine copes 1661 /// with the difference between C and C++ scoping rules in structs and 1662 /// unions. For example, the following code is well-formed in C but 1663 /// ill-formed in C++: 1664 /// @code 1665 /// struct S6 { 1666 /// enum { BAR } e; 1667 /// }; 1668 /// 1669 /// void test_S6() { 1670 /// struct S6 a; 1671 /// a.e = BAR; 1672 /// } 1673 /// @endcode 1674 /// For the declaration of BAR, this routine will return a different 1675 /// scope. The scope S will be the scope of the unnamed enumeration 1676 /// within S6. In C++, this routine will return the scope associated 1677 /// with S6, because the enumeration's scope is a transparent 1678 /// context but structures can contain non-field names. In C, this 1679 /// routine will return the translation unit scope, since the 1680 /// enumeration's scope is a transparent context and structures cannot 1681 /// contain non-field names. 1682 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1683 while (((S->getFlags() & Scope::DeclScope) == 0) || 1684 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1685 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1686 S = S->getParent(); 1687 return S; 1688 } 1689 1690 /// \brief Looks up the declaration of "struct objc_super" and 1691 /// saves it for later use in building builtin declaration of 1692 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1693 /// pre-existing declaration exists no action takes place. 1694 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1695 IdentifierInfo *II) { 1696 if (!II->isStr("objc_msgSendSuper")) 1697 return; 1698 ASTContext &Context = ThisSema.Context; 1699 1700 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1701 SourceLocation(), Sema::LookupTagName); 1702 ThisSema.LookupName(Result, S); 1703 if (Result.getResultKind() == LookupResult::Found) 1704 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1705 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1706 } 1707 1708 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1709 switch (Error) { 1710 case ASTContext::GE_None: 1711 return ""; 1712 case ASTContext::GE_Missing_stdio: 1713 return "stdio.h"; 1714 case ASTContext::GE_Missing_setjmp: 1715 return "setjmp.h"; 1716 case ASTContext::GE_Missing_ucontext: 1717 return "ucontext.h"; 1718 } 1719 llvm_unreachable("unhandled error kind"); 1720 } 1721 1722 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1723 /// file scope. lazily create a decl for it. ForRedeclaration is true 1724 /// if we're creating this built-in in anticipation of redeclaring the 1725 /// built-in. 1726 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1727 Scope *S, bool ForRedeclaration, 1728 SourceLocation Loc) { 1729 LookupPredefedObjCSuperType(*this, S, II); 1730 1731 ASTContext::GetBuiltinTypeError Error; 1732 QualType R = Context.GetBuiltinType(ID, Error); 1733 if (Error) { 1734 if (ForRedeclaration) 1735 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1736 << getHeaderName(Error) 1737 << Context.BuiltinInfo.GetName(ID); 1738 return nullptr; 1739 } 1740 1741 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1742 Diag(Loc, diag::ext_implicit_lib_function_decl) 1743 << Context.BuiltinInfo.GetName(ID) 1744 << R; 1745 if (Context.BuiltinInfo.getHeaderName(ID) && 1746 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1747 Diag(Loc, diag::note_include_header_or_declare) 1748 << Context.BuiltinInfo.getHeaderName(ID) 1749 << Context.BuiltinInfo.GetName(ID); 1750 } 1751 1752 DeclContext *Parent = Context.getTranslationUnitDecl(); 1753 if (getLangOpts().CPlusPlus) { 1754 LinkageSpecDecl *CLinkageDecl = 1755 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1756 LinkageSpecDecl::lang_c, false); 1757 CLinkageDecl->setImplicit(); 1758 Parent->addDecl(CLinkageDecl); 1759 Parent = CLinkageDecl; 1760 } 1761 1762 FunctionDecl *New = FunctionDecl::Create(Context, 1763 Parent, 1764 Loc, Loc, II, R, /*TInfo=*/nullptr, 1765 SC_Extern, 1766 false, 1767 R->isFunctionProtoType()); 1768 New->setImplicit(); 1769 1770 // Create Decl objects for each parameter, adding them to the 1771 // FunctionDecl. 1772 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1773 SmallVector<ParmVarDecl*, 16> Params; 1774 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1775 ParmVarDecl *parm = 1776 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1777 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1778 SC_None, nullptr); 1779 parm->setScopeInfo(0, i); 1780 Params.push_back(parm); 1781 } 1782 New->setParams(Params); 1783 } 1784 1785 AddKnownFunctionAttributes(New); 1786 RegisterLocallyScopedExternCDecl(New, S); 1787 1788 // TUScope is the translation-unit scope to insert this function into. 1789 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1790 // relate Scopes to DeclContexts, and probably eliminate CurContext 1791 // entirely, but we're not there yet. 1792 DeclContext *SavedContext = CurContext; 1793 CurContext = Parent; 1794 PushOnScopeChains(New, TUScope); 1795 CurContext = SavedContext; 1796 return New; 1797 } 1798 1799 /// \brief Filter out any previous declarations that the given declaration 1800 /// should not consider because they are not permitted to conflict, e.g., 1801 /// because they come from hidden sub-modules and do not refer to the same 1802 /// entity. 1803 static void filterNonConflictingPreviousDecls(Sema &S, 1804 NamedDecl *decl, 1805 LookupResult &previous){ 1806 // This is only interesting when modules are enabled. 1807 if ((!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) || 1808 !S.getLangOpts().ModulesHideInternalLinkage) 1809 return; 1810 1811 // Empty sets are uninteresting. 1812 if (previous.empty()) 1813 return; 1814 1815 LookupResult::Filter filter = previous.makeFilter(); 1816 while (filter.hasNext()) { 1817 NamedDecl *old = filter.next(); 1818 1819 // Non-hidden declarations are never ignored. 1820 if (S.isVisible(old)) 1821 continue; 1822 1823 if (!old->isExternallyVisible()) 1824 filter.erase(); 1825 } 1826 1827 filter.done(); 1828 } 1829 1830 /// Typedef declarations don't have linkage, but they still denote the same 1831 /// entity if their types are the same. 1832 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1833 /// isSameEntity. 1834 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1835 TypedefNameDecl *Decl, 1836 LookupResult &Previous) { 1837 // This is only interesting when modules are enabled. 1838 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 1839 return; 1840 1841 // Empty sets are uninteresting. 1842 if (Previous.empty()) 1843 return; 1844 1845 LookupResult::Filter Filter = Previous.makeFilter(); 1846 while (Filter.hasNext()) { 1847 NamedDecl *Old = Filter.next(); 1848 1849 // Non-hidden declarations are never ignored. 1850 if (S.isVisible(Old)) 1851 continue; 1852 1853 // Declarations of the same entity are not ignored, even if they have 1854 // different linkages. 1855 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1856 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1857 Decl->getUnderlyingType())) 1858 continue; 1859 1860 // If both declarations give a tag declaration a typedef name for linkage 1861 // purposes, then they declare the same entity. 1862 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1863 Decl->getAnonDeclWithTypedefName()) 1864 continue; 1865 } 1866 1867 if (!Old->isExternallyVisible()) 1868 Filter.erase(); 1869 } 1870 1871 Filter.done(); 1872 } 1873 1874 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1875 QualType OldType; 1876 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1877 OldType = OldTypedef->getUnderlyingType(); 1878 else 1879 OldType = Context.getTypeDeclType(Old); 1880 QualType NewType = New->getUnderlyingType(); 1881 1882 if (NewType->isVariablyModifiedType()) { 1883 // Must not redefine a typedef with a variably-modified type. 1884 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1885 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1886 << Kind << NewType; 1887 if (Old->getLocation().isValid()) 1888 Diag(Old->getLocation(), diag::note_previous_definition); 1889 New->setInvalidDecl(); 1890 return true; 1891 } 1892 1893 if (OldType != NewType && 1894 !OldType->isDependentType() && 1895 !NewType->isDependentType() && 1896 !Context.hasSameType(OldType, NewType)) { 1897 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1898 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1899 << Kind << NewType << OldType; 1900 if (Old->getLocation().isValid()) 1901 Diag(Old->getLocation(), diag::note_previous_definition); 1902 New->setInvalidDecl(); 1903 return true; 1904 } 1905 return false; 1906 } 1907 1908 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1909 /// same name and scope as a previous declaration 'Old'. Figure out 1910 /// how to resolve this situation, merging decls or emitting 1911 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1912 /// 1913 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1914 // If the new decl is known invalid already, don't bother doing any 1915 // merging checks. 1916 if (New->isInvalidDecl()) return; 1917 1918 // Allow multiple definitions for ObjC built-in typedefs. 1919 // FIXME: Verify the underlying types are equivalent! 1920 if (getLangOpts().ObjC1) { 1921 const IdentifierInfo *TypeID = New->getIdentifier(); 1922 switch (TypeID->getLength()) { 1923 default: break; 1924 case 2: 1925 { 1926 if (!TypeID->isStr("id")) 1927 break; 1928 QualType T = New->getUnderlyingType(); 1929 if (!T->isPointerType()) 1930 break; 1931 if (!T->isVoidPointerType()) { 1932 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1933 if (!PT->isStructureType()) 1934 break; 1935 } 1936 Context.setObjCIdRedefinitionType(T); 1937 // Install the built-in type for 'id', ignoring the current definition. 1938 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1939 return; 1940 } 1941 case 5: 1942 if (!TypeID->isStr("Class")) 1943 break; 1944 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1945 // Install the built-in type for 'Class', ignoring the current definition. 1946 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1947 return; 1948 case 3: 1949 if (!TypeID->isStr("SEL")) 1950 break; 1951 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1952 // Install the built-in type for 'SEL', ignoring the current definition. 1953 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1954 return; 1955 } 1956 // Fall through - the typedef name was not a builtin type. 1957 } 1958 1959 // Verify the old decl was also a type. 1960 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1961 if (!Old) { 1962 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1963 << New->getDeclName(); 1964 1965 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1966 if (OldD->getLocation().isValid()) 1967 Diag(OldD->getLocation(), diag::note_previous_definition); 1968 1969 return New->setInvalidDecl(); 1970 } 1971 1972 // If the old declaration is invalid, just give up here. 1973 if (Old->isInvalidDecl()) 1974 return New->setInvalidDecl(); 1975 1976 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1977 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 1978 auto *NewTag = New->getAnonDeclWithTypedefName(); 1979 NamedDecl *Hidden = nullptr; 1980 if (getLangOpts().CPlusPlus && OldTag && NewTag && 1981 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 1982 !hasVisibleDefinition(OldTag, &Hidden)) { 1983 // There is a definition of this tag, but it is not visible. Use it 1984 // instead of our tag. 1985 New->setTypeForDecl(OldTD->getTypeForDecl()); 1986 if (OldTD->isModed()) 1987 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 1988 OldTD->getUnderlyingType()); 1989 else 1990 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 1991 1992 // Make the old tag definition visible. 1993 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 1994 } 1995 } 1996 1997 // If the typedef types are not identical, reject them in all languages and 1998 // with any extensions enabled. 1999 if (isIncompatibleTypedef(Old, New)) 2000 return; 2001 2002 // The types match. Link up the redeclaration chain and merge attributes if 2003 // the old declaration was a typedef. 2004 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 2005 New->setPreviousDecl(Typedef); 2006 mergeDeclAttributes(New, Old); 2007 } 2008 2009 if (getLangOpts().MicrosoftExt) 2010 return; 2011 2012 if (getLangOpts().CPlusPlus) { 2013 // C++ [dcl.typedef]p2: 2014 // In a given non-class scope, a typedef specifier can be used to 2015 // redefine the name of any type declared in that scope to refer 2016 // to the type to which it already refers. 2017 if (!isa<CXXRecordDecl>(CurContext)) 2018 return; 2019 2020 // C++0x [dcl.typedef]p4: 2021 // In a given class scope, a typedef specifier can be used to redefine 2022 // any class-name declared in that scope that is not also a typedef-name 2023 // to refer to the type to which it already refers. 2024 // 2025 // This wording came in via DR424, which was a correction to the 2026 // wording in DR56, which accidentally banned code like: 2027 // 2028 // struct S { 2029 // typedef struct A { } A; 2030 // }; 2031 // 2032 // in the C++03 standard. We implement the C++0x semantics, which 2033 // allow the above but disallow 2034 // 2035 // struct S { 2036 // typedef int I; 2037 // typedef int I; 2038 // }; 2039 // 2040 // since that was the intent of DR56. 2041 if (!isa<TypedefNameDecl>(Old)) 2042 return; 2043 2044 Diag(New->getLocation(), diag::err_redefinition) 2045 << New->getDeclName(); 2046 Diag(Old->getLocation(), diag::note_previous_definition); 2047 return New->setInvalidDecl(); 2048 } 2049 2050 // Modules always permit redefinition of typedefs, as does C11. 2051 if (getLangOpts().Modules || getLangOpts().C11) 2052 return; 2053 2054 // If we have a redefinition of a typedef in C, emit a warning. This warning 2055 // is normally mapped to an error, but can be controlled with 2056 // -Wtypedef-redefinition. If either the original or the redefinition is 2057 // in a system header, don't emit this for compatibility with GCC. 2058 if (getDiagnostics().getSuppressSystemWarnings() && 2059 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2060 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2061 return; 2062 2063 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2064 << New->getDeclName(); 2065 Diag(Old->getLocation(), diag::note_previous_definition); 2066 } 2067 2068 /// DeclhasAttr - returns true if decl Declaration already has the target 2069 /// attribute. 2070 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2071 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2072 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2073 for (const auto *i : D->attrs()) 2074 if (i->getKind() == A->getKind()) { 2075 if (Ann) { 2076 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2077 return true; 2078 continue; 2079 } 2080 // FIXME: Don't hardcode this check 2081 if (OA && isa<OwnershipAttr>(i)) 2082 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2083 return true; 2084 } 2085 2086 return false; 2087 } 2088 2089 static bool isAttributeTargetADefinition(Decl *D) { 2090 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2091 return VD->isThisDeclarationADefinition(); 2092 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2093 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2094 return true; 2095 } 2096 2097 /// Merge alignment attributes from \p Old to \p New, taking into account the 2098 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2099 /// 2100 /// \return \c true if any attributes were added to \p New. 2101 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2102 // Look for alignas attributes on Old, and pick out whichever attribute 2103 // specifies the strictest alignment requirement. 2104 AlignedAttr *OldAlignasAttr = nullptr; 2105 AlignedAttr *OldStrictestAlignAttr = nullptr; 2106 unsigned OldAlign = 0; 2107 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2108 // FIXME: We have no way of representing inherited dependent alignments 2109 // in a case like: 2110 // template<int A, int B> struct alignas(A) X; 2111 // template<int A, int B> struct alignas(B) X {}; 2112 // For now, we just ignore any alignas attributes which are not on the 2113 // definition in such a case. 2114 if (I->isAlignmentDependent()) 2115 return false; 2116 2117 if (I->isAlignas()) 2118 OldAlignasAttr = I; 2119 2120 unsigned Align = I->getAlignment(S.Context); 2121 if (Align > OldAlign) { 2122 OldAlign = Align; 2123 OldStrictestAlignAttr = I; 2124 } 2125 } 2126 2127 // Look for alignas attributes on New. 2128 AlignedAttr *NewAlignasAttr = nullptr; 2129 unsigned NewAlign = 0; 2130 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2131 if (I->isAlignmentDependent()) 2132 return false; 2133 2134 if (I->isAlignas()) 2135 NewAlignasAttr = I; 2136 2137 unsigned Align = I->getAlignment(S.Context); 2138 if (Align > NewAlign) 2139 NewAlign = Align; 2140 } 2141 2142 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2143 // Both declarations have 'alignas' attributes. We require them to match. 2144 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2145 // fall short. (If two declarations both have alignas, they must both match 2146 // every definition, and so must match each other if there is a definition.) 2147 2148 // If either declaration only contains 'alignas(0)' specifiers, then it 2149 // specifies the natural alignment for the type. 2150 if (OldAlign == 0 || NewAlign == 0) { 2151 QualType Ty; 2152 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2153 Ty = VD->getType(); 2154 else 2155 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2156 2157 if (OldAlign == 0) 2158 OldAlign = S.Context.getTypeAlign(Ty); 2159 if (NewAlign == 0) 2160 NewAlign = S.Context.getTypeAlign(Ty); 2161 } 2162 2163 if (OldAlign != NewAlign) { 2164 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2165 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2166 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2167 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2168 } 2169 } 2170 2171 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2172 // C++11 [dcl.align]p6: 2173 // if any declaration of an entity has an alignment-specifier, 2174 // every defining declaration of that entity shall specify an 2175 // equivalent alignment. 2176 // C11 6.7.5/7: 2177 // If the definition of an object does not have an alignment 2178 // specifier, any other declaration of that object shall also 2179 // have no alignment specifier. 2180 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2181 << OldAlignasAttr; 2182 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2183 << OldAlignasAttr; 2184 } 2185 2186 bool AnyAdded = false; 2187 2188 // Ensure we have an attribute representing the strictest alignment. 2189 if (OldAlign > NewAlign) { 2190 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2191 Clone->setInherited(true); 2192 New->addAttr(Clone); 2193 AnyAdded = true; 2194 } 2195 2196 // Ensure we have an alignas attribute if the old declaration had one. 2197 if (OldAlignasAttr && !NewAlignasAttr && 2198 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2199 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2200 Clone->setInherited(true); 2201 New->addAttr(Clone); 2202 AnyAdded = true; 2203 } 2204 2205 return AnyAdded; 2206 } 2207 2208 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2209 const InheritableAttr *Attr, bool Override) { 2210 InheritableAttr *NewAttr = nullptr; 2211 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2212 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2213 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2214 AA->getIntroduced(), AA->getDeprecated(), 2215 AA->getObsoleted(), AA->getUnavailable(), 2216 AA->getMessage(), Override, 2217 AttrSpellingListIndex); 2218 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2219 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2220 AttrSpellingListIndex); 2221 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2222 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2223 AttrSpellingListIndex); 2224 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2225 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2226 AttrSpellingListIndex); 2227 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2228 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2229 AttrSpellingListIndex); 2230 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2231 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2232 FA->getFormatIdx(), FA->getFirstArg(), 2233 AttrSpellingListIndex); 2234 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2235 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2236 AttrSpellingListIndex); 2237 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2238 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2239 AttrSpellingListIndex, 2240 IA->getSemanticSpelling()); 2241 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2242 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2243 &S.Context.Idents.get(AA->getSpelling()), 2244 AttrSpellingListIndex); 2245 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2246 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2247 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2248 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2249 else if (isa<AlignedAttr>(Attr)) 2250 // AlignedAttrs are handled separately, because we need to handle all 2251 // such attributes on a declaration at the same time. 2252 NewAttr = nullptr; 2253 else if (isa<DeprecatedAttr>(Attr) && Override) 2254 NewAttr = nullptr; 2255 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2256 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2257 2258 if (NewAttr) { 2259 NewAttr->setInherited(true); 2260 D->addAttr(NewAttr); 2261 return true; 2262 } 2263 2264 return false; 2265 } 2266 2267 static const Decl *getDefinition(const Decl *D) { 2268 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2269 return TD->getDefinition(); 2270 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2271 const VarDecl *Def = VD->getDefinition(); 2272 if (Def) 2273 return Def; 2274 return VD->getActingDefinition(); 2275 } 2276 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2277 const FunctionDecl* Def; 2278 if (FD->isDefined(Def)) 2279 return Def; 2280 } 2281 return nullptr; 2282 } 2283 2284 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2285 for (const auto *Attribute : D->attrs()) 2286 if (Attribute->getKind() == Kind) 2287 return true; 2288 return false; 2289 } 2290 2291 /// checkNewAttributesAfterDef - If we already have a definition, check that 2292 /// there are no new attributes in this declaration. 2293 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2294 if (!New->hasAttrs()) 2295 return; 2296 2297 const Decl *Def = getDefinition(Old); 2298 if (!Def || Def == New) 2299 return; 2300 2301 AttrVec &NewAttributes = New->getAttrs(); 2302 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2303 const Attr *NewAttribute = NewAttributes[I]; 2304 2305 if (isa<AliasAttr>(NewAttribute)) { 2306 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2307 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2308 else { 2309 VarDecl *VD = cast<VarDecl>(New); 2310 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2311 VarDecl::TentativeDefinition 2312 ? diag::err_alias_after_tentative 2313 : diag::err_redefinition; 2314 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2315 S.Diag(Def->getLocation(), diag::note_previous_definition); 2316 VD->setInvalidDecl(); 2317 } 2318 ++I; 2319 continue; 2320 } 2321 2322 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2323 // Tentative definitions are only interesting for the alias check above. 2324 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2325 ++I; 2326 continue; 2327 } 2328 } 2329 2330 if (hasAttribute(Def, NewAttribute->getKind())) { 2331 ++I; 2332 continue; // regular attr merging will take care of validating this. 2333 } 2334 2335 if (isa<C11NoReturnAttr>(NewAttribute)) { 2336 // C's _Noreturn is allowed to be added to a function after it is defined. 2337 ++I; 2338 continue; 2339 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2340 if (AA->isAlignas()) { 2341 // C++11 [dcl.align]p6: 2342 // if any declaration of an entity has an alignment-specifier, 2343 // every defining declaration of that entity shall specify an 2344 // equivalent alignment. 2345 // C11 6.7.5/7: 2346 // If the definition of an object does not have an alignment 2347 // specifier, any other declaration of that object shall also 2348 // have no alignment specifier. 2349 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2350 << AA; 2351 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2352 << AA; 2353 NewAttributes.erase(NewAttributes.begin() + I); 2354 --E; 2355 continue; 2356 } 2357 } 2358 2359 S.Diag(NewAttribute->getLocation(), 2360 diag::warn_attribute_precede_definition); 2361 S.Diag(Def->getLocation(), diag::note_previous_definition); 2362 NewAttributes.erase(NewAttributes.begin() + I); 2363 --E; 2364 } 2365 } 2366 2367 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2368 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2369 AvailabilityMergeKind AMK) { 2370 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2371 UsedAttr *NewAttr = OldAttr->clone(Context); 2372 NewAttr->setInherited(true); 2373 New->addAttr(NewAttr); 2374 } 2375 2376 if (!Old->hasAttrs() && !New->hasAttrs()) 2377 return; 2378 2379 // attributes declared post-definition are currently ignored 2380 checkNewAttributesAfterDef(*this, New, Old); 2381 2382 if (!Old->hasAttrs()) 2383 return; 2384 2385 bool foundAny = New->hasAttrs(); 2386 2387 // Ensure that any moving of objects within the allocated map is done before 2388 // we process them. 2389 if (!foundAny) New->setAttrs(AttrVec()); 2390 2391 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2392 bool Override = false; 2393 // Ignore deprecated/unavailable/availability attributes if requested. 2394 if (isa<DeprecatedAttr>(I) || 2395 isa<UnavailableAttr>(I) || 2396 isa<AvailabilityAttr>(I)) { 2397 switch (AMK) { 2398 case AMK_None: 2399 continue; 2400 2401 case AMK_Redeclaration: 2402 break; 2403 2404 case AMK_Override: 2405 Override = true; 2406 break; 2407 } 2408 } 2409 2410 // Already handled. 2411 if (isa<UsedAttr>(I)) 2412 continue; 2413 2414 if (mergeDeclAttribute(*this, New, I, Override)) 2415 foundAny = true; 2416 } 2417 2418 if (mergeAlignedAttrs(*this, New, Old)) 2419 foundAny = true; 2420 2421 if (!foundAny) New->dropAttrs(); 2422 } 2423 2424 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2425 /// to the new one. 2426 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2427 const ParmVarDecl *oldDecl, 2428 Sema &S) { 2429 // C++11 [dcl.attr.depend]p2: 2430 // The first declaration of a function shall specify the 2431 // carries_dependency attribute for its declarator-id if any declaration 2432 // of the function specifies the carries_dependency attribute. 2433 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2434 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2435 S.Diag(CDA->getLocation(), 2436 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2437 // Find the first declaration of the parameter. 2438 // FIXME: Should we build redeclaration chains for function parameters? 2439 const FunctionDecl *FirstFD = 2440 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2441 const ParmVarDecl *FirstVD = 2442 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2443 S.Diag(FirstVD->getLocation(), 2444 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2445 } 2446 2447 if (!oldDecl->hasAttrs()) 2448 return; 2449 2450 bool foundAny = newDecl->hasAttrs(); 2451 2452 // Ensure that any moving of objects within the allocated map is 2453 // done before we process them. 2454 if (!foundAny) newDecl->setAttrs(AttrVec()); 2455 2456 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2457 if (!DeclHasAttr(newDecl, I)) { 2458 InheritableAttr *newAttr = 2459 cast<InheritableParamAttr>(I->clone(S.Context)); 2460 newAttr->setInherited(true); 2461 newDecl->addAttr(newAttr); 2462 foundAny = true; 2463 } 2464 } 2465 2466 if (!foundAny) newDecl->dropAttrs(); 2467 } 2468 2469 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2470 const ParmVarDecl *OldParam, 2471 Sema &S) { 2472 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2473 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2474 if (*Oldnullability != *Newnullability) { 2475 unsigned unsNewnullability = static_cast<unsigned>(*Newnullability); 2476 unsigned unsOldnullability = static_cast<unsigned>(*Oldnullability); 2477 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2478 << unsNewnullability 2479 << ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) != 0) 2480 << unsOldnullability 2481 << ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) != 0); 2482 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2483 } 2484 } else { 2485 QualType NewT = NewParam->getType(); 2486 NewT = S.Context.getAttributedType( 2487 AttributedType::getNullabilityAttrKind(*Oldnullability), 2488 NewT, NewT); 2489 NewParam->setType(NewT); 2490 } 2491 } 2492 } 2493 2494 namespace { 2495 2496 /// Used in MergeFunctionDecl to keep track of function parameters in 2497 /// C. 2498 struct GNUCompatibleParamWarning { 2499 ParmVarDecl *OldParm; 2500 ParmVarDecl *NewParm; 2501 QualType PromotedType; 2502 }; 2503 2504 } // namespace 2505 2506 /// getSpecialMember - get the special member enum for a method. 2507 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2508 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2509 if (Ctor->isDefaultConstructor()) 2510 return Sema::CXXDefaultConstructor; 2511 2512 if (Ctor->isCopyConstructor()) 2513 return Sema::CXXCopyConstructor; 2514 2515 if (Ctor->isMoveConstructor()) 2516 return Sema::CXXMoveConstructor; 2517 } else if (isa<CXXDestructorDecl>(MD)) { 2518 return Sema::CXXDestructor; 2519 } else if (MD->isCopyAssignmentOperator()) { 2520 return Sema::CXXCopyAssignment; 2521 } else if (MD->isMoveAssignmentOperator()) { 2522 return Sema::CXXMoveAssignment; 2523 } 2524 2525 return Sema::CXXInvalid; 2526 } 2527 2528 // Determine whether the previous declaration was a definition, implicit 2529 // declaration, or a declaration. 2530 template <typename T> 2531 static std::pair<diag::kind, SourceLocation> 2532 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2533 diag::kind PrevDiag; 2534 SourceLocation OldLocation = Old->getLocation(); 2535 if (Old->isThisDeclarationADefinition()) 2536 PrevDiag = diag::note_previous_definition; 2537 else if (Old->isImplicit()) { 2538 PrevDiag = diag::note_previous_implicit_declaration; 2539 if (OldLocation.isInvalid()) 2540 OldLocation = New->getLocation(); 2541 } else 2542 PrevDiag = diag::note_previous_declaration; 2543 return std::make_pair(PrevDiag, OldLocation); 2544 } 2545 2546 /// canRedefineFunction - checks if a function can be redefined. Currently, 2547 /// only extern inline functions can be redefined, and even then only in 2548 /// GNU89 mode. 2549 static bool canRedefineFunction(const FunctionDecl *FD, 2550 const LangOptions& LangOpts) { 2551 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2552 !LangOpts.CPlusPlus && 2553 FD->isInlineSpecified() && 2554 FD->getStorageClass() == SC_Extern); 2555 } 2556 2557 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2558 const AttributedType *AT = T->getAs<AttributedType>(); 2559 while (AT && !AT->isCallingConv()) 2560 AT = AT->getModifiedType()->getAs<AttributedType>(); 2561 return AT; 2562 } 2563 2564 template <typename T> 2565 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2566 const DeclContext *DC = Old->getDeclContext(); 2567 if (DC->isRecord()) 2568 return false; 2569 2570 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2571 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2572 return true; 2573 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2574 return true; 2575 return false; 2576 } 2577 2578 /// MergeFunctionDecl - We just parsed a function 'New' from 2579 /// declarator D which has the same name and scope as a previous 2580 /// declaration 'Old'. Figure out how to resolve this situation, 2581 /// merging decls or emitting diagnostics as appropriate. 2582 /// 2583 /// In C++, New and Old must be declarations that are not 2584 /// overloaded. Use IsOverload to determine whether New and Old are 2585 /// overloaded, and to select the Old declaration that New should be 2586 /// merged with. 2587 /// 2588 /// Returns true if there was an error, false otherwise. 2589 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2590 Scope *S, bool MergeTypeWithOld) { 2591 // Verify the old decl was also a function. 2592 FunctionDecl *Old = OldD->getAsFunction(); 2593 if (!Old) { 2594 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2595 if (New->getFriendObjectKind()) { 2596 Diag(New->getLocation(), diag::err_using_decl_friend); 2597 Diag(Shadow->getTargetDecl()->getLocation(), 2598 diag::note_using_decl_target); 2599 Diag(Shadow->getUsingDecl()->getLocation(), 2600 diag::note_using_decl) << 0; 2601 return true; 2602 } 2603 2604 // C++11 [namespace.udecl]p14: 2605 // If a function declaration in namespace scope or block scope has the 2606 // same name and the same parameter-type-list as a function introduced 2607 // by a using-declaration, and the declarations do not declare the same 2608 // function, the program is ill-formed. 2609 2610 // Check whether the two declarations might declare the same function. 2611 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2612 if (Old && 2613 !Old->getDeclContext()->getRedeclContext()->Equals( 2614 New->getDeclContext()->getRedeclContext()) && 2615 !(Old->isExternC() && New->isExternC())) 2616 Old = nullptr; 2617 2618 if (!Old) { 2619 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2620 Diag(Shadow->getTargetDecl()->getLocation(), 2621 diag::note_using_decl_target); 2622 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2623 return true; 2624 } 2625 OldD = Old; 2626 } else { 2627 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2628 << New->getDeclName(); 2629 Diag(OldD->getLocation(), diag::note_previous_definition); 2630 return true; 2631 } 2632 } 2633 2634 // If the old declaration is invalid, just give up here. 2635 if (Old->isInvalidDecl()) 2636 return true; 2637 2638 diag::kind PrevDiag; 2639 SourceLocation OldLocation; 2640 std::tie(PrevDiag, OldLocation) = 2641 getNoteDiagForInvalidRedeclaration(Old, New); 2642 2643 // Don't complain about this if we're in GNU89 mode and the old function 2644 // is an extern inline function. 2645 // Don't complain about specializations. They are not supposed to have 2646 // storage classes. 2647 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2648 New->getStorageClass() == SC_Static && 2649 Old->hasExternalFormalLinkage() && 2650 !New->getTemplateSpecializationInfo() && 2651 !canRedefineFunction(Old, getLangOpts())) { 2652 if (getLangOpts().MicrosoftExt) { 2653 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2654 Diag(OldLocation, PrevDiag); 2655 } else { 2656 Diag(New->getLocation(), diag::err_static_non_static) << New; 2657 Diag(OldLocation, PrevDiag); 2658 return true; 2659 } 2660 } 2661 2662 2663 // If a function is first declared with a calling convention, but is later 2664 // declared or defined without one, all following decls assume the calling 2665 // convention of the first. 2666 // 2667 // It's OK if a function is first declared without a calling convention, 2668 // but is later declared or defined with the default calling convention. 2669 // 2670 // To test if either decl has an explicit calling convention, we look for 2671 // AttributedType sugar nodes on the type as written. If they are missing or 2672 // were canonicalized away, we assume the calling convention was implicit. 2673 // 2674 // Note also that we DO NOT return at this point, because we still have 2675 // other tests to run. 2676 QualType OldQType = Context.getCanonicalType(Old->getType()); 2677 QualType NewQType = Context.getCanonicalType(New->getType()); 2678 const FunctionType *OldType = cast<FunctionType>(OldQType); 2679 const FunctionType *NewType = cast<FunctionType>(NewQType); 2680 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2681 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2682 bool RequiresAdjustment = false; 2683 2684 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2685 FunctionDecl *First = Old->getFirstDecl(); 2686 const FunctionType *FT = 2687 First->getType().getCanonicalType()->castAs<FunctionType>(); 2688 FunctionType::ExtInfo FI = FT->getExtInfo(); 2689 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2690 if (!NewCCExplicit) { 2691 // Inherit the CC from the previous declaration if it was specified 2692 // there but not here. 2693 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2694 RequiresAdjustment = true; 2695 } else { 2696 // Calling conventions aren't compatible, so complain. 2697 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2698 Diag(New->getLocation(), diag::err_cconv_change) 2699 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2700 << !FirstCCExplicit 2701 << (!FirstCCExplicit ? "" : 2702 FunctionType::getNameForCallConv(FI.getCC())); 2703 2704 // Put the note on the first decl, since it is the one that matters. 2705 Diag(First->getLocation(), diag::note_previous_declaration); 2706 return true; 2707 } 2708 } 2709 2710 // FIXME: diagnose the other way around? 2711 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2712 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2713 RequiresAdjustment = true; 2714 } 2715 2716 // Merge regparm attribute. 2717 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2718 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2719 if (NewTypeInfo.getHasRegParm()) { 2720 Diag(New->getLocation(), diag::err_regparm_mismatch) 2721 << NewType->getRegParmType() 2722 << OldType->getRegParmType(); 2723 Diag(OldLocation, diag::note_previous_declaration); 2724 return true; 2725 } 2726 2727 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2728 RequiresAdjustment = true; 2729 } 2730 2731 // Merge ns_returns_retained attribute. 2732 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2733 if (NewTypeInfo.getProducesResult()) { 2734 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2735 Diag(OldLocation, diag::note_previous_declaration); 2736 return true; 2737 } 2738 2739 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2740 RequiresAdjustment = true; 2741 } 2742 2743 if (RequiresAdjustment) { 2744 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2745 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2746 New->setType(QualType(AdjustedType, 0)); 2747 NewQType = Context.getCanonicalType(New->getType()); 2748 NewType = cast<FunctionType>(NewQType); 2749 } 2750 2751 // If this redeclaration makes the function inline, we may need to add it to 2752 // UndefinedButUsed. 2753 if (!Old->isInlined() && New->isInlined() && 2754 !New->hasAttr<GNUInlineAttr>() && 2755 !getLangOpts().GNUInline && 2756 Old->isUsed(false) && 2757 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2758 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2759 SourceLocation())); 2760 2761 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2762 // about it. 2763 if (New->hasAttr<GNUInlineAttr>() && 2764 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2765 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2766 } 2767 2768 if (getLangOpts().CPlusPlus) { 2769 // (C++98 13.1p2): 2770 // Certain function declarations cannot be overloaded: 2771 // -- Function declarations that differ only in the return type 2772 // cannot be overloaded. 2773 2774 // Go back to the type source info to compare the declared return types, 2775 // per C++1y [dcl.type.auto]p13: 2776 // Redeclarations or specializations of a function or function template 2777 // with a declared return type that uses a placeholder type shall also 2778 // use that placeholder, not a deduced type. 2779 QualType OldDeclaredReturnType = 2780 (Old->getTypeSourceInfo() 2781 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2782 : OldType)->getReturnType(); 2783 QualType NewDeclaredReturnType = 2784 (New->getTypeSourceInfo() 2785 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2786 : NewType)->getReturnType(); 2787 QualType ResQT; 2788 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2789 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2790 New->isLocalExternDecl())) { 2791 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2792 OldDeclaredReturnType->isObjCObjectPointerType()) 2793 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2794 if (ResQT.isNull()) { 2795 if (New->isCXXClassMember() && New->isOutOfLine()) 2796 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2797 << New << New->getReturnTypeSourceRange(); 2798 else 2799 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2800 << New->getReturnTypeSourceRange(); 2801 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2802 << Old->getReturnTypeSourceRange(); 2803 return true; 2804 } 2805 else 2806 NewQType = ResQT; 2807 } 2808 2809 QualType OldReturnType = OldType->getReturnType(); 2810 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2811 if (OldReturnType != NewReturnType) { 2812 // If this function has a deduced return type and has already been 2813 // defined, copy the deduced value from the old declaration. 2814 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2815 if (OldAT && OldAT->isDeduced()) { 2816 New->setType( 2817 SubstAutoType(New->getType(), 2818 OldAT->isDependentType() ? Context.DependentTy 2819 : OldAT->getDeducedType())); 2820 NewQType = Context.getCanonicalType( 2821 SubstAutoType(NewQType, 2822 OldAT->isDependentType() ? Context.DependentTy 2823 : OldAT->getDeducedType())); 2824 } 2825 } 2826 2827 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2828 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2829 if (OldMethod && NewMethod) { 2830 // Preserve triviality. 2831 NewMethod->setTrivial(OldMethod->isTrivial()); 2832 2833 // MSVC allows explicit template specialization at class scope: 2834 // 2 CXXMethodDecls referring to the same function will be injected. 2835 // We don't want a redeclaration error. 2836 bool IsClassScopeExplicitSpecialization = 2837 OldMethod->isFunctionTemplateSpecialization() && 2838 NewMethod->isFunctionTemplateSpecialization(); 2839 bool isFriend = NewMethod->getFriendObjectKind(); 2840 2841 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2842 !IsClassScopeExplicitSpecialization) { 2843 // -- Member function declarations with the same name and the 2844 // same parameter types cannot be overloaded if any of them 2845 // is a static member function declaration. 2846 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2847 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2848 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2849 return true; 2850 } 2851 2852 // C++ [class.mem]p1: 2853 // [...] A member shall not be declared twice in the 2854 // member-specification, except that a nested class or member 2855 // class template can be declared and then later defined. 2856 if (ActiveTemplateInstantiations.empty()) { 2857 unsigned NewDiag; 2858 if (isa<CXXConstructorDecl>(OldMethod)) 2859 NewDiag = diag::err_constructor_redeclared; 2860 else if (isa<CXXDestructorDecl>(NewMethod)) 2861 NewDiag = diag::err_destructor_redeclared; 2862 else if (isa<CXXConversionDecl>(NewMethod)) 2863 NewDiag = diag::err_conv_function_redeclared; 2864 else 2865 NewDiag = diag::err_member_redeclared; 2866 2867 Diag(New->getLocation(), NewDiag); 2868 } else { 2869 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2870 << New << New->getType(); 2871 } 2872 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2873 return true; 2874 2875 // Complain if this is an explicit declaration of a special 2876 // member that was initially declared implicitly. 2877 // 2878 // As an exception, it's okay to befriend such methods in order 2879 // to permit the implicit constructor/destructor/operator calls. 2880 } else if (OldMethod->isImplicit()) { 2881 if (isFriend) { 2882 NewMethod->setImplicit(); 2883 } else { 2884 Diag(NewMethod->getLocation(), 2885 diag::err_definition_of_implicitly_declared_member) 2886 << New << getSpecialMember(OldMethod); 2887 return true; 2888 } 2889 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2890 Diag(NewMethod->getLocation(), 2891 diag::err_definition_of_explicitly_defaulted_member) 2892 << getSpecialMember(OldMethod); 2893 return true; 2894 } 2895 } 2896 2897 // C++11 [dcl.attr.noreturn]p1: 2898 // The first declaration of a function shall specify the noreturn 2899 // attribute if any declaration of that function specifies the noreturn 2900 // attribute. 2901 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2902 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2903 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2904 Diag(Old->getFirstDecl()->getLocation(), 2905 diag::note_noreturn_missing_first_decl); 2906 } 2907 2908 // C++11 [dcl.attr.depend]p2: 2909 // The first declaration of a function shall specify the 2910 // carries_dependency attribute for its declarator-id if any declaration 2911 // of the function specifies the carries_dependency attribute. 2912 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2913 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2914 Diag(CDA->getLocation(), 2915 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2916 Diag(Old->getFirstDecl()->getLocation(), 2917 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2918 } 2919 2920 // (C++98 8.3.5p3): 2921 // All declarations for a function shall agree exactly in both the 2922 // return type and the parameter-type-list. 2923 // We also want to respect all the extended bits except noreturn. 2924 2925 // noreturn should now match unless the old type info didn't have it. 2926 QualType OldQTypeForComparison = OldQType; 2927 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2928 assert(OldQType == QualType(OldType, 0)); 2929 const FunctionType *OldTypeForComparison 2930 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2931 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2932 assert(OldQTypeForComparison.isCanonical()); 2933 } 2934 2935 if (haveIncompatibleLanguageLinkages(Old, New)) { 2936 // As a special case, retain the language linkage from previous 2937 // declarations of a friend function as an extension. 2938 // 2939 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2940 // and is useful because there's otherwise no way to specify language 2941 // linkage within class scope. 2942 // 2943 // Check cautiously as the friend object kind isn't yet complete. 2944 if (New->getFriendObjectKind() != Decl::FOK_None) { 2945 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2946 Diag(OldLocation, PrevDiag); 2947 } else { 2948 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2949 Diag(OldLocation, PrevDiag); 2950 return true; 2951 } 2952 } 2953 2954 if (OldQTypeForComparison == NewQType) 2955 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2956 2957 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2958 New->isLocalExternDecl()) { 2959 // It's OK if we couldn't merge types for a local function declaraton 2960 // if either the old or new type is dependent. We'll merge the types 2961 // when we instantiate the function. 2962 return false; 2963 } 2964 2965 // Fall through for conflicting redeclarations and redefinitions. 2966 } 2967 2968 // C: Function types need to be compatible, not identical. This handles 2969 // duplicate function decls like "void f(int); void f(enum X);" properly. 2970 if (!getLangOpts().CPlusPlus && 2971 Context.typesAreCompatible(OldQType, NewQType)) { 2972 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2973 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2974 const FunctionProtoType *OldProto = nullptr; 2975 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2976 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2977 // The old declaration provided a function prototype, but the 2978 // new declaration does not. Merge in the prototype. 2979 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2980 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2981 NewQType = 2982 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2983 OldProto->getExtProtoInfo()); 2984 New->setType(NewQType); 2985 New->setHasInheritedPrototype(); 2986 2987 // Synthesize parameters with the same types. 2988 SmallVector<ParmVarDecl*, 16> Params; 2989 for (const auto &ParamType : OldProto->param_types()) { 2990 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2991 SourceLocation(), nullptr, 2992 ParamType, /*TInfo=*/nullptr, 2993 SC_None, nullptr); 2994 Param->setScopeInfo(0, Params.size()); 2995 Param->setImplicit(); 2996 Params.push_back(Param); 2997 } 2998 2999 New->setParams(Params); 3000 } 3001 3002 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3003 } 3004 3005 // GNU C permits a K&R definition to follow a prototype declaration 3006 // if the declared types of the parameters in the K&R definition 3007 // match the types in the prototype declaration, even when the 3008 // promoted types of the parameters from the K&R definition differ 3009 // from the types in the prototype. GCC then keeps the types from 3010 // the prototype. 3011 // 3012 // If a variadic prototype is followed by a non-variadic K&R definition, 3013 // the K&R definition becomes variadic. This is sort of an edge case, but 3014 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3015 // C99 6.9.1p8. 3016 if (!getLangOpts().CPlusPlus && 3017 Old->hasPrototype() && !New->hasPrototype() && 3018 New->getType()->getAs<FunctionProtoType>() && 3019 Old->getNumParams() == New->getNumParams()) { 3020 SmallVector<QualType, 16> ArgTypes; 3021 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3022 const FunctionProtoType *OldProto 3023 = Old->getType()->getAs<FunctionProtoType>(); 3024 const FunctionProtoType *NewProto 3025 = New->getType()->getAs<FunctionProtoType>(); 3026 3027 // Determine whether this is the GNU C extension. 3028 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3029 NewProto->getReturnType()); 3030 bool LooseCompatible = !MergedReturn.isNull(); 3031 for (unsigned Idx = 0, End = Old->getNumParams(); 3032 LooseCompatible && Idx != End; ++Idx) { 3033 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3034 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3035 if (Context.typesAreCompatible(OldParm->getType(), 3036 NewProto->getParamType(Idx))) { 3037 ArgTypes.push_back(NewParm->getType()); 3038 } else if (Context.typesAreCompatible(OldParm->getType(), 3039 NewParm->getType(), 3040 /*CompareUnqualified=*/true)) { 3041 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3042 NewProto->getParamType(Idx) }; 3043 Warnings.push_back(Warn); 3044 ArgTypes.push_back(NewParm->getType()); 3045 } else 3046 LooseCompatible = false; 3047 } 3048 3049 if (LooseCompatible) { 3050 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3051 Diag(Warnings[Warn].NewParm->getLocation(), 3052 diag::ext_param_promoted_not_compatible_with_prototype) 3053 << Warnings[Warn].PromotedType 3054 << Warnings[Warn].OldParm->getType(); 3055 if (Warnings[Warn].OldParm->getLocation().isValid()) 3056 Diag(Warnings[Warn].OldParm->getLocation(), 3057 diag::note_previous_declaration); 3058 } 3059 3060 if (MergeTypeWithOld) 3061 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3062 OldProto->getExtProtoInfo())); 3063 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3064 } 3065 3066 // Fall through to diagnose conflicting types. 3067 } 3068 3069 // A function that has already been declared has been redeclared or 3070 // defined with a different type; show an appropriate diagnostic. 3071 3072 // If the previous declaration was an implicitly-generated builtin 3073 // declaration, then at the very least we should use a specialized note. 3074 unsigned BuiltinID; 3075 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3076 // If it's actually a library-defined builtin function like 'malloc' 3077 // or 'printf', just warn about the incompatible redeclaration. 3078 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3079 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3080 Diag(OldLocation, diag::note_previous_builtin_declaration) 3081 << Old << Old->getType(); 3082 3083 // If this is a global redeclaration, just forget hereafter 3084 // about the "builtin-ness" of the function. 3085 // 3086 // Doing this for local extern declarations is problematic. If 3087 // the builtin declaration remains visible, a second invalid 3088 // local declaration will produce a hard error; if it doesn't 3089 // remain visible, a single bogus local redeclaration (which is 3090 // actually only a warning) could break all the downstream code. 3091 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3092 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 3093 3094 return false; 3095 } 3096 3097 PrevDiag = diag::note_previous_builtin_declaration; 3098 } 3099 3100 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3101 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3102 return true; 3103 } 3104 3105 /// \brief Completes the merge of two function declarations that are 3106 /// known to be compatible. 3107 /// 3108 /// This routine handles the merging of attributes and other 3109 /// properties of function declarations from the old declaration to 3110 /// the new declaration, once we know that New is in fact a 3111 /// redeclaration of Old. 3112 /// 3113 /// \returns false 3114 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3115 Scope *S, bool MergeTypeWithOld) { 3116 // Merge the attributes 3117 mergeDeclAttributes(New, Old); 3118 3119 // Merge "pure" flag. 3120 if (Old->isPure()) 3121 New->setPure(); 3122 3123 // Merge "used" flag. 3124 if (Old->getMostRecentDecl()->isUsed(false)) 3125 New->setIsUsed(); 3126 3127 // Merge attributes from the parameters. These can mismatch with K&R 3128 // declarations. 3129 if (New->getNumParams() == Old->getNumParams()) 3130 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3131 ParmVarDecl *NewParam = New->getParamDecl(i); 3132 ParmVarDecl *OldParam = Old->getParamDecl(i); 3133 mergeParamDeclAttributes(NewParam, OldParam, *this); 3134 mergeParamDeclTypes(NewParam, OldParam, *this); 3135 } 3136 3137 if (getLangOpts().CPlusPlus) 3138 return MergeCXXFunctionDecl(New, Old, S); 3139 3140 // Merge the function types so the we get the composite types for the return 3141 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3142 // was visible. 3143 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3144 if (!Merged.isNull() && MergeTypeWithOld) 3145 New->setType(Merged); 3146 3147 return false; 3148 } 3149 3150 3151 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3152 ObjCMethodDecl *oldMethod) { 3153 3154 // Merge the attributes, including deprecated/unavailable 3155 AvailabilityMergeKind MergeKind = 3156 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3157 : AMK_Override; 3158 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3159 3160 // Merge attributes from the parameters. 3161 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3162 oe = oldMethod->param_end(); 3163 for (ObjCMethodDecl::param_iterator 3164 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3165 ni != ne && oi != oe; ++ni, ++oi) 3166 mergeParamDeclAttributes(*ni, *oi, *this); 3167 3168 CheckObjCMethodOverride(newMethod, oldMethod); 3169 } 3170 3171 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3172 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3173 /// emitting diagnostics as appropriate. 3174 /// 3175 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3176 /// to here in AddInitializerToDecl. We can't check them before the initializer 3177 /// is attached. 3178 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3179 bool MergeTypeWithOld) { 3180 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3181 return; 3182 3183 QualType MergedT; 3184 if (getLangOpts().CPlusPlus) { 3185 if (New->getType()->isUndeducedType()) { 3186 // We don't know what the new type is until the initializer is attached. 3187 return; 3188 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3189 // These could still be something that needs exception specs checked. 3190 return MergeVarDeclExceptionSpecs(New, Old); 3191 } 3192 // C++ [basic.link]p10: 3193 // [...] the types specified by all declarations referring to a given 3194 // object or function shall be identical, except that declarations for an 3195 // array object can specify array types that differ by the presence or 3196 // absence of a major array bound (8.3.4). 3197 else if (Old->getType()->isIncompleteArrayType() && 3198 New->getType()->isArrayType()) { 3199 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3200 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3201 if (Context.hasSameType(OldArray->getElementType(), 3202 NewArray->getElementType())) 3203 MergedT = New->getType(); 3204 } else if (Old->getType()->isArrayType() && 3205 New->getType()->isIncompleteArrayType()) { 3206 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3207 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3208 if (Context.hasSameType(OldArray->getElementType(), 3209 NewArray->getElementType())) 3210 MergedT = Old->getType(); 3211 } else if (New->getType()->isObjCObjectPointerType() && 3212 Old->getType()->isObjCObjectPointerType()) { 3213 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3214 Old->getType()); 3215 } 3216 } else { 3217 // C 6.2.7p2: 3218 // All declarations that refer to the same object or function shall have 3219 // compatible type. 3220 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3221 } 3222 if (MergedT.isNull()) { 3223 // It's OK if we couldn't merge types if either type is dependent, for a 3224 // block-scope variable. In other cases (static data members of class 3225 // templates, variable templates, ...), we require the types to be 3226 // equivalent. 3227 // FIXME: The C++ standard doesn't say anything about this. 3228 if ((New->getType()->isDependentType() || 3229 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3230 // If the old type was dependent, we can't merge with it, so the new type 3231 // becomes dependent for now. We'll reproduce the original type when we 3232 // instantiate the TypeSourceInfo for the variable. 3233 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3234 New->setType(Context.DependentTy); 3235 return; 3236 } 3237 3238 // FIXME: Even if this merging succeeds, some other non-visible declaration 3239 // of this variable might have an incompatible type. For instance: 3240 // 3241 // extern int arr[]; 3242 // void f() { extern int arr[2]; } 3243 // void g() { extern int arr[3]; } 3244 // 3245 // Neither C nor C++ requires a diagnostic for this, but we should still try 3246 // to diagnose it. 3247 Diag(New->getLocation(), diag::err_redefinition_different_type) 3248 << New->getDeclName() << New->getType() << Old->getType(); 3249 Diag(Old->getLocation(), diag::note_previous_definition); 3250 return New->setInvalidDecl(); 3251 } 3252 3253 // Don't actually update the type on the new declaration if the old 3254 // declaration was an extern declaration in a different scope. 3255 if (MergeTypeWithOld) 3256 New->setType(MergedT); 3257 } 3258 3259 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3260 LookupResult &Previous) { 3261 // C11 6.2.7p4: 3262 // For an identifier with internal or external linkage declared 3263 // in a scope in which a prior declaration of that identifier is 3264 // visible, if the prior declaration specifies internal or 3265 // external linkage, the type of the identifier at the later 3266 // declaration becomes the composite type. 3267 // 3268 // If the variable isn't visible, we do not merge with its type. 3269 if (Previous.isShadowed()) 3270 return false; 3271 3272 if (S.getLangOpts().CPlusPlus) { 3273 // C++11 [dcl.array]p3: 3274 // If there is a preceding declaration of the entity in the same 3275 // scope in which the bound was specified, an omitted array bound 3276 // is taken to be the same as in that earlier declaration. 3277 return NewVD->isPreviousDeclInSameBlockScope() || 3278 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3279 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3280 } else { 3281 // If the old declaration was function-local, don't merge with its 3282 // type unless we're in the same function. 3283 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3284 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3285 } 3286 } 3287 3288 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3289 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3290 /// situation, merging decls or emitting diagnostics as appropriate. 3291 /// 3292 /// Tentative definition rules (C99 6.9.2p2) are checked by 3293 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3294 /// definitions here, since the initializer hasn't been attached. 3295 /// 3296 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3297 // If the new decl is already invalid, don't do any other checking. 3298 if (New->isInvalidDecl()) 3299 return; 3300 3301 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3302 3303 // Verify the old decl was also a variable or variable template. 3304 VarDecl *Old = nullptr; 3305 VarTemplateDecl *OldTemplate = nullptr; 3306 if (Previous.isSingleResult()) { 3307 if (NewTemplate) { 3308 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3309 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3310 } else 3311 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3312 } 3313 if (!Old) { 3314 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3315 << New->getDeclName(); 3316 Diag(Previous.getRepresentativeDecl()->getLocation(), 3317 diag::note_previous_definition); 3318 return New->setInvalidDecl(); 3319 } 3320 3321 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3322 return; 3323 3324 // Ensure the template parameters are compatible. 3325 if (NewTemplate && 3326 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3327 OldTemplate->getTemplateParameters(), 3328 /*Complain=*/true, TPL_TemplateMatch)) 3329 return; 3330 3331 // C++ [class.mem]p1: 3332 // A member shall not be declared twice in the member-specification [...] 3333 // 3334 // Here, we need only consider static data members. 3335 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3336 Diag(New->getLocation(), diag::err_duplicate_member) 3337 << New->getIdentifier(); 3338 Diag(Old->getLocation(), diag::note_previous_declaration); 3339 New->setInvalidDecl(); 3340 } 3341 3342 mergeDeclAttributes(New, Old); 3343 // Warn if an already-declared variable is made a weak_import in a subsequent 3344 // declaration 3345 if (New->hasAttr<WeakImportAttr>() && 3346 Old->getStorageClass() == SC_None && 3347 !Old->hasAttr<WeakImportAttr>()) { 3348 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3349 Diag(Old->getLocation(), diag::note_previous_definition); 3350 // Remove weak_import attribute on new declaration. 3351 New->dropAttr<WeakImportAttr>(); 3352 } 3353 3354 // Merge the types. 3355 VarDecl *MostRecent = Old->getMostRecentDecl(); 3356 if (MostRecent != Old) { 3357 MergeVarDeclTypes(New, MostRecent, 3358 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3359 if (New->isInvalidDecl()) 3360 return; 3361 } 3362 3363 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3364 if (New->isInvalidDecl()) 3365 return; 3366 3367 diag::kind PrevDiag; 3368 SourceLocation OldLocation; 3369 std::tie(PrevDiag, OldLocation) = 3370 getNoteDiagForInvalidRedeclaration(Old, New); 3371 3372 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3373 if (New->getStorageClass() == SC_Static && 3374 !New->isStaticDataMember() && 3375 Old->hasExternalFormalLinkage()) { 3376 if (getLangOpts().MicrosoftExt) { 3377 Diag(New->getLocation(), diag::ext_static_non_static) 3378 << New->getDeclName(); 3379 Diag(OldLocation, PrevDiag); 3380 } else { 3381 Diag(New->getLocation(), diag::err_static_non_static) 3382 << New->getDeclName(); 3383 Diag(OldLocation, PrevDiag); 3384 return New->setInvalidDecl(); 3385 } 3386 } 3387 // C99 6.2.2p4: 3388 // For an identifier declared with the storage-class specifier 3389 // extern in a scope in which a prior declaration of that 3390 // identifier is visible,23) if the prior declaration specifies 3391 // internal or external linkage, the linkage of the identifier at 3392 // the later declaration is the same as the linkage specified at 3393 // the prior declaration. If no prior declaration is visible, or 3394 // if the prior declaration specifies no linkage, then the 3395 // identifier has external linkage. 3396 if (New->hasExternalStorage() && Old->hasLinkage()) 3397 /* Okay */; 3398 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3399 !New->isStaticDataMember() && 3400 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3401 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3402 Diag(OldLocation, PrevDiag); 3403 return New->setInvalidDecl(); 3404 } 3405 3406 // Check if extern is followed by non-extern and vice-versa. 3407 if (New->hasExternalStorage() && 3408 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3409 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3410 Diag(OldLocation, PrevDiag); 3411 return New->setInvalidDecl(); 3412 } 3413 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3414 !New->hasExternalStorage()) { 3415 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3416 Diag(OldLocation, PrevDiag); 3417 return New->setInvalidDecl(); 3418 } 3419 3420 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3421 3422 // FIXME: The test for external storage here seems wrong? We still 3423 // need to check for mismatches. 3424 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3425 // Don't complain about out-of-line definitions of static members. 3426 !(Old->getLexicalDeclContext()->isRecord() && 3427 !New->getLexicalDeclContext()->isRecord())) { 3428 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3429 Diag(OldLocation, PrevDiag); 3430 return New->setInvalidDecl(); 3431 } 3432 3433 if (New->getTLSKind() != Old->getTLSKind()) { 3434 if (!Old->getTLSKind()) { 3435 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3436 Diag(OldLocation, PrevDiag); 3437 } else if (!New->getTLSKind()) { 3438 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3439 Diag(OldLocation, PrevDiag); 3440 } else { 3441 // Do not allow redeclaration to change the variable between requiring 3442 // static and dynamic initialization. 3443 // FIXME: GCC allows this, but uses the TLS keyword on the first 3444 // declaration to determine the kind. Do we need to be compatible here? 3445 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3446 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3447 Diag(OldLocation, PrevDiag); 3448 } 3449 } 3450 3451 // C++ doesn't have tentative definitions, so go right ahead and check here. 3452 VarDecl *Def; 3453 if (getLangOpts().CPlusPlus && 3454 New->isThisDeclarationADefinition() == VarDecl::Definition && 3455 (Def = Old->getDefinition())) { 3456 NamedDecl *Hidden = nullptr; 3457 if (!hasVisibleDefinition(Def, &Hidden) && 3458 (New->getFormalLinkage() == InternalLinkage || 3459 New->getDescribedVarTemplate() || 3460 New->getNumTemplateParameterLists() || 3461 New->getDeclContext()->isDependentContext())) { 3462 // The previous definition is hidden, and multiple definitions are 3463 // permitted (in separate TUs). Form another definition of it. 3464 } else { 3465 Diag(New->getLocation(), diag::err_redefinition) << New; 3466 Diag(Def->getLocation(), diag::note_previous_definition); 3467 New->setInvalidDecl(); 3468 return; 3469 } 3470 } 3471 3472 if (haveIncompatibleLanguageLinkages(Old, New)) { 3473 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3474 Diag(OldLocation, PrevDiag); 3475 New->setInvalidDecl(); 3476 return; 3477 } 3478 3479 // Merge "used" flag. 3480 if (Old->getMostRecentDecl()->isUsed(false)) 3481 New->setIsUsed(); 3482 3483 // Keep a chain of previous declarations. 3484 New->setPreviousDecl(Old); 3485 if (NewTemplate) 3486 NewTemplate->setPreviousDecl(OldTemplate); 3487 3488 // Inherit access appropriately. 3489 New->setAccess(Old->getAccess()); 3490 if (NewTemplate) 3491 NewTemplate->setAccess(New->getAccess()); 3492 } 3493 3494 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3495 /// no declarator (e.g. "struct foo;") is parsed. 3496 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3497 DeclSpec &DS) { 3498 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3499 } 3500 3501 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3502 // disambiguate entities defined in different scopes. 3503 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3504 // compatibility. 3505 // We will pick our mangling number depending on which version of MSVC is being 3506 // targeted. 3507 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3508 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3509 ? S->getMSCurManglingNumber() 3510 : S->getMSLastManglingNumber(); 3511 } 3512 3513 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3514 if (!Context.getLangOpts().CPlusPlus) 3515 return; 3516 3517 if (isa<CXXRecordDecl>(Tag->getParent())) { 3518 // If this tag is the direct child of a class, number it if 3519 // it is anonymous. 3520 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3521 return; 3522 MangleNumberingContext &MCtx = 3523 Context.getManglingNumberContext(Tag->getParent()); 3524 Context.setManglingNumber( 3525 Tag, MCtx.getManglingNumber( 3526 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3527 return; 3528 } 3529 3530 // If this tag isn't a direct child of a class, number it if it is local. 3531 Decl *ManglingContextDecl; 3532 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3533 Tag->getDeclContext(), ManglingContextDecl)) { 3534 Context.setManglingNumber( 3535 Tag, MCtx->getManglingNumber( 3536 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3537 } 3538 } 3539 3540 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3541 TypedefNameDecl *NewTD) { 3542 // Do nothing if the tag is not anonymous or already has an 3543 // associated typedef (from an earlier typedef in this decl group). 3544 if (TagFromDeclSpec->getIdentifier()) 3545 return; 3546 if (TagFromDeclSpec->getTypedefNameForAnonDecl()) 3547 return; 3548 3549 // A well-formed anonymous tag must always be a TUK_Definition. 3550 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3551 3552 // The type must match the tag exactly; no qualifiers allowed. 3553 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3554 Context.getTagDeclType(TagFromDeclSpec))) 3555 return; 3556 3557 // If we've already computed linkage for the anonymous tag, then 3558 // adding a typedef name for the anonymous decl can change that 3559 // linkage, which might be a serious problem. Diagnose this as 3560 // unsupported and ignore the typedef name. TODO: we should 3561 // pursue this as a language defect and establish a formal rule 3562 // for how to handle it. 3563 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3564 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3565 3566 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3567 tagLoc = getLocForEndOfToken(tagLoc); 3568 3569 llvm::SmallString<40> textToInsert; 3570 textToInsert += ' '; 3571 textToInsert += NewTD->getIdentifier()->getName(); 3572 Diag(tagLoc, diag::note_typedef_changes_linkage) 3573 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3574 return; 3575 } 3576 3577 // Otherwise, set this is the anon-decl typedef for the tag. 3578 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3579 } 3580 3581 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3582 switch (T) { 3583 case DeclSpec::TST_class: 3584 return 0; 3585 case DeclSpec::TST_struct: 3586 return 1; 3587 case DeclSpec::TST_interface: 3588 return 2; 3589 case DeclSpec::TST_union: 3590 return 3; 3591 case DeclSpec::TST_enum: 3592 return 4; 3593 default: 3594 llvm_unreachable("unexpected type specifier"); 3595 } 3596 } 3597 3598 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3599 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3600 /// parameters to cope with template friend declarations. 3601 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3602 DeclSpec &DS, 3603 MultiTemplateParamsArg TemplateParams, 3604 bool IsExplicitInstantiation) { 3605 Decl *TagD = nullptr; 3606 TagDecl *Tag = nullptr; 3607 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3608 DS.getTypeSpecType() == DeclSpec::TST_struct || 3609 DS.getTypeSpecType() == DeclSpec::TST_interface || 3610 DS.getTypeSpecType() == DeclSpec::TST_union || 3611 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3612 TagD = DS.getRepAsDecl(); 3613 3614 if (!TagD) // We probably had an error 3615 return nullptr; 3616 3617 // Note that the above type specs guarantee that the 3618 // type rep is a Decl, whereas in many of the others 3619 // it's a Type. 3620 if (isa<TagDecl>(TagD)) 3621 Tag = cast<TagDecl>(TagD); 3622 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3623 Tag = CTD->getTemplatedDecl(); 3624 } 3625 3626 if (Tag) { 3627 handleTagNumbering(Tag, S); 3628 Tag->setFreeStanding(); 3629 if (Tag->isInvalidDecl()) 3630 return Tag; 3631 } 3632 3633 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3634 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3635 // or incomplete types shall not be restrict-qualified." 3636 if (TypeQuals & DeclSpec::TQ_restrict) 3637 Diag(DS.getRestrictSpecLoc(), 3638 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3639 << DS.getSourceRange(); 3640 } 3641 3642 if (DS.isConstexprSpecified()) { 3643 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3644 // and definitions of functions and variables. 3645 if (Tag) 3646 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3647 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3648 else 3649 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3650 // Don't emit warnings after this error. 3651 return TagD; 3652 } 3653 3654 DiagnoseFunctionSpecifiers(DS); 3655 3656 if (DS.isFriendSpecified()) { 3657 // If we're dealing with a decl but not a TagDecl, assume that 3658 // whatever routines created it handled the friendship aspect. 3659 if (TagD && !Tag) 3660 return nullptr; 3661 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3662 } 3663 3664 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3665 bool IsExplicitSpecialization = 3666 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3667 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3668 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3669 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3670 // nested-name-specifier unless it is an explicit instantiation 3671 // or an explicit specialization. 3672 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3673 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3674 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 3675 return nullptr; 3676 } 3677 3678 // Track whether this decl-specifier declares anything. 3679 bool DeclaresAnything = true; 3680 3681 // Handle anonymous struct definitions. 3682 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3683 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3684 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3685 if (getLangOpts().CPlusPlus || 3686 Record->getDeclContext()->isRecord()) 3687 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3688 Context.getPrintingPolicy()); 3689 3690 DeclaresAnything = false; 3691 } 3692 } 3693 3694 // C11 6.7.2.1p2: 3695 // A struct-declaration that does not declare an anonymous structure or 3696 // anonymous union shall contain a struct-declarator-list. 3697 // 3698 // This rule also existed in C89 and C99; the grammar for struct-declaration 3699 // did not permit a struct-declaration without a struct-declarator-list. 3700 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3701 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3702 // Check for Microsoft C extension: anonymous struct/union member. 3703 // Handle 2 kinds of anonymous struct/union: 3704 // struct STRUCT; 3705 // union UNION; 3706 // and 3707 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3708 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3709 if ((Tag && Tag->getDeclName()) || 3710 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3711 RecordDecl *Record = nullptr; 3712 if (Tag) 3713 Record = dyn_cast<RecordDecl>(Tag); 3714 else if (const RecordType *RT = 3715 DS.getRepAsType().get()->getAsStructureType()) 3716 Record = RT->getDecl(); 3717 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3718 Record = UT->getDecl(); 3719 3720 if (Record && getLangOpts().MicrosoftExt) { 3721 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3722 << Record->isUnion() << DS.getSourceRange(); 3723 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3724 } 3725 3726 DeclaresAnything = false; 3727 } 3728 } 3729 3730 // Skip all the checks below if we have a type error. 3731 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3732 (TagD && TagD->isInvalidDecl())) 3733 return TagD; 3734 3735 if (getLangOpts().CPlusPlus && 3736 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3737 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3738 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3739 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3740 DeclaresAnything = false; 3741 3742 if (!DS.isMissingDeclaratorOk()) { 3743 // Customize diagnostic for a typedef missing a name. 3744 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3745 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3746 << DS.getSourceRange(); 3747 else 3748 DeclaresAnything = false; 3749 } 3750 3751 if (DS.isModulePrivateSpecified() && 3752 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3753 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3754 << Tag->getTagKind() 3755 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3756 3757 ActOnDocumentableDecl(TagD); 3758 3759 // C 6.7/2: 3760 // A declaration [...] shall declare at least a declarator [...], a tag, 3761 // or the members of an enumeration. 3762 // C++ [dcl.dcl]p3: 3763 // [If there are no declarators], and except for the declaration of an 3764 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3765 // names into the program, or shall redeclare a name introduced by a 3766 // previous declaration. 3767 if (!DeclaresAnything) { 3768 // In C, we allow this as a (popular) extension / bug. Don't bother 3769 // producing further diagnostics for redundant qualifiers after this. 3770 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3771 return TagD; 3772 } 3773 3774 // C++ [dcl.stc]p1: 3775 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3776 // init-declarator-list of the declaration shall not be empty. 3777 // C++ [dcl.fct.spec]p1: 3778 // If a cv-qualifier appears in a decl-specifier-seq, the 3779 // init-declarator-list of the declaration shall not be empty. 3780 // 3781 // Spurious qualifiers here appear to be valid in C. 3782 unsigned DiagID = diag::warn_standalone_specifier; 3783 if (getLangOpts().CPlusPlus) 3784 DiagID = diag::ext_standalone_specifier; 3785 3786 // Note that a linkage-specification sets a storage class, but 3787 // 'extern "C" struct foo;' is actually valid and not theoretically 3788 // useless. 3789 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3790 if (SCS == DeclSpec::SCS_mutable) 3791 // Since mutable is not a viable storage class specifier in C, there is 3792 // no reason to treat it as an extension. Instead, diagnose as an error. 3793 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3794 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3795 Diag(DS.getStorageClassSpecLoc(), DiagID) 3796 << DeclSpec::getSpecifierName(SCS); 3797 } 3798 3799 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3800 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3801 << DeclSpec::getSpecifierName(TSCS); 3802 if (DS.getTypeQualifiers()) { 3803 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3804 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3805 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3806 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3807 // Restrict is covered above. 3808 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3809 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3810 } 3811 3812 // Warn about ignored type attributes, for example: 3813 // __attribute__((aligned)) struct A; 3814 // Attributes should be placed after tag to apply to type declaration. 3815 if (!DS.getAttributes().empty()) { 3816 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3817 if (TypeSpecType == DeclSpec::TST_class || 3818 TypeSpecType == DeclSpec::TST_struct || 3819 TypeSpecType == DeclSpec::TST_interface || 3820 TypeSpecType == DeclSpec::TST_union || 3821 TypeSpecType == DeclSpec::TST_enum) { 3822 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 3823 attrs = attrs->getNext()) 3824 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3825 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 3826 } 3827 } 3828 3829 return TagD; 3830 } 3831 3832 /// We are trying to inject an anonymous member into the given scope; 3833 /// check if there's an existing declaration that can't be overloaded. 3834 /// 3835 /// \return true if this is a forbidden redeclaration 3836 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3837 Scope *S, 3838 DeclContext *Owner, 3839 DeclarationName Name, 3840 SourceLocation NameLoc, 3841 unsigned diagnostic) { 3842 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3843 Sema::ForRedeclaration); 3844 if (!SemaRef.LookupName(R, S)) return false; 3845 3846 if (R.getAsSingle<TagDecl>()) 3847 return false; 3848 3849 // Pick a representative declaration. 3850 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3851 assert(PrevDecl && "Expected a non-null Decl"); 3852 3853 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3854 return false; 3855 3856 SemaRef.Diag(NameLoc, diagnostic) << Name; 3857 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3858 3859 return true; 3860 } 3861 3862 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3863 /// anonymous struct or union AnonRecord into the owning context Owner 3864 /// and scope S. This routine will be invoked just after we realize 3865 /// that an unnamed union or struct is actually an anonymous union or 3866 /// struct, e.g., 3867 /// 3868 /// @code 3869 /// union { 3870 /// int i; 3871 /// float f; 3872 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3873 /// // f into the surrounding scope.x 3874 /// @endcode 3875 /// 3876 /// This routine is recursive, injecting the names of nested anonymous 3877 /// structs/unions into the owning context and scope as well. 3878 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3879 DeclContext *Owner, 3880 RecordDecl *AnonRecord, 3881 AccessSpecifier AS, 3882 SmallVectorImpl<NamedDecl *> &Chaining, 3883 bool MSAnonStruct) { 3884 unsigned diagKind 3885 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3886 : diag::err_anonymous_struct_member_redecl; 3887 3888 bool Invalid = false; 3889 3890 // Look every FieldDecl and IndirectFieldDecl with a name. 3891 for (auto *D : AnonRecord->decls()) { 3892 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3893 cast<NamedDecl>(D)->getDeclName()) { 3894 ValueDecl *VD = cast<ValueDecl>(D); 3895 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3896 VD->getLocation(), diagKind)) { 3897 // C++ [class.union]p2: 3898 // The names of the members of an anonymous union shall be 3899 // distinct from the names of any other entity in the 3900 // scope in which the anonymous union is declared. 3901 Invalid = true; 3902 } else { 3903 // C++ [class.union]p2: 3904 // For the purpose of name lookup, after the anonymous union 3905 // definition, the members of the anonymous union are 3906 // considered to have been defined in the scope in which the 3907 // anonymous union is declared. 3908 unsigned OldChainingSize = Chaining.size(); 3909 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3910 Chaining.append(IF->chain_begin(), IF->chain_end()); 3911 else 3912 Chaining.push_back(VD); 3913 3914 assert(Chaining.size() >= 2); 3915 NamedDecl **NamedChain = 3916 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3917 for (unsigned i = 0; i < Chaining.size(); i++) 3918 NamedChain[i] = Chaining[i]; 3919 3920 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 3921 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 3922 VD->getType(), NamedChain, Chaining.size()); 3923 3924 for (const auto *Attr : VD->attrs()) 3925 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 3926 3927 IndirectField->setAccess(AS); 3928 IndirectField->setImplicit(); 3929 SemaRef.PushOnScopeChains(IndirectField, S); 3930 3931 // That includes picking up the appropriate access specifier. 3932 if (AS != AS_none) IndirectField->setAccess(AS); 3933 3934 Chaining.resize(OldChainingSize); 3935 } 3936 } 3937 } 3938 3939 return Invalid; 3940 } 3941 3942 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3943 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3944 /// illegal input values are mapped to SC_None. 3945 static StorageClass 3946 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3947 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3948 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3949 "Parser allowed 'typedef' as storage class VarDecl."); 3950 switch (StorageClassSpec) { 3951 case DeclSpec::SCS_unspecified: return SC_None; 3952 case DeclSpec::SCS_extern: 3953 if (DS.isExternInLinkageSpec()) 3954 return SC_None; 3955 return SC_Extern; 3956 case DeclSpec::SCS_static: return SC_Static; 3957 case DeclSpec::SCS_auto: return SC_Auto; 3958 case DeclSpec::SCS_register: return SC_Register; 3959 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3960 // Illegal SCSs map to None: error reporting is up to the caller. 3961 case DeclSpec::SCS_mutable: // Fall through. 3962 case DeclSpec::SCS_typedef: return SC_None; 3963 } 3964 llvm_unreachable("unknown storage class specifier"); 3965 } 3966 3967 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3968 assert(Record->hasInClassInitializer()); 3969 3970 for (const auto *I : Record->decls()) { 3971 const auto *FD = dyn_cast<FieldDecl>(I); 3972 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3973 FD = IFD->getAnonField(); 3974 if (FD && FD->hasInClassInitializer()) 3975 return FD->getLocation(); 3976 } 3977 3978 llvm_unreachable("couldn't find in-class initializer"); 3979 } 3980 3981 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3982 SourceLocation DefaultInitLoc) { 3983 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3984 return; 3985 3986 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3987 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3988 } 3989 3990 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3991 CXXRecordDecl *AnonUnion) { 3992 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3993 return; 3994 3995 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3996 } 3997 3998 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3999 /// anonymous structure or union. Anonymous unions are a C++ feature 4000 /// (C++ [class.union]) and a C11 feature; anonymous structures 4001 /// are a C11 feature and GNU C++ extension. 4002 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4003 AccessSpecifier AS, 4004 RecordDecl *Record, 4005 const PrintingPolicy &Policy) { 4006 DeclContext *Owner = Record->getDeclContext(); 4007 4008 // Diagnose whether this anonymous struct/union is an extension. 4009 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4010 Diag(Record->getLocation(), diag::ext_anonymous_union); 4011 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4012 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4013 else if (!Record->isUnion() && !getLangOpts().C11) 4014 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4015 4016 // C and C++ require different kinds of checks for anonymous 4017 // structs/unions. 4018 bool Invalid = false; 4019 if (getLangOpts().CPlusPlus) { 4020 const char *PrevSpec = nullptr; 4021 unsigned DiagID; 4022 if (Record->isUnion()) { 4023 // C++ [class.union]p6: 4024 // Anonymous unions declared in a named namespace or in the 4025 // global namespace shall be declared static. 4026 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4027 (isa<TranslationUnitDecl>(Owner) || 4028 (isa<NamespaceDecl>(Owner) && 4029 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4030 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4031 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4032 4033 // Recover by adding 'static'. 4034 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4035 PrevSpec, DiagID, Policy); 4036 } 4037 // C++ [class.union]p6: 4038 // A storage class is not allowed in a declaration of an 4039 // anonymous union in a class scope. 4040 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4041 isa<RecordDecl>(Owner)) { 4042 Diag(DS.getStorageClassSpecLoc(), 4043 diag::err_anonymous_union_with_storage_spec) 4044 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4045 4046 // Recover by removing the storage specifier. 4047 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4048 SourceLocation(), 4049 PrevSpec, DiagID, Context.getPrintingPolicy()); 4050 } 4051 } 4052 4053 // Ignore const/volatile/restrict qualifiers. 4054 if (DS.getTypeQualifiers()) { 4055 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4056 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4057 << Record->isUnion() << "const" 4058 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4059 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4060 Diag(DS.getVolatileSpecLoc(), 4061 diag::ext_anonymous_struct_union_qualified) 4062 << Record->isUnion() << "volatile" 4063 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4064 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4065 Diag(DS.getRestrictSpecLoc(), 4066 diag::ext_anonymous_struct_union_qualified) 4067 << Record->isUnion() << "restrict" 4068 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4069 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4070 Diag(DS.getAtomicSpecLoc(), 4071 diag::ext_anonymous_struct_union_qualified) 4072 << Record->isUnion() << "_Atomic" 4073 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4074 4075 DS.ClearTypeQualifiers(); 4076 } 4077 4078 // C++ [class.union]p2: 4079 // The member-specification of an anonymous union shall only 4080 // define non-static data members. [Note: nested types and 4081 // functions cannot be declared within an anonymous union. ] 4082 for (auto *Mem : Record->decls()) { 4083 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4084 // C++ [class.union]p3: 4085 // An anonymous union shall not have private or protected 4086 // members (clause 11). 4087 assert(FD->getAccess() != AS_none); 4088 if (FD->getAccess() != AS_public) { 4089 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4090 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 4091 Invalid = true; 4092 } 4093 4094 // C++ [class.union]p1 4095 // An object of a class with a non-trivial constructor, a non-trivial 4096 // copy constructor, a non-trivial destructor, or a non-trivial copy 4097 // assignment operator cannot be a member of a union, nor can an 4098 // array of such objects. 4099 if (CheckNontrivialField(FD)) 4100 Invalid = true; 4101 } else if (Mem->isImplicit()) { 4102 // Any implicit members are fine. 4103 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4104 // This is a type that showed up in an 4105 // elaborated-type-specifier inside the anonymous struct or 4106 // union, but which actually declares a type outside of the 4107 // anonymous struct or union. It's okay. 4108 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4109 if (!MemRecord->isAnonymousStructOrUnion() && 4110 MemRecord->getDeclName()) { 4111 // Visual C++ allows type definition in anonymous struct or union. 4112 if (getLangOpts().MicrosoftExt) 4113 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4114 << (int)Record->isUnion(); 4115 else { 4116 // This is a nested type declaration. 4117 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4118 << (int)Record->isUnion(); 4119 Invalid = true; 4120 } 4121 } else { 4122 // This is an anonymous type definition within another anonymous type. 4123 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4124 // not part of standard C++. 4125 Diag(MemRecord->getLocation(), 4126 diag::ext_anonymous_record_with_anonymous_type) 4127 << (int)Record->isUnion(); 4128 } 4129 } else if (isa<AccessSpecDecl>(Mem)) { 4130 // Any access specifier is fine. 4131 } else if (isa<StaticAssertDecl>(Mem)) { 4132 // In C++1z, static_assert declarations are also fine. 4133 } else { 4134 // We have something that isn't a non-static data 4135 // member. Complain about it. 4136 unsigned DK = diag::err_anonymous_record_bad_member; 4137 if (isa<TypeDecl>(Mem)) 4138 DK = diag::err_anonymous_record_with_type; 4139 else if (isa<FunctionDecl>(Mem)) 4140 DK = diag::err_anonymous_record_with_function; 4141 else if (isa<VarDecl>(Mem)) 4142 DK = diag::err_anonymous_record_with_static; 4143 4144 // Visual C++ allows type definition in anonymous struct or union. 4145 if (getLangOpts().MicrosoftExt && 4146 DK == diag::err_anonymous_record_with_type) 4147 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4148 << (int)Record->isUnion(); 4149 else { 4150 Diag(Mem->getLocation(), DK) 4151 << (int)Record->isUnion(); 4152 Invalid = true; 4153 } 4154 } 4155 } 4156 4157 // C++11 [class.union]p8 (DR1460): 4158 // At most one variant member of a union may have a 4159 // brace-or-equal-initializer. 4160 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4161 Owner->isRecord()) 4162 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4163 cast<CXXRecordDecl>(Record)); 4164 } 4165 4166 if (!Record->isUnion() && !Owner->isRecord()) { 4167 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4168 << (int)getLangOpts().CPlusPlus; 4169 Invalid = true; 4170 } 4171 4172 // Mock up a declarator. 4173 Declarator Dc(DS, Declarator::MemberContext); 4174 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4175 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4176 4177 // Create a declaration for this anonymous struct/union. 4178 NamedDecl *Anon = nullptr; 4179 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4180 Anon = FieldDecl::Create(Context, OwningClass, 4181 DS.getLocStart(), 4182 Record->getLocation(), 4183 /*IdentifierInfo=*/nullptr, 4184 Context.getTypeDeclType(Record), 4185 TInfo, 4186 /*BitWidth=*/nullptr, /*Mutable=*/false, 4187 /*InitStyle=*/ICIS_NoInit); 4188 Anon->setAccess(AS); 4189 if (getLangOpts().CPlusPlus) 4190 FieldCollector->Add(cast<FieldDecl>(Anon)); 4191 } else { 4192 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4193 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4194 if (SCSpec == DeclSpec::SCS_mutable) { 4195 // mutable can only appear on non-static class members, so it's always 4196 // an error here 4197 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4198 Invalid = true; 4199 SC = SC_None; 4200 } 4201 4202 Anon = VarDecl::Create(Context, Owner, 4203 DS.getLocStart(), 4204 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4205 Context.getTypeDeclType(Record), 4206 TInfo, SC); 4207 4208 // Default-initialize the implicit variable. This initialization will be 4209 // trivial in almost all cases, except if a union member has an in-class 4210 // initializer: 4211 // union { int n = 0; }; 4212 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4213 } 4214 Anon->setImplicit(); 4215 4216 // Mark this as an anonymous struct/union type. 4217 Record->setAnonymousStructOrUnion(true); 4218 4219 // Add the anonymous struct/union object to the current 4220 // context. We'll be referencing this object when we refer to one of 4221 // its members. 4222 Owner->addDecl(Anon); 4223 4224 // Inject the members of the anonymous struct/union into the owning 4225 // context and into the identifier resolver chain for name lookup 4226 // purposes. 4227 SmallVector<NamedDecl*, 2> Chain; 4228 Chain.push_back(Anon); 4229 4230 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 4231 Chain, false)) 4232 Invalid = true; 4233 4234 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4235 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4236 Decl *ManglingContextDecl; 4237 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4238 NewVD->getDeclContext(), ManglingContextDecl)) { 4239 Context.setManglingNumber( 4240 NewVD, MCtx->getManglingNumber( 4241 NewVD, getMSManglingNumber(getLangOpts(), S))); 4242 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4243 } 4244 } 4245 } 4246 4247 if (Invalid) 4248 Anon->setInvalidDecl(); 4249 4250 return Anon; 4251 } 4252 4253 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4254 /// Microsoft C anonymous structure. 4255 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4256 /// Example: 4257 /// 4258 /// struct A { int a; }; 4259 /// struct B { struct A; int b; }; 4260 /// 4261 /// void foo() { 4262 /// B var; 4263 /// var.a = 3; 4264 /// } 4265 /// 4266 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4267 RecordDecl *Record) { 4268 assert(Record && "expected a record!"); 4269 4270 // Mock up a declarator. 4271 Declarator Dc(DS, Declarator::TypeNameContext); 4272 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4273 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4274 4275 auto *ParentDecl = cast<RecordDecl>(CurContext); 4276 QualType RecTy = Context.getTypeDeclType(Record); 4277 4278 // Create a declaration for this anonymous struct. 4279 NamedDecl *Anon = FieldDecl::Create(Context, 4280 ParentDecl, 4281 DS.getLocStart(), 4282 DS.getLocStart(), 4283 /*IdentifierInfo=*/nullptr, 4284 RecTy, 4285 TInfo, 4286 /*BitWidth=*/nullptr, /*Mutable=*/false, 4287 /*InitStyle=*/ICIS_NoInit); 4288 Anon->setImplicit(); 4289 4290 // Add the anonymous struct object to the current context. 4291 CurContext->addDecl(Anon); 4292 4293 // Inject the members of the anonymous struct into the current 4294 // context and into the identifier resolver chain for name lookup 4295 // purposes. 4296 SmallVector<NamedDecl*, 2> Chain; 4297 Chain.push_back(Anon); 4298 4299 RecordDecl *RecordDef = Record->getDefinition(); 4300 if (RequireCompleteType(Anon->getLocation(), RecTy, 4301 diag::err_field_incomplete) || 4302 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4303 AS_none, Chain, true)) { 4304 Anon->setInvalidDecl(); 4305 ParentDecl->setInvalidDecl(); 4306 } 4307 4308 return Anon; 4309 } 4310 4311 /// GetNameForDeclarator - Determine the full declaration name for the 4312 /// given Declarator. 4313 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4314 return GetNameFromUnqualifiedId(D.getName()); 4315 } 4316 4317 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4318 DeclarationNameInfo 4319 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4320 DeclarationNameInfo NameInfo; 4321 NameInfo.setLoc(Name.StartLocation); 4322 4323 switch (Name.getKind()) { 4324 4325 case UnqualifiedId::IK_ImplicitSelfParam: 4326 case UnqualifiedId::IK_Identifier: 4327 NameInfo.setName(Name.Identifier); 4328 NameInfo.setLoc(Name.StartLocation); 4329 return NameInfo; 4330 4331 case UnqualifiedId::IK_OperatorFunctionId: 4332 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4333 Name.OperatorFunctionId.Operator)); 4334 NameInfo.setLoc(Name.StartLocation); 4335 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4336 = Name.OperatorFunctionId.SymbolLocations[0]; 4337 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4338 = Name.EndLocation.getRawEncoding(); 4339 return NameInfo; 4340 4341 case UnqualifiedId::IK_LiteralOperatorId: 4342 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4343 Name.Identifier)); 4344 NameInfo.setLoc(Name.StartLocation); 4345 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4346 return NameInfo; 4347 4348 case UnqualifiedId::IK_ConversionFunctionId: { 4349 TypeSourceInfo *TInfo; 4350 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4351 if (Ty.isNull()) 4352 return DeclarationNameInfo(); 4353 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4354 Context.getCanonicalType(Ty))); 4355 NameInfo.setLoc(Name.StartLocation); 4356 NameInfo.setNamedTypeInfo(TInfo); 4357 return NameInfo; 4358 } 4359 4360 case UnqualifiedId::IK_ConstructorName: { 4361 TypeSourceInfo *TInfo; 4362 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4363 if (Ty.isNull()) 4364 return DeclarationNameInfo(); 4365 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4366 Context.getCanonicalType(Ty))); 4367 NameInfo.setLoc(Name.StartLocation); 4368 NameInfo.setNamedTypeInfo(TInfo); 4369 return NameInfo; 4370 } 4371 4372 case UnqualifiedId::IK_ConstructorTemplateId: { 4373 // In well-formed code, we can only have a constructor 4374 // template-id that refers to the current context, so go there 4375 // to find the actual type being constructed. 4376 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4377 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4378 return DeclarationNameInfo(); 4379 4380 // Determine the type of the class being constructed. 4381 QualType CurClassType = Context.getTypeDeclType(CurClass); 4382 4383 // FIXME: Check two things: that the template-id names the same type as 4384 // CurClassType, and that the template-id does not occur when the name 4385 // was qualified. 4386 4387 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4388 Context.getCanonicalType(CurClassType))); 4389 NameInfo.setLoc(Name.StartLocation); 4390 // FIXME: should we retrieve TypeSourceInfo? 4391 NameInfo.setNamedTypeInfo(nullptr); 4392 return NameInfo; 4393 } 4394 4395 case UnqualifiedId::IK_DestructorName: { 4396 TypeSourceInfo *TInfo; 4397 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4398 if (Ty.isNull()) 4399 return DeclarationNameInfo(); 4400 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4401 Context.getCanonicalType(Ty))); 4402 NameInfo.setLoc(Name.StartLocation); 4403 NameInfo.setNamedTypeInfo(TInfo); 4404 return NameInfo; 4405 } 4406 4407 case UnqualifiedId::IK_TemplateId: { 4408 TemplateName TName = Name.TemplateId->Template.get(); 4409 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4410 return Context.getNameForTemplate(TName, TNameLoc); 4411 } 4412 4413 } // switch (Name.getKind()) 4414 4415 llvm_unreachable("Unknown name kind"); 4416 } 4417 4418 static QualType getCoreType(QualType Ty) { 4419 do { 4420 if (Ty->isPointerType() || Ty->isReferenceType()) 4421 Ty = Ty->getPointeeType(); 4422 else if (Ty->isArrayType()) 4423 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4424 else 4425 return Ty.withoutLocalFastQualifiers(); 4426 } while (true); 4427 } 4428 4429 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4430 /// and Definition have "nearly" matching parameters. This heuristic is 4431 /// used to improve diagnostics in the case where an out-of-line function 4432 /// definition doesn't match any declaration within the class or namespace. 4433 /// Also sets Params to the list of indices to the parameters that differ 4434 /// between the declaration and the definition. If hasSimilarParameters 4435 /// returns true and Params is empty, then all of the parameters match. 4436 static bool hasSimilarParameters(ASTContext &Context, 4437 FunctionDecl *Declaration, 4438 FunctionDecl *Definition, 4439 SmallVectorImpl<unsigned> &Params) { 4440 Params.clear(); 4441 if (Declaration->param_size() != Definition->param_size()) 4442 return false; 4443 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4444 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4445 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4446 4447 // The parameter types are identical 4448 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4449 continue; 4450 4451 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4452 QualType DefParamBaseTy = getCoreType(DefParamTy); 4453 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4454 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4455 4456 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4457 (DeclTyName && DeclTyName == DefTyName)) 4458 Params.push_back(Idx); 4459 else // The two parameters aren't even close 4460 return false; 4461 } 4462 4463 return true; 4464 } 4465 4466 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4467 /// declarator needs to be rebuilt in the current instantiation. 4468 /// Any bits of declarator which appear before the name are valid for 4469 /// consideration here. That's specifically the type in the decl spec 4470 /// and the base type in any member-pointer chunks. 4471 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4472 DeclarationName Name) { 4473 // The types we specifically need to rebuild are: 4474 // - typenames, typeofs, and decltypes 4475 // - types which will become injected class names 4476 // Of course, we also need to rebuild any type referencing such a 4477 // type. It's safest to just say "dependent", but we call out a 4478 // few cases here. 4479 4480 DeclSpec &DS = D.getMutableDeclSpec(); 4481 switch (DS.getTypeSpecType()) { 4482 case DeclSpec::TST_typename: 4483 case DeclSpec::TST_typeofType: 4484 case DeclSpec::TST_underlyingType: 4485 case DeclSpec::TST_atomic: { 4486 // Grab the type from the parser. 4487 TypeSourceInfo *TSI = nullptr; 4488 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4489 if (T.isNull() || !T->isDependentType()) break; 4490 4491 // Make sure there's a type source info. This isn't really much 4492 // of a waste; most dependent types should have type source info 4493 // attached already. 4494 if (!TSI) 4495 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4496 4497 // Rebuild the type in the current instantiation. 4498 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4499 if (!TSI) return true; 4500 4501 // Store the new type back in the decl spec. 4502 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4503 DS.UpdateTypeRep(LocType); 4504 break; 4505 } 4506 4507 case DeclSpec::TST_decltype: 4508 case DeclSpec::TST_typeofExpr: { 4509 Expr *E = DS.getRepAsExpr(); 4510 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4511 if (Result.isInvalid()) return true; 4512 DS.UpdateExprRep(Result.get()); 4513 break; 4514 } 4515 4516 default: 4517 // Nothing to do for these decl specs. 4518 break; 4519 } 4520 4521 // It doesn't matter what order we do this in. 4522 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4523 DeclaratorChunk &Chunk = D.getTypeObject(I); 4524 4525 // The only type information in the declarator which can come 4526 // before the declaration name is the base type of a member 4527 // pointer. 4528 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4529 continue; 4530 4531 // Rebuild the scope specifier in-place. 4532 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4533 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4534 return true; 4535 } 4536 4537 return false; 4538 } 4539 4540 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4541 D.setFunctionDefinitionKind(FDK_Declaration); 4542 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4543 4544 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4545 Dcl && Dcl->getDeclContext()->isFileContext()) 4546 Dcl->setTopLevelDeclInObjCContainer(); 4547 4548 return Dcl; 4549 } 4550 4551 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4552 /// If T is the name of a class, then each of the following shall have a 4553 /// name different from T: 4554 /// - every static data member of class T; 4555 /// - every member function of class T 4556 /// - every member of class T that is itself a type; 4557 /// \returns true if the declaration name violates these rules. 4558 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4559 DeclarationNameInfo NameInfo) { 4560 DeclarationName Name = NameInfo.getName(); 4561 4562 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4563 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4564 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4565 return true; 4566 } 4567 4568 return false; 4569 } 4570 4571 /// \brief Diagnose a declaration whose declarator-id has the given 4572 /// nested-name-specifier. 4573 /// 4574 /// \param SS The nested-name-specifier of the declarator-id. 4575 /// 4576 /// \param DC The declaration context to which the nested-name-specifier 4577 /// resolves. 4578 /// 4579 /// \param Name The name of the entity being declared. 4580 /// 4581 /// \param Loc The location of the name of the entity being declared. 4582 /// 4583 /// \returns true if we cannot safely recover from this error, false otherwise. 4584 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4585 DeclarationName Name, 4586 SourceLocation Loc) { 4587 DeclContext *Cur = CurContext; 4588 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4589 Cur = Cur->getParent(); 4590 4591 // If the user provided a superfluous scope specifier that refers back to the 4592 // class in which the entity is already declared, diagnose and ignore it. 4593 // 4594 // class X { 4595 // void X::f(); 4596 // }; 4597 // 4598 // Note, it was once ill-formed to give redundant qualification in all 4599 // contexts, but that rule was removed by DR482. 4600 if (Cur->Equals(DC)) { 4601 if (Cur->isRecord()) { 4602 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4603 : diag::err_member_extra_qualification) 4604 << Name << FixItHint::CreateRemoval(SS.getRange()); 4605 SS.clear(); 4606 } else { 4607 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4608 } 4609 return false; 4610 } 4611 4612 // Check whether the qualifying scope encloses the scope of the original 4613 // declaration. 4614 if (!Cur->Encloses(DC)) { 4615 if (Cur->isRecord()) 4616 Diag(Loc, diag::err_member_qualification) 4617 << Name << SS.getRange(); 4618 else if (isa<TranslationUnitDecl>(DC)) 4619 Diag(Loc, diag::err_invalid_declarator_global_scope) 4620 << Name << SS.getRange(); 4621 else if (isa<FunctionDecl>(Cur)) 4622 Diag(Loc, diag::err_invalid_declarator_in_function) 4623 << Name << SS.getRange(); 4624 else if (isa<BlockDecl>(Cur)) 4625 Diag(Loc, diag::err_invalid_declarator_in_block) 4626 << Name << SS.getRange(); 4627 else 4628 Diag(Loc, diag::err_invalid_declarator_scope) 4629 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4630 4631 return true; 4632 } 4633 4634 if (Cur->isRecord()) { 4635 // Cannot qualify members within a class. 4636 Diag(Loc, diag::err_member_qualification) 4637 << Name << SS.getRange(); 4638 SS.clear(); 4639 4640 // C++ constructors and destructors with incorrect scopes can break 4641 // our AST invariants by having the wrong underlying types. If 4642 // that's the case, then drop this declaration entirely. 4643 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4644 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4645 !Context.hasSameType(Name.getCXXNameType(), 4646 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4647 return true; 4648 4649 return false; 4650 } 4651 4652 // C++11 [dcl.meaning]p1: 4653 // [...] "The nested-name-specifier of the qualified declarator-id shall 4654 // not begin with a decltype-specifer" 4655 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4656 while (SpecLoc.getPrefix()) 4657 SpecLoc = SpecLoc.getPrefix(); 4658 if (dyn_cast_or_null<DecltypeType>( 4659 SpecLoc.getNestedNameSpecifier()->getAsType())) 4660 Diag(Loc, diag::err_decltype_in_declarator) 4661 << SpecLoc.getTypeLoc().getSourceRange(); 4662 4663 return false; 4664 } 4665 4666 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4667 MultiTemplateParamsArg TemplateParamLists) { 4668 // TODO: consider using NameInfo for diagnostic. 4669 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4670 DeclarationName Name = NameInfo.getName(); 4671 4672 // All of these full declarators require an identifier. If it doesn't have 4673 // one, the ParsedFreeStandingDeclSpec action should be used. 4674 if (!Name) { 4675 if (!D.isInvalidType()) // Reject this if we think it is valid. 4676 Diag(D.getDeclSpec().getLocStart(), 4677 diag::err_declarator_need_ident) 4678 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4679 return nullptr; 4680 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4681 return nullptr; 4682 4683 // The scope passed in may not be a decl scope. Zip up the scope tree until 4684 // we find one that is. 4685 while ((S->getFlags() & Scope::DeclScope) == 0 || 4686 (S->getFlags() & Scope::TemplateParamScope) != 0) 4687 S = S->getParent(); 4688 4689 DeclContext *DC = CurContext; 4690 if (D.getCXXScopeSpec().isInvalid()) 4691 D.setInvalidType(); 4692 else if (D.getCXXScopeSpec().isSet()) { 4693 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4694 UPPC_DeclarationQualifier)) 4695 return nullptr; 4696 4697 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4698 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4699 if (!DC || isa<EnumDecl>(DC)) { 4700 // If we could not compute the declaration context, it's because the 4701 // declaration context is dependent but does not refer to a class, 4702 // class template, or class template partial specialization. Complain 4703 // and return early, to avoid the coming semantic disaster. 4704 Diag(D.getIdentifierLoc(), 4705 diag::err_template_qualified_declarator_no_match) 4706 << D.getCXXScopeSpec().getScopeRep() 4707 << D.getCXXScopeSpec().getRange(); 4708 return nullptr; 4709 } 4710 bool IsDependentContext = DC->isDependentContext(); 4711 4712 if (!IsDependentContext && 4713 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4714 return nullptr; 4715 4716 // If a class is incomplete, do not parse entities inside it. 4717 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4718 Diag(D.getIdentifierLoc(), 4719 diag::err_member_def_undefined_record) 4720 << Name << DC << D.getCXXScopeSpec().getRange(); 4721 return nullptr; 4722 } 4723 if (!D.getDeclSpec().isFriendSpecified()) { 4724 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4725 Name, D.getIdentifierLoc())) { 4726 if (DC->isRecord()) 4727 return nullptr; 4728 4729 D.setInvalidType(); 4730 } 4731 } 4732 4733 // Check whether we need to rebuild the type of the given 4734 // declaration in the current instantiation. 4735 if (EnteringContext && IsDependentContext && 4736 TemplateParamLists.size() != 0) { 4737 ContextRAII SavedContext(*this, DC); 4738 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4739 D.setInvalidType(); 4740 } 4741 } 4742 4743 if (DiagnoseClassNameShadow(DC, NameInfo)) 4744 // If this is a typedef, we'll end up spewing multiple diagnostics. 4745 // Just return early; it's safer. 4746 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4747 return nullptr; 4748 4749 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4750 QualType R = TInfo->getType(); 4751 4752 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4753 UPPC_DeclarationType)) 4754 D.setInvalidType(); 4755 4756 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4757 ForRedeclaration); 4758 4759 // See if this is a redefinition of a variable in the same scope. 4760 if (!D.getCXXScopeSpec().isSet()) { 4761 bool IsLinkageLookup = false; 4762 bool CreateBuiltins = false; 4763 4764 // If the declaration we're planning to build will be a function 4765 // or object with linkage, then look for another declaration with 4766 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4767 // 4768 // If the declaration we're planning to build will be declared with 4769 // external linkage in the translation unit, create any builtin with 4770 // the same name. 4771 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4772 /* Do nothing*/; 4773 else if (CurContext->isFunctionOrMethod() && 4774 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4775 R->isFunctionType())) { 4776 IsLinkageLookup = true; 4777 CreateBuiltins = 4778 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4779 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4780 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4781 CreateBuiltins = true; 4782 4783 if (IsLinkageLookup) 4784 Previous.clear(LookupRedeclarationWithLinkage); 4785 4786 LookupName(Previous, S, CreateBuiltins); 4787 } else { // Something like "int foo::x;" 4788 LookupQualifiedName(Previous, DC); 4789 4790 // C++ [dcl.meaning]p1: 4791 // When the declarator-id is qualified, the declaration shall refer to a 4792 // previously declared member of the class or namespace to which the 4793 // qualifier refers (or, in the case of a namespace, of an element of the 4794 // inline namespace set of that namespace (7.3.1)) or to a specialization 4795 // thereof; [...] 4796 // 4797 // Note that we already checked the context above, and that we do not have 4798 // enough information to make sure that Previous contains the declaration 4799 // we want to match. For example, given: 4800 // 4801 // class X { 4802 // void f(); 4803 // void f(float); 4804 // }; 4805 // 4806 // void X::f(int) { } // ill-formed 4807 // 4808 // In this case, Previous will point to the overload set 4809 // containing the two f's declared in X, but neither of them 4810 // matches. 4811 4812 // C++ [dcl.meaning]p1: 4813 // [...] the member shall not merely have been introduced by a 4814 // using-declaration in the scope of the class or namespace nominated by 4815 // the nested-name-specifier of the declarator-id. 4816 RemoveUsingDecls(Previous); 4817 } 4818 4819 if (Previous.isSingleResult() && 4820 Previous.getFoundDecl()->isTemplateParameter()) { 4821 // Maybe we will complain about the shadowed template parameter. 4822 if (!D.isInvalidType()) 4823 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4824 Previous.getFoundDecl()); 4825 4826 // Just pretend that we didn't see the previous declaration. 4827 Previous.clear(); 4828 } 4829 4830 // In C++, the previous declaration we find might be a tag type 4831 // (class or enum). In this case, the new declaration will hide the 4832 // tag type. Note that this does does not apply if we're declaring a 4833 // typedef (C++ [dcl.typedef]p4). 4834 if (Previous.isSingleTagDecl() && 4835 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4836 Previous.clear(); 4837 4838 // Check that there are no default arguments other than in the parameters 4839 // of a function declaration (C++ only). 4840 if (getLangOpts().CPlusPlus) 4841 CheckExtraCXXDefaultArguments(D); 4842 4843 NamedDecl *New; 4844 4845 bool AddToScope = true; 4846 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4847 if (TemplateParamLists.size()) { 4848 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4849 return nullptr; 4850 } 4851 4852 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4853 } else if (R->isFunctionType()) { 4854 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4855 TemplateParamLists, 4856 AddToScope); 4857 } else { 4858 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4859 AddToScope); 4860 } 4861 4862 if (!New) 4863 return nullptr; 4864 4865 // If this has an identifier and is not an invalid redeclaration or 4866 // function template specialization, add it to the scope stack. 4867 if (New->getDeclName() && AddToScope && 4868 !(D.isRedeclaration() && New->isInvalidDecl())) { 4869 // Only make a locally-scoped extern declaration visible if it is the first 4870 // declaration of this entity. Qualified lookup for such an entity should 4871 // only find this declaration if there is no visible declaration of it. 4872 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4873 PushOnScopeChains(New, S, AddToContext); 4874 if (!AddToContext) 4875 CurContext->addHiddenDecl(New); 4876 } 4877 4878 return New; 4879 } 4880 4881 /// Helper method to turn variable array types into constant array 4882 /// types in certain situations which would otherwise be errors (for 4883 /// GCC compatibility). 4884 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4885 ASTContext &Context, 4886 bool &SizeIsNegative, 4887 llvm::APSInt &Oversized) { 4888 // This method tries to turn a variable array into a constant 4889 // array even when the size isn't an ICE. This is necessary 4890 // for compatibility with code that depends on gcc's buggy 4891 // constant expression folding, like struct {char x[(int)(char*)2];} 4892 SizeIsNegative = false; 4893 Oversized = 0; 4894 4895 if (T->isDependentType()) 4896 return QualType(); 4897 4898 QualifierCollector Qs; 4899 const Type *Ty = Qs.strip(T); 4900 4901 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4902 QualType Pointee = PTy->getPointeeType(); 4903 QualType FixedType = 4904 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4905 Oversized); 4906 if (FixedType.isNull()) return FixedType; 4907 FixedType = Context.getPointerType(FixedType); 4908 return Qs.apply(Context, FixedType); 4909 } 4910 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4911 QualType Inner = PTy->getInnerType(); 4912 QualType FixedType = 4913 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4914 Oversized); 4915 if (FixedType.isNull()) return FixedType; 4916 FixedType = Context.getParenType(FixedType); 4917 return Qs.apply(Context, FixedType); 4918 } 4919 4920 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4921 if (!VLATy) 4922 return QualType(); 4923 // FIXME: We should probably handle this case 4924 if (VLATy->getElementType()->isVariablyModifiedType()) 4925 return QualType(); 4926 4927 llvm::APSInt Res; 4928 if (!VLATy->getSizeExpr() || 4929 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4930 return QualType(); 4931 4932 // Check whether the array size is negative. 4933 if (Res.isSigned() && Res.isNegative()) { 4934 SizeIsNegative = true; 4935 return QualType(); 4936 } 4937 4938 // Check whether the array is too large to be addressed. 4939 unsigned ActiveSizeBits 4940 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4941 Res); 4942 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4943 Oversized = Res; 4944 return QualType(); 4945 } 4946 4947 return Context.getConstantArrayType(VLATy->getElementType(), 4948 Res, ArrayType::Normal, 0); 4949 } 4950 4951 static void 4952 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4953 SrcTL = SrcTL.getUnqualifiedLoc(); 4954 DstTL = DstTL.getUnqualifiedLoc(); 4955 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4956 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4957 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4958 DstPTL.getPointeeLoc()); 4959 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4960 return; 4961 } 4962 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4963 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4964 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4965 DstPTL.getInnerLoc()); 4966 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4967 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4968 return; 4969 } 4970 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4971 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4972 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4973 TypeLoc DstElemTL = DstATL.getElementLoc(); 4974 DstElemTL.initializeFullCopy(SrcElemTL); 4975 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4976 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4977 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4978 } 4979 4980 /// Helper method to turn variable array types into constant array 4981 /// types in certain situations which would otherwise be errors (for 4982 /// GCC compatibility). 4983 static TypeSourceInfo* 4984 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4985 ASTContext &Context, 4986 bool &SizeIsNegative, 4987 llvm::APSInt &Oversized) { 4988 QualType FixedTy 4989 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4990 SizeIsNegative, Oversized); 4991 if (FixedTy.isNull()) 4992 return nullptr; 4993 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4994 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4995 FixedTInfo->getTypeLoc()); 4996 return FixedTInfo; 4997 } 4998 4999 /// \brief Register the given locally-scoped extern "C" declaration so 5000 /// that it can be found later for redeclarations. We include any extern "C" 5001 /// declaration that is not visible in the translation unit here, not just 5002 /// function-scope declarations. 5003 void 5004 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5005 if (!getLangOpts().CPlusPlus && 5006 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5007 // Don't need to track declarations in the TU in C. 5008 return; 5009 5010 // Note that we have a locally-scoped external with this name. 5011 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5012 } 5013 5014 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5015 // FIXME: We can have multiple results via __attribute__((overloadable)). 5016 auto Result = Context.getExternCContextDecl()->lookup(Name); 5017 return Result.empty() ? nullptr : *Result.begin(); 5018 } 5019 5020 /// \brief Diagnose function specifiers on a declaration of an identifier that 5021 /// does not identify a function. 5022 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5023 // FIXME: We should probably indicate the identifier in question to avoid 5024 // confusion for constructs like "inline int a(), b;" 5025 if (DS.isInlineSpecified()) 5026 Diag(DS.getInlineSpecLoc(), 5027 diag::err_inline_non_function); 5028 5029 if (DS.isVirtualSpecified()) 5030 Diag(DS.getVirtualSpecLoc(), 5031 diag::err_virtual_non_function); 5032 5033 if (DS.isExplicitSpecified()) 5034 Diag(DS.getExplicitSpecLoc(), 5035 diag::err_explicit_non_function); 5036 5037 if (DS.isNoreturnSpecified()) 5038 Diag(DS.getNoreturnSpecLoc(), 5039 diag::err_noreturn_non_function); 5040 } 5041 5042 NamedDecl* 5043 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5044 TypeSourceInfo *TInfo, LookupResult &Previous) { 5045 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5046 if (D.getCXXScopeSpec().isSet()) { 5047 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5048 << D.getCXXScopeSpec().getRange(); 5049 D.setInvalidType(); 5050 // Pretend we didn't see the scope specifier. 5051 DC = CurContext; 5052 Previous.clear(); 5053 } 5054 5055 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5056 5057 if (D.getDeclSpec().isConstexprSpecified()) 5058 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5059 << 1; 5060 5061 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5062 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5063 << D.getName().getSourceRange(); 5064 return nullptr; 5065 } 5066 5067 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5068 if (!NewTD) return nullptr; 5069 5070 // Handle attributes prior to checking for duplicates in MergeVarDecl 5071 ProcessDeclAttributes(S, NewTD, D); 5072 5073 CheckTypedefForVariablyModifiedType(S, NewTD); 5074 5075 bool Redeclaration = D.isRedeclaration(); 5076 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5077 D.setRedeclaration(Redeclaration); 5078 return ND; 5079 } 5080 5081 void 5082 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5083 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5084 // then it shall have block scope. 5085 // Note that variably modified types must be fixed before merging the decl so 5086 // that redeclarations will match. 5087 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5088 QualType T = TInfo->getType(); 5089 if (T->isVariablyModifiedType()) { 5090 getCurFunction()->setHasBranchProtectedScope(); 5091 5092 if (S->getFnParent() == nullptr) { 5093 bool SizeIsNegative; 5094 llvm::APSInt Oversized; 5095 TypeSourceInfo *FixedTInfo = 5096 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5097 SizeIsNegative, 5098 Oversized); 5099 if (FixedTInfo) { 5100 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5101 NewTD->setTypeSourceInfo(FixedTInfo); 5102 } else { 5103 if (SizeIsNegative) 5104 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5105 else if (T->isVariableArrayType()) 5106 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5107 else if (Oversized.getBoolValue()) 5108 Diag(NewTD->getLocation(), diag::err_array_too_large) 5109 << Oversized.toString(10); 5110 else 5111 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5112 NewTD->setInvalidDecl(); 5113 } 5114 } 5115 } 5116 } 5117 5118 5119 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5120 /// declares a typedef-name, either using the 'typedef' type specifier or via 5121 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5122 NamedDecl* 5123 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5124 LookupResult &Previous, bool &Redeclaration) { 5125 // Merge the decl with the existing one if appropriate. If the decl is 5126 // in an outer scope, it isn't the same thing. 5127 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5128 /*AllowInlineNamespace*/false); 5129 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5130 if (!Previous.empty()) { 5131 Redeclaration = true; 5132 MergeTypedefNameDecl(NewTD, Previous); 5133 } 5134 5135 // If this is the C FILE type, notify the AST context. 5136 if (IdentifierInfo *II = NewTD->getIdentifier()) 5137 if (!NewTD->isInvalidDecl() && 5138 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5139 if (II->isStr("FILE")) 5140 Context.setFILEDecl(NewTD); 5141 else if (II->isStr("jmp_buf")) 5142 Context.setjmp_bufDecl(NewTD); 5143 else if (II->isStr("sigjmp_buf")) 5144 Context.setsigjmp_bufDecl(NewTD); 5145 else if (II->isStr("ucontext_t")) 5146 Context.setucontext_tDecl(NewTD); 5147 } 5148 5149 return NewTD; 5150 } 5151 5152 /// \brief Determines whether the given declaration is an out-of-scope 5153 /// previous declaration. 5154 /// 5155 /// This routine should be invoked when name lookup has found a 5156 /// previous declaration (PrevDecl) that is not in the scope where a 5157 /// new declaration by the same name is being introduced. If the new 5158 /// declaration occurs in a local scope, previous declarations with 5159 /// linkage may still be considered previous declarations (C99 5160 /// 6.2.2p4-5, C++ [basic.link]p6). 5161 /// 5162 /// \param PrevDecl the previous declaration found by name 5163 /// lookup 5164 /// 5165 /// \param DC the context in which the new declaration is being 5166 /// declared. 5167 /// 5168 /// \returns true if PrevDecl is an out-of-scope previous declaration 5169 /// for a new delcaration with the same name. 5170 static bool 5171 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5172 ASTContext &Context) { 5173 if (!PrevDecl) 5174 return false; 5175 5176 if (!PrevDecl->hasLinkage()) 5177 return false; 5178 5179 if (Context.getLangOpts().CPlusPlus) { 5180 // C++ [basic.link]p6: 5181 // If there is a visible declaration of an entity with linkage 5182 // having the same name and type, ignoring entities declared 5183 // outside the innermost enclosing namespace scope, the block 5184 // scope declaration declares that same entity and receives the 5185 // linkage of the previous declaration. 5186 DeclContext *OuterContext = DC->getRedeclContext(); 5187 if (!OuterContext->isFunctionOrMethod()) 5188 // This rule only applies to block-scope declarations. 5189 return false; 5190 5191 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5192 if (PrevOuterContext->isRecord()) 5193 // We found a member function: ignore it. 5194 return false; 5195 5196 // Find the innermost enclosing namespace for the new and 5197 // previous declarations. 5198 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5199 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5200 5201 // The previous declaration is in a different namespace, so it 5202 // isn't the same function. 5203 if (!OuterContext->Equals(PrevOuterContext)) 5204 return false; 5205 } 5206 5207 return true; 5208 } 5209 5210 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5211 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5212 if (!SS.isSet()) return; 5213 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5214 } 5215 5216 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5217 QualType type = decl->getType(); 5218 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5219 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5220 // Various kinds of declaration aren't allowed to be __autoreleasing. 5221 unsigned kind = -1U; 5222 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5223 if (var->hasAttr<BlocksAttr>()) 5224 kind = 0; // __block 5225 else if (!var->hasLocalStorage()) 5226 kind = 1; // global 5227 } else if (isa<ObjCIvarDecl>(decl)) { 5228 kind = 3; // ivar 5229 } else if (isa<FieldDecl>(decl)) { 5230 kind = 2; // field 5231 } 5232 5233 if (kind != -1U) { 5234 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5235 << kind; 5236 } 5237 } else if (lifetime == Qualifiers::OCL_None) { 5238 // Try to infer lifetime. 5239 if (!type->isObjCLifetimeType()) 5240 return false; 5241 5242 lifetime = type->getObjCARCImplicitLifetime(); 5243 type = Context.getLifetimeQualifiedType(type, lifetime); 5244 decl->setType(type); 5245 } 5246 5247 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5248 // Thread-local variables cannot have lifetime. 5249 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5250 var->getTLSKind()) { 5251 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5252 << var->getType(); 5253 return true; 5254 } 5255 } 5256 5257 return false; 5258 } 5259 5260 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5261 // Ensure that an auto decl is deduced otherwise the checks below might cache 5262 // the wrong linkage. 5263 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5264 5265 // 'weak' only applies to declarations with external linkage. 5266 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5267 if (!ND.isExternallyVisible()) { 5268 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5269 ND.dropAttr<WeakAttr>(); 5270 } 5271 } 5272 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5273 if (ND.isExternallyVisible()) { 5274 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5275 ND.dropAttr<WeakRefAttr>(); 5276 ND.dropAttr<AliasAttr>(); 5277 } 5278 } 5279 5280 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5281 if (VD->hasInit()) { 5282 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5283 assert(VD->isThisDeclarationADefinition() && 5284 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5285 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD; 5286 VD->dropAttr<AliasAttr>(); 5287 } 5288 } 5289 } 5290 5291 // 'selectany' only applies to externally visible variable declarations. 5292 // It does not apply to functions. 5293 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5294 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5295 S.Diag(Attr->getLocation(), 5296 diag::err_attribute_selectany_non_extern_data); 5297 ND.dropAttr<SelectAnyAttr>(); 5298 } 5299 } 5300 5301 // dll attributes require external linkage. 5302 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5303 if (!ND.isExternallyVisible()) { 5304 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5305 << &ND << Attr; 5306 ND.setInvalidDecl(); 5307 } 5308 } 5309 } 5310 5311 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5312 NamedDecl *NewDecl, 5313 bool IsSpecialization) { 5314 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5315 OldDecl = OldTD->getTemplatedDecl(); 5316 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5317 NewDecl = NewTD->getTemplatedDecl(); 5318 5319 if (!OldDecl || !NewDecl) 5320 return; 5321 5322 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5323 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5324 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5325 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5326 5327 // dllimport and dllexport are inheritable attributes so we have to exclude 5328 // inherited attribute instances. 5329 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5330 (NewExportAttr && !NewExportAttr->isInherited()); 5331 5332 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5333 // the only exception being explicit specializations. 5334 // Implicitly generated declarations are also excluded for now because there 5335 // is no other way to switch these to use dllimport or dllexport. 5336 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5337 5338 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5339 // If the declaration hasn't been used yet, allow with a warning for 5340 // free functions and global variables. 5341 bool JustWarn = false; 5342 if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) { 5343 auto *VD = dyn_cast<VarDecl>(OldDecl); 5344 if (VD && !VD->getDescribedVarTemplate()) 5345 JustWarn = true; 5346 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5347 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5348 JustWarn = true; 5349 } 5350 5351 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5352 : diag::err_attribute_dll_redeclaration; 5353 S.Diag(NewDecl->getLocation(), DiagID) 5354 << NewDecl 5355 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5356 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5357 if (!JustWarn) { 5358 NewDecl->setInvalidDecl(); 5359 return; 5360 } 5361 } 5362 5363 // A redeclaration is not allowed to drop a dllimport attribute, the only 5364 // exceptions being inline function definitions, local extern declarations, 5365 // and qualified friend declarations. 5366 // NB: MSVC converts such a declaration to dllexport. 5367 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5368 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5369 // Ignore static data because out-of-line definitions are diagnosed 5370 // separately. 5371 IsStaticDataMember = VD->isStaticDataMember(); 5372 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5373 IsInline = FD->isInlined(); 5374 IsQualifiedFriend = FD->getQualifier() && 5375 FD->getFriendObjectKind() == Decl::FOK_Declared; 5376 } 5377 5378 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5379 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5380 S.Diag(NewDecl->getLocation(), 5381 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5382 << NewDecl << OldImportAttr; 5383 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5384 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5385 OldDecl->dropAttr<DLLImportAttr>(); 5386 NewDecl->dropAttr<DLLImportAttr>(); 5387 } else if (IsInline && OldImportAttr && 5388 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5389 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5390 OldDecl->dropAttr<DLLImportAttr>(); 5391 NewDecl->dropAttr<DLLImportAttr>(); 5392 S.Diag(NewDecl->getLocation(), 5393 diag::warn_dllimport_dropped_from_inline_function) 5394 << NewDecl << OldImportAttr; 5395 } 5396 } 5397 5398 /// Given that we are within the definition of the given function, 5399 /// will that definition behave like C99's 'inline', where the 5400 /// definition is discarded except for optimization purposes? 5401 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5402 // Try to avoid calling GetGVALinkageForFunction. 5403 5404 // All cases of this require the 'inline' keyword. 5405 if (!FD->isInlined()) return false; 5406 5407 // This is only possible in C++ with the gnu_inline attribute. 5408 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5409 return false; 5410 5411 // Okay, go ahead and call the relatively-more-expensive function. 5412 5413 #ifndef NDEBUG 5414 // AST quite reasonably asserts that it's working on a function 5415 // definition. We don't really have a way to tell it that we're 5416 // currently defining the function, so just lie to it in +Asserts 5417 // builds. This is an awful hack. 5418 FD->setLazyBody(1); 5419 #endif 5420 5421 bool isC99Inline = 5422 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5423 5424 #ifndef NDEBUG 5425 FD->setLazyBody(0); 5426 #endif 5427 5428 return isC99Inline; 5429 } 5430 5431 /// Determine whether a variable is extern "C" prior to attaching 5432 /// an initializer. We can't just call isExternC() here, because that 5433 /// will also compute and cache whether the declaration is externally 5434 /// visible, which might change when we attach the initializer. 5435 /// 5436 /// This can only be used if the declaration is known to not be a 5437 /// redeclaration of an internal linkage declaration. 5438 /// 5439 /// For instance: 5440 /// 5441 /// auto x = []{}; 5442 /// 5443 /// Attaching the initializer here makes this declaration not externally 5444 /// visible, because its type has internal linkage. 5445 /// 5446 /// FIXME: This is a hack. 5447 template<typename T> 5448 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5449 if (S.getLangOpts().CPlusPlus) { 5450 // In C++, the overloadable attribute negates the effects of extern "C". 5451 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5452 return false; 5453 } 5454 return D->isExternC(); 5455 } 5456 5457 static bool shouldConsiderLinkage(const VarDecl *VD) { 5458 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5459 if (DC->isFunctionOrMethod()) 5460 return VD->hasExternalStorage(); 5461 if (DC->isFileContext()) 5462 return true; 5463 if (DC->isRecord()) 5464 return false; 5465 llvm_unreachable("Unexpected context"); 5466 } 5467 5468 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5469 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5470 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5471 return true; 5472 if (DC->isRecord()) 5473 return false; 5474 llvm_unreachable("Unexpected context"); 5475 } 5476 5477 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5478 AttributeList::Kind Kind) { 5479 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5480 if (L->getKind() == Kind) 5481 return true; 5482 return false; 5483 } 5484 5485 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5486 AttributeList::Kind Kind) { 5487 // Check decl attributes on the DeclSpec. 5488 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5489 return true; 5490 5491 // Walk the declarator structure, checking decl attributes that were in a type 5492 // position to the decl itself. 5493 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5494 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5495 return true; 5496 } 5497 5498 // Finally, check attributes on the decl itself. 5499 return hasParsedAttr(S, PD.getAttributes(), Kind); 5500 } 5501 5502 /// Adjust the \c DeclContext for a function or variable that might be a 5503 /// function-local external declaration. 5504 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5505 if (!DC->isFunctionOrMethod()) 5506 return false; 5507 5508 // If this is a local extern function or variable declared within a function 5509 // template, don't add it into the enclosing namespace scope until it is 5510 // instantiated; it might have a dependent type right now. 5511 if (DC->isDependentContext()) 5512 return true; 5513 5514 // C++11 [basic.link]p7: 5515 // When a block scope declaration of an entity with linkage is not found to 5516 // refer to some other declaration, then that entity is a member of the 5517 // innermost enclosing namespace. 5518 // 5519 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5520 // semantically-enclosing namespace, not a lexically-enclosing one. 5521 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5522 DC = DC->getParent(); 5523 return true; 5524 } 5525 5526 NamedDecl * 5527 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5528 TypeSourceInfo *TInfo, LookupResult &Previous, 5529 MultiTemplateParamsArg TemplateParamLists, 5530 bool &AddToScope) { 5531 QualType R = TInfo->getType(); 5532 DeclarationName Name = GetNameForDeclarator(D).getName(); 5533 5534 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5535 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5536 5537 // dllimport globals without explicit storage class are treated as extern. We 5538 // have to change the storage class this early to get the right DeclContext. 5539 if (SC == SC_None && !DC->isRecord() && 5540 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5541 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5542 SC = SC_Extern; 5543 5544 DeclContext *OriginalDC = DC; 5545 bool IsLocalExternDecl = SC == SC_Extern && 5546 adjustContextForLocalExternDecl(DC); 5547 5548 if (getLangOpts().OpenCL) { 5549 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5550 QualType NR = R; 5551 while (NR->isPointerType()) { 5552 if (NR->isFunctionPointerType()) { 5553 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5554 D.setInvalidType(); 5555 break; 5556 } 5557 NR = NR->getPointeeType(); 5558 } 5559 5560 if (!getOpenCLOptions().cl_khr_fp16) { 5561 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5562 // half array type (unless the cl_khr_fp16 extension is enabled). 5563 if (Context.getBaseElementType(R)->isHalfType()) { 5564 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5565 D.setInvalidType(); 5566 } 5567 } 5568 } 5569 5570 if (SCSpec == DeclSpec::SCS_mutable) { 5571 // mutable can only appear on non-static class members, so it's always 5572 // an error here 5573 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5574 D.setInvalidType(); 5575 SC = SC_None; 5576 } 5577 5578 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5579 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5580 D.getDeclSpec().getStorageClassSpecLoc())) { 5581 // In C++11, the 'register' storage class specifier is deprecated. 5582 // Suppress the warning in system macros, it's used in macros in some 5583 // popular C system headers, such as in glibc's htonl() macro. 5584 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5585 diag::warn_deprecated_register) 5586 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5587 } 5588 5589 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5590 if (!II) { 5591 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5592 << Name; 5593 return nullptr; 5594 } 5595 5596 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5597 5598 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5599 // C99 6.9p2: The storage-class specifiers auto and register shall not 5600 // appear in the declaration specifiers in an external declaration. 5601 // Global Register+Asm is a GNU extension we support. 5602 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5603 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5604 D.setInvalidType(); 5605 } 5606 } 5607 5608 if (getLangOpts().OpenCL) { 5609 // Set up the special work-group-local storage class for variables in the 5610 // OpenCL __local address space. 5611 if (R.getAddressSpace() == LangAS::opencl_local) { 5612 SC = SC_OpenCLWorkGroupLocal; 5613 } 5614 5615 // OpenCL v1.2 s6.9.b p4: 5616 // The sampler type cannot be used with the __local and __global address 5617 // space qualifiers. 5618 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5619 R.getAddressSpace() == LangAS::opencl_global)) { 5620 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5621 } 5622 5623 // OpenCL 1.2 spec, p6.9 r: 5624 // The event type cannot be used to declare a program scope variable. 5625 // The event type cannot be used with the __local, __constant and __global 5626 // address space qualifiers. 5627 if (R->isEventT()) { 5628 if (S->getParent() == nullptr) { 5629 Diag(D.getLocStart(), diag::err_event_t_global_var); 5630 D.setInvalidType(); 5631 } 5632 5633 if (R.getAddressSpace()) { 5634 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5635 D.setInvalidType(); 5636 } 5637 } 5638 } 5639 5640 bool IsExplicitSpecialization = false; 5641 bool IsVariableTemplateSpecialization = false; 5642 bool IsPartialSpecialization = false; 5643 bool IsVariableTemplate = false; 5644 VarDecl *NewVD = nullptr; 5645 VarTemplateDecl *NewTemplate = nullptr; 5646 TemplateParameterList *TemplateParams = nullptr; 5647 if (!getLangOpts().CPlusPlus) { 5648 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5649 D.getIdentifierLoc(), II, 5650 R, TInfo, SC); 5651 5652 if (D.isInvalidType()) 5653 NewVD->setInvalidDecl(); 5654 } else { 5655 bool Invalid = false; 5656 5657 if (DC->isRecord() && !CurContext->isRecord()) { 5658 // This is an out-of-line definition of a static data member. 5659 switch (SC) { 5660 case SC_None: 5661 break; 5662 case SC_Static: 5663 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5664 diag::err_static_out_of_line) 5665 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5666 break; 5667 case SC_Auto: 5668 case SC_Register: 5669 case SC_Extern: 5670 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5671 // to names of variables declared in a block or to function parameters. 5672 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5673 // of class members 5674 5675 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5676 diag::err_storage_class_for_static_member) 5677 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5678 break; 5679 case SC_PrivateExtern: 5680 llvm_unreachable("C storage class in c++!"); 5681 case SC_OpenCLWorkGroupLocal: 5682 llvm_unreachable("OpenCL storage class in c++!"); 5683 } 5684 } 5685 5686 if (SC == SC_Static && CurContext->isRecord()) { 5687 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5688 if (RD->isLocalClass()) 5689 Diag(D.getIdentifierLoc(), 5690 diag::err_static_data_member_not_allowed_in_local_class) 5691 << Name << RD->getDeclName(); 5692 5693 // C++98 [class.union]p1: If a union contains a static data member, 5694 // the program is ill-formed. C++11 drops this restriction. 5695 if (RD->isUnion()) 5696 Diag(D.getIdentifierLoc(), 5697 getLangOpts().CPlusPlus11 5698 ? diag::warn_cxx98_compat_static_data_member_in_union 5699 : diag::ext_static_data_member_in_union) << Name; 5700 // We conservatively disallow static data members in anonymous structs. 5701 else if (!RD->getDeclName()) 5702 Diag(D.getIdentifierLoc(), 5703 diag::err_static_data_member_not_allowed_in_anon_struct) 5704 << Name << RD->isUnion(); 5705 } 5706 } 5707 5708 // Match up the template parameter lists with the scope specifier, then 5709 // determine whether we have a template or a template specialization. 5710 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5711 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5712 D.getCXXScopeSpec(), 5713 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5714 ? D.getName().TemplateId 5715 : nullptr, 5716 TemplateParamLists, 5717 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5718 5719 if (TemplateParams) { 5720 if (!TemplateParams->size() && 5721 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5722 // There is an extraneous 'template<>' for this variable. Complain 5723 // about it, but allow the declaration of the variable. 5724 Diag(TemplateParams->getTemplateLoc(), 5725 diag::err_template_variable_noparams) 5726 << II 5727 << SourceRange(TemplateParams->getTemplateLoc(), 5728 TemplateParams->getRAngleLoc()); 5729 TemplateParams = nullptr; 5730 } else { 5731 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5732 // This is an explicit specialization or a partial specialization. 5733 // FIXME: Check that we can declare a specialization here. 5734 IsVariableTemplateSpecialization = true; 5735 IsPartialSpecialization = TemplateParams->size() > 0; 5736 } else { // if (TemplateParams->size() > 0) 5737 // This is a template declaration. 5738 IsVariableTemplate = true; 5739 5740 // Check that we can declare a template here. 5741 if (CheckTemplateDeclScope(S, TemplateParams)) 5742 return nullptr; 5743 5744 // Only C++1y supports variable templates (N3651). 5745 Diag(D.getIdentifierLoc(), 5746 getLangOpts().CPlusPlus14 5747 ? diag::warn_cxx11_compat_variable_template 5748 : diag::ext_variable_template); 5749 } 5750 } 5751 } else { 5752 assert( 5753 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 5754 "should have a 'template<>' for this decl"); 5755 } 5756 5757 if (IsVariableTemplateSpecialization) { 5758 SourceLocation TemplateKWLoc = 5759 TemplateParamLists.size() > 0 5760 ? TemplateParamLists[0]->getTemplateLoc() 5761 : SourceLocation(); 5762 DeclResult Res = ActOnVarTemplateSpecialization( 5763 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5764 IsPartialSpecialization); 5765 if (Res.isInvalid()) 5766 return nullptr; 5767 NewVD = cast<VarDecl>(Res.get()); 5768 AddToScope = false; 5769 } else 5770 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5771 D.getIdentifierLoc(), II, R, TInfo, SC); 5772 5773 // If this is supposed to be a variable template, create it as such. 5774 if (IsVariableTemplate) { 5775 NewTemplate = 5776 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5777 TemplateParams, NewVD); 5778 NewVD->setDescribedVarTemplate(NewTemplate); 5779 } 5780 5781 // If this decl has an auto type in need of deduction, make a note of the 5782 // Decl so we can diagnose uses of it in its own initializer. 5783 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5784 ParsingInitForAutoVars.insert(NewVD); 5785 5786 if (D.isInvalidType() || Invalid) { 5787 NewVD->setInvalidDecl(); 5788 if (NewTemplate) 5789 NewTemplate->setInvalidDecl(); 5790 } 5791 5792 SetNestedNameSpecifier(NewVD, D); 5793 5794 // If we have any template parameter lists that don't directly belong to 5795 // the variable (matching the scope specifier), store them. 5796 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5797 if (TemplateParamLists.size() > VDTemplateParamLists) 5798 NewVD->setTemplateParameterListsInfo( 5799 Context, TemplateParamLists.size() - VDTemplateParamLists, 5800 TemplateParamLists.data()); 5801 5802 if (D.getDeclSpec().isConstexprSpecified()) 5803 NewVD->setConstexpr(true); 5804 } 5805 5806 // Set the lexical context. If the declarator has a C++ scope specifier, the 5807 // lexical context will be different from the semantic context. 5808 NewVD->setLexicalDeclContext(CurContext); 5809 if (NewTemplate) 5810 NewTemplate->setLexicalDeclContext(CurContext); 5811 5812 if (IsLocalExternDecl) 5813 NewVD->setLocalExternDecl(); 5814 5815 bool EmitTLSUnsupportedError = false; 5816 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5817 // C++11 [dcl.stc]p4: 5818 // When thread_local is applied to a variable of block scope the 5819 // storage-class-specifier static is implied if it does not appear 5820 // explicitly. 5821 // Core issue: 'static' is not implied if the variable is declared 5822 // 'extern'. 5823 if (NewVD->hasLocalStorage() && 5824 (SCSpec != DeclSpec::SCS_unspecified || 5825 TSCS != DeclSpec::TSCS_thread_local || 5826 !DC->isFunctionOrMethod())) 5827 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5828 diag::err_thread_non_global) 5829 << DeclSpec::getSpecifierName(TSCS); 5830 else if (!Context.getTargetInfo().isTLSSupported()) { 5831 if (getLangOpts().CUDA) { 5832 // Postpone error emission until we've collected attributes required to 5833 // figure out whether it's a host or device variable and whether the 5834 // error should be ignored. 5835 EmitTLSUnsupportedError = true; 5836 // We still need to mark the variable as TLS so it shows up in AST with 5837 // proper storage class for other tools to use even if we're not going 5838 // to emit any code for it. 5839 NewVD->setTSCSpec(TSCS); 5840 } else 5841 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5842 diag::err_thread_unsupported); 5843 } else 5844 NewVD->setTSCSpec(TSCS); 5845 } 5846 5847 // C99 6.7.4p3 5848 // An inline definition of a function with external linkage shall 5849 // not contain a definition of a modifiable object with static or 5850 // thread storage duration... 5851 // We only apply this when the function is required to be defined 5852 // elsewhere, i.e. when the function is not 'extern inline'. Note 5853 // that a local variable with thread storage duration still has to 5854 // be marked 'static'. Also note that it's possible to get these 5855 // semantics in C++ using __attribute__((gnu_inline)). 5856 if (SC == SC_Static && S->getFnParent() != nullptr && 5857 !NewVD->getType().isConstQualified()) { 5858 FunctionDecl *CurFD = getCurFunctionDecl(); 5859 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5860 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5861 diag::warn_static_local_in_extern_inline); 5862 MaybeSuggestAddingStaticToDecl(CurFD); 5863 } 5864 } 5865 5866 if (D.getDeclSpec().isModulePrivateSpecified()) { 5867 if (IsVariableTemplateSpecialization) 5868 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5869 << (IsPartialSpecialization ? 1 : 0) 5870 << FixItHint::CreateRemoval( 5871 D.getDeclSpec().getModulePrivateSpecLoc()); 5872 else if (IsExplicitSpecialization) 5873 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5874 << 2 5875 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5876 else if (NewVD->hasLocalStorage()) 5877 Diag(NewVD->getLocation(), diag::err_module_private_local) 5878 << 0 << NewVD->getDeclName() 5879 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5880 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5881 else { 5882 NewVD->setModulePrivate(); 5883 if (NewTemplate) 5884 NewTemplate->setModulePrivate(); 5885 } 5886 } 5887 5888 // Handle attributes prior to checking for duplicates in MergeVarDecl 5889 ProcessDeclAttributes(S, NewVD, D); 5890 5891 if (getLangOpts().CUDA) { 5892 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 5893 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5894 diag::err_thread_unsupported); 5895 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5896 // storage [duration]." 5897 if (SC == SC_None && S->getFnParent() != nullptr && 5898 (NewVD->hasAttr<CUDASharedAttr>() || 5899 NewVD->hasAttr<CUDAConstantAttr>())) { 5900 NewVD->setStorageClass(SC_Static); 5901 } 5902 } 5903 5904 // Ensure that dllimport globals without explicit storage class are treated as 5905 // extern. The storage class is set above using parsed attributes. Now we can 5906 // check the VarDecl itself. 5907 assert(!NewVD->hasAttr<DLLImportAttr>() || 5908 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5909 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5910 5911 // In auto-retain/release, infer strong retension for variables of 5912 // retainable type. 5913 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5914 NewVD->setInvalidDecl(); 5915 5916 // Handle GNU asm-label extension (encoded as an attribute). 5917 if (Expr *E = (Expr*)D.getAsmLabel()) { 5918 // The parser guarantees this is a string. 5919 StringLiteral *SE = cast<StringLiteral>(E); 5920 StringRef Label = SE->getString(); 5921 if (S->getFnParent() != nullptr) { 5922 switch (SC) { 5923 case SC_None: 5924 case SC_Auto: 5925 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5926 break; 5927 case SC_Register: 5928 // Local Named register 5929 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5930 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5931 break; 5932 case SC_Static: 5933 case SC_Extern: 5934 case SC_PrivateExtern: 5935 case SC_OpenCLWorkGroupLocal: 5936 break; 5937 } 5938 } else if (SC == SC_Register) { 5939 // Global Named register 5940 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5941 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5942 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5943 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5944 NewVD->setInvalidDecl(true); 5945 } 5946 } 5947 5948 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5949 Context, Label, 0)); 5950 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5951 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5952 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5953 if (I != ExtnameUndeclaredIdentifiers.end()) { 5954 NewVD->addAttr(I->second); 5955 ExtnameUndeclaredIdentifiers.erase(I); 5956 } 5957 } 5958 5959 // Diagnose shadowed variables before filtering for scope. 5960 if (D.getCXXScopeSpec().isEmpty()) 5961 CheckShadow(S, NewVD, Previous); 5962 5963 // Don't consider existing declarations that are in a different 5964 // scope and are out-of-semantic-context declarations (if the new 5965 // declaration has linkage). 5966 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5967 D.getCXXScopeSpec().isNotEmpty() || 5968 IsExplicitSpecialization || 5969 IsVariableTemplateSpecialization); 5970 5971 // Check whether the previous declaration is in the same block scope. This 5972 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5973 if (getLangOpts().CPlusPlus && 5974 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5975 NewVD->setPreviousDeclInSameBlockScope( 5976 Previous.isSingleResult() && !Previous.isShadowed() && 5977 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5978 5979 if (!getLangOpts().CPlusPlus) { 5980 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5981 } else { 5982 // If this is an explicit specialization of a static data member, check it. 5983 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5984 CheckMemberSpecialization(NewVD, Previous)) 5985 NewVD->setInvalidDecl(); 5986 5987 // Merge the decl with the existing one if appropriate. 5988 if (!Previous.empty()) { 5989 if (Previous.isSingleResult() && 5990 isa<FieldDecl>(Previous.getFoundDecl()) && 5991 D.getCXXScopeSpec().isSet()) { 5992 // The user tried to define a non-static data member 5993 // out-of-line (C++ [dcl.meaning]p1). 5994 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5995 << D.getCXXScopeSpec().getRange(); 5996 Previous.clear(); 5997 NewVD->setInvalidDecl(); 5998 } 5999 } else if (D.getCXXScopeSpec().isSet()) { 6000 // No previous declaration in the qualifying scope. 6001 Diag(D.getIdentifierLoc(), diag::err_no_member) 6002 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6003 << D.getCXXScopeSpec().getRange(); 6004 NewVD->setInvalidDecl(); 6005 } 6006 6007 if (!IsVariableTemplateSpecialization) 6008 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6009 6010 if (NewTemplate) { 6011 VarTemplateDecl *PrevVarTemplate = 6012 NewVD->getPreviousDecl() 6013 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6014 : nullptr; 6015 6016 // Check the template parameter list of this declaration, possibly 6017 // merging in the template parameter list from the previous variable 6018 // template declaration. 6019 if (CheckTemplateParameterList( 6020 TemplateParams, 6021 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6022 : nullptr, 6023 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6024 DC->isDependentContext()) 6025 ? TPC_ClassTemplateMember 6026 : TPC_VarTemplate)) 6027 NewVD->setInvalidDecl(); 6028 6029 // If we are providing an explicit specialization of a static variable 6030 // template, make a note of that. 6031 if (PrevVarTemplate && 6032 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6033 PrevVarTemplate->setMemberSpecialization(); 6034 } 6035 } 6036 6037 ProcessPragmaWeak(S, NewVD); 6038 6039 // If this is the first declaration of an extern C variable, update 6040 // the map of such variables. 6041 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6042 isIncompleteDeclExternC(*this, NewVD)) 6043 RegisterLocallyScopedExternCDecl(NewVD, S); 6044 6045 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6046 Decl *ManglingContextDecl; 6047 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6048 NewVD->getDeclContext(), ManglingContextDecl)) { 6049 Context.setManglingNumber( 6050 NewVD, MCtx->getManglingNumber( 6051 NewVD, getMSManglingNumber(getLangOpts(), S))); 6052 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6053 } 6054 } 6055 6056 if (D.isRedeclaration() && !Previous.empty()) { 6057 checkDLLAttributeRedeclaration( 6058 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6059 IsExplicitSpecialization); 6060 } 6061 6062 if (NewTemplate) { 6063 if (NewVD->isInvalidDecl()) 6064 NewTemplate->setInvalidDecl(); 6065 ActOnDocumentableDecl(NewTemplate); 6066 return NewTemplate; 6067 } 6068 6069 return NewVD; 6070 } 6071 6072 /// \brief Diagnose variable or built-in function shadowing. Implements 6073 /// -Wshadow. 6074 /// 6075 /// This method is called whenever a VarDecl is added to a "useful" 6076 /// scope. 6077 /// 6078 /// \param S the scope in which the shadowing name is being declared 6079 /// \param R the lookup of the name 6080 /// 6081 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6082 // Return if warning is ignored. 6083 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6084 return; 6085 6086 // Don't diagnose declarations at file scope. 6087 if (D->hasGlobalStorage()) 6088 return; 6089 6090 DeclContext *NewDC = D->getDeclContext(); 6091 6092 // Only diagnose if we're shadowing an unambiguous field or variable. 6093 if (R.getResultKind() != LookupResult::Found) 6094 return; 6095 6096 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6097 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6098 return; 6099 6100 // Fields are not shadowed by variables in C++ static methods. 6101 if (isa<FieldDecl>(ShadowedDecl)) 6102 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6103 if (MD->isStatic()) 6104 return; 6105 6106 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6107 if (shadowedVar->isExternC()) { 6108 // For shadowing external vars, make sure that we point to the global 6109 // declaration, not a locally scoped extern declaration. 6110 for (auto I : shadowedVar->redecls()) 6111 if (I->isFileVarDecl()) { 6112 ShadowedDecl = I; 6113 break; 6114 } 6115 } 6116 6117 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6118 6119 // Only warn about certain kinds of shadowing for class members. 6120 if (NewDC && NewDC->isRecord()) { 6121 // In particular, don't warn about shadowing non-class members. 6122 if (!OldDC->isRecord()) 6123 return; 6124 6125 // TODO: should we warn about static data members shadowing 6126 // static data members from base classes? 6127 6128 // TODO: don't diagnose for inaccessible shadowed members. 6129 // This is hard to do perfectly because we might friend the 6130 // shadowing context, but that's just a false negative. 6131 } 6132 6133 // Determine what kind of declaration we're shadowing. 6134 unsigned Kind; 6135 if (isa<RecordDecl>(OldDC)) { 6136 if (isa<FieldDecl>(ShadowedDecl)) 6137 Kind = 3; // field 6138 else 6139 Kind = 2; // static data member 6140 } else if (OldDC->isFileContext()) 6141 Kind = 1; // global 6142 else 6143 Kind = 0; // local 6144 6145 DeclarationName Name = R.getLookupName(); 6146 6147 // Emit warning and note. 6148 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6149 return; 6150 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6151 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6152 } 6153 6154 /// \brief Check -Wshadow without the advantage of a previous lookup. 6155 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6156 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6157 return; 6158 6159 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6160 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6161 LookupName(R, S); 6162 CheckShadow(S, D, R); 6163 } 6164 6165 /// Check for conflict between this global or extern "C" declaration and 6166 /// previous global or extern "C" declarations. This is only used in C++. 6167 template<typename T> 6168 static bool checkGlobalOrExternCConflict( 6169 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6170 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6171 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6172 6173 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6174 // The common case: this global doesn't conflict with any extern "C" 6175 // declaration. 6176 return false; 6177 } 6178 6179 if (Prev) { 6180 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6181 // Both the old and new declarations have C language linkage. This is a 6182 // redeclaration. 6183 Previous.clear(); 6184 Previous.addDecl(Prev); 6185 return true; 6186 } 6187 6188 // This is a global, non-extern "C" declaration, and there is a previous 6189 // non-global extern "C" declaration. Diagnose if this is a variable 6190 // declaration. 6191 if (!isa<VarDecl>(ND)) 6192 return false; 6193 } else { 6194 // The declaration is extern "C". Check for any declaration in the 6195 // translation unit which might conflict. 6196 if (IsGlobal) { 6197 // We have already performed the lookup into the translation unit. 6198 IsGlobal = false; 6199 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6200 I != E; ++I) { 6201 if (isa<VarDecl>(*I)) { 6202 Prev = *I; 6203 break; 6204 } 6205 } 6206 } else { 6207 DeclContext::lookup_result R = 6208 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6209 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6210 I != E; ++I) { 6211 if (isa<VarDecl>(*I)) { 6212 Prev = *I; 6213 break; 6214 } 6215 // FIXME: If we have any other entity with this name in global scope, 6216 // the declaration is ill-formed, but that is a defect: it breaks the 6217 // 'stat' hack, for instance. Only variables can have mangled name 6218 // clashes with extern "C" declarations, so only they deserve a 6219 // diagnostic. 6220 } 6221 } 6222 6223 if (!Prev) 6224 return false; 6225 } 6226 6227 // Use the first declaration's location to ensure we point at something which 6228 // is lexically inside an extern "C" linkage-spec. 6229 assert(Prev && "should have found a previous declaration to diagnose"); 6230 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6231 Prev = FD->getFirstDecl(); 6232 else 6233 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6234 6235 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6236 << IsGlobal << ND; 6237 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6238 << IsGlobal; 6239 return false; 6240 } 6241 6242 /// Apply special rules for handling extern "C" declarations. Returns \c true 6243 /// if we have found that this is a redeclaration of some prior entity. 6244 /// 6245 /// Per C++ [dcl.link]p6: 6246 /// Two declarations [for a function or variable] with C language linkage 6247 /// with the same name that appear in different scopes refer to the same 6248 /// [entity]. An entity with C language linkage shall not be declared with 6249 /// the same name as an entity in global scope. 6250 template<typename T> 6251 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6252 LookupResult &Previous) { 6253 if (!S.getLangOpts().CPlusPlus) { 6254 // In C, when declaring a global variable, look for a corresponding 'extern' 6255 // variable declared in function scope. We don't need this in C++, because 6256 // we find local extern decls in the surrounding file-scope DeclContext. 6257 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6258 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6259 Previous.clear(); 6260 Previous.addDecl(Prev); 6261 return true; 6262 } 6263 } 6264 return false; 6265 } 6266 6267 // A declaration in the translation unit can conflict with an extern "C" 6268 // declaration. 6269 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6270 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6271 6272 // An extern "C" declaration can conflict with a declaration in the 6273 // translation unit or can be a redeclaration of an extern "C" declaration 6274 // in another scope. 6275 if (isIncompleteDeclExternC(S,ND)) 6276 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6277 6278 // Neither global nor extern "C": nothing to do. 6279 return false; 6280 } 6281 6282 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6283 // If the decl is already known invalid, don't check it. 6284 if (NewVD->isInvalidDecl()) 6285 return; 6286 6287 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6288 QualType T = TInfo->getType(); 6289 6290 // Defer checking an 'auto' type until its initializer is attached. 6291 if (T->isUndeducedType()) 6292 return; 6293 6294 if (NewVD->hasAttrs()) 6295 CheckAlignasUnderalignment(NewVD); 6296 6297 if (T->isObjCObjectType()) { 6298 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6299 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6300 T = Context.getObjCObjectPointerType(T); 6301 NewVD->setType(T); 6302 } 6303 6304 // Emit an error if an address space was applied to decl with local storage. 6305 // This includes arrays of objects with address space qualifiers, but not 6306 // automatic variables that point to other address spaces. 6307 // ISO/IEC TR 18037 S5.1.2 6308 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6309 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6310 NewVD->setInvalidDecl(); 6311 return; 6312 } 6313 6314 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6315 // __constant address space. 6316 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 6317 && T.getAddressSpace() != LangAS::opencl_constant 6318 && !T->isSamplerT()){ 6319 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 6320 NewVD->setInvalidDecl(); 6321 return; 6322 } 6323 6324 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6325 // scope. 6326 if ((getLangOpts().OpenCLVersion >= 120) 6327 && NewVD->isStaticLocal()) { 6328 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6329 NewVD->setInvalidDecl(); 6330 return; 6331 } 6332 6333 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6334 && !NewVD->hasAttr<BlocksAttr>()) { 6335 if (getLangOpts().getGC() != LangOptions::NonGC) 6336 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6337 else { 6338 assert(!getLangOpts().ObjCAutoRefCount); 6339 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6340 } 6341 } 6342 6343 bool isVM = T->isVariablyModifiedType(); 6344 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6345 NewVD->hasAttr<BlocksAttr>()) 6346 getCurFunction()->setHasBranchProtectedScope(); 6347 6348 if ((isVM && NewVD->hasLinkage()) || 6349 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6350 bool SizeIsNegative; 6351 llvm::APSInt Oversized; 6352 TypeSourceInfo *FixedTInfo = 6353 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6354 SizeIsNegative, Oversized); 6355 if (!FixedTInfo && T->isVariableArrayType()) { 6356 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6357 // FIXME: This won't give the correct result for 6358 // int a[10][n]; 6359 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6360 6361 if (NewVD->isFileVarDecl()) 6362 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6363 << SizeRange; 6364 else if (NewVD->isStaticLocal()) 6365 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6366 << SizeRange; 6367 else 6368 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6369 << SizeRange; 6370 NewVD->setInvalidDecl(); 6371 return; 6372 } 6373 6374 if (!FixedTInfo) { 6375 if (NewVD->isFileVarDecl()) 6376 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6377 else 6378 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6379 NewVD->setInvalidDecl(); 6380 return; 6381 } 6382 6383 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6384 NewVD->setType(FixedTInfo->getType()); 6385 NewVD->setTypeSourceInfo(FixedTInfo); 6386 } 6387 6388 if (T->isVoidType()) { 6389 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6390 // of objects and functions. 6391 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6392 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6393 << T; 6394 NewVD->setInvalidDecl(); 6395 return; 6396 } 6397 } 6398 6399 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6400 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6401 NewVD->setInvalidDecl(); 6402 return; 6403 } 6404 6405 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6406 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6407 NewVD->setInvalidDecl(); 6408 return; 6409 } 6410 6411 if (NewVD->isConstexpr() && !T->isDependentType() && 6412 RequireLiteralType(NewVD->getLocation(), T, 6413 diag::err_constexpr_var_non_literal)) { 6414 NewVD->setInvalidDecl(); 6415 return; 6416 } 6417 } 6418 6419 /// \brief Perform semantic checking on a newly-created variable 6420 /// declaration. 6421 /// 6422 /// This routine performs all of the type-checking required for a 6423 /// variable declaration once it has been built. It is used both to 6424 /// check variables after they have been parsed and their declarators 6425 /// have been translated into a declaration, and to check variables 6426 /// that have been instantiated from a template. 6427 /// 6428 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6429 /// 6430 /// Returns true if the variable declaration is a redeclaration. 6431 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6432 CheckVariableDeclarationType(NewVD); 6433 6434 // If the decl is already known invalid, don't check it. 6435 if (NewVD->isInvalidDecl()) 6436 return false; 6437 6438 // If we did not find anything by this name, look for a non-visible 6439 // extern "C" declaration with the same name. 6440 if (Previous.empty() && 6441 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6442 Previous.setShadowed(); 6443 6444 // Filter out any non-conflicting previous declarations. 6445 filterNonConflictingPreviousDecls(*this, NewVD, Previous); 6446 6447 if (!Previous.empty()) { 6448 MergeVarDecl(NewVD, Previous); 6449 return true; 6450 } 6451 return false; 6452 } 6453 6454 /// \brief Data used with FindOverriddenMethod 6455 struct FindOverriddenMethodData { 6456 Sema *S; 6457 CXXMethodDecl *Method; 6458 }; 6459 6460 /// \brief Member lookup function that determines whether a given C++ 6461 /// method overrides a method in a base class, to be used with 6462 /// CXXRecordDecl::lookupInBases(). 6463 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6464 CXXBasePath &Path, 6465 void *UserData) { 6466 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6467 6468 FindOverriddenMethodData *Data 6469 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6470 6471 DeclarationName Name = Data->Method->getDeclName(); 6472 6473 // FIXME: Do we care about other names here too? 6474 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6475 // We really want to find the base class destructor here. 6476 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6477 CanQualType CT = Data->S->Context.getCanonicalType(T); 6478 6479 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6480 } 6481 6482 for (Path.Decls = BaseRecord->lookup(Name); 6483 !Path.Decls.empty(); 6484 Path.Decls = Path.Decls.slice(1)) { 6485 NamedDecl *D = Path.Decls.front(); 6486 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6487 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6488 return true; 6489 } 6490 } 6491 6492 return false; 6493 } 6494 6495 namespace { 6496 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6497 } 6498 /// \brief Report an error regarding overriding, along with any relevant 6499 /// overriden methods. 6500 /// 6501 /// \param DiagID the primary error to report. 6502 /// \param MD the overriding method. 6503 /// \param OEK which overrides to include as notes. 6504 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6505 OverrideErrorKind OEK = OEK_All) { 6506 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6507 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6508 E = MD->end_overridden_methods(); 6509 I != E; ++I) { 6510 // This check (& the OEK parameter) could be replaced by a predicate, but 6511 // without lambdas that would be overkill. This is still nicer than writing 6512 // out the diag loop 3 times. 6513 if ((OEK == OEK_All) || 6514 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6515 (OEK == OEK_Deleted && (*I)->isDeleted())) 6516 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6517 } 6518 } 6519 6520 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6521 /// and if so, check that it's a valid override and remember it. 6522 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6523 // Look for methods in base classes that this method might override. 6524 CXXBasePaths Paths; 6525 FindOverriddenMethodData Data; 6526 Data.Method = MD; 6527 Data.S = this; 6528 bool hasDeletedOverridenMethods = false; 6529 bool hasNonDeletedOverridenMethods = false; 6530 bool AddedAny = false; 6531 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6532 for (auto *I : Paths.found_decls()) { 6533 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6534 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6535 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6536 !CheckOverridingFunctionAttributes(MD, OldMD) && 6537 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6538 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6539 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6540 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6541 AddedAny = true; 6542 } 6543 } 6544 } 6545 } 6546 6547 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6548 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6549 } 6550 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6551 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6552 } 6553 6554 return AddedAny; 6555 } 6556 6557 namespace { 6558 // Struct for holding all of the extra arguments needed by 6559 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6560 struct ActOnFDArgs { 6561 Scope *S; 6562 Declarator &D; 6563 MultiTemplateParamsArg TemplateParamLists; 6564 bool AddToScope; 6565 }; 6566 } 6567 6568 namespace { 6569 6570 // Callback to only accept typo corrections that have a non-zero edit distance. 6571 // Also only accept corrections that have the same parent decl. 6572 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6573 public: 6574 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6575 CXXRecordDecl *Parent) 6576 : Context(Context), OriginalFD(TypoFD), 6577 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6578 6579 bool ValidateCandidate(const TypoCorrection &candidate) override { 6580 if (candidate.getEditDistance() == 0) 6581 return false; 6582 6583 SmallVector<unsigned, 1> MismatchedParams; 6584 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6585 CDeclEnd = candidate.end(); 6586 CDecl != CDeclEnd; ++CDecl) { 6587 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6588 6589 if (FD && !FD->hasBody() && 6590 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6591 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6592 CXXRecordDecl *Parent = MD->getParent(); 6593 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6594 return true; 6595 } else if (!ExpectedParent) { 6596 return true; 6597 } 6598 } 6599 } 6600 6601 return false; 6602 } 6603 6604 private: 6605 ASTContext &Context; 6606 FunctionDecl *OriginalFD; 6607 CXXRecordDecl *ExpectedParent; 6608 }; 6609 6610 } // namespace 6611 6612 /// \brief Generate diagnostics for an invalid function redeclaration. 6613 /// 6614 /// This routine handles generating the diagnostic messages for an invalid 6615 /// function redeclaration, including finding possible similar declarations 6616 /// or performing typo correction if there are no previous declarations with 6617 /// the same name. 6618 /// 6619 /// Returns a NamedDecl iff typo correction was performed and substituting in 6620 /// the new declaration name does not cause new errors. 6621 static NamedDecl *DiagnoseInvalidRedeclaration( 6622 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6623 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6624 DeclarationName Name = NewFD->getDeclName(); 6625 DeclContext *NewDC = NewFD->getDeclContext(); 6626 SmallVector<unsigned, 1> MismatchedParams; 6627 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6628 TypoCorrection Correction; 6629 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6630 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6631 : diag::err_member_decl_does_not_match; 6632 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6633 IsLocalFriend ? Sema::LookupLocalFriendName 6634 : Sema::LookupOrdinaryName, 6635 Sema::ForRedeclaration); 6636 6637 NewFD->setInvalidDecl(); 6638 if (IsLocalFriend) 6639 SemaRef.LookupName(Prev, S); 6640 else 6641 SemaRef.LookupQualifiedName(Prev, NewDC); 6642 assert(!Prev.isAmbiguous() && 6643 "Cannot have an ambiguity in previous-declaration lookup"); 6644 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6645 if (!Prev.empty()) { 6646 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6647 Func != FuncEnd; ++Func) { 6648 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6649 if (FD && 6650 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6651 // Add 1 to the index so that 0 can mean the mismatch didn't 6652 // involve a parameter 6653 unsigned ParamNum = 6654 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6655 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6656 } 6657 } 6658 // If the qualified name lookup yielded nothing, try typo correction 6659 } else if ((Correction = SemaRef.CorrectTypo( 6660 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6661 &ExtraArgs.D.getCXXScopeSpec(), 6662 llvm::make_unique<DifferentNameValidatorCCC>( 6663 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 6664 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6665 // Set up everything for the call to ActOnFunctionDeclarator 6666 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6667 ExtraArgs.D.getIdentifierLoc()); 6668 Previous.clear(); 6669 Previous.setLookupName(Correction.getCorrection()); 6670 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6671 CDeclEnd = Correction.end(); 6672 CDecl != CDeclEnd; ++CDecl) { 6673 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6674 if (FD && !FD->hasBody() && 6675 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6676 Previous.addDecl(FD); 6677 } 6678 } 6679 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6680 6681 NamedDecl *Result; 6682 // Retry building the function declaration with the new previous 6683 // declarations, and with errors suppressed. 6684 { 6685 // Trap errors. 6686 Sema::SFINAETrap Trap(SemaRef); 6687 6688 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6689 // pieces need to verify the typo-corrected C++ declaration and hopefully 6690 // eliminate the need for the parameter pack ExtraArgs. 6691 Result = SemaRef.ActOnFunctionDeclarator( 6692 ExtraArgs.S, ExtraArgs.D, 6693 Correction.getCorrectionDecl()->getDeclContext(), 6694 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6695 ExtraArgs.AddToScope); 6696 6697 if (Trap.hasErrorOccurred()) 6698 Result = nullptr; 6699 } 6700 6701 if (Result) { 6702 // Determine which correction we picked. 6703 Decl *Canonical = Result->getCanonicalDecl(); 6704 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6705 I != E; ++I) 6706 if ((*I)->getCanonicalDecl() == Canonical) 6707 Correction.setCorrectionDecl(*I); 6708 6709 SemaRef.diagnoseTypo( 6710 Correction, 6711 SemaRef.PDiag(IsLocalFriend 6712 ? diag::err_no_matching_local_friend_suggest 6713 : diag::err_member_decl_does_not_match_suggest) 6714 << Name << NewDC << IsDefinition); 6715 return Result; 6716 } 6717 6718 // Pretend the typo correction never occurred 6719 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6720 ExtraArgs.D.getIdentifierLoc()); 6721 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6722 Previous.clear(); 6723 Previous.setLookupName(Name); 6724 } 6725 6726 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6727 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6728 6729 bool NewFDisConst = false; 6730 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6731 NewFDisConst = NewMD->isConst(); 6732 6733 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6734 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6735 NearMatch != NearMatchEnd; ++NearMatch) { 6736 FunctionDecl *FD = NearMatch->first; 6737 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6738 bool FDisConst = MD && MD->isConst(); 6739 bool IsMember = MD || !IsLocalFriend; 6740 6741 // FIXME: These notes are poorly worded for the local friend case. 6742 if (unsigned Idx = NearMatch->second) { 6743 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6744 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6745 if (Loc.isInvalid()) Loc = FD->getLocation(); 6746 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6747 : diag::note_local_decl_close_param_match) 6748 << Idx << FDParam->getType() 6749 << NewFD->getParamDecl(Idx - 1)->getType(); 6750 } else if (FDisConst != NewFDisConst) { 6751 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6752 << NewFDisConst << FD->getSourceRange().getEnd(); 6753 } else 6754 SemaRef.Diag(FD->getLocation(), 6755 IsMember ? diag::note_member_def_close_match 6756 : diag::note_local_decl_close_match); 6757 } 6758 return nullptr; 6759 } 6760 6761 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 6762 switch (D.getDeclSpec().getStorageClassSpec()) { 6763 default: llvm_unreachable("Unknown storage class!"); 6764 case DeclSpec::SCS_auto: 6765 case DeclSpec::SCS_register: 6766 case DeclSpec::SCS_mutable: 6767 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6768 diag::err_typecheck_sclass_func); 6769 D.setInvalidType(); 6770 break; 6771 case DeclSpec::SCS_unspecified: break; 6772 case DeclSpec::SCS_extern: 6773 if (D.getDeclSpec().isExternInLinkageSpec()) 6774 return SC_None; 6775 return SC_Extern; 6776 case DeclSpec::SCS_static: { 6777 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6778 // C99 6.7.1p5: 6779 // The declaration of an identifier for a function that has 6780 // block scope shall have no explicit storage-class specifier 6781 // other than extern 6782 // See also (C++ [dcl.stc]p4). 6783 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6784 diag::err_static_block_func); 6785 break; 6786 } else 6787 return SC_Static; 6788 } 6789 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6790 } 6791 6792 // No explicit storage class has already been returned 6793 return SC_None; 6794 } 6795 6796 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6797 DeclContext *DC, QualType &R, 6798 TypeSourceInfo *TInfo, 6799 StorageClass SC, 6800 bool &IsVirtualOkay) { 6801 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6802 DeclarationName Name = NameInfo.getName(); 6803 6804 FunctionDecl *NewFD = nullptr; 6805 bool isInline = D.getDeclSpec().isInlineSpecified(); 6806 6807 if (!SemaRef.getLangOpts().CPlusPlus) { 6808 // Determine whether the function was written with a 6809 // prototype. This true when: 6810 // - there is a prototype in the declarator, or 6811 // - the type R of the function is some kind of typedef or other reference 6812 // to a type name (which eventually refers to a function type). 6813 bool HasPrototype = 6814 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6815 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6816 6817 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6818 D.getLocStart(), NameInfo, R, 6819 TInfo, SC, isInline, 6820 HasPrototype, false); 6821 if (D.isInvalidType()) 6822 NewFD->setInvalidDecl(); 6823 6824 return NewFD; 6825 } 6826 6827 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6828 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6829 6830 // Check that the return type is not an abstract class type. 6831 // For record types, this is done by the AbstractClassUsageDiagnoser once 6832 // the class has been completely parsed. 6833 if (!DC->isRecord() && 6834 SemaRef.RequireNonAbstractType( 6835 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6836 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6837 D.setInvalidType(); 6838 6839 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6840 // This is a C++ constructor declaration. 6841 assert(DC->isRecord() && 6842 "Constructors can only be declared in a member context"); 6843 6844 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6845 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6846 D.getLocStart(), NameInfo, 6847 R, TInfo, isExplicit, isInline, 6848 /*isImplicitlyDeclared=*/false, 6849 isConstexpr); 6850 6851 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6852 // This is a C++ destructor declaration. 6853 if (DC->isRecord()) { 6854 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6855 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6856 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6857 SemaRef.Context, Record, 6858 D.getLocStart(), 6859 NameInfo, R, TInfo, isInline, 6860 /*isImplicitlyDeclared=*/false); 6861 6862 // If the class is complete, then we now create the implicit exception 6863 // specification. If the class is incomplete or dependent, we can't do 6864 // it yet. 6865 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6866 Record->getDefinition() && !Record->isBeingDefined() && 6867 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6868 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6869 } 6870 6871 IsVirtualOkay = true; 6872 return NewDD; 6873 6874 } else { 6875 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6876 D.setInvalidType(); 6877 6878 // Create a FunctionDecl to satisfy the function definition parsing 6879 // code path. 6880 return FunctionDecl::Create(SemaRef.Context, DC, 6881 D.getLocStart(), 6882 D.getIdentifierLoc(), Name, R, TInfo, 6883 SC, isInline, 6884 /*hasPrototype=*/true, isConstexpr); 6885 } 6886 6887 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6888 if (!DC->isRecord()) { 6889 SemaRef.Diag(D.getIdentifierLoc(), 6890 diag::err_conv_function_not_member); 6891 return nullptr; 6892 } 6893 6894 SemaRef.CheckConversionDeclarator(D, R, SC); 6895 IsVirtualOkay = true; 6896 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6897 D.getLocStart(), NameInfo, 6898 R, TInfo, isInline, isExplicit, 6899 isConstexpr, SourceLocation()); 6900 6901 } else if (DC->isRecord()) { 6902 // If the name of the function is the same as the name of the record, 6903 // then this must be an invalid constructor that has a return type. 6904 // (The parser checks for a return type and makes the declarator a 6905 // constructor if it has no return type). 6906 if (Name.getAsIdentifierInfo() && 6907 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6908 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6909 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6910 << SourceRange(D.getIdentifierLoc()); 6911 return nullptr; 6912 } 6913 6914 // This is a C++ method declaration. 6915 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6916 cast<CXXRecordDecl>(DC), 6917 D.getLocStart(), NameInfo, R, 6918 TInfo, SC, isInline, 6919 isConstexpr, SourceLocation()); 6920 IsVirtualOkay = !Ret->isStatic(); 6921 return Ret; 6922 } else { 6923 bool isFriend = 6924 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 6925 if (!isFriend && SemaRef.CurContext->isRecord()) 6926 return nullptr; 6927 6928 // Determine whether the function was written with a 6929 // prototype. This true when: 6930 // - we're in C++ (where every function has a prototype), 6931 return FunctionDecl::Create(SemaRef.Context, DC, 6932 D.getLocStart(), 6933 NameInfo, R, TInfo, SC, isInline, 6934 true/*HasPrototype*/, isConstexpr); 6935 } 6936 } 6937 6938 enum OpenCLParamType { 6939 ValidKernelParam, 6940 PtrPtrKernelParam, 6941 PtrKernelParam, 6942 PrivatePtrKernelParam, 6943 InvalidKernelParam, 6944 RecordKernelParam 6945 }; 6946 6947 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6948 if (PT->isPointerType()) { 6949 QualType PointeeType = PT->getPointeeType(); 6950 if (PointeeType->isPointerType()) 6951 return PtrPtrKernelParam; 6952 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6953 : PtrKernelParam; 6954 } 6955 6956 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6957 // be used as builtin types. 6958 6959 if (PT->isImageType()) 6960 return PtrKernelParam; 6961 6962 if (PT->isBooleanType()) 6963 return InvalidKernelParam; 6964 6965 if (PT->isEventT()) 6966 return InvalidKernelParam; 6967 6968 if (PT->isHalfType()) 6969 return InvalidKernelParam; 6970 6971 if (PT->isRecordType()) 6972 return RecordKernelParam; 6973 6974 return ValidKernelParam; 6975 } 6976 6977 static void checkIsValidOpenCLKernelParameter( 6978 Sema &S, 6979 Declarator &D, 6980 ParmVarDecl *Param, 6981 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 6982 QualType PT = Param->getType(); 6983 6984 // Cache the valid types we encounter to avoid rechecking structs that are 6985 // used again 6986 if (ValidTypes.count(PT.getTypePtr())) 6987 return; 6988 6989 switch (getOpenCLKernelParameterType(PT)) { 6990 case PtrPtrKernelParam: 6991 // OpenCL v1.2 s6.9.a: 6992 // A kernel function argument cannot be declared as a 6993 // pointer to a pointer type. 6994 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6995 D.setInvalidType(); 6996 return; 6997 6998 case PrivatePtrKernelParam: 6999 // OpenCL v1.2 s6.9.a: 7000 // A kernel function argument cannot be declared as a 7001 // pointer to the private address space. 7002 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 7003 D.setInvalidType(); 7004 return; 7005 7006 // OpenCL v1.2 s6.9.k: 7007 // Arguments to kernel functions in a program cannot be declared with the 7008 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7009 // uintptr_t or a struct and/or union that contain fields declared to be 7010 // one of these built-in scalar types. 7011 7012 case InvalidKernelParam: 7013 // OpenCL v1.2 s6.8 n: 7014 // A kernel function argument cannot be declared 7015 // of event_t type. 7016 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7017 D.setInvalidType(); 7018 return; 7019 7020 case PtrKernelParam: 7021 case ValidKernelParam: 7022 ValidTypes.insert(PT.getTypePtr()); 7023 return; 7024 7025 case RecordKernelParam: 7026 break; 7027 } 7028 7029 // Track nested structs we will inspect 7030 SmallVector<const Decl *, 4> VisitStack; 7031 7032 // Track where we are in the nested structs. Items will migrate from 7033 // VisitStack to HistoryStack as we do the DFS for bad field. 7034 SmallVector<const FieldDecl *, 4> HistoryStack; 7035 HistoryStack.push_back(nullptr); 7036 7037 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7038 VisitStack.push_back(PD); 7039 7040 assert(VisitStack.back() && "First decl null?"); 7041 7042 do { 7043 const Decl *Next = VisitStack.pop_back_val(); 7044 if (!Next) { 7045 assert(!HistoryStack.empty()); 7046 // Found a marker, we have gone up a level 7047 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7048 ValidTypes.insert(Hist->getType().getTypePtr()); 7049 7050 continue; 7051 } 7052 7053 // Adds everything except the original parameter declaration (which is not a 7054 // field itself) to the history stack. 7055 const RecordDecl *RD; 7056 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7057 HistoryStack.push_back(Field); 7058 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7059 } else { 7060 RD = cast<RecordDecl>(Next); 7061 } 7062 7063 // Add a null marker so we know when we've gone back up a level 7064 VisitStack.push_back(nullptr); 7065 7066 for (const auto *FD : RD->fields()) { 7067 QualType QT = FD->getType(); 7068 7069 if (ValidTypes.count(QT.getTypePtr())) 7070 continue; 7071 7072 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 7073 if (ParamType == ValidKernelParam) 7074 continue; 7075 7076 if (ParamType == RecordKernelParam) { 7077 VisitStack.push_back(FD); 7078 continue; 7079 } 7080 7081 // OpenCL v1.2 s6.9.p: 7082 // Arguments to kernel functions that are declared to be a struct or union 7083 // do not allow OpenCL objects to be passed as elements of the struct or 7084 // union. 7085 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7086 ParamType == PrivatePtrKernelParam) { 7087 S.Diag(Param->getLocation(), 7088 diag::err_record_with_pointers_kernel_param) 7089 << PT->isUnionType() 7090 << PT; 7091 } else { 7092 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7093 } 7094 7095 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7096 << PD->getDeclName(); 7097 7098 // We have an error, now let's go back up through history and show where 7099 // the offending field came from 7100 for (ArrayRef<const FieldDecl *>::const_iterator 7101 I = HistoryStack.begin() + 1, 7102 E = HistoryStack.end(); 7103 I != E; ++I) { 7104 const FieldDecl *OuterField = *I; 7105 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7106 << OuterField->getType(); 7107 } 7108 7109 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7110 << QT->isPointerType() 7111 << QT; 7112 D.setInvalidType(); 7113 return; 7114 } 7115 } while (!VisitStack.empty()); 7116 } 7117 7118 NamedDecl* 7119 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7120 TypeSourceInfo *TInfo, LookupResult &Previous, 7121 MultiTemplateParamsArg TemplateParamLists, 7122 bool &AddToScope) { 7123 QualType R = TInfo->getType(); 7124 7125 assert(R.getTypePtr()->isFunctionType()); 7126 7127 // TODO: consider using NameInfo for diagnostic. 7128 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7129 DeclarationName Name = NameInfo.getName(); 7130 StorageClass SC = getFunctionStorageClass(*this, D); 7131 7132 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7133 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7134 diag::err_invalid_thread) 7135 << DeclSpec::getSpecifierName(TSCS); 7136 7137 if (D.isFirstDeclarationOfMember()) 7138 adjustMemberFunctionCC(R, D.isStaticMember()); 7139 7140 bool isFriend = false; 7141 FunctionTemplateDecl *FunctionTemplate = nullptr; 7142 bool isExplicitSpecialization = false; 7143 bool isFunctionTemplateSpecialization = false; 7144 7145 bool isDependentClassScopeExplicitSpecialization = false; 7146 bool HasExplicitTemplateArgs = false; 7147 TemplateArgumentListInfo TemplateArgs; 7148 7149 bool isVirtualOkay = false; 7150 7151 DeclContext *OriginalDC = DC; 7152 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7153 7154 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7155 isVirtualOkay); 7156 if (!NewFD) return nullptr; 7157 7158 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7159 NewFD->setTopLevelDeclInObjCContainer(); 7160 7161 // Set the lexical context. If this is a function-scope declaration, or has a 7162 // C++ scope specifier, or is the object of a friend declaration, the lexical 7163 // context will be different from the semantic context. 7164 NewFD->setLexicalDeclContext(CurContext); 7165 7166 if (IsLocalExternDecl) 7167 NewFD->setLocalExternDecl(); 7168 7169 if (getLangOpts().CPlusPlus) { 7170 bool isInline = D.getDeclSpec().isInlineSpecified(); 7171 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7172 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7173 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7174 isFriend = D.getDeclSpec().isFriendSpecified(); 7175 if (isFriend && !isInline && D.isFunctionDefinition()) { 7176 // C++ [class.friend]p5 7177 // A function can be defined in a friend declaration of a 7178 // class . . . . Such a function is implicitly inline. 7179 NewFD->setImplicitlyInline(); 7180 } 7181 7182 // If this is a method defined in an __interface, and is not a constructor 7183 // or an overloaded operator, then set the pure flag (isVirtual will already 7184 // return true). 7185 if (const CXXRecordDecl *Parent = 7186 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7187 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7188 NewFD->setPure(true); 7189 } 7190 7191 SetNestedNameSpecifier(NewFD, D); 7192 isExplicitSpecialization = false; 7193 isFunctionTemplateSpecialization = false; 7194 if (D.isInvalidType()) 7195 NewFD->setInvalidDecl(); 7196 7197 // Match up the template parameter lists with the scope specifier, then 7198 // determine whether we have a template or a template specialization. 7199 bool Invalid = false; 7200 if (TemplateParameterList *TemplateParams = 7201 MatchTemplateParametersToScopeSpecifier( 7202 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7203 D.getCXXScopeSpec(), 7204 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7205 ? D.getName().TemplateId 7206 : nullptr, 7207 TemplateParamLists, isFriend, isExplicitSpecialization, 7208 Invalid)) { 7209 if (TemplateParams->size() > 0) { 7210 // This is a function template 7211 7212 // Check that we can declare a template here. 7213 if (CheckTemplateDeclScope(S, TemplateParams)) 7214 NewFD->setInvalidDecl(); 7215 7216 // A destructor cannot be a template. 7217 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7218 Diag(NewFD->getLocation(), diag::err_destructor_template); 7219 NewFD->setInvalidDecl(); 7220 } 7221 7222 // If we're adding a template to a dependent context, we may need to 7223 // rebuilding some of the types used within the template parameter list, 7224 // now that we know what the current instantiation is. 7225 if (DC->isDependentContext()) { 7226 ContextRAII SavedContext(*this, DC); 7227 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7228 Invalid = true; 7229 } 7230 7231 7232 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7233 NewFD->getLocation(), 7234 Name, TemplateParams, 7235 NewFD); 7236 FunctionTemplate->setLexicalDeclContext(CurContext); 7237 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7238 7239 // For source fidelity, store the other template param lists. 7240 if (TemplateParamLists.size() > 1) { 7241 NewFD->setTemplateParameterListsInfo(Context, 7242 TemplateParamLists.size() - 1, 7243 TemplateParamLists.data()); 7244 } 7245 } else { 7246 // This is a function template specialization. 7247 isFunctionTemplateSpecialization = true; 7248 // For source fidelity, store all the template param lists. 7249 if (TemplateParamLists.size() > 0) 7250 NewFD->setTemplateParameterListsInfo(Context, 7251 TemplateParamLists.size(), 7252 TemplateParamLists.data()); 7253 7254 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7255 if (isFriend) { 7256 // We want to remove the "template<>", found here. 7257 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7258 7259 // If we remove the template<> and the name is not a 7260 // template-id, we're actually silently creating a problem: 7261 // the friend declaration will refer to an untemplated decl, 7262 // and clearly the user wants a template specialization. So 7263 // we need to insert '<>' after the name. 7264 SourceLocation InsertLoc; 7265 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7266 InsertLoc = D.getName().getSourceRange().getEnd(); 7267 InsertLoc = getLocForEndOfToken(InsertLoc); 7268 } 7269 7270 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7271 << Name << RemoveRange 7272 << FixItHint::CreateRemoval(RemoveRange) 7273 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7274 } 7275 } 7276 } 7277 else { 7278 // All template param lists were matched against the scope specifier: 7279 // this is NOT (an explicit specialization of) a template. 7280 if (TemplateParamLists.size() > 0) 7281 // For source fidelity, store all the template param lists. 7282 NewFD->setTemplateParameterListsInfo(Context, 7283 TemplateParamLists.size(), 7284 TemplateParamLists.data()); 7285 } 7286 7287 if (Invalid) { 7288 NewFD->setInvalidDecl(); 7289 if (FunctionTemplate) 7290 FunctionTemplate->setInvalidDecl(); 7291 } 7292 7293 // C++ [dcl.fct.spec]p5: 7294 // The virtual specifier shall only be used in declarations of 7295 // nonstatic class member functions that appear within a 7296 // member-specification of a class declaration; see 10.3. 7297 // 7298 if (isVirtual && !NewFD->isInvalidDecl()) { 7299 if (!isVirtualOkay) { 7300 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7301 diag::err_virtual_non_function); 7302 } else if (!CurContext->isRecord()) { 7303 // 'virtual' was specified outside of the class. 7304 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7305 diag::err_virtual_out_of_class) 7306 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7307 } else if (NewFD->getDescribedFunctionTemplate()) { 7308 // C++ [temp.mem]p3: 7309 // A member function template shall not be virtual. 7310 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7311 diag::err_virtual_member_function_template) 7312 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7313 } else { 7314 // Okay: Add virtual to the method. 7315 NewFD->setVirtualAsWritten(true); 7316 } 7317 7318 if (getLangOpts().CPlusPlus14 && 7319 NewFD->getReturnType()->isUndeducedType()) 7320 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7321 } 7322 7323 if (getLangOpts().CPlusPlus14 && 7324 (NewFD->isDependentContext() || 7325 (isFriend && CurContext->isDependentContext())) && 7326 NewFD->getReturnType()->isUndeducedType()) { 7327 // If the function template is referenced directly (for instance, as a 7328 // member of the current instantiation), pretend it has a dependent type. 7329 // This is not really justified by the standard, but is the only sane 7330 // thing to do. 7331 // FIXME: For a friend function, we have not marked the function as being 7332 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7333 const FunctionProtoType *FPT = 7334 NewFD->getType()->castAs<FunctionProtoType>(); 7335 QualType Result = 7336 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7337 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7338 FPT->getExtProtoInfo())); 7339 } 7340 7341 // C++ [dcl.fct.spec]p3: 7342 // The inline specifier shall not appear on a block scope function 7343 // declaration. 7344 if (isInline && !NewFD->isInvalidDecl()) { 7345 if (CurContext->isFunctionOrMethod()) { 7346 // 'inline' is not allowed on block scope function declaration. 7347 Diag(D.getDeclSpec().getInlineSpecLoc(), 7348 diag::err_inline_declaration_block_scope) << Name 7349 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7350 } 7351 } 7352 7353 // C++ [dcl.fct.spec]p6: 7354 // The explicit specifier shall be used only in the declaration of a 7355 // constructor or conversion function within its class definition; 7356 // see 12.3.1 and 12.3.2. 7357 if (isExplicit && !NewFD->isInvalidDecl()) { 7358 if (!CurContext->isRecord()) { 7359 // 'explicit' was specified outside of the class. 7360 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7361 diag::err_explicit_out_of_class) 7362 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7363 } else if (!isa<CXXConstructorDecl>(NewFD) && 7364 !isa<CXXConversionDecl>(NewFD)) { 7365 // 'explicit' was specified on a function that wasn't a constructor 7366 // or conversion function. 7367 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7368 diag::err_explicit_non_ctor_or_conv_function) 7369 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7370 } 7371 } 7372 7373 if (isConstexpr) { 7374 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7375 // are implicitly inline. 7376 NewFD->setImplicitlyInline(); 7377 7378 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7379 // be either constructors or to return a literal type. Therefore, 7380 // destructors cannot be declared constexpr. 7381 if (isa<CXXDestructorDecl>(NewFD)) 7382 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7383 } 7384 7385 // If __module_private__ was specified, mark the function accordingly. 7386 if (D.getDeclSpec().isModulePrivateSpecified()) { 7387 if (isFunctionTemplateSpecialization) { 7388 SourceLocation ModulePrivateLoc 7389 = D.getDeclSpec().getModulePrivateSpecLoc(); 7390 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7391 << 0 7392 << FixItHint::CreateRemoval(ModulePrivateLoc); 7393 } else { 7394 NewFD->setModulePrivate(); 7395 if (FunctionTemplate) 7396 FunctionTemplate->setModulePrivate(); 7397 } 7398 } 7399 7400 if (isFriend) { 7401 if (FunctionTemplate) { 7402 FunctionTemplate->setObjectOfFriendDecl(); 7403 FunctionTemplate->setAccess(AS_public); 7404 } 7405 NewFD->setObjectOfFriendDecl(); 7406 NewFD->setAccess(AS_public); 7407 } 7408 7409 // If a function is defined as defaulted or deleted, mark it as such now. 7410 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7411 // definition kind to FDK_Definition. 7412 switch (D.getFunctionDefinitionKind()) { 7413 case FDK_Declaration: 7414 case FDK_Definition: 7415 break; 7416 7417 case FDK_Defaulted: 7418 NewFD->setDefaulted(); 7419 break; 7420 7421 case FDK_Deleted: 7422 NewFD->setDeletedAsWritten(); 7423 break; 7424 } 7425 7426 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7427 D.isFunctionDefinition()) { 7428 // C++ [class.mfct]p2: 7429 // A member function may be defined (8.4) in its class definition, in 7430 // which case it is an inline member function (7.1.2) 7431 NewFD->setImplicitlyInline(); 7432 } 7433 7434 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7435 !CurContext->isRecord()) { 7436 // C++ [class.static]p1: 7437 // A data or function member of a class may be declared static 7438 // in a class definition, in which case it is a static member of 7439 // the class. 7440 7441 // Complain about the 'static' specifier if it's on an out-of-line 7442 // member function definition. 7443 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7444 diag::err_static_out_of_line) 7445 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7446 } 7447 7448 // C++11 [except.spec]p15: 7449 // A deallocation function with no exception-specification is treated 7450 // as if it were specified with noexcept(true). 7451 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7452 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7453 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7454 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7455 NewFD->setType(Context.getFunctionType( 7456 FPT->getReturnType(), FPT->getParamTypes(), 7457 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7458 } 7459 7460 // Filter out previous declarations that don't match the scope. 7461 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7462 D.getCXXScopeSpec().isNotEmpty() || 7463 isExplicitSpecialization || 7464 isFunctionTemplateSpecialization); 7465 7466 // Handle GNU asm-label extension (encoded as an attribute). 7467 if (Expr *E = (Expr*) D.getAsmLabel()) { 7468 // The parser guarantees this is a string. 7469 StringLiteral *SE = cast<StringLiteral>(E); 7470 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7471 SE->getString(), 0)); 7472 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7473 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7474 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7475 if (I != ExtnameUndeclaredIdentifiers.end()) { 7476 NewFD->addAttr(I->second); 7477 ExtnameUndeclaredIdentifiers.erase(I); 7478 } 7479 } 7480 7481 // Copy the parameter declarations from the declarator D to the function 7482 // declaration NewFD, if they are available. First scavenge them into Params. 7483 SmallVector<ParmVarDecl*, 16> Params; 7484 if (D.isFunctionDeclarator()) { 7485 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7486 7487 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7488 // function that takes no arguments, not a function that takes a 7489 // single void argument. 7490 // We let through "const void" here because Sema::GetTypeForDeclarator 7491 // already checks for that case. 7492 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7493 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7494 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7495 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7496 Param->setDeclContext(NewFD); 7497 Params.push_back(Param); 7498 7499 if (Param->isInvalidDecl()) 7500 NewFD->setInvalidDecl(); 7501 } 7502 } 7503 7504 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7505 // When we're declaring a function with a typedef, typeof, etc as in the 7506 // following example, we'll need to synthesize (unnamed) 7507 // parameters for use in the declaration. 7508 // 7509 // @code 7510 // typedef void fn(int); 7511 // fn f; 7512 // @endcode 7513 7514 // Synthesize a parameter for each argument type. 7515 for (const auto &AI : FT->param_types()) { 7516 ParmVarDecl *Param = 7517 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7518 Param->setScopeInfo(0, Params.size()); 7519 Params.push_back(Param); 7520 } 7521 } else { 7522 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7523 "Should not need args for typedef of non-prototype fn"); 7524 } 7525 7526 // Finally, we know we have the right number of parameters, install them. 7527 NewFD->setParams(Params); 7528 7529 // Find all anonymous symbols defined during the declaration of this function 7530 // and add to NewFD. This lets us track decls such 'enum Y' in: 7531 // 7532 // void f(enum Y {AA} x) {} 7533 // 7534 // which would otherwise incorrectly end up in the translation unit scope. 7535 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7536 DeclsInPrototypeScope.clear(); 7537 7538 if (D.getDeclSpec().isNoreturnSpecified()) 7539 NewFD->addAttr( 7540 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7541 Context, 0)); 7542 7543 // Functions returning a variably modified type violate C99 6.7.5.2p2 7544 // because all functions have linkage. 7545 if (!NewFD->isInvalidDecl() && 7546 NewFD->getReturnType()->isVariablyModifiedType()) { 7547 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7548 NewFD->setInvalidDecl(); 7549 } 7550 7551 // Apply an implicit SectionAttr if #pragma code_seg is active. 7552 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 7553 !NewFD->hasAttr<SectionAttr>()) { 7554 NewFD->addAttr( 7555 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7556 CodeSegStack.CurrentValue->getString(), 7557 CodeSegStack.CurrentPragmaLocation)); 7558 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7559 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 7560 ASTContext::PSF_Read, 7561 NewFD)) 7562 NewFD->dropAttr<SectionAttr>(); 7563 } 7564 7565 // Handle attributes. 7566 ProcessDeclAttributes(S, NewFD, D); 7567 7568 if (getLangOpts().OpenCL) { 7569 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7570 // type declaration will generate a compilation error. 7571 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 7572 if (AddressSpace == LangAS::opencl_local || 7573 AddressSpace == LangAS::opencl_global || 7574 AddressSpace == LangAS::opencl_constant) { 7575 Diag(NewFD->getLocation(), 7576 diag::err_opencl_return_value_with_address_space); 7577 NewFD->setInvalidDecl(); 7578 } 7579 } 7580 7581 if (!getLangOpts().CPlusPlus) { 7582 // Perform semantic checking on the function declaration. 7583 bool isExplicitSpecialization=false; 7584 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7585 CheckMain(NewFD, D.getDeclSpec()); 7586 7587 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7588 CheckMSVCRTEntryPoint(NewFD); 7589 7590 if (!NewFD->isInvalidDecl()) 7591 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7592 isExplicitSpecialization)); 7593 else if (!Previous.empty()) 7594 // Recover gracefully from an invalid redeclaration. 7595 D.setRedeclaration(true); 7596 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7597 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7598 "previous declaration set still overloaded"); 7599 7600 // Diagnose no-prototype function declarations with calling conventions that 7601 // don't support variadic calls. Only do this in C and do it after merging 7602 // possibly prototyped redeclarations. 7603 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 7604 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 7605 CallingConv CC = FT->getExtInfo().getCC(); 7606 if (!supportsVariadicCall(CC)) { 7607 // Windows system headers sometimes accidentally use stdcall without 7608 // (void) parameters, so we relax this to a warning. 7609 int DiagID = 7610 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 7611 Diag(NewFD->getLocation(), DiagID) 7612 << FunctionType::getNameForCallConv(CC); 7613 } 7614 } 7615 } else { 7616 // C++11 [replacement.functions]p3: 7617 // The program's definitions shall not be specified as inline. 7618 // 7619 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7620 // 7621 // Suppress the diagnostic if the function is __attribute__((used)), since 7622 // that forces an external definition to be emitted. 7623 if (D.getDeclSpec().isInlineSpecified() && 7624 NewFD->isReplaceableGlobalAllocationFunction() && 7625 !NewFD->hasAttr<UsedAttr>()) 7626 Diag(D.getDeclSpec().getInlineSpecLoc(), 7627 diag::ext_operator_new_delete_declared_inline) 7628 << NewFD->getDeclName(); 7629 7630 // If the declarator is a template-id, translate the parser's template 7631 // argument list into our AST format. 7632 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7633 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7634 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7635 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7636 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7637 TemplateId->NumArgs); 7638 translateTemplateArguments(TemplateArgsPtr, 7639 TemplateArgs); 7640 7641 HasExplicitTemplateArgs = true; 7642 7643 if (NewFD->isInvalidDecl()) { 7644 HasExplicitTemplateArgs = false; 7645 } else if (FunctionTemplate) { 7646 // Function template with explicit template arguments. 7647 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7648 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7649 7650 HasExplicitTemplateArgs = false; 7651 } else { 7652 assert((isFunctionTemplateSpecialization || 7653 D.getDeclSpec().isFriendSpecified()) && 7654 "should have a 'template<>' for this decl"); 7655 // "friend void foo<>(int);" is an implicit specialization decl. 7656 isFunctionTemplateSpecialization = true; 7657 } 7658 } else if (isFriend && isFunctionTemplateSpecialization) { 7659 // This combination is only possible in a recovery case; the user 7660 // wrote something like: 7661 // template <> friend void foo(int); 7662 // which we're recovering from as if the user had written: 7663 // friend void foo<>(int); 7664 // Go ahead and fake up a template id. 7665 HasExplicitTemplateArgs = true; 7666 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7667 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7668 } 7669 7670 // If it's a friend (and only if it's a friend), it's possible 7671 // that either the specialized function type or the specialized 7672 // template is dependent, and therefore matching will fail. In 7673 // this case, don't check the specialization yet. 7674 bool InstantiationDependent = false; 7675 if (isFunctionTemplateSpecialization && isFriend && 7676 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7677 TemplateSpecializationType::anyDependentTemplateArguments( 7678 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7679 InstantiationDependent))) { 7680 assert(HasExplicitTemplateArgs && 7681 "friend function specialization without template args"); 7682 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7683 Previous)) 7684 NewFD->setInvalidDecl(); 7685 } else if (isFunctionTemplateSpecialization) { 7686 if (CurContext->isDependentContext() && CurContext->isRecord() 7687 && !isFriend) { 7688 isDependentClassScopeExplicitSpecialization = true; 7689 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7690 diag::ext_function_specialization_in_class : 7691 diag::err_function_specialization_in_class) 7692 << NewFD->getDeclName(); 7693 } else if (CheckFunctionTemplateSpecialization(NewFD, 7694 (HasExplicitTemplateArgs ? &TemplateArgs 7695 : nullptr), 7696 Previous)) 7697 NewFD->setInvalidDecl(); 7698 7699 // C++ [dcl.stc]p1: 7700 // A storage-class-specifier shall not be specified in an explicit 7701 // specialization (14.7.3) 7702 FunctionTemplateSpecializationInfo *Info = 7703 NewFD->getTemplateSpecializationInfo(); 7704 if (Info && SC != SC_None) { 7705 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7706 Diag(NewFD->getLocation(), 7707 diag::err_explicit_specialization_inconsistent_storage_class) 7708 << SC 7709 << FixItHint::CreateRemoval( 7710 D.getDeclSpec().getStorageClassSpecLoc()); 7711 7712 else 7713 Diag(NewFD->getLocation(), 7714 diag::ext_explicit_specialization_storage_class) 7715 << FixItHint::CreateRemoval( 7716 D.getDeclSpec().getStorageClassSpecLoc()); 7717 } 7718 7719 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7720 if (CheckMemberSpecialization(NewFD, Previous)) 7721 NewFD->setInvalidDecl(); 7722 } 7723 7724 // Perform semantic checking on the function declaration. 7725 if (!isDependentClassScopeExplicitSpecialization) { 7726 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7727 CheckMain(NewFD, D.getDeclSpec()); 7728 7729 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7730 CheckMSVCRTEntryPoint(NewFD); 7731 7732 if (!NewFD->isInvalidDecl()) 7733 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7734 isExplicitSpecialization)); 7735 else if (!Previous.empty()) 7736 // Recover gracefully from an invalid redeclaration. 7737 D.setRedeclaration(true); 7738 } 7739 7740 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7741 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7742 "previous declaration set still overloaded"); 7743 7744 NamedDecl *PrincipalDecl = (FunctionTemplate 7745 ? cast<NamedDecl>(FunctionTemplate) 7746 : NewFD); 7747 7748 if (isFriend && D.isRedeclaration()) { 7749 AccessSpecifier Access = AS_public; 7750 if (!NewFD->isInvalidDecl()) 7751 Access = NewFD->getPreviousDecl()->getAccess(); 7752 7753 NewFD->setAccess(Access); 7754 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7755 } 7756 7757 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7758 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7759 PrincipalDecl->setNonMemberOperator(); 7760 7761 // If we have a function template, check the template parameter 7762 // list. This will check and merge default template arguments. 7763 if (FunctionTemplate) { 7764 FunctionTemplateDecl *PrevTemplate = 7765 FunctionTemplate->getPreviousDecl(); 7766 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7767 PrevTemplate ? PrevTemplate->getTemplateParameters() 7768 : nullptr, 7769 D.getDeclSpec().isFriendSpecified() 7770 ? (D.isFunctionDefinition() 7771 ? TPC_FriendFunctionTemplateDefinition 7772 : TPC_FriendFunctionTemplate) 7773 : (D.getCXXScopeSpec().isSet() && 7774 DC && DC->isRecord() && 7775 DC->isDependentContext()) 7776 ? TPC_ClassTemplateMember 7777 : TPC_FunctionTemplate); 7778 } 7779 7780 if (NewFD->isInvalidDecl()) { 7781 // Ignore all the rest of this. 7782 } else if (!D.isRedeclaration()) { 7783 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7784 AddToScope }; 7785 // Fake up an access specifier if it's supposed to be a class member. 7786 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7787 NewFD->setAccess(AS_public); 7788 7789 // Qualified decls generally require a previous declaration. 7790 if (D.getCXXScopeSpec().isSet()) { 7791 // ...with the major exception of templated-scope or 7792 // dependent-scope friend declarations. 7793 7794 // TODO: we currently also suppress this check in dependent 7795 // contexts because (1) the parameter depth will be off when 7796 // matching friend templates and (2) we might actually be 7797 // selecting a friend based on a dependent factor. But there 7798 // are situations where these conditions don't apply and we 7799 // can actually do this check immediately. 7800 if (isFriend && 7801 (TemplateParamLists.size() || 7802 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7803 CurContext->isDependentContext())) { 7804 // ignore these 7805 } else { 7806 // The user tried to provide an out-of-line definition for a 7807 // function that is a member of a class or namespace, but there 7808 // was no such member function declared (C++ [class.mfct]p2, 7809 // C++ [namespace.memdef]p2). For example: 7810 // 7811 // class X { 7812 // void f() const; 7813 // }; 7814 // 7815 // void X::f() { } // ill-formed 7816 // 7817 // Complain about this problem, and attempt to suggest close 7818 // matches (e.g., those that differ only in cv-qualifiers and 7819 // whether the parameter types are references). 7820 7821 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7822 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7823 AddToScope = ExtraArgs.AddToScope; 7824 return Result; 7825 } 7826 } 7827 7828 // Unqualified local friend declarations are required to resolve 7829 // to something. 7830 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7831 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7832 *this, Previous, NewFD, ExtraArgs, true, S)) { 7833 AddToScope = ExtraArgs.AddToScope; 7834 return Result; 7835 } 7836 } 7837 7838 } else if (!D.isFunctionDefinition() && 7839 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7840 !isFriend && !isFunctionTemplateSpecialization && 7841 !isExplicitSpecialization) { 7842 // An out-of-line member function declaration must also be a 7843 // definition (C++ [class.mfct]p2). 7844 // Note that this is not the case for explicit specializations of 7845 // function templates or member functions of class templates, per 7846 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7847 // extension for compatibility with old SWIG code which likes to 7848 // generate them. 7849 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7850 << D.getCXXScopeSpec().getRange(); 7851 } 7852 } 7853 7854 ProcessPragmaWeak(S, NewFD); 7855 checkAttributesAfterMerging(*this, *NewFD); 7856 7857 AddKnownFunctionAttributes(NewFD); 7858 7859 if (NewFD->hasAttr<OverloadableAttr>() && 7860 !NewFD->getType()->getAs<FunctionProtoType>()) { 7861 Diag(NewFD->getLocation(), 7862 diag::err_attribute_overloadable_no_prototype) 7863 << NewFD; 7864 7865 // Turn this into a variadic function with no parameters. 7866 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7867 FunctionProtoType::ExtProtoInfo EPI( 7868 Context.getDefaultCallingConvention(true, false)); 7869 EPI.Variadic = true; 7870 EPI.ExtInfo = FT->getExtInfo(); 7871 7872 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7873 NewFD->setType(R); 7874 } 7875 7876 // If there's a #pragma GCC visibility in scope, and this isn't a class 7877 // member, set the visibility of this function. 7878 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7879 AddPushedVisibilityAttribute(NewFD); 7880 7881 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7882 // marking the function. 7883 AddCFAuditedAttribute(NewFD); 7884 7885 // If this is a function definition, check if we have to apply optnone due to 7886 // a pragma. 7887 if(D.isFunctionDefinition()) 7888 AddRangeBasedOptnone(NewFD); 7889 7890 // If this is the first declaration of an extern C variable, update 7891 // the map of such variables. 7892 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7893 isIncompleteDeclExternC(*this, NewFD)) 7894 RegisterLocallyScopedExternCDecl(NewFD, S); 7895 7896 // Set this FunctionDecl's range up to the right paren. 7897 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7898 7899 if (D.isRedeclaration() && !Previous.empty()) { 7900 checkDLLAttributeRedeclaration( 7901 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7902 isExplicitSpecialization || isFunctionTemplateSpecialization); 7903 } 7904 7905 if (getLangOpts().CPlusPlus) { 7906 if (FunctionTemplate) { 7907 if (NewFD->isInvalidDecl()) 7908 FunctionTemplate->setInvalidDecl(); 7909 return FunctionTemplate; 7910 } 7911 } 7912 7913 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7914 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7915 if ((getLangOpts().OpenCLVersion >= 120) 7916 && (SC == SC_Static)) { 7917 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7918 D.setInvalidType(); 7919 } 7920 7921 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7922 if (!NewFD->getReturnType()->isVoidType()) { 7923 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 7924 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 7925 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 7926 : FixItHint()); 7927 D.setInvalidType(); 7928 } 7929 7930 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7931 for (auto Param : NewFD->params()) 7932 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7933 } 7934 7935 MarkUnusedFileScopedDecl(NewFD); 7936 7937 if (getLangOpts().CUDA) 7938 if (IdentifierInfo *II = NewFD->getIdentifier()) 7939 if (!NewFD->isInvalidDecl() && 7940 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7941 if (II->isStr("cudaConfigureCall")) { 7942 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7943 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7944 7945 Context.setcudaConfigureCallDecl(NewFD); 7946 } 7947 } 7948 7949 // Here we have an function template explicit specialization at class scope. 7950 // The actually specialization will be postponed to template instatiation 7951 // time via the ClassScopeFunctionSpecializationDecl node. 7952 if (isDependentClassScopeExplicitSpecialization) { 7953 ClassScopeFunctionSpecializationDecl *NewSpec = 7954 ClassScopeFunctionSpecializationDecl::Create( 7955 Context, CurContext, SourceLocation(), 7956 cast<CXXMethodDecl>(NewFD), 7957 HasExplicitTemplateArgs, TemplateArgs); 7958 CurContext->addDecl(NewSpec); 7959 AddToScope = false; 7960 } 7961 7962 return NewFD; 7963 } 7964 7965 /// \brief Perform semantic checking of a new function declaration. 7966 /// 7967 /// Performs semantic analysis of the new function declaration 7968 /// NewFD. This routine performs all semantic checking that does not 7969 /// require the actual declarator involved in the declaration, and is 7970 /// used both for the declaration of functions as they are parsed 7971 /// (called via ActOnDeclarator) and for the declaration of functions 7972 /// that have been instantiated via C++ template instantiation (called 7973 /// via InstantiateDecl). 7974 /// 7975 /// \param IsExplicitSpecialization whether this new function declaration is 7976 /// an explicit specialization of the previous declaration. 7977 /// 7978 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7979 /// 7980 /// \returns true if the function declaration is a redeclaration. 7981 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7982 LookupResult &Previous, 7983 bool IsExplicitSpecialization) { 7984 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7985 "Variably modified return types are not handled here"); 7986 7987 // Determine whether the type of this function should be merged with 7988 // a previous visible declaration. This never happens for functions in C++, 7989 // and always happens in C if the previous declaration was visible. 7990 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7991 !Previous.isShadowed(); 7992 7993 // Filter out any non-conflicting previous declarations. 7994 filterNonConflictingPreviousDecls(*this, NewFD, Previous); 7995 7996 bool Redeclaration = false; 7997 NamedDecl *OldDecl = nullptr; 7998 7999 // Merge or overload the declaration with an existing declaration of 8000 // the same name, if appropriate. 8001 if (!Previous.empty()) { 8002 // Determine whether NewFD is an overload of PrevDecl or 8003 // a declaration that requires merging. If it's an overload, 8004 // there's no more work to do here; we'll just add the new 8005 // function to the scope. 8006 if (!AllowOverloadingOfFunction(Previous, Context)) { 8007 NamedDecl *Candidate = Previous.getFoundDecl(); 8008 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8009 Redeclaration = true; 8010 OldDecl = Candidate; 8011 } 8012 } else { 8013 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8014 /*NewIsUsingDecl*/ false)) { 8015 case Ovl_Match: 8016 Redeclaration = true; 8017 break; 8018 8019 case Ovl_NonFunction: 8020 Redeclaration = true; 8021 break; 8022 8023 case Ovl_Overload: 8024 Redeclaration = false; 8025 break; 8026 } 8027 8028 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8029 // If a function name is overloadable in C, then every function 8030 // with that name must be marked "overloadable". 8031 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8032 << Redeclaration << NewFD; 8033 NamedDecl *OverloadedDecl = nullptr; 8034 if (Redeclaration) 8035 OverloadedDecl = OldDecl; 8036 else if (!Previous.empty()) 8037 OverloadedDecl = Previous.getRepresentativeDecl(); 8038 if (OverloadedDecl) 8039 Diag(OverloadedDecl->getLocation(), 8040 diag::note_attribute_overloadable_prev_overload); 8041 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8042 } 8043 } 8044 } 8045 8046 // Check for a previous extern "C" declaration with this name. 8047 if (!Redeclaration && 8048 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8049 filterNonConflictingPreviousDecls(*this, NewFD, Previous); 8050 if (!Previous.empty()) { 8051 // This is an extern "C" declaration with the same name as a previous 8052 // declaration, and thus redeclares that entity... 8053 Redeclaration = true; 8054 OldDecl = Previous.getFoundDecl(); 8055 MergeTypeWithPrevious = false; 8056 8057 // ... except in the presence of __attribute__((overloadable)). 8058 if (OldDecl->hasAttr<OverloadableAttr>()) { 8059 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8060 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8061 << Redeclaration << NewFD; 8062 Diag(Previous.getFoundDecl()->getLocation(), 8063 diag::note_attribute_overloadable_prev_overload); 8064 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8065 } 8066 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8067 Redeclaration = false; 8068 OldDecl = nullptr; 8069 } 8070 } 8071 } 8072 } 8073 8074 // C++11 [dcl.constexpr]p8: 8075 // A constexpr specifier for a non-static member function that is not 8076 // a constructor declares that member function to be const. 8077 // 8078 // This needs to be delayed until we know whether this is an out-of-line 8079 // definition of a static member function. 8080 // 8081 // This rule is not present in C++1y, so we produce a backwards 8082 // compatibility warning whenever it happens in C++11. 8083 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8084 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8085 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8086 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8087 CXXMethodDecl *OldMD = nullptr; 8088 if (OldDecl) 8089 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8090 if (!OldMD || !OldMD->isStatic()) { 8091 const FunctionProtoType *FPT = 8092 MD->getType()->castAs<FunctionProtoType>(); 8093 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8094 EPI.TypeQuals |= Qualifiers::Const; 8095 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8096 FPT->getParamTypes(), EPI)); 8097 8098 // Warn that we did this, if we're not performing template instantiation. 8099 // In that case, we'll have warned already when the template was defined. 8100 if (ActiveTemplateInstantiations.empty()) { 8101 SourceLocation AddConstLoc; 8102 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8103 .IgnoreParens().getAs<FunctionTypeLoc>()) 8104 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8105 8106 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8107 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8108 } 8109 } 8110 } 8111 8112 if (Redeclaration) { 8113 // NewFD and OldDecl represent declarations that need to be 8114 // merged. 8115 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8116 NewFD->setInvalidDecl(); 8117 return Redeclaration; 8118 } 8119 8120 Previous.clear(); 8121 Previous.addDecl(OldDecl); 8122 8123 if (FunctionTemplateDecl *OldTemplateDecl 8124 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8125 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8126 FunctionTemplateDecl *NewTemplateDecl 8127 = NewFD->getDescribedFunctionTemplate(); 8128 assert(NewTemplateDecl && "Template/non-template mismatch"); 8129 if (CXXMethodDecl *Method 8130 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8131 Method->setAccess(OldTemplateDecl->getAccess()); 8132 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8133 } 8134 8135 // If this is an explicit specialization of a member that is a function 8136 // template, mark it as a member specialization. 8137 if (IsExplicitSpecialization && 8138 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8139 NewTemplateDecl->setMemberSpecialization(); 8140 assert(OldTemplateDecl->isMemberSpecialization()); 8141 } 8142 8143 } else { 8144 // This needs to happen first so that 'inline' propagates. 8145 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8146 8147 if (isa<CXXMethodDecl>(NewFD)) 8148 NewFD->setAccess(OldDecl->getAccess()); 8149 } 8150 } 8151 8152 // Semantic checking for this function declaration (in isolation). 8153 8154 if (getLangOpts().CPlusPlus) { 8155 // C++-specific checks. 8156 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8157 CheckConstructor(Constructor); 8158 } else if (CXXDestructorDecl *Destructor = 8159 dyn_cast<CXXDestructorDecl>(NewFD)) { 8160 CXXRecordDecl *Record = Destructor->getParent(); 8161 QualType ClassType = Context.getTypeDeclType(Record); 8162 8163 // FIXME: Shouldn't we be able to perform this check even when the class 8164 // type is dependent? Both gcc and edg can handle that. 8165 if (!ClassType->isDependentType()) { 8166 DeclarationName Name 8167 = Context.DeclarationNames.getCXXDestructorName( 8168 Context.getCanonicalType(ClassType)); 8169 if (NewFD->getDeclName() != Name) { 8170 Diag(NewFD->getLocation(), diag::err_destructor_name); 8171 NewFD->setInvalidDecl(); 8172 return Redeclaration; 8173 } 8174 } 8175 } else if (CXXConversionDecl *Conversion 8176 = dyn_cast<CXXConversionDecl>(NewFD)) { 8177 ActOnConversionDeclarator(Conversion); 8178 } 8179 8180 // Find any virtual functions that this function overrides. 8181 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8182 if (!Method->isFunctionTemplateSpecialization() && 8183 !Method->getDescribedFunctionTemplate() && 8184 Method->isCanonicalDecl()) { 8185 if (AddOverriddenMethods(Method->getParent(), Method)) { 8186 // If the function was marked as "static", we have a problem. 8187 if (NewFD->getStorageClass() == SC_Static) { 8188 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8189 } 8190 } 8191 } 8192 8193 if (Method->isStatic()) 8194 checkThisInStaticMemberFunctionType(Method); 8195 } 8196 8197 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8198 if (NewFD->isOverloadedOperator() && 8199 CheckOverloadedOperatorDeclaration(NewFD)) { 8200 NewFD->setInvalidDecl(); 8201 return Redeclaration; 8202 } 8203 8204 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8205 if (NewFD->getLiteralIdentifier() && 8206 CheckLiteralOperatorDeclaration(NewFD)) { 8207 NewFD->setInvalidDecl(); 8208 return Redeclaration; 8209 } 8210 8211 // In C++, check default arguments now that we have merged decls. Unless 8212 // the lexical context is the class, because in this case this is done 8213 // during delayed parsing anyway. 8214 if (!CurContext->isRecord()) 8215 CheckCXXDefaultArguments(NewFD); 8216 8217 // If this function declares a builtin function, check the type of this 8218 // declaration against the expected type for the builtin. 8219 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8220 ASTContext::GetBuiltinTypeError Error; 8221 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8222 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8223 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8224 // The type of this function differs from the type of the builtin, 8225 // so forget about the builtin entirely. 8226 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 8227 } 8228 } 8229 8230 // If this function is declared as being extern "C", then check to see if 8231 // the function returns a UDT (class, struct, or union type) that is not C 8232 // compatible, and if it does, warn the user. 8233 // But, issue any diagnostic on the first declaration only. 8234 if (Previous.empty() && NewFD->isExternC()) { 8235 QualType R = NewFD->getReturnType(); 8236 if (R->isIncompleteType() && !R->isVoidType()) 8237 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8238 << NewFD << R; 8239 else if (!R.isPODType(Context) && !R->isVoidType() && 8240 !R->isObjCObjectPointerType()) 8241 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8242 } 8243 } 8244 return Redeclaration; 8245 } 8246 8247 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8248 // C++11 [basic.start.main]p3: 8249 // A program that [...] declares main to be inline, static or 8250 // constexpr is ill-formed. 8251 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8252 // appear in a declaration of main. 8253 // static main is not an error under C99, but we should warn about it. 8254 // We accept _Noreturn main as an extension. 8255 if (FD->getStorageClass() == SC_Static) 8256 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8257 ? diag::err_static_main : diag::warn_static_main) 8258 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8259 if (FD->isInlineSpecified()) 8260 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8261 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8262 if (DS.isNoreturnSpecified()) { 8263 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8264 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8265 Diag(NoreturnLoc, diag::ext_noreturn_main); 8266 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8267 << FixItHint::CreateRemoval(NoreturnRange); 8268 } 8269 if (FD->isConstexpr()) { 8270 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8271 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8272 FD->setConstexpr(false); 8273 } 8274 8275 if (getLangOpts().OpenCL) { 8276 Diag(FD->getLocation(), diag::err_opencl_no_main) 8277 << FD->hasAttr<OpenCLKernelAttr>(); 8278 FD->setInvalidDecl(); 8279 return; 8280 } 8281 8282 QualType T = FD->getType(); 8283 assert(T->isFunctionType() && "function decl is not of function type"); 8284 const FunctionType* FT = T->castAs<FunctionType>(); 8285 8286 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8287 // In C with GNU extensions we allow main() to have non-integer return 8288 // type, but we should warn about the extension, and we disable the 8289 // implicit-return-zero rule. 8290 8291 // GCC in C mode accepts qualified 'int'. 8292 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8293 FD->setHasImplicitReturnZero(true); 8294 else { 8295 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8296 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8297 if (RTRange.isValid()) 8298 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8299 << FixItHint::CreateReplacement(RTRange, "int"); 8300 } 8301 } else { 8302 // In C and C++, main magically returns 0 if you fall off the end; 8303 // set the flag which tells us that. 8304 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8305 8306 // All the standards say that main() should return 'int'. 8307 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8308 FD->setHasImplicitReturnZero(true); 8309 else { 8310 // Otherwise, this is just a flat-out error. 8311 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8312 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8313 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8314 : FixItHint()); 8315 FD->setInvalidDecl(true); 8316 } 8317 } 8318 8319 // Treat protoless main() as nullary. 8320 if (isa<FunctionNoProtoType>(FT)) return; 8321 8322 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8323 unsigned nparams = FTP->getNumParams(); 8324 assert(FD->getNumParams() == nparams); 8325 8326 bool HasExtraParameters = (nparams > 3); 8327 8328 if (FTP->isVariadic()) { 8329 Diag(FD->getLocation(), diag::ext_variadic_main); 8330 // FIXME: if we had information about the location of the ellipsis, we 8331 // could add a FixIt hint to remove it as a parameter. 8332 } 8333 8334 // Darwin passes an undocumented fourth argument of type char**. If 8335 // other platforms start sprouting these, the logic below will start 8336 // getting shifty. 8337 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8338 HasExtraParameters = false; 8339 8340 if (HasExtraParameters) { 8341 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8342 FD->setInvalidDecl(true); 8343 nparams = 3; 8344 } 8345 8346 // FIXME: a lot of the following diagnostics would be improved 8347 // if we had some location information about types. 8348 8349 QualType CharPP = 8350 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8351 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8352 8353 for (unsigned i = 0; i < nparams; ++i) { 8354 QualType AT = FTP->getParamType(i); 8355 8356 bool mismatch = true; 8357 8358 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8359 mismatch = false; 8360 else if (Expected[i] == CharPP) { 8361 // As an extension, the following forms are okay: 8362 // char const ** 8363 // char const * const * 8364 // char * const * 8365 8366 QualifierCollector qs; 8367 const PointerType* PT; 8368 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8369 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8370 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8371 Context.CharTy)) { 8372 qs.removeConst(); 8373 mismatch = !qs.empty(); 8374 } 8375 } 8376 8377 if (mismatch) { 8378 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8379 // TODO: suggest replacing given type with expected type 8380 FD->setInvalidDecl(true); 8381 } 8382 } 8383 8384 if (nparams == 1 && !FD->isInvalidDecl()) { 8385 Diag(FD->getLocation(), diag::warn_main_one_arg); 8386 } 8387 8388 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8389 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8390 FD->setInvalidDecl(); 8391 } 8392 } 8393 8394 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8395 QualType T = FD->getType(); 8396 assert(T->isFunctionType() && "function decl is not of function type"); 8397 const FunctionType *FT = T->castAs<FunctionType>(); 8398 8399 // Set an implicit return of 'zero' if the function can return some integral, 8400 // enumeration, pointer or nullptr type. 8401 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8402 FT->getReturnType()->isAnyPointerType() || 8403 FT->getReturnType()->isNullPtrType()) 8404 // DllMain is exempt because a return value of zero means it failed. 8405 if (FD->getName() != "DllMain") 8406 FD->setHasImplicitReturnZero(true); 8407 8408 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8409 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8410 FD->setInvalidDecl(); 8411 } 8412 } 8413 8414 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8415 // FIXME: Need strict checking. In C89, we need to check for 8416 // any assignment, increment, decrement, function-calls, or 8417 // commas outside of a sizeof. In C99, it's the same list, 8418 // except that the aforementioned are allowed in unevaluated 8419 // expressions. Everything else falls under the 8420 // "may accept other forms of constant expressions" exception. 8421 // (We never end up here for C++, so the constant expression 8422 // rules there don't matter.) 8423 const Expr *Culprit; 8424 if (Init->isConstantInitializer(Context, false, &Culprit)) 8425 return false; 8426 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8427 << Culprit->getSourceRange(); 8428 return true; 8429 } 8430 8431 namespace { 8432 // Visits an initialization expression to see if OrigDecl is evaluated in 8433 // its own initialization and throws a warning if it does. 8434 class SelfReferenceChecker 8435 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8436 Sema &S; 8437 Decl *OrigDecl; 8438 bool isRecordType; 8439 bool isPODType; 8440 bool isReferenceType; 8441 8442 bool isInitList; 8443 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8444 public: 8445 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8446 8447 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8448 S(S), OrigDecl(OrigDecl) { 8449 isPODType = false; 8450 isRecordType = false; 8451 isReferenceType = false; 8452 isInitList = false; 8453 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8454 isPODType = VD->getType().isPODType(S.Context); 8455 isRecordType = VD->getType()->isRecordType(); 8456 isReferenceType = VD->getType()->isReferenceType(); 8457 } 8458 } 8459 8460 // For most expressions, just call the visitor. For initializer lists, 8461 // track the index of the field being initialized since fields are 8462 // initialized in order allowing use of previously initialized fields. 8463 void CheckExpr(Expr *E) { 8464 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8465 if (!InitList) { 8466 Visit(E); 8467 return; 8468 } 8469 8470 // Track and increment the index here. 8471 isInitList = true; 8472 InitFieldIndex.push_back(0); 8473 for (auto Child : InitList->children()) { 8474 CheckExpr(cast<Expr>(Child)); 8475 ++InitFieldIndex.back(); 8476 } 8477 InitFieldIndex.pop_back(); 8478 } 8479 8480 // Returns true if MemberExpr is checked and no futher checking is needed. 8481 // Returns false if additional checking is required. 8482 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8483 llvm::SmallVector<FieldDecl*, 4> Fields; 8484 Expr *Base = E; 8485 bool ReferenceField = false; 8486 8487 // Get the field memebers used. 8488 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8489 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8490 if (!FD) 8491 return false; 8492 Fields.push_back(FD); 8493 if (FD->getType()->isReferenceType()) 8494 ReferenceField = true; 8495 Base = ME->getBase()->IgnoreParenImpCasts(); 8496 } 8497 8498 // Keep checking only if the base Decl is the same. 8499 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8500 if (!DRE || DRE->getDecl() != OrigDecl) 8501 return false; 8502 8503 // A reference field can be bound to an unininitialized field. 8504 if (CheckReference && !ReferenceField) 8505 return true; 8506 8507 // Convert FieldDecls to their index number. 8508 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8509 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) { 8510 UsedFieldIndex.push_back((*I)->getFieldIndex()); 8511 } 8512 8513 // See if a warning is needed by checking the first difference in index 8514 // numbers. If field being used has index less than the field being 8515 // initialized, then the use is safe. 8516 for (auto UsedIter = UsedFieldIndex.begin(), 8517 UsedEnd = UsedFieldIndex.end(), 8518 OrigIter = InitFieldIndex.begin(), 8519 OrigEnd = InitFieldIndex.end(); 8520 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8521 if (*UsedIter < *OrigIter) 8522 return true; 8523 if (*UsedIter > *OrigIter) 8524 break; 8525 } 8526 8527 // TODO: Add a different warning which will print the field names. 8528 HandleDeclRefExpr(DRE); 8529 return true; 8530 } 8531 8532 // For most expressions, the cast is directly above the DeclRefExpr. 8533 // For conditional operators, the cast can be outside the conditional 8534 // operator if both expressions are DeclRefExpr's. 8535 void HandleValue(Expr *E) { 8536 E = E->IgnoreParens(); 8537 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8538 HandleDeclRefExpr(DRE); 8539 return; 8540 } 8541 8542 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8543 Visit(CO->getCond()); 8544 HandleValue(CO->getTrueExpr()); 8545 HandleValue(CO->getFalseExpr()); 8546 return; 8547 } 8548 8549 if (BinaryConditionalOperator *BCO = 8550 dyn_cast<BinaryConditionalOperator>(E)) { 8551 Visit(BCO->getCond()); 8552 HandleValue(BCO->getFalseExpr()); 8553 return; 8554 } 8555 8556 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8557 HandleValue(OVE->getSourceExpr()); 8558 return; 8559 } 8560 8561 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8562 if (BO->getOpcode() == BO_Comma) { 8563 Visit(BO->getLHS()); 8564 HandleValue(BO->getRHS()); 8565 return; 8566 } 8567 } 8568 8569 if (isa<MemberExpr>(E)) { 8570 if (isInitList) { 8571 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8572 false /*CheckReference*/)) 8573 return; 8574 } 8575 8576 Expr *Base = E->IgnoreParenImpCasts(); 8577 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8578 // Check for static member variables and don't warn on them. 8579 if (!isa<FieldDecl>(ME->getMemberDecl())) 8580 return; 8581 Base = ME->getBase()->IgnoreParenImpCasts(); 8582 } 8583 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8584 HandleDeclRefExpr(DRE); 8585 return; 8586 } 8587 8588 Visit(E); 8589 } 8590 8591 // Reference types not handled in HandleValue are handled here since all 8592 // uses of references are bad, not just r-value uses. 8593 void VisitDeclRefExpr(DeclRefExpr *E) { 8594 if (isReferenceType) 8595 HandleDeclRefExpr(E); 8596 } 8597 8598 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8599 if (E->getCastKind() == CK_LValueToRValue) { 8600 HandleValue(E->getSubExpr()); 8601 return; 8602 } 8603 8604 Inherited::VisitImplicitCastExpr(E); 8605 } 8606 8607 void VisitMemberExpr(MemberExpr *E) { 8608 if (isInitList) { 8609 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 8610 return; 8611 } 8612 8613 // Don't warn on arrays since they can be treated as pointers. 8614 if (E->getType()->canDecayToPointerType()) return; 8615 8616 // Warn when a non-static method call is followed by non-static member 8617 // field accesses, which is followed by a DeclRefExpr. 8618 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8619 bool Warn = (MD && !MD->isStatic()); 8620 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8621 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8622 if (!isa<FieldDecl>(ME->getMemberDecl())) 8623 Warn = false; 8624 Base = ME->getBase()->IgnoreParenImpCasts(); 8625 } 8626 8627 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8628 if (Warn) 8629 HandleDeclRefExpr(DRE); 8630 return; 8631 } 8632 8633 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8634 // Visit that expression. 8635 Visit(Base); 8636 } 8637 8638 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8639 Expr *Callee = E->getCallee(); 8640 8641 if (isa<UnresolvedLookupExpr>(Callee)) 8642 return Inherited::VisitCXXOperatorCallExpr(E); 8643 8644 Visit(Callee); 8645 for (auto Arg: E->arguments()) 8646 HandleValue(Arg->IgnoreParenImpCasts()); 8647 } 8648 8649 void VisitUnaryOperator(UnaryOperator *E) { 8650 // For POD record types, addresses of its own members are well-defined. 8651 if (E->getOpcode() == UO_AddrOf && isRecordType && 8652 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8653 if (!isPODType) 8654 HandleValue(E->getSubExpr()); 8655 return; 8656 } 8657 8658 if (E->isIncrementDecrementOp()) { 8659 HandleValue(E->getSubExpr()); 8660 return; 8661 } 8662 8663 Inherited::VisitUnaryOperator(E); 8664 } 8665 8666 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8667 8668 void VisitCXXConstructExpr(CXXConstructExpr *E) { 8669 if (E->getConstructor()->isCopyConstructor()) { 8670 Expr *ArgExpr = E->getArg(0); 8671 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 8672 if (ILE->getNumInits() == 1) 8673 ArgExpr = ILE->getInit(0); 8674 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8675 if (ICE->getCastKind() == CK_NoOp) 8676 ArgExpr = ICE->getSubExpr(); 8677 HandleValue(ArgExpr); 8678 return; 8679 } 8680 Inherited::VisitCXXConstructExpr(E); 8681 } 8682 8683 void VisitCallExpr(CallExpr *E) { 8684 // Treat std::move as a use. 8685 if (E->getNumArgs() == 1) { 8686 if (FunctionDecl *FD = E->getDirectCallee()) { 8687 if (FD->isInStdNamespace() && FD->getIdentifier() && 8688 FD->getIdentifier()->isStr("move")) { 8689 HandleValue(E->getArg(0)); 8690 return; 8691 } 8692 } 8693 } 8694 8695 Inherited::VisitCallExpr(E); 8696 } 8697 8698 void VisitBinaryOperator(BinaryOperator *E) { 8699 if (E->isCompoundAssignmentOp()) { 8700 HandleValue(E->getLHS()); 8701 Visit(E->getRHS()); 8702 return; 8703 } 8704 8705 Inherited::VisitBinaryOperator(E); 8706 } 8707 8708 // A custom visitor for BinaryConditionalOperator is needed because the 8709 // regular visitor would check the condition and true expression separately 8710 // but both point to the same place giving duplicate diagnostics. 8711 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 8712 Visit(E->getCond()); 8713 Visit(E->getFalseExpr()); 8714 } 8715 8716 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8717 Decl* ReferenceDecl = DRE->getDecl(); 8718 if (OrigDecl != ReferenceDecl) return; 8719 unsigned diag; 8720 if (isReferenceType) { 8721 diag = diag::warn_uninit_self_reference_in_reference_init; 8722 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8723 diag = diag::warn_static_self_reference_in_init; 8724 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 8725 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 8726 DRE->getDecl()->getType()->isRecordType()) { 8727 diag = diag::warn_uninit_self_reference_in_init; 8728 } else { 8729 // Local variables will be handled by the CFG analysis. 8730 return; 8731 } 8732 8733 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8734 S.PDiag(diag) 8735 << DRE->getNameInfo().getName() 8736 << OrigDecl->getLocation() 8737 << DRE->getSourceRange()); 8738 } 8739 }; 8740 8741 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8742 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8743 bool DirectInit) { 8744 // Parameters arguments are occassionially constructed with itself, 8745 // for instance, in recursive functions. Skip them. 8746 if (isa<ParmVarDecl>(OrigDecl)) 8747 return; 8748 8749 E = E->IgnoreParens(); 8750 8751 // Skip checking T a = a where T is not a record or reference type. 8752 // Doing so is a way to silence uninitialized warnings. 8753 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8754 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8755 if (ICE->getCastKind() == CK_LValueToRValue) 8756 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8757 if (DRE->getDecl() == OrigDecl) 8758 return; 8759 8760 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 8761 } 8762 } // namespace 8763 8764 /// AddInitializerToDecl - Adds the initializer Init to the 8765 /// declaration dcl. If DirectInit is true, this is C++ direct 8766 /// initialization rather than copy initialization. 8767 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8768 bool DirectInit, bool TypeMayContainAuto) { 8769 // If there is no declaration, there was an error parsing it. Just ignore 8770 // the initializer. 8771 if (!RealDecl || RealDecl->isInvalidDecl()) { 8772 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 8773 return; 8774 } 8775 8776 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8777 // With declarators parsed the way they are, the parser cannot 8778 // distinguish between a normal initializer and a pure-specifier. 8779 // Thus this grotesque test. 8780 IntegerLiteral *IL; 8781 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8782 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8783 CheckPureMethod(Method, Init->getSourceRange()); 8784 else { 8785 Diag(Method->getLocation(), diag::err_member_function_initialization) 8786 << Method->getDeclName() << Init->getSourceRange(); 8787 Method->setInvalidDecl(); 8788 } 8789 return; 8790 } 8791 8792 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8793 if (!VDecl) { 8794 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8795 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8796 RealDecl->setInvalidDecl(); 8797 return; 8798 } 8799 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8800 8801 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8802 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8803 // Attempt typo correction early so that the type of the init expression can 8804 // be deduced based on the chosen correction:if the original init contains a 8805 // TypoExpr. 8806 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 8807 if (!Res.isUsable()) { 8808 RealDecl->setInvalidDecl(); 8809 return; 8810 } 8811 8812 if (Res.get() != Init) { 8813 Init = Res.get(); 8814 if (CXXDirectInit) 8815 CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8816 } 8817 8818 Expr *DeduceInit = Init; 8819 // Initializer could be a C++ direct-initializer. Deduction only works if it 8820 // contains exactly one expression. 8821 if (CXXDirectInit) { 8822 if (CXXDirectInit->getNumExprs() == 0) { 8823 // It isn't possible to write this directly, but it is possible to 8824 // end up in this situation with "auto x(some_pack...);" 8825 Diag(CXXDirectInit->getLocStart(), 8826 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8827 : diag::err_auto_var_init_no_expression) 8828 << VDecl->getDeclName() << VDecl->getType() 8829 << VDecl->getSourceRange(); 8830 RealDecl->setInvalidDecl(); 8831 return; 8832 } else if (CXXDirectInit->getNumExprs() > 1) { 8833 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8834 VDecl->isInitCapture() 8835 ? diag::err_init_capture_multiple_expressions 8836 : diag::err_auto_var_init_multiple_expressions) 8837 << VDecl->getDeclName() << VDecl->getType() 8838 << VDecl->getSourceRange(); 8839 RealDecl->setInvalidDecl(); 8840 return; 8841 } else { 8842 DeduceInit = CXXDirectInit->getExpr(0); 8843 if (isa<InitListExpr>(DeduceInit)) 8844 Diag(CXXDirectInit->getLocStart(), 8845 diag::err_auto_var_init_paren_braces) 8846 << VDecl->getDeclName() << VDecl->getType() 8847 << VDecl->getSourceRange(); 8848 } 8849 } 8850 8851 // Expressions default to 'id' when we're in a debugger. 8852 bool DefaultedToAuto = false; 8853 if (getLangOpts().DebuggerCastResultToId && 8854 Init->getType() == Context.UnknownAnyTy) { 8855 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8856 if (Result.isInvalid()) { 8857 VDecl->setInvalidDecl(); 8858 return; 8859 } 8860 Init = Result.get(); 8861 DefaultedToAuto = true; 8862 } 8863 8864 QualType DeducedType; 8865 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8866 DAR_Failed) 8867 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8868 if (DeducedType.isNull()) { 8869 RealDecl->setInvalidDecl(); 8870 return; 8871 } 8872 VDecl->setType(DeducedType); 8873 assert(VDecl->isLinkageValid()); 8874 8875 // In ARC, infer lifetime. 8876 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8877 VDecl->setInvalidDecl(); 8878 8879 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8880 // 'id' instead of a specific object type prevents most of our usual checks. 8881 // We only want to warn outside of template instantiations, though: 8882 // inside a template, the 'id' could have come from a parameter. 8883 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8884 DeducedType->isObjCIdType()) { 8885 SourceLocation Loc = 8886 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8887 Diag(Loc, diag::warn_auto_var_is_id) 8888 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8889 } 8890 8891 // If this is a redeclaration, check that the type we just deduced matches 8892 // the previously declared type. 8893 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8894 // We never need to merge the type, because we cannot form an incomplete 8895 // array of auto, nor deduce such a type. 8896 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8897 } 8898 8899 // Check the deduced type is valid for a variable declaration. 8900 CheckVariableDeclarationType(VDecl); 8901 if (VDecl->isInvalidDecl()) 8902 return; 8903 8904 // If all looks well, warn if this is a case that will change meaning when 8905 // we implement N3922. 8906 if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) { 8907 Diag(Init->getLocStart(), 8908 diag::warn_auto_var_direct_list_init) 8909 << FixItHint::CreateInsertion(Init->getLocStart(), "="); 8910 } 8911 } 8912 8913 // dllimport cannot be used on variable definitions. 8914 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8915 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8916 VDecl->setInvalidDecl(); 8917 return; 8918 } 8919 8920 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8921 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8922 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8923 VDecl->setInvalidDecl(); 8924 return; 8925 } 8926 8927 if (!VDecl->getType()->isDependentType()) { 8928 // A definition must end up with a complete type, which means it must be 8929 // complete with the restriction that an array type might be completed by 8930 // the initializer; note that later code assumes this restriction. 8931 QualType BaseDeclType = VDecl->getType(); 8932 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8933 BaseDeclType = Array->getElementType(); 8934 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8935 diag::err_typecheck_decl_incomplete_type)) { 8936 RealDecl->setInvalidDecl(); 8937 return; 8938 } 8939 8940 // The variable can not have an abstract class type. 8941 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8942 diag::err_abstract_type_in_decl, 8943 AbstractVariableType)) 8944 VDecl->setInvalidDecl(); 8945 } 8946 8947 VarDecl *Def; 8948 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8949 NamedDecl *Hidden = nullptr; 8950 if (!hasVisibleDefinition(Def, &Hidden) && 8951 (VDecl->getFormalLinkage() == InternalLinkage || 8952 VDecl->getDescribedVarTemplate() || 8953 VDecl->getNumTemplateParameterLists() || 8954 VDecl->getDeclContext()->isDependentContext())) { 8955 // The previous definition is hidden, and multiple definitions are 8956 // permitted (in separate TUs). Form another definition of it. 8957 } else { 8958 Diag(VDecl->getLocation(), diag::err_redefinition) 8959 << VDecl->getDeclName(); 8960 Diag(Def->getLocation(), diag::note_previous_definition); 8961 VDecl->setInvalidDecl(); 8962 return; 8963 } 8964 } 8965 8966 if (getLangOpts().CPlusPlus) { 8967 // C++ [class.static.data]p4 8968 // If a static data member is of const integral or const 8969 // enumeration type, its declaration in the class definition can 8970 // specify a constant-initializer which shall be an integral 8971 // constant expression (5.19). In that case, the member can appear 8972 // in integral constant expressions. The member shall still be 8973 // defined in a namespace scope if it is used in the program and the 8974 // namespace scope definition shall not contain an initializer. 8975 // 8976 // We already performed a redefinition check above, but for static 8977 // data members we also need to check whether there was an in-class 8978 // declaration with an initializer. 8979 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 8980 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8981 << VDecl->getDeclName(); 8982 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 8983 diag::note_previous_initializer) 8984 << 0; 8985 return; 8986 } 8987 8988 if (VDecl->hasLocalStorage()) 8989 getCurFunction()->setHasBranchProtectedScope(); 8990 8991 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8992 VDecl->setInvalidDecl(); 8993 return; 8994 } 8995 } 8996 8997 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8998 // a kernel function cannot be initialized." 8999 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 9000 Diag(VDecl->getLocation(), diag::err_local_cant_init); 9001 VDecl->setInvalidDecl(); 9002 return; 9003 } 9004 9005 // Get the decls type and save a reference for later, since 9006 // CheckInitializerTypes may change it. 9007 QualType DclT = VDecl->getType(), SavT = DclT; 9008 9009 // Expressions default to 'id' when we're in a debugger 9010 // and we are assigning it to a variable of Objective-C pointer type. 9011 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 9012 Init->getType() == Context.UnknownAnyTy) { 9013 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9014 if (Result.isInvalid()) { 9015 VDecl->setInvalidDecl(); 9016 return; 9017 } 9018 Init = Result.get(); 9019 } 9020 9021 // Perform the initialization. 9022 if (!VDecl->isInvalidDecl()) { 9023 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9024 InitializationKind Kind 9025 = DirectInit ? 9026 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 9027 Init->getLocStart(), 9028 Init->getLocEnd()) 9029 : InitializationKind::CreateDirectList( 9030 VDecl->getLocation()) 9031 : InitializationKind::CreateCopy(VDecl->getLocation(), 9032 Init->getLocStart()); 9033 9034 MultiExprArg Args = Init; 9035 if (CXXDirectInit) 9036 Args = MultiExprArg(CXXDirectInit->getExprs(), 9037 CXXDirectInit->getNumExprs()); 9038 9039 // Try to correct any TypoExprs in the initialization arguments. 9040 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9041 ExprResult Res = CorrectDelayedTyposInExpr( 9042 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9043 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9044 return Init.Failed() ? ExprError() : E; 9045 }); 9046 if (Res.isInvalid()) { 9047 VDecl->setInvalidDecl(); 9048 } else if (Res.get() != Args[Idx]) { 9049 Args[Idx] = Res.get(); 9050 } 9051 } 9052 if (VDecl->isInvalidDecl()) 9053 return; 9054 9055 InitializationSequence InitSeq(*this, Entity, Kind, Args); 9056 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9057 if (Result.isInvalid()) { 9058 VDecl->setInvalidDecl(); 9059 return; 9060 } 9061 9062 Init = Result.getAs<Expr>(); 9063 } 9064 9065 // Check for self-references within variable initializers. 9066 // Variables declared within a function/method body (except for references) 9067 // are handled by a dataflow analysis. 9068 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9069 VDecl->getType()->isReferenceType()) { 9070 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9071 } 9072 9073 // If the type changed, it means we had an incomplete type that was 9074 // completed by the initializer. For example: 9075 // int ary[] = { 1, 3, 5 }; 9076 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9077 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9078 VDecl->setType(DclT); 9079 9080 if (!VDecl->isInvalidDecl()) { 9081 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9082 9083 if (VDecl->hasAttr<BlocksAttr>()) 9084 checkRetainCycles(VDecl, Init); 9085 9086 // It is safe to assign a weak reference into a strong variable. 9087 // Although this code can still have problems: 9088 // id x = self.weakProp; 9089 // id y = self.weakProp; 9090 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9091 // paths through the function. This should be revisited if 9092 // -Wrepeated-use-of-weak is made flow-sensitive. 9093 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9094 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9095 Init->getLocStart())) 9096 getCurFunction()->markSafeWeakUse(Init); 9097 } 9098 9099 // The initialization is usually a full-expression. 9100 // 9101 // FIXME: If this is a braced initialization of an aggregate, it is not 9102 // an expression, and each individual field initializer is a separate 9103 // full-expression. For instance, in: 9104 // 9105 // struct Temp { ~Temp(); }; 9106 // struct S { S(Temp); }; 9107 // struct T { S a, b; } t = { Temp(), Temp() } 9108 // 9109 // we should destroy the first Temp before constructing the second. 9110 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9111 false, 9112 VDecl->isConstexpr()); 9113 if (Result.isInvalid()) { 9114 VDecl->setInvalidDecl(); 9115 return; 9116 } 9117 Init = Result.get(); 9118 9119 // Attach the initializer to the decl. 9120 VDecl->setInit(Init); 9121 9122 if (VDecl->isLocalVarDecl()) { 9123 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9124 // static storage duration shall be constant expressions or string literals. 9125 // C++ does not have this restriction. 9126 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9127 const Expr *Culprit; 9128 if (VDecl->getStorageClass() == SC_Static) 9129 CheckForConstantInitializer(Init, DclT); 9130 // C89 is stricter than C99 for non-static aggregate types. 9131 // C89 6.5.7p3: All the expressions [...] in an initializer list 9132 // for an object that has aggregate or union type shall be 9133 // constant expressions. 9134 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9135 isa<InitListExpr>(Init) && 9136 !Init->isConstantInitializer(Context, false, &Culprit)) 9137 Diag(Culprit->getExprLoc(), 9138 diag::ext_aggregate_init_not_constant) 9139 << Culprit->getSourceRange(); 9140 } 9141 } else if (VDecl->isStaticDataMember() && 9142 VDecl->getLexicalDeclContext()->isRecord()) { 9143 // This is an in-class initialization for a static data member, e.g., 9144 // 9145 // struct S { 9146 // static const int value = 17; 9147 // }; 9148 9149 // C++ [class.mem]p4: 9150 // A member-declarator can contain a constant-initializer only 9151 // if it declares a static member (9.4) of const integral or 9152 // const enumeration type, see 9.4.2. 9153 // 9154 // C++11 [class.static.data]p3: 9155 // If a non-volatile const static data member is of integral or 9156 // enumeration type, its declaration in the class definition can 9157 // specify a brace-or-equal-initializer in which every initalizer-clause 9158 // that is an assignment-expression is a constant expression. A static 9159 // data member of literal type can be declared in the class definition 9160 // with the constexpr specifier; if so, its declaration shall specify a 9161 // brace-or-equal-initializer in which every initializer-clause that is 9162 // an assignment-expression is a constant expression. 9163 9164 // Do nothing on dependent types. 9165 if (DclT->isDependentType()) { 9166 9167 // Allow any 'static constexpr' members, whether or not they are of literal 9168 // type. We separately check that every constexpr variable is of literal 9169 // type. 9170 } else if (VDecl->isConstexpr()) { 9171 9172 // Require constness. 9173 } else if (!DclT.isConstQualified()) { 9174 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9175 << Init->getSourceRange(); 9176 VDecl->setInvalidDecl(); 9177 9178 // We allow integer constant expressions in all cases. 9179 } else if (DclT->isIntegralOrEnumerationType()) { 9180 // Check whether the expression is a constant expression. 9181 SourceLocation Loc; 9182 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9183 // In C++11, a non-constexpr const static data member with an 9184 // in-class initializer cannot be volatile. 9185 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9186 else if (Init->isValueDependent()) 9187 ; // Nothing to check. 9188 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9189 ; // Ok, it's an ICE! 9190 else if (Init->isEvaluatable(Context)) { 9191 // If we can constant fold the initializer through heroics, accept it, 9192 // but report this as a use of an extension for -pedantic. 9193 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9194 << Init->getSourceRange(); 9195 } else { 9196 // Otherwise, this is some crazy unknown case. Report the issue at the 9197 // location provided by the isIntegerConstantExpr failed check. 9198 Diag(Loc, diag::err_in_class_initializer_non_constant) 9199 << Init->getSourceRange(); 9200 VDecl->setInvalidDecl(); 9201 } 9202 9203 // We allow foldable floating-point constants as an extension. 9204 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9205 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9206 // it anyway and provide a fixit to add the 'constexpr'. 9207 if (getLangOpts().CPlusPlus11) { 9208 Diag(VDecl->getLocation(), 9209 diag::ext_in_class_initializer_float_type_cxx11) 9210 << DclT << Init->getSourceRange(); 9211 Diag(VDecl->getLocStart(), 9212 diag::note_in_class_initializer_float_type_cxx11) 9213 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9214 } else { 9215 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9216 << DclT << Init->getSourceRange(); 9217 9218 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9219 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9220 << Init->getSourceRange(); 9221 VDecl->setInvalidDecl(); 9222 } 9223 } 9224 9225 // Suggest adding 'constexpr' in C++11 for literal types. 9226 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9227 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9228 << DclT << Init->getSourceRange() 9229 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9230 VDecl->setConstexpr(true); 9231 9232 } else { 9233 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9234 << DclT << Init->getSourceRange(); 9235 VDecl->setInvalidDecl(); 9236 } 9237 } else if (VDecl->isFileVarDecl()) { 9238 if (VDecl->getStorageClass() == SC_Extern && 9239 (!getLangOpts().CPlusPlus || 9240 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 9241 VDecl->isExternC())) && 9242 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9243 Diag(VDecl->getLocation(), diag::warn_extern_init); 9244 9245 // C99 6.7.8p4. All file scoped initializers need to be constant. 9246 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9247 CheckForConstantInitializer(Init, DclT); 9248 } 9249 9250 // We will represent direct-initialization similarly to copy-initialization: 9251 // int x(1); -as-> int x = 1; 9252 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9253 // 9254 // Clients that want to distinguish between the two forms, can check for 9255 // direct initializer using VarDecl::getInitStyle(). 9256 // A major benefit is that clients that don't particularly care about which 9257 // exactly form was it (like the CodeGen) can handle both cases without 9258 // special case code. 9259 9260 // C++ 8.5p11: 9261 // The form of initialization (using parentheses or '=') is generally 9262 // insignificant, but does matter when the entity being initialized has a 9263 // class type. 9264 if (CXXDirectInit) { 9265 assert(DirectInit && "Call-style initializer must be direct init."); 9266 VDecl->setInitStyle(VarDecl::CallInit); 9267 } else if (DirectInit) { 9268 // This must be list-initialization. No other way is direct-initialization. 9269 VDecl->setInitStyle(VarDecl::ListInit); 9270 } 9271 9272 CheckCompleteVariableDeclaration(VDecl); 9273 } 9274 9275 /// ActOnInitializerError - Given that there was an error parsing an 9276 /// initializer for the given declaration, try to return to some form 9277 /// of sanity. 9278 void Sema::ActOnInitializerError(Decl *D) { 9279 // Our main concern here is re-establishing invariants like "a 9280 // variable's type is either dependent or complete". 9281 if (!D || D->isInvalidDecl()) return; 9282 9283 VarDecl *VD = dyn_cast<VarDecl>(D); 9284 if (!VD) return; 9285 9286 // Auto types are meaningless if we can't make sense of the initializer. 9287 if (ParsingInitForAutoVars.count(D)) { 9288 D->setInvalidDecl(); 9289 return; 9290 } 9291 9292 QualType Ty = VD->getType(); 9293 if (Ty->isDependentType()) return; 9294 9295 // Require a complete type. 9296 if (RequireCompleteType(VD->getLocation(), 9297 Context.getBaseElementType(Ty), 9298 diag::err_typecheck_decl_incomplete_type)) { 9299 VD->setInvalidDecl(); 9300 return; 9301 } 9302 9303 // Require a non-abstract type. 9304 if (RequireNonAbstractType(VD->getLocation(), Ty, 9305 diag::err_abstract_type_in_decl, 9306 AbstractVariableType)) { 9307 VD->setInvalidDecl(); 9308 return; 9309 } 9310 9311 // Don't bother complaining about constructors or destructors, 9312 // though. 9313 } 9314 9315 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9316 bool TypeMayContainAuto) { 9317 // If there is no declaration, there was an error parsing it. Just ignore it. 9318 if (!RealDecl) 9319 return; 9320 9321 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9322 QualType Type = Var->getType(); 9323 9324 // C++11 [dcl.spec.auto]p3 9325 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9326 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9327 << Var->getDeclName() << Type; 9328 Var->setInvalidDecl(); 9329 return; 9330 } 9331 9332 // C++11 [class.static.data]p3: A static data member can be declared with 9333 // the constexpr specifier; if so, its declaration shall specify 9334 // a brace-or-equal-initializer. 9335 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9336 // the definition of a variable [...] or the declaration of a static data 9337 // member. 9338 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9339 if (Var->isStaticDataMember()) 9340 Diag(Var->getLocation(), 9341 diag::err_constexpr_static_mem_var_requires_init) 9342 << Var->getDeclName(); 9343 else 9344 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9345 Var->setInvalidDecl(); 9346 return; 9347 } 9348 9349 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9350 // be initialized. 9351 if (!Var->isInvalidDecl() && 9352 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9353 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9354 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9355 Var->setInvalidDecl(); 9356 return; 9357 } 9358 9359 switch (Var->isThisDeclarationADefinition()) { 9360 case VarDecl::Definition: 9361 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9362 break; 9363 9364 // We have an out-of-line definition of a static data member 9365 // that has an in-class initializer, so we type-check this like 9366 // a declaration. 9367 // 9368 // Fall through 9369 9370 case VarDecl::DeclarationOnly: 9371 // It's only a declaration. 9372 9373 // Block scope. C99 6.7p7: If an identifier for an object is 9374 // declared with no linkage (C99 6.2.2p6), the type for the 9375 // object shall be complete. 9376 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9377 !Var->hasLinkage() && !Var->isInvalidDecl() && 9378 RequireCompleteType(Var->getLocation(), Type, 9379 diag::err_typecheck_decl_incomplete_type)) 9380 Var->setInvalidDecl(); 9381 9382 // Make sure that the type is not abstract. 9383 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9384 RequireNonAbstractType(Var->getLocation(), Type, 9385 diag::err_abstract_type_in_decl, 9386 AbstractVariableType)) 9387 Var->setInvalidDecl(); 9388 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9389 Var->getStorageClass() == SC_PrivateExtern) { 9390 Diag(Var->getLocation(), diag::warn_private_extern); 9391 Diag(Var->getLocation(), diag::note_private_extern); 9392 } 9393 9394 return; 9395 9396 case VarDecl::TentativeDefinition: 9397 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9398 // object that has file scope without an initializer, and without a 9399 // storage-class specifier or with the storage-class specifier "static", 9400 // constitutes a tentative definition. Note: A tentative definition with 9401 // external linkage is valid (C99 6.2.2p5). 9402 if (!Var->isInvalidDecl()) { 9403 if (const IncompleteArrayType *ArrayT 9404 = Context.getAsIncompleteArrayType(Type)) { 9405 if (RequireCompleteType(Var->getLocation(), 9406 ArrayT->getElementType(), 9407 diag::err_illegal_decl_array_incomplete_type)) 9408 Var->setInvalidDecl(); 9409 } else if (Var->getStorageClass() == SC_Static) { 9410 // C99 6.9.2p3: If the declaration of an identifier for an object is 9411 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9412 // declared type shall not be an incomplete type. 9413 // NOTE: code such as the following 9414 // static struct s; 9415 // struct s { int a; }; 9416 // is accepted by gcc. Hence here we issue a warning instead of 9417 // an error and we do not invalidate the static declaration. 9418 // NOTE: to avoid multiple warnings, only check the first declaration. 9419 if (Var->isFirstDecl()) 9420 RequireCompleteType(Var->getLocation(), Type, 9421 diag::ext_typecheck_decl_incomplete_type); 9422 } 9423 } 9424 9425 // Record the tentative definition; we're done. 9426 if (!Var->isInvalidDecl()) 9427 TentativeDefinitions.push_back(Var); 9428 return; 9429 } 9430 9431 // Provide a specific diagnostic for uninitialized variable 9432 // definitions with incomplete array type. 9433 if (Type->isIncompleteArrayType()) { 9434 Diag(Var->getLocation(), 9435 diag::err_typecheck_incomplete_array_needs_initializer); 9436 Var->setInvalidDecl(); 9437 return; 9438 } 9439 9440 // Provide a specific diagnostic for uninitialized variable 9441 // definitions with reference type. 9442 if (Type->isReferenceType()) { 9443 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9444 << Var->getDeclName() 9445 << SourceRange(Var->getLocation(), Var->getLocation()); 9446 Var->setInvalidDecl(); 9447 return; 9448 } 9449 9450 // Do not attempt to type-check the default initializer for a 9451 // variable with dependent type. 9452 if (Type->isDependentType()) 9453 return; 9454 9455 if (Var->isInvalidDecl()) 9456 return; 9457 9458 if (!Var->hasAttr<AliasAttr>()) { 9459 if (RequireCompleteType(Var->getLocation(), 9460 Context.getBaseElementType(Type), 9461 diag::err_typecheck_decl_incomplete_type)) { 9462 Var->setInvalidDecl(); 9463 return; 9464 } 9465 } else { 9466 return; 9467 } 9468 9469 // The variable can not have an abstract class type. 9470 if (RequireNonAbstractType(Var->getLocation(), Type, 9471 diag::err_abstract_type_in_decl, 9472 AbstractVariableType)) { 9473 Var->setInvalidDecl(); 9474 return; 9475 } 9476 9477 // Check for jumps past the implicit initializer. C++0x 9478 // clarifies that this applies to a "variable with automatic 9479 // storage duration", not a "local variable". 9480 // C++11 [stmt.dcl]p3 9481 // A program that jumps from a point where a variable with automatic 9482 // storage duration is not in scope to a point where it is in scope is 9483 // ill-formed unless the variable has scalar type, class type with a 9484 // trivial default constructor and a trivial destructor, a cv-qualified 9485 // version of one of these types, or an array of one of the preceding 9486 // types and is declared without an initializer. 9487 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9488 if (const RecordType *Record 9489 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9490 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9491 // Mark the function for further checking even if the looser rules of 9492 // C++11 do not require such checks, so that we can diagnose 9493 // incompatibilities with C++98. 9494 if (!CXXRecord->isPOD()) 9495 getCurFunction()->setHasBranchProtectedScope(); 9496 } 9497 } 9498 9499 // C++03 [dcl.init]p9: 9500 // If no initializer is specified for an object, and the 9501 // object is of (possibly cv-qualified) non-POD class type (or 9502 // array thereof), the object shall be default-initialized; if 9503 // the object is of const-qualified type, the underlying class 9504 // type shall have a user-declared default 9505 // constructor. Otherwise, if no initializer is specified for 9506 // a non- static object, the object and its subobjects, if 9507 // any, have an indeterminate initial value); if the object 9508 // or any of its subobjects are of const-qualified type, the 9509 // program is ill-formed. 9510 // C++0x [dcl.init]p11: 9511 // If no initializer is specified for an object, the object is 9512 // default-initialized; [...]. 9513 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9514 InitializationKind Kind 9515 = InitializationKind::CreateDefault(Var->getLocation()); 9516 9517 InitializationSequence InitSeq(*this, Entity, Kind, None); 9518 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9519 if (Init.isInvalid()) 9520 Var->setInvalidDecl(); 9521 else if (Init.get()) { 9522 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9523 // This is important for template substitution. 9524 Var->setInitStyle(VarDecl::CallInit); 9525 } 9526 9527 CheckCompleteVariableDeclaration(Var); 9528 } 9529 } 9530 9531 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9532 VarDecl *VD = dyn_cast<VarDecl>(D); 9533 if (!VD) { 9534 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9535 D->setInvalidDecl(); 9536 return; 9537 } 9538 9539 VD->setCXXForRangeDecl(true); 9540 9541 // for-range-declaration cannot be given a storage class specifier. 9542 int Error = -1; 9543 switch (VD->getStorageClass()) { 9544 case SC_None: 9545 break; 9546 case SC_Extern: 9547 Error = 0; 9548 break; 9549 case SC_Static: 9550 Error = 1; 9551 break; 9552 case SC_PrivateExtern: 9553 Error = 2; 9554 break; 9555 case SC_Auto: 9556 Error = 3; 9557 break; 9558 case SC_Register: 9559 Error = 4; 9560 break; 9561 case SC_OpenCLWorkGroupLocal: 9562 llvm_unreachable("Unexpected storage class"); 9563 } 9564 if (Error != -1) { 9565 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9566 << VD->getDeclName() << Error; 9567 D->setInvalidDecl(); 9568 } 9569 } 9570 9571 StmtResult 9572 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9573 IdentifierInfo *Ident, 9574 ParsedAttributes &Attrs, 9575 SourceLocation AttrEnd) { 9576 // C++1y [stmt.iter]p1: 9577 // A range-based for statement of the form 9578 // for ( for-range-identifier : for-range-initializer ) statement 9579 // is equivalent to 9580 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9581 DeclSpec DS(Attrs.getPool().getFactory()); 9582 9583 const char *PrevSpec; 9584 unsigned DiagID; 9585 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 9586 getPrintingPolicy()); 9587 9588 Declarator D(DS, Declarator::ForContext); 9589 D.SetIdentifier(Ident, IdentLoc); 9590 D.takeAttributes(Attrs, AttrEnd); 9591 9592 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 9593 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 9594 EmptyAttrs, IdentLoc); 9595 Decl *Var = ActOnDeclarator(S, D); 9596 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 9597 FinalizeDeclaration(Var); 9598 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 9599 AttrEnd.isValid() ? AttrEnd : IdentLoc); 9600 } 9601 9602 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 9603 if (var->isInvalidDecl()) return; 9604 9605 // In ARC, don't allow jumps past the implicit initialization of a 9606 // local retaining variable. 9607 if (getLangOpts().ObjCAutoRefCount && 9608 var->hasLocalStorage()) { 9609 switch (var->getType().getObjCLifetime()) { 9610 case Qualifiers::OCL_None: 9611 case Qualifiers::OCL_ExplicitNone: 9612 case Qualifiers::OCL_Autoreleasing: 9613 break; 9614 9615 case Qualifiers::OCL_Weak: 9616 case Qualifiers::OCL_Strong: 9617 getCurFunction()->setHasBranchProtectedScope(); 9618 break; 9619 } 9620 } 9621 9622 // Warn about externally-visible variables being defined without a 9623 // prior declaration. We only want to do this for global 9624 // declarations, but we also specifically need to avoid doing it for 9625 // class members because the linkage of an anonymous class can 9626 // change if it's later given a typedef name. 9627 if (var->isThisDeclarationADefinition() && 9628 var->getDeclContext()->getRedeclContext()->isFileContext() && 9629 var->isExternallyVisible() && var->hasLinkage() && 9630 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9631 var->getLocation())) { 9632 // Find a previous declaration that's not a definition. 9633 VarDecl *prev = var->getPreviousDecl(); 9634 while (prev && prev->isThisDeclarationADefinition()) 9635 prev = prev->getPreviousDecl(); 9636 9637 if (!prev) 9638 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9639 } 9640 9641 if (var->getTLSKind() == VarDecl::TLS_Static) { 9642 const Expr *Culprit; 9643 if (var->getType().isDestructedType()) { 9644 // GNU C++98 edits for __thread, [basic.start.term]p3: 9645 // The type of an object with thread storage duration shall not 9646 // have a non-trivial destructor. 9647 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9648 if (getLangOpts().CPlusPlus11) 9649 Diag(var->getLocation(), diag::note_use_thread_local); 9650 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9651 !var->getInit()->isConstantInitializer( 9652 Context, var->getType()->isReferenceType(), &Culprit)) { 9653 // GNU C++98 edits for __thread, [basic.start.init]p4: 9654 // An object of thread storage duration shall not require dynamic 9655 // initialization. 9656 // FIXME: Need strict checking here. 9657 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9658 << Culprit->getSourceRange(); 9659 if (getLangOpts().CPlusPlus11) 9660 Diag(var->getLocation(), diag::note_use_thread_local); 9661 } 9662 9663 } 9664 9665 // Apply section attributes and pragmas to global variables. 9666 bool GlobalStorage = var->hasGlobalStorage(); 9667 if (GlobalStorage && var->isThisDeclarationADefinition() && 9668 ActiveTemplateInstantiations.empty()) { 9669 PragmaStack<StringLiteral *> *Stack = nullptr; 9670 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 9671 if (var->getType().isConstQualified()) 9672 Stack = &ConstSegStack; 9673 else if (!var->getInit()) { 9674 Stack = &BSSSegStack; 9675 SectionFlags |= ASTContext::PSF_Write; 9676 } else { 9677 Stack = &DataSegStack; 9678 SectionFlags |= ASTContext::PSF_Write; 9679 } 9680 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 9681 var->addAttr(SectionAttr::CreateImplicit( 9682 Context, SectionAttr::Declspec_allocate, 9683 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 9684 } 9685 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9686 if (UnifySection(SA->getName(), SectionFlags, var)) 9687 var->dropAttr<SectionAttr>(); 9688 9689 // Apply the init_seg attribute if this has an initializer. If the 9690 // initializer turns out to not be dynamic, we'll end up ignoring this 9691 // attribute. 9692 if (CurInitSeg && var->getInit()) 9693 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 9694 CurInitSegLoc)); 9695 } 9696 9697 // All the following checks are C++ only. 9698 if (!getLangOpts().CPlusPlus) return; 9699 9700 QualType type = var->getType(); 9701 if (type->isDependentType()) return; 9702 9703 // __block variables might require us to capture a copy-initializer. 9704 if (var->hasAttr<BlocksAttr>()) { 9705 // It's currently invalid to ever have a __block variable with an 9706 // array type; should we diagnose that here? 9707 9708 // Regardless, we don't want to ignore array nesting when 9709 // constructing this copy. 9710 if (type->isStructureOrClassType()) { 9711 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9712 SourceLocation poi = var->getLocation(); 9713 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9714 ExprResult result 9715 = PerformMoveOrCopyInitialization( 9716 InitializedEntity::InitializeBlock(poi, type, false), 9717 var, var->getType(), varRef, /*AllowNRVO=*/true); 9718 if (!result.isInvalid()) { 9719 result = MaybeCreateExprWithCleanups(result); 9720 Expr *init = result.getAs<Expr>(); 9721 Context.setBlockVarCopyInits(var, init); 9722 } 9723 } 9724 } 9725 9726 Expr *Init = var->getInit(); 9727 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 9728 QualType baseType = Context.getBaseElementType(type); 9729 9730 if (!var->getDeclContext()->isDependentContext() && 9731 Init && !Init->isValueDependent()) { 9732 if (IsGlobal && !var->isConstexpr() && 9733 !getDiagnostics().isIgnored(diag::warn_global_constructor, 9734 var->getLocation())) { 9735 // Warn about globals which don't have a constant initializer. Don't 9736 // warn about globals with a non-trivial destructor because we already 9737 // warned about them. 9738 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9739 if (!(RD && !RD->hasTrivialDestructor()) && 9740 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9741 Diag(var->getLocation(), diag::warn_global_constructor) 9742 << Init->getSourceRange(); 9743 } 9744 9745 if (var->isConstexpr()) { 9746 SmallVector<PartialDiagnosticAt, 8> Notes; 9747 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9748 SourceLocation DiagLoc = var->getLocation(); 9749 // If the note doesn't add any useful information other than a source 9750 // location, fold it into the primary diagnostic. 9751 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9752 diag::note_invalid_subexpr_in_const_expr) { 9753 DiagLoc = Notes[0].first; 9754 Notes.clear(); 9755 } 9756 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9757 << var << Init->getSourceRange(); 9758 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9759 Diag(Notes[I].first, Notes[I].second); 9760 } 9761 } else if (var->isUsableInConstantExpressions(Context)) { 9762 // Check whether the initializer of a const variable of integral or 9763 // enumeration type is an ICE now, since we can't tell whether it was 9764 // initialized by a constant expression if we check later. 9765 var->checkInitIsICE(); 9766 } 9767 } 9768 9769 // Require the destructor. 9770 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9771 FinalizeVarWithDestructor(var, recordType); 9772 } 9773 9774 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9775 /// any semantic actions necessary after any initializer has been attached. 9776 void 9777 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9778 // Note that we are no longer parsing the initializer for this declaration. 9779 ParsingInitForAutoVars.erase(ThisDecl); 9780 9781 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9782 if (!VD) 9783 return; 9784 9785 checkAttributesAfterMerging(*this, *VD); 9786 9787 // Static locals inherit dll attributes from their function. 9788 if (VD->isStaticLocal()) { 9789 if (FunctionDecl *FD = 9790 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 9791 if (Attr *A = getDLLAttr(FD)) { 9792 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 9793 NewAttr->setInherited(true); 9794 VD->addAttr(NewAttr); 9795 } 9796 } 9797 } 9798 9799 // Grab the dllimport or dllexport attribute off of the VarDecl. 9800 const InheritableAttr *DLLAttr = getDLLAttr(VD); 9801 9802 // Imported static data members cannot be defined out-of-line. 9803 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 9804 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9805 VD->isThisDeclarationADefinition()) { 9806 // We allow definitions of dllimport class template static data members 9807 // with a warning. 9808 CXXRecordDecl *Context = 9809 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9810 bool IsClassTemplateMember = 9811 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9812 Context->getDescribedClassTemplate(); 9813 9814 Diag(VD->getLocation(), 9815 IsClassTemplateMember 9816 ? diag::warn_attribute_dllimport_static_field_definition 9817 : diag::err_attribute_dllimport_static_field_definition); 9818 Diag(IA->getLocation(), diag::note_attribute); 9819 if (!IsClassTemplateMember) 9820 VD->setInvalidDecl(); 9821 } 9822 } 9823 9824 // dllimport/dllexport variables cannot be thread local, their TLS index 9825 // isn't exported with the variable. 9826 if (DLLAttr && VD->getTLSKind()) { 9827 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 9828 << DLLAttr; 9829 VD->setInvalidDecl(); 9830 } 9831 9832 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9833 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9834 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9835 VD->dropAttr<UsedAttr>(); 9836 } 9837 } 9838 9839 const DeclContext *DC = VD->getDeclContext(); 9840 // If there's a #pragma GCC visibility in scope, and this isn't a class 9841 // member, set the visibility of this variable. 9842 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9843 AddPushedVisibilityAttribute(VD); 9844 9845 // FIXME: Warn on unused templates. 9846 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9847 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9848 MarkUnusedFileScopedDecl(VD); 9849 9850 // Now we have parsed the initializer and can update the table of magic 9851 // tag values. 9852 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9853 !VD->getType()->isIntegralOrEnumerationType()) 9854 return; 9855 9856 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9857 const Expr *MagicValueExpr = VD->getInit(); 9858 if (!MagicValueExpr) { 9859 continue; 9860 } 9861 llvm::APSInt MagicValueInt; 9862 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9863 Diag(I->getRange().getBegin(), 9864 diag::err_type_tag_for_datatype_not_ice) 9865 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9866 continue; 9867 } 9868 if (MagicValueInt.getActiveBits() > 64) { 9869 Diag(I->getRange().getBegin(), 9870 diag::err_type_tag_for_datatype_too_large) 9871 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9872 continue; 9873 } 9874 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9875 RegisterTypeTagForDatatype(I->getArgumentKind(), 9876 MagicValue, 9877 I->getMatchingCType(), 9878 I->getLayoutCompatible(), 9879 I->getMustBeNull()); 9880 } 9881 } 9882 9883 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9884 ArrayRef<Decl *> Group) { 9885 SmallVector<Decl*, 8> Decls; 9886 9887 if (DS.isTypeSpecOwned()) 9888 Decls.push_back(DS.getRepAsDecl()); 9889 9890 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9891 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9892 if (Decl *D = Group[i]) { 9893 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9894 if (!FirstDeclaratorInGroup) 9895 FirstDeclaratorInGroup = DD; 9896 Decls.push_back(D); 9897 } 9898 9899 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9900 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9901 handleTagNumbering(Tag, S); 9902 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9903 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9904 } 9905 } 9906 9907 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9908 } 9909 9910 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9911 /// group, performing any necessary semantic checking. 9912 Sema::DeclGroupPtrTy 9913 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 9914 bool TypeMayContainAuto) { 9915 // C++0x [dcl.spec.auto]p7: 9916 // If the type deduced for the template parameter U is not the same in each 9917 // deduction, the program is ill-formed. 9918 // FIXME: When initializer-list support is added, a distinction is needed 9919 // between the deduced type U and the deduced type which 'auto' stands for. 9920 // auto a = 0, b = { 1, 2, 3 }; 9921 // is legal because the deduced type U is 'int' in both cases. 9922 if (TypeMayContainAuto && Group.size() > 1) { 9923 QualType Deduced; 9924 CanQualType DeducedCanon; 9925 VarDecl *DeducedDecl = nullptr; 9926 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9927 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9928 AutoType *AT = D->getType()->getContainedAutoType(); 9929 // Don't reissue diagnostics when instantiating a template. 9930 if (AT && D->isInvalidDecl()) 9931 break; 9932 QualType U = AT ? AT->getDeducedType() : QualType(); 9933 if (!U.isNull()) { 9934 CanQualType UCanon = Context.getCanonicalType(U); 9935 if (Deduced.isNull()) { 9936 Deduced = U; 9937 DeducedCanon = UCanon; 9938 DeducedDecl = D; 9939 } else if (DeducedCanon != UCanon) { 9940 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9941 diag::err_auto_different_deductions) 9942 << (AT->isDecltypeAuto() ? 1 : 0) 9943 << Deduced << DeducedDecl->getDeclName() 9944 << U << D->getDeclName() 9945 << DeducedDecl->getInit()->getSourceRange() 9946 << D->getInit()->getSourceRange(); 9947 D->setInvalidDecl(); 9948 break; 9949 } 9950 } 9951 } 9952 } 9953 } 9954 9955 ActOnDocumentableDecls(Group); 9956 9957 return DeclGroupPtrTy::make( 9958 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9959 } 9960 9961 void Sema::ActOnDocumentableDecl(Decl *D) { 9962 ActOnDocumentableDecls(D); 9963 } 9964 9965 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9966 // Don't parse the comment if Doxygen diagnostics are ignored. 9967 if (Group.empty() || !Group[0]) 9968 return; 9969 9970 if (Diags.isIgnored(diag::warn_doc_param_not_found, 9971 Group[0]->getLocation()) && 9972 Diags.isIgnored(diag::warn_unknown_comment_command_name, 9973 Group[0]->getLocation())) 9974 return; 9975 9976 if (Group.size() >= 2) { 9977 // This is a decl group. Normally it will contain only declarations 9978 // produced from declarator list. But in case we have any definitions or 9979 // additional declaration references: 9980 // 'typedef struct S {} S;' 9981 // 'typedef struct S *S;' 9982 // 'struct S *pS;' 9983 // FinalizeDeclaratorGroup adds these as separate declarations. 9984 Decl *MaybeTagDecl = Group[0]; 9985 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9986 Group = Group.slice(1); 9987 } 9988 } 9989 9990 // See if there are any new comments that are not attached to a decl. 9991 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9992 if (!Comments.empty() && 9993 !Comments.back()->isAttached()) { 9994 // There is at least one comment that not attached to a decl. 9995 // Maybe it should be attached to one of these decls? 9996 // 9997 // Note that this way we pick up not only comments that precede the 9998 // declaration, but also comments that *follow* the declaration -- thanks to 9999 // the lookahead in the lexer: we've consumed the semicolon and looked 10000 // ahead through comments. 10001 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10002 Context.getCommentForDecl(Group[i], &PP); 10003 } 10004 } 10005 10006 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 10007 /// to introduce parameters into function prototype scope. 10008 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 10009 const DeclSpec &DS = D.getDeclSpec(); 10010 10011 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 10012 10013 // C++03 [dcl.stc]p2 also permits 'auto'. 10014 StorageClass SC = SC_None; 10015 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 10016 SC = SC_Register; 10017 } else if (getLangOpts().CPlusPlus && 10018 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 10019 SC = SC_Auto; 10020 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 10021 Diag(DS.getStorageClassSpecLoc(), 10022 diag::err_invalid_storage_class_in_func_decl); 10023 D.getMutableDeclSpec().ClearStorageClassSpecs(); 10024 } 10025 10026 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 10027 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 10028 << DeclSpec::getSpecifierName(TSCS); 10029 if (DS.isConstexprSpecified()) 10030 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 10031 << 0; 10032 10033 DiagnoseFunctionSpecifiers(DS); 10034 10035 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10036 QualType parmDeclType = TInfo->getType(); 10037 10038 if (getLangOpts().CPlusPlus) { 10039 // Check that there are no default arguments inside the type of this 10040 // parameter. 10041 CheckExtraCXXDefaultArguments(D); 10042 10043 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 10044 if (D.getCXXScopeSpec().isSet()) { 10045 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 10046 << D.getCXXScopeSpec().getRange(); 10047 D.getCXXScopeSpec().clear(); 10048 } 10049 } 10050 10051 // Ensure we have a valid name 10052 IdentifierInfo *II = nullptr; 10053 if (D.hasName()) { 10054 II = D.getIdentifier(); 10055 if (!II) { 10056 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 10057 << GetNameForDeclarator(D).getName(); 10058 D.setInvalidType(true); 10059 } 10060 } 10061 10062 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 10063 if (II) { 10064 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 10065 ForRedeclaration); 10066 LookupName(R, S); 10067 if (R.isSingleResult()) { 10068 NamedDecl *PrevDecl = R.getFoundDecl(); 10069 if (PrevDecl->isTemplateParameter()) { 10070 // Maybe we will complain about the shadowed template parameter. 10071 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10072 // Just pretend that we didn't see the previous declaration. 10073 PrevDecl = nullptr; 10074 } else if (S->isDeclScope(PrevDecl)) { 10075 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 10076 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10077 10078 // Recover by removing the name 10079 II = nullptr; 10080 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 10081 D.setInvalidType(true); 10082 } 10083 } 10084 } 10085 10086 // Temporarily put parameter variables in the translation unit, not 10087 // the enclosing context. This prevents them from accidentally 10088 // looking like class members in C++. 10089 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 10090 D.getLocStart(), 10091 D.getIdentifierLoc(), II, 10092 parmDeclType, TInfo, 10093 SC); 10094 10095 if (D.isInvalidType()) 10096 New->setInvalidDecl(); 10097 10098 assert(S->isFunctionPrototypeScope()); 10099 assert(S->getFunctionPrototypeDepth() >= 1); 10100 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 10101 S->getNextFunctionPrototypeIndex()); 10102 10103 // Add the parameter declaration into this scope. 10104 S->AddDecl(New); 10105 if (II) 10106 IdResolver.AddDecl(New); 10107 10108 ProcessDeclAttributes(S, New, D); 10109 10110 if (D.getDeclSpec().isModulePrivateSpecified()) 10111 Diag(New->getLocation(), diag::err_module_private_local) 10112 << 1 << New->getDeclName() 10113 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10114 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10115 10116 if (New->hasAttr<BlocksAttr>()) { 10117 Diag(New->getLocation(), diag::err_block_on_nonlocal); 10118 } 10119 return New; 10120 } 10121 10122 /// \brief Synthesizes a variable for a parameter arising from a 10123 /// typedef. 10124 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 10125 SourceLocation Loc, 10126 QualType T) { 10127 /* FIXME: setting StartLoc == Loc. 10128 Would it be worth to modify callers so as to provide proper source 10129 location for the unnamed parameters, embedding the parameter's type? */ 10130 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 10131 T, Context.getTrivialTypeSourceInfo(T, Loc), 10132 SC_None, nullptr); 10133 Param->setImplicit(); 10134 return Param; 10135 } 10136 10137 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 10138 ParmVarDecl * const *ParamEnd) { 10139 // Don't diagnose unused-parameter errors in template instantiations; we 10140 // will already have done so in the template itself. 10141 if (!ActiveTemplateInstantiations.empty()) 10142 return; 10143 10144 for (; Param != ParamEnd; ++Param) { 10145 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 10146 !(*Param)->hasAttr<UnusedAttr>()) { 10147 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 10148 << (*Param)->getDeclName(); 10149 } 10150 } 10151 } 10152 10153 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 10154 ParmVarDecl * const *ParamEnd, 10155 QualType ReturnTy, 10156 NamedDecl *D) { 10157 if (LangOpts.NumLargeByValueCopy == 0) // No check. 10158 return; 10159 10160 // Warn if the return value is pass-by-value and larger than the specified 10161 // threshold. 10162 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 10163 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 10164 if (Size > LangOpts.NumLargeByValueCopy) 10165 Diag(D->getLocation(), diag::warn_return_value_size) 10166 << D->getDeclName() << Size; 10167 } 10168 10169 // Warn if any parameter is pass-by-value and larger than the specified 10170 // threshold. 10171 for (; Param != ParamEnd; ++Param) { 10172 QualType T = (*Param)->getType(); 10173 if (T->isDependentType() || !T.isPODType(Context)) 10174 continue; 10175 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 10176 if (Size > LangOpts.NumLargeByValueCopy) 10177 Diag((*Param)->getLocation(), diag::warn_parameter_size) 10178 << (*Param)->getDeclName() << Size; 10179 } 10180 } 10181 10182 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 10183 SourceLocation NameLoc, IdentifierInfo *Name, 10184 QualType T, TypeSourceInfo *TSInfo, 10185 StorageClass SC) { 10186 // In ARC, infer a lifetime qualifier for appropriate parameter types. 10187 if (getLangOpts().ObjCAutoRefCount && 10188 T.getObjCLifetime() == Qualifiers::OCL_None && 10189 T->isObjCLifetimeType()) { 10190 10191 Qualifiers::ObjCLifetime lifetime; 10192 10193 // Special cases for arrays: 10194 // - if it's const, use __unsafe_unretained 10195 // - otherwise, it's an error 10196 if (T->isArrayType()) { 10197 if (!T.isConstQualified()) { 10198 DelayedDiagnostics.add( 10199 sema::DelayedDiagnostic::makeForbiddenType( 10200 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 10201 } 10202 lifetime = Qualifiers::OCL_ExplicitNone; 10203 } else { 10204 lifetime = T->getObjCARCImplicitLifetime(); 10205 } 10206 T = Context.getLifetimeQualifiedType(T, lifetime); 10207 } 10208 10209 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 10210 Context.getAdjustedParameterType(T), 10211 TSInfo, SC, nullptr); 10212 10213 // Parameters can not be abstract class types. 10214 // For record types, this is done by the AbstractClassUsageDiagnoser once 10215 // the class has been completely parsed. 10216 if (!CurContext->isRecord() && 10217 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 10218 AbstractParamType)) 10219 New->setInvalidDecl(); 10220 10221 // Parameter declarators cannot be interface types. All ObjC objects are 10222 // passed by reference. 10223 if (T->isObjCObjectType()) { 10224 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 10225 Diag(NameLoc, 10226 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 10227 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 10228 T = Context.getObjCObjectPointerType(T); 10229 New->setType(T); 10230 } 10231 10232 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 10233 // duration shall not be qualified by an address-space qualifier." 10234 // Since all parameters have automatic store duration, they can not have 10235 // an address space. 10236 if (T.getAddressSpace() != 0) { 10237 // OpenCL allows function arguments declared to be an array of a type 10238 // to be qualified with an address space. 10239 if (!(getLangOpts().OpenCL && T->isArrayType())) { 10240 Diag(NameLoc, diag::err_arg_with_address_space); 10241 New->setInvalidDecl(); 10242 } 10243 } 10244 10245 return New; 10246 } 10247 10248 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 10249 SourceLocation LocAfterDecls) { 10250 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10251 10252 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 10253 // for a K&R function. 10254 if (!FTI.hasPrototype) { 10255 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10256 --i; 10257 if (FTI.Params[i].Param == nullptr) { 10258 SmallString<256> Code; 10259 llvm::raw_svector_ostream(Code) 10260 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10261 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10262 << FTI.Params[i].Ident 10263 << FixItHint::CreateInsertion(LocAfterDecls, Code); 10264 10265 // Implicitly declare the argument as type 'int' for lack of a better 10266 // type. 10267 AttributeFactory attrs; 10268 DeclSpec DS(attrs); 10269 const char* PrevSpec; // unused 10270 unsigned DiagID; // unused 10271 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10272 DiagID, Context.getPrintingPolicy()); 10273 // Use the identifier location for the type source range. 10274 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10275 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10276 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10277 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10278 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10279 } 10280 } 10281 } 10282 } 10283 10284 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 10285 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10286 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10287 Scope *ParentScope = FnBodyScope->getParent(); 10288 10289 D.setFunctionDefinitionKind(FDK_Definition); 10290 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 10291 return ActOnStartOfFunctionDef(FnBodyScope, DP); 10292 } 10293 10294 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10295 Consumer.HandleInlineMethodDefinition(D); 10296 } 10297 10298 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10299 const FunctionDecl*& PossibleZeroParamPrototype) { 10300 // Don't warn about invalid declarations. 10301 if (FD->isInvalidDecl()) 10302 return false; 10303 10304 // Or declarations that aren't global. 10305 if (!FD->isGlobal()) 10306 return false; 10307 10308 // Don't warn about C++ member functions. 10309 if (isa<CXXMethodDecl>(FD)) 10310 return false; 10311 10312 // Don't warn about 'main'. 10313 if (FD->isMain()) 10314 return false; 10315 10316 // Don't warn about inline functions. 10317 if (FD->isInlined()) 10318 return false; 10319 10320 // Don't warn about function templates. 10321 if (FD->getDescribedFunctionTemplate()) 10322 return false; 10323 10324 // Don't warn about function template specializations. 10325 if (FD->isFunctionTemplateSpecialization()) 10326 return false; 10327 10328 // Don't warn for OpenCL kernels. 10329 if (FD->hasAttr<OpenCLKernelAttr>()) 10330 return false; 10331 10332 // Don't warn on explicitly deleted functions. 10333 if (FD->isDeleted()) 10334 return false; 10335 10336 bool MissingPrototype = true; 10337 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10338 Prev; Prev = Prev->getPreviousDecl()) { 10339 // Ignore any declarations that occur in function or method 10340 // scope, because they aren't visible from the header. 10341 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10342 continue; 10343 10344 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10345 if (FD->getNumParams() == 0) 10346 PossibleZeroParamPrototype = Prev; 10347 break; 10348 } 10349 10350 return MissingPrototype; 10351 } 10352 10353 void 10354 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10355 const FunctionDecl *EffectiveDefinition) { 10356 // Don't complain if we're in GNU89 mode and the previous definition 10357 // was an extern inline function. 10358 const FunctionDecl *Definition = EffectiveDefinition; 10359 if (!Definition) 10360 if (!FD->isDefined(Definition)) 10361 return; 10362 10363 if (canRedefineFunction(Definition, getLangOpts())) 10364 return; 10365 10366 // If we don't have a visible definition of the function, and it's inline or 10367 // a template, it's OK to form another definition of it. 10368 // 10369 // FIXME: Should we skip the body of the function and use the old definition 10370 // in this case? That may be necessary for functions that return local types 10371 // through a deduced return type, or instantiate templates with local types. 10372 if (!hasVisibleDefinition(Definition) && 10373 (Definition->getFormalLinkage() == InternalLinkage || 10374 Definition->isInlineSpecified() || 10375 Definition->getDescribedFunctionTemplate() || 10376 Definition->getNumTemplateParameterLists())) 10377 return; 10378 10379 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10380 Definition->getStorageClass() == SC_Extern) 10381 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10382 << FD->getDeclName() << getLangOpts().CPlusPlus; 10383 else 10384 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10385 10386 Diag(Definition->getLocation(), diag::note_previous_definition); 10387 FD->setInvalidDecl(); 10388 } 10389 10390 10391 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10392 Sema &S) { 10393 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10394 10395 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10396 LSI->CallOperator = CallOperator; 10397 LSI->Lambda = LambdaClass; 10398 LSI->ReturnType = CallOperator->getReturnType(); 10399 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10400 10401 if (LCD == LCD_None) 10402 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10403 else if (LCD == LCD_ByCopy) 10404 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10405 else if (LCD == LCD_ByRef) 10406 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10407 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10408 10409 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10410 LSI->Mutable = !CallOperator->isConst(); 10411 10412 // Add the captures to the LSI so they can be noted as already 10413 // captured within tryCaptureVar. 10414 auto I = LambdaClass->field_begin(); 10415 for (const auto &C : LambdaClass->captures()) { 10416 if (C.capturesVariable()) { 10417 VarDecl *VD = C.getCapturedVar(); 10418 if (VD->isInitCapture()) 10419 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10420 QualType CaptureType = VD->getType(); 10421 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10422 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10423 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 10424 /*EllipsisLoc*/C.isPackExpansion() 10425 ? C.getEllipsisLoc() : SourceLocation(), 10426 CaptureType, /*Expr*/ nullptr); 10427 10428 } else if (C.capturesThis()) { 10429 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10430 S.getCurrentThisType(), /*Expr*/ nullptr); 10431 } else { 10432 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10433 } 10434 ++I; 10435 } 10436 } 10437 10438 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 10439 // Clear the last template instantiation error context. 10440 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10441 10442 if (!D) 10443 return D; 10444 FunctionDecl *FD = nullptr; 10445 10446 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10447 FD = FunTmpl->getTemplatedDecl(); 10448 else 10449 FD = cast<FunctionDecl>(D); 10450 // If we are instantiating a generic lambda call operator, push 10451 // a LambdaScopeInfo onto the function stack. But use the information 10452 // that's already been calculated (ActOnLambdaExpr) to prime the current 10453 // LambdaScopeInfo. 10454 // When the template operator is being specialized, the LambdaScopeInfo, 10455 // has to be properly restored so that tryCaptureVariable doesn't try 10456 // and capture any new variables. In addition when calculating potential 10457 // captures during transformation of nested lambdas, it is necessary to 10458 // have the LSI properly restored. 10459 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10460 assert(ActiveTemplateInstantiations.size() && 10461 "There should be an active template instantiation on the stack " 10462 "when instantiating a generic lambda!"); 10463 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10464 } 10465 else 10466 // Enter a new function scope 10467 PushFunctionScope(); 10468 10469 // See if this is a redefinition. 10470 if (!FD->isLateTemplateParsed()) 10471 CheckForFunctionRedefinition(FD); 10472 10473 // Builtin functions cannot be defined. 10474 if (unsigned BuiltinID = FD->getBuiltinID()) { 10475 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10476 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10477 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10478 FD->setInvalidDecl(); 10479 } 10480 } 10481 10482 // The return type of a function definition must be complete 10483 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10484 QualType ResultType = FD->getReturnType(); 10485 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10486 !FD->isInvalidDecl() && 10487 RequireCompleteType(FD->getLocation(), ResultType, 10488 diag::err_func_def_incomplete_result)) 10489 FD->setInvalidDecl(); 10490 10491 if (FnBodyScope) 10492 PushDeclContext(FnBodyScope, FD); 10493 10494 // Check the validity of our function parameters 10495 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10496 /*CheckParameterNames=*/true); 10497 10498 // Introduce our parameters into the function scope 10499 for (auto Param : FD->params()) { 10500 Param->setOwningFunction(FD); 10501 10502 // If this has an identifier, add it to the scope stack. 10503 if (Param->getIdentifier() && FnBodyScope) { 10504 CheckShadow(FnBodyScope, Param); 10505 10506 PushOnScopeChains(Param, FnBodyScope); 10507 } 10508 } 10509 10510 // If we had any tags defined in the function prototype, 10511 // introduce them into the function scope. 10512 if (FnBodyScope) { 10513 for (ArrayRef<NamedDecl *>::iterator 10514 I = FD->getDeclsInPrototypeScope().begin(), 10515 E = FD->getDeclsInPrototypeScope().end(); 10516 I != E; ++I) { 10517 NamedDecl *D = *I; 10518 10519 // Some of these decls (like enums) may have been pinned to the 10520 // translation unit for lack of a real context earlier. If so, remove 10521 // from the translation unit and reattach to the current context. 10522 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 10523 // Is the decl actually in the context? 10524 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 10525 if (DI == D) { 10526 Context.getTranslationUnitDecl()->removeDecl(D); 10527 break; 10528 } 10529 } 10530 // Either way, reassign the lexical decl context to our FunctionDecl. 10531 D->setLexicalDeclContext(CurContext); 10532 } 10533 10534 // If the decl has a non-null name, make accessible in the current scope. 10535 if (!D->getName().empty()) 10536 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 10537 10538 // Similarly, dive into enums and fish their constants out, making them 10539 // accessible in this scope. 10540 if (auto *ED = dyn_cast<EnumDecl>(D)) { 10541 for (auto *EI : ED->enumerators()) 10542 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 10543 } 10544 } 10545 } 10546 10547 // Ensure that the function's exception specification is instantiated. 10548 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 10549 ResolveExceptionSpec(D->getLocation(), FPT); 10550 10551 // dllimport cannot be applied to non-inline function definitions. 10552 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 10553 !FD->isTemplateInstantiation()) { 10554 assert(!FD->hasAttr<DLLExportAttr>()); 10555 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 10556 FD->setInvalidDecl(); 10557 return D; 10558 } 10559 // We want to attach documentation to original Decl (which might be 10560 // a function template). 10561 ActOnDocumentableDecl(D); 10562 if (getCurLexicalContext()->isObjCContainer() && 10563 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 10564 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 10565 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 10566 10567 return D; 10568 } 10569 10570 /// \brief Given the set of return statements within a function body, 10571 /// compute the variables that are subject to the named return value 10572 /// optimization. 10573 /// 10574 /// Each of the variables that is subject to the named return value 10575 /// optimization will be marked as NRVO variables in the AST, and any 10576 /// return statement that has a marked NRVO variable as its NRVO candidate can 10577 /// use the named return value optimization. 10578 /// 10579 /// This function applies a very simplistic algorithm for NRVO: if every return 10580 /// statement in the scope of a variable has the same NRVO candidate, that 10581 /// candidate is an NRVO variable. 10582 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 10583 ReturnStmt **Returns = Scope->Returns.data(); 10584 10585 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 10586 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 10587 if (!NRVOCandidate->isNRVOVariable()) 10588 Returns[I]->setNRVOCandidate(nullptr); 10589 } 10590 } 10591 } 10592 10593 bool Sema::canDelayFunctionBody(const Declarator &D) { 10594 // We can't delay parsing the body of a constexpr function template (yet). 10595 if (D.getDeclSpec().isConstexprSpecified()) 10596 return false; 10597 10598 // We can't delay parsing the body of a function template with a deduced 10599 // return type (yet). 10600 if (D.getDeclSpec().containsPlaceholderType()) { 10601 // If the placeholder introduces a non-deduced trailing return type, 10602 // we can still delay parsing it. 10603 if (D.getNumTypeObjects()) { 10604 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 10605 if (Outer.Kind == DeclaratorChunk::Function && 10606 Outer.Fun.hasTrailingReturnType()) { 10607 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 10608 return Ty.isNull() || !Ty->isUndeducedType(); 10609 } 10610 } 10611 return false; 10612 } 10613 10614 return true; 10615 } 10616 10617 bool Sema::canSkipFunctionBody(Decl *D) { 10618 // We cannot skip the body of a function (or function template) which is 10619 // constexpr, since we may need to evaluate its body in order to parse the 10620 // rest of the file. 10621 // We cannot skip the body of a function with an undeduced return type, 10622 // because any callers of that function need to know the type. 10623 if (const FunctionDecl *FD = D->getAsFunction()) 10624 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 10625 return false; 10626 return Consumer.shouldSkipFunctionBody(D); 10627 } 10628 10629 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 10630 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 10631 FD->setHasSkippedBody(); 10632 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10633 MD->setHasSkippedBody(); 10634 return ActOnFinishFunctionBody(Decl, nullptr); 10635 } 10636 10637 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10638 return ActOnFinishFunctionBody(D, BodyArg, false); 10639 } 10640 10641 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10642 bool IsInstantiation) { 10643 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10644 10645 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10646 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10647 10648 if (FD) { 10649 FD->setBody(Body); 10650 10651 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body && 10652 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10653 // If the function has a deduced result type but contains no 'return' 10654 // statements, the result type as written must be exactly 'auto', and 10655 // the deduced result type is 'void'. 10656 if (!FD->getReturnType()->getAs<AutoType>()) { 10657 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10658 << FD->getReturnType(); 10659 FD->setInvalidDecl(); 10660 } else { 10661 // Substitute 'void' for the 'auto' in the type. 10662 TypeLoc ResultType = getReturnTypeLoc(FD); 10663 Context.adjustDeducedFunctionResultType( 10664 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10665 } 10666 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 10667 auto *LSI = getCurLambda(); 10668 if (LSI->HasImplicitReturnType) { 10669 deduceClosureReturnType(*LSI); 10670 10671 // C++11 [expr.prim.lambda]p4: 10672 // [...] if there are no return statements in the compound-statement 10673 // [the deduced type is] the type void 10674 QualType RetType = 10675 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 10676 10677 // Update the return type to the deduced type. 10678 const FunctionProtoType *Proto = 10679 FD->getType()->getAs<FunctionProtoType>(); 10680 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 10681 Proto->getExtProtoInfo())); 10682 } 10683 } 10684 10685 // The only way to be included in UndefinedButUsed is if there is an 10686 // ODR use before the definition. Avoid the expensive map lookup if this 10687 // is the first declaration. 10688 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 10689 if (!FD->isExternallyVisible()) 10690 UndefinedButUsed.erase(FD); 10691 else if (FD->isInlined() && 10692 !LangOpts.GNUInline && 10693 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 10694 UndefinedButUsed.erase(FD); 10695 } 10696 10697 // If the function implicitly returns zero (like 'main') or is naked, 10698 // don't complain about missing return statements. 10699 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 10700 WP.disableCheckFallThrough(); 10701 10702 // MSVC permits the use of pure specifier (=0) on function definition, 10703 // defined at class scope, warn about this non-standard construct. 10704 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10705 Diag(FD->getLocation(), diag::ext_pure_function_definition); 10706 10707 if (!FD->isInvalidDecl()) { 10708 // Don't diagnose unused parameters of defaulted or deleted functions. 10709 if (!FD->isDeleted() && !FD->isDefaulted()) 10710 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10711 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10712 FD->getReturnType(), FD); 10713 10714 // If this is a structor, we need a vtable. 10715 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10716 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10717 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 10718 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 10719 10720 // Try to apply the named return value optimization. We have to check 10721 // if we can do this here because lambdas keep return statements around 10722 // to deduce an implicit return type. 10723 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10724 !FD->isDependentContext()) 10725 computeNRVO(Body, getCurFunction()); 10726 } 10727 10728 // GNU warning -Wmissing-prototypes: 10729 // Warn if a global function is defined without a previous 10730 // prototype declaration. This warning is issued even if the 10731 // definition itself provides a prototype. The aim is to detect 10732 // global functions that fail to be declared in header files. 10733 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 10734 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 10735 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 10736 10737 if (PossibleZeroParamPrototype) { 10738 // We found a declaration that is not a prototype, 10739 // but that could be a zero-parameter prototype 10740 if (TypeSourceInfo *TI = 10741 PossibleZeroParamPrototype->getTypeSourceInfo()) { 10742 TypeLoc TL = TI->getTypeLoc(); 10743 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 10744 Diag(PossibleZeroParamPrototype->getLocation(), 10745 diag::note_declaration_not_a_prototype) 10746 << PossibleZeroParamPrototype 10747 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 10748 } 10749 } 10750 } 10751 10752 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 10753 const CXXMethodDecl *KeyFunction; 10754 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 10755 MD->isVirtual() && 10756 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 10757 MD == KeyFunction->getCanonicalDecl()) { 10758 // Update the key-function state if necessary for this ABI. 10759 if (FD->isInlined() && 10760 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 10761 Context.setNonKeyFunction(MD); 10762 10763 // If the newly-chosen key function is already defined, then we 10764 // need to mark the vtable as used retroactively. 10765 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 10766 const FunctionDecl *Definition; 10767 if (KeyFunction && KeyFunction->isDefined(Definition)) 10768 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 10769 } else { 10770 // We just defined they key function; mark the vtable as used. 10771 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 10772 } 10773 } 10774 } 10775 10776 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10777 "Function parsing confused"); 10778 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10779 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10780 MD->setBody(Body); 10781 if (!MD->isInvalidDecl()) { 10782 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10783 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10784 MD->getReturnType(), MD); 10785 10786 if (Body) 10787 computeNRVO(Body, getCurFunction()); 10788 } 10789 if (getCurFunction()->ObjCShouldCallSuper) { 10790 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10791 << MD->getSelector().getAsString(); 10792 getCurFunction()->ObjCShouldCallSuper = false; 10793 } 10794 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10795 const ObjCMethodDecl *InitMethod = nullptr; 10796 bool isDesignated = 10797 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10798 assert(isDesignated && InitMethod); 10799 (void)isDesignated; 10800 10801 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10802 auto IFace = MD->getClassInterface(); 10803 if (!IFace) 10804 return false; 10805 auto SuperD = IFace->getSuperClass(); 10806 if (!SuperD) 10807 return false; 10808 return SuperD->getIdentifier() == 10809 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10810 }; 10811 // Don't issue this warning for unavailable inits or direct subclasses 10812 // of NSObject. 10813 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10814 Diag(MD->getLocation(), 10815 diag::warn_objc_designated_init_missing_super_call); 10816 Diag(InitMethod->getLocation(), 10817 diag::note_objc_designated_init_marked_here); 10818 } 10819 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10820 } 10821 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10822 // Don't issue this warning for unavaialable inits. 10823 if (!MD->isUnavailable()) 10824 Diag(MD->getLocation(), 10825 diag::warn_objc_secondary_init_missing_init_call); 10826 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10827 } 10828 } else { 10829 return nullptr; 10830 } 10831 10832 assert(!getCurFunction()->ObjCShouldCallSuper && 10833 "This should only be set for ObjC methods, which should have been " 10834 "handled in the block above."); 10835 10836 // Verify and clean out per-function state. 10837 if (Body && (!FD || !FD->isDefaulted())) { 10838 // C++ constructors that have function-try-blocks can't have return 10839 // statements in the handlers of that block. (C++ [except.handle]p14) 10840 // Verify this. 10841 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10842 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10843 10844 // Verify that gotos and switch cases don't jump into scopes illegally. 10845 if (getCurFunction()->NeedsScopeChecking() && 10846 !PP.isCodeCompletionEnabled()) 10847 DiagnoseInvalidJumps(Body); 10848 10849 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10850 if (!Destructor->getParent()->isDependentType()) 10851 CheckDestructor(Destructor); 10852 10853 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10854 Destructor->getParent()); 10855 } 10856 10857 // If any errors have occurred, clear out any temporaries that may have 10858 // been leftover. This ensures that these temporaries won't be picked up for 10859 // deletion in some later function. 10860 if (getDiagnostics().hasErrorOccurred() || 10861 getDiagnostics().getSuppressAllDiagnostics()) { 10862 DiscardCleanupsInEvaluationContext(); 10863 } 10864 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10865 !isa<FunctionTemplateDecl>(dcl)) { 10866 // Since the body is valid, issue any analysis-based warnings that are 10867 // enabled. 10868 ActivePolicy = &WP; 10869 } 10870 10871 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10872 (!CheckConstexprFunctionDecl(FD) || 10873 !CheckConstexprFunctionBody(FD, Body))) 10874 FD->setInvalidDecl(); 10875 10876 if (FD && FD->hasAttr<NakedAttr>()) { 10877 for (const Stmt *S : Body->children()) { 10878 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 10879 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 10880 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 10881 FD->setInvalidDecl(); 10882 break; 10883 } 10884 } 10885 } 10886 10887 assert(ExprCleanupObjects.size() == 10888 ExprEvalContexts.back().NumCleanupObjects && 10889 "Leftover temporaries in function"); 10890 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10891 assert(MaybeODRUseExprs.empty() && 10892 "Leftover expressions for odr-use checking"); 10893 } 10894 10895 if (!IsInstantiation) 10896 PopDeclContext(); 10897 10898 PopFunctionScopeInfo(ActivePolicy, dcl); 10899 // If any errors have occurred, clear out any temporaries that may have 10900 // been leftover. This ensures that these temporaries won't be picked up for 10901 // deletion in some later function. 10902 if (getDiagnostics().hasErrorOccurred()) { 10903 DiscardCleanupsInEvaluationContext(); 10904 } 10905 10906 return dcl; 10907 } 10908 10909 10910 /// When we finish delayed parsing of an attribute, we must attach it to the 10911 /// relevant Decl. 10912 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10913 ParsedAttributes &Attrs) { 10914 // Always attach attributes to the underlying decl. 10915 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10916 D = TD->getTemplatedDecl(); 10917 ProcessDeclAttributeList(S, D, Attrs.getList()); 10918 10919 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10920 if (Method->isStatic()) 10921 checkThisInStaticMemberFunctionAttributes(Method); 10922 } 10923 10924 10925 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10926 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10927 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10928 IdentifierInfo &II, Scope *S) { 10929 // Before we produce a declaration for an implicitly defined 10930 // function, see whether there was a locally-scoped declaration of 10931 // this name as a function or variable. If so, use that 10932 // (non-visible) declaration, and complain about it. 10933 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10934 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10935 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10936 return ExternCPrev; 10937 } 10938 10939 // Extension in C99. Legal in C90, but warn about it. 10940 unsigned diag_id; 10941 if (II.getName().startswith("__builtin_")) 10942 diag_id = diag::warn_builtin_unknown; 10943 else if (getLangOpts().C99) 10944 diag_id = diag::ext_implicit_function_decl; 10945 else 10946 diag_id = diag::warn_implicit_function_decl; 10947 Diag(Loc, diag_id) << &II; 10948 10949 // Because typo correction is expensive, only do it if the implicit 10950 // function declaration is going to be treated as an error. 10951 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10952 TypoCorrection Corrected; 10953 if (S && 10954 (Corrected = CorrectTypo( 10955 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 10956 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 10957 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10958 /*ErrorRecovery*/false); 10959 } 10960 10961 // Set a Declarator for the implicit definition: int foo(); 10962 const char *Dummy; 10963 AttributeFactory attrFactory; 10964 DeclSpec DS(attrFactory); 10965 unsigned DiagID; 10966 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10967 Context.getPrintingPolicy()); 10968 (void)Error; // Silence warning. 10969 assert(!Error && "Error setting up implicit decl!"); 10970 SourceLocation NoLoc; 10971 Declarator D(DS, Declarator::BlockContext); 10972 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10973 /*IsAmbiguous=*/false, 10974 /*LParenLoc=*/NoLoc, 10975 /*Params=*/nullptr, 10976 /*NumParams=*/0, 10977 /*EllipsisLoc=*/NoLoc, 10978 /*RParenLoc=*/NoLoc, 10979 /*TypeQuals=*/0, 10980 /*RefQualifierIsLvalueRef=*/true, 10981 /*RefQualifierLoc=*/NoLoc, 10982 /*ConstQualifierLoc=*/NoLoc, 10983 /*VolatileQualifierLoc=*/NoLoc, 10984 /*RestrictQualifierLoc=*/NoLoc, 10985 /*MutableLoc=*/NoLoc, 10986 EST_None, 10987 /*ESpecLoc=*/NoLoc, 10988 /*Exceptions=*/nullptr, 10989 /*ExceptionRanges=*/nullptr, 10990 /*NumExceptions=*/0, 10991 /*NoexceptExpr=*/nullptr, 10992 /*ExceptionSpecTokens=*/nullptr, 10993 Loc, Loc, D), 10994 DS.getAttributes(), 10995 SourceLocation()); 10996 D.SetIdentifier(&II, Loc); 10997 10998 // Insert this function into translation-unit scope. 10999 11000 DeclContext *PrevDC = CurContext; 11001 CurContext = Context.getTranslationUnitDecl(); 11002 11003 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 11004 FD->setImplicit(); 11005 11006 CurContext = PrevDC; 11007 11008 AddKnownFunctionAttributes(FD); 11009 11010 return FD; 11011 } 11012 11013 /// \brief Adds any function attributes that we know a priori based on 11014 /// the declaration of this function. 11015 /// 11016 /// These attributes can apply both to implicitly-declared builtins 11017 /// (like __builtin___printf_chk) or to library-declared functions 11018 /// like NSLog or printf. 11019 /// 11020 /// We need to check for duplicate attributes both here and where user-written 11021 /// attributes are applied to declarations. 11022 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 11023 if (FD->isInvalidDecl()) 11024 return; 11025 11026 // If this is a built-in function, map its builtin attributes to 11027 // actual attributes. 11028 if (unsigned BuiltinID = FD->getBuiltinID()) { 11029 // Handle printf-formatting attributes. 11030 unsigned FormatIdx; 11031 bool HasVAListArg; 11032 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 11033 if (!FD->hasAttr<FormatAttr>()) { 11034 const char *fmt = "printf"; 11035 unsigned int NumParams = FD->getNumParams(); 11036 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 11037 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 11038 fmt = "NSString"; 11039 FD->addAttr(FormatAttr::CreateImplicit(Context, 11040 &Context.Idents.get(fmt), 11041 FormatIdx+1, 11042 HasVAListArg ? 0 : FormatIdx+2, 11043 FD->getLocation())); 11044 } 11045 } 11046 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 11047 HasVAListArg)) { 11048 if (!FD->hasAttr<FormatAttr>()) 11049 FD->addAttr(FormatAttr::CreateImplicit(Context, 11050 &Context.Idents.get("scanf"), 11051 FormatIdx+1, 11052 HasVAListArg ? 0 : FormatIdx+2, 11053 FD->getLocation())); 11054 } 11055 11056 // Mark const if we don't care about errno and that is the only 11057 // thing preventing the function from being const. This allows 11058 // IRgen to use LLVM intrinsics for such functions. 11059 if (!getLangOpts().MathErrno && 11060 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 11061 if (!FD->hasAttr<ConstAttr>()) 11062 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11063 } 11064 11065 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 11066 !FD->hasAttr<ReturnsTwiceAttr>()) 11067 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 11068 FD->getLocation())); 11069 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 11070 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 11071 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 11072 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11073 } 11074 11075 IdentifierInfo *Name = FD->getIdentifier(); 11076 if (!Name) 11077 return; 11078 if ((!getLangOpts().CPlusPlus && 11079 FD->getDeclContext()->isTranslationUnit()) || 11080 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 11081 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 11082 LinkageSpecDecl::lang_c)) { 11083 // Okay: this could be a libc/libm/Objective-C function we know 11084 // about. 11085 } else 11086 return; 11087 11088 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 11089 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 11090 // target-specific builtins, perhaps? 11091 if (!FD->hasAttr<FormatAttr>()) 11092 FD->addAttr(FormatAttr::CreateImplicit(Context, 11093 &Context.Idents.get("printf"), 2, 11094 Name->isStr("vasprintf") ? 0 : 3, 11095 FD->getLocation())); 11096 } 11097 11098 if (Name->isStr("__CFStringMakeConstantString")) { 11099 // We already have a __builtin___CFStringMakeConstantString, 11100 // but builds that use -fno-constant-cfstrings don't go through that. 11101 if (!FD->hasAttr<FormatArgAttr>()) 11102 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 11103 FD->getLocation())); 11104 } 11105 } 11106 11107 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 11108 TypeSourceInfo *TInfo) { 11109 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 11110 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 11111 11112 if (!TInfo) { 11113 assert(D.isInvalidType() && "no declarator info for valid type"); 11114 TInfo = Context.getTrivialTypeSourceInfo(T); 11115 } 11116 11117 // Scope manipulation handled by caller. 11118 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 11119 D.getLocStart(), 11120 D.getIdentifierLoc(), 11121 D.getIdentifier(), 11122 TInfo); 11123 11124 // Bail out immediately if we have an invalid declaration. 11125 if (D.isInvalidType()) { 11126 NewTD->setInvalidDecl(); 11127 return NewTD; 11128 } 11129 11130 if (D.getDeclSpec().isModulePrivateSpecified()) { 11131 if (CurContext->isFunctionOrMethod()) 11132 Diag(NewTD->getLocation(), diag::err_module_private_local) 11133 << 2 << NewTD->getDeclName() 11134 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11135 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11136 else 11137 NewTD->setModulePrivate(); 11138 } 11139 11140 // C++ [dcl.typedef]p8: 11141 // If the typedef declaration defines an unnamed class (or 11142 // enum), the first typedef-name declared by the declaration 11143 // to be that class type (or enum type) is used to denote the 11144 // class type (or enum type) for linkage purposes only. 11145 // We need to check whether the type was declared in the declaration. 11146 switch (D.getDeclSpec().getTypeSpecType()) { 11147 case TST_enum: 11148 case TST_struct: 11149 case TST_interface: 11150 case TST_union: 11151 case TST_class: { 11152 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 11153 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 11154 break; 11155 } 11156 11157 default: 11158 break; 11159 } 11160 11161 return NewTD; 11162 } 11163 11164 11165 /// \brief Check that this is a valid underlying type for an enum declaration. 11166 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 11167 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 11168 QualType T = TI->getType(); 11169 11170 if (T->isDependentType()) 11171 return false; 11172 11173 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 11174 if (BT->isInteger()) 11175 return false; 11176 11177 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 11178 return true; 11179 } 11180 11181 /// Check whether this is a valid redeclaration of a previous enumeration. 11182 /// \return true if the redeclaration was invalid. 11183 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 11184 QualType EnumUnderlyingTy, 11185 const EnumDecl *Prev) { 11186 bool IsFixed = !EnumUnderlyingTy.isNull(); 11187 11188 if (IsScoped != Prev->isScoped()) { 11189 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 11190 << Prev->isScoped(); 11191 Diag(Prev->getLocation(), diag::note_previous_declaration); 11192 return true; 11193 } 11194 11195 if (IsFixed && Prev->isFixed()) { 11196 if (!EnumUnderlyingTy->isDependentType() && 11197 !Prev->getIntegerType()->isDependentType() && 11198 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 11199 Prev->getIntegerType())) { 11200 // TODO: Highlight the underlying type of the redeclaration. 11201 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 11202 << EnumUnderlyingTy << Prev->getIntegerType(); 11203 Diag(Prev->getLocation(), diag::note_previous_declaration) 11204 << Prev->getIntegerTypeRange(); 11205 return true; 11206 } 11207 } else if (IsFixed != Prev->isFixed()) { 11208 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 11209 << Prev->isFixed(); 11210 Diag(Prev->getLocation(), diag::note_previous_declaration); 11211 return true; 11212 } 11213 11214 return false; 11215 } 11216 11217 /// \brief Get diagnostic %select index for tag kind for 11218 /// redeclaration diagnostic message. 11219 /// WARNING: Indexes apply to particular diagnostics only! 11220 /// 11221 /// \returns diagnostic %select index. 11222 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 11223 switch (Tag) { 11224 case TTK_Struct: return 0; 11225 case TTK_Interface: return 1; 11226 case TTK_Class: return 2; 11227 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 11228 } 11229 } 11230 11231 /// \brief Determine if tag kind is a class-key compatible with 11232 /// class for redeclaration (class, struct, or __interface). 11233 /// 11234 /// \returns true iff the tag kind is compatible. 11235 static bool isClassCompatTagKind(TagTypeKind Tag) 11236 { 11237 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 11238 } 11239 11240 /// \brief Determine whether a tag with a given kind is acceptable 11241 /// as a redeclaration of the given tag declaration. 11242 /// 11243 /// \returns true if the new tag kind is acceptable, false otherwise. 11244 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 11245 TagTypeKind NewTag, bool isDefinition, 11246 SourceLocation NewTagLoc, 11247 const IdentifierInfo &Name) { 11248 // C++ [dcl.type.elab]p3: 11249 // The class-key or enum keyword present in the 11250 // elaborated-type-specifier shall agree in kind with the 11251 // declaration to which the name in the elaborated-type-specifier 11252 // refers. This rule also applies to the form of 11253 // elaborated-type-specifier that declares a class-name or 11254 // friend class since it can be construed as referring to the 11255 // definition of the class. Thus, in any 11256 // elaborated-type-specifier, the enum keyword shall be used to 11257 // refer to an enumeration (7.2), the union class-key shall be 11258 // used to refer to a union (clause 9), and either the class or 11259 // struct class-key shall be used to refer to a class (clause 9) 11260 // declared using the class or struct class-key. 11261 TagTypeKind OldTag = Previous->getTagKind(); 11262 if (!isDefinition || !isClassCompatTagKind(NewTag)) 11263 if (OldTag == NewTag) 11264 return true; 11265 11266 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 11267 // Warn about the struct/class tag mismatch. 11268 bool isTemplate = false; 11269 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 11270 isTemplate = Record->getDescribedClassTemplate(); 11271 11272 if (!ActiveTemplateInstantiations.empty()) { 11273 // In a template instantiation, do not offer fix-its for tag mismatches 11274 // since they usually mess up the template instead of fixing the problem. 11275 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11276 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11277 << getRedeclDiagFromTagKind(OldTag); 11278 return true; 11279 } 11280 11281 if (isDefinition) { 11282 // On definitions, check previous tags and issue a fix-it for each 11283 // one that doesn't match the current tag. 11284 if (Previous->getDefinition()) { 11285 // Don't suggest fix-its for redefinitions. 11286 return true; 11287 } 11288 11289 bool previousMismatch = false; 11290 for (auto I : Previous->redecls()) { 11291 if (I->getTagKind() != NewTag) { 11292 if (!previousMismatch) { 11293 previousMismatch = true; 11294 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11295 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11296 << getRedeclDiagFromTagKind(I->getTagKind()); 11297 } 11298 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11299 << getRedeclDiagFromTagKind(NewTag) 11300 << FixItHint::CreateReplacement(I->getInnerLocStart(), 11301 TypeWithKeyword::getTagTypeKindName(NewTag)); 11302 } 11303 } 11304 return true; 11305 } 11306 11307 // Check for a previous definition. If current tag and definition 11308 // are same type, do nothing. If no definition, but disagree with 11309 // with previous tag type, give a warning, but no fix-it. 11310 const TagDecl *Redecl = Previous->getDefinition() ? 11311 Previous->getDefinition() : Previous; 11312 if (Redecl->getTagKind() == NewTag) { 11313 return true; 11314 } 11315 11316 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11317 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11318 << getRedeclDiagFromTagKind(OldTag); 11319 Diag(Redecl->getLocation(), diag::note_previous_use); 11320 11321 // If there is a previous definition, suggest a fix-it. 11322 if (Previous->getDefinition()) { 11323 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11324 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11325 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11326 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11327 } 11328 11329 return true; 11330 } 11331 return false; 11332 } 11333 11334 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11335 /// from an outer enclosing namespace or file scope inside a friend declaration. 11336 /// This should provide the commented out code in the following snippet: 11337 /// namespace N { 11338 /// struct X; 11339 /// namespace M { 11340 /// struct Y { friend struct /*N::*/ X; }; 11341 /// } 11342 /// } 11343 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11344 SourceLocation NameLoc) { 11345 // While the decl is in a namespace, do repeated lookup of that name and see 11346 // if we get the same namespace back. If we do not, continue until 11347 // translation unit scope, at which point we have a fully qualified NNS. 11348 SmallVector<IdentifierInfo *, 4> Namespaces; 11349 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11350 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11351 // This tag should be declared in a namespace, which can only be enclosed by 11352 // other namespaces. Bail if there's an anonymous namespace in the chain. 11353 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11354 if (!Namespace || Namespace->isAnonymousNamespace()) 11355 return FixItHint(); 11356 IdentifierInfo *II = Namespace->getIdentifier(); 11357 Namespaces.push_back(II); 11358 NamedDecl *Lookup = SemaRef.LookupSingleName( 11359 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11360 if (Lookup == Namespace) 11361 break; 11362 } 11363 11364 // Once we have all the namespaces, reverse them to go outermost first, and 11365 // build an NNS. 11366 SmallString<64> Insertion; 11367 llvm::raw_svector_ostream OS(Insertion); 11368 if (DC->isTranslationUnit()) 11369 OS << "::"; 11370 std::reverse(Namespaces.begin(), Namespaces.end()); 11371 for (auto *II : Namespaces) 11372 OS << II->getName() << "::"; 11373 OS.flush(); 11374 return FixItHint::CreateInsertion(NameLoc, Insertion); 11375 } 11376 11377 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 11378 /// former case, Name will be non-null. In the later case, Name will be null. 11379 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11380 /// reference/declaration/definition of a tag. 11381 /// 11382 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 11383 /// trailing-type-specifier) other than one in an alias-declaration. 11384 /// 11385 /// \param SkipBody If non-null, will be set to indicate if the caller should 11386 /// skip the definition of this tag and treat it as if it were a declaration. 11387 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11388 SourceLocation KWLoc, CXXScopeSpec &SS, 11389 IdentifierInfo *Name, SourceLocation NameLoc, 11390 AttributeList *Attr, AccessSpecifier AS, 11391 SourceLocation ModulePrivateLoc, 11392 MultiTemplateParamsArg TemplateParameterLists, 11393 bool &OwnedDecl, bool &IsDependent, 11394 SourceLocation ScopedEnumKWLoc, 11395 bool ScopedEnumUsesClassTag, 11396 TypeResult UnderlyingType, 11397 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 11398 // If this is not a definition, it must have a name. 11399 IdentifierInfo *OrigName = Name; 11400 assert((Name != nullptr || TUK == TUK_Definition) && 11401 "Nameless record must be a definition!"); 11402 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11403 11404 OwnedDecl = false; 11405 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11406 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11407 11408 // FIXME: Check explicit specializations more carefully. 11409 bool isExplicitSpecialization = false; 11410 bool Invalid = false; 11411 11412 // We only need to do this matching if we have template parameters 11413 // or a scope specifier, which also conveniently avoids this work 11414 // for non-C++ cases. 11415 if (TemplateParameterLists.size() > 0 || 11416 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11417 if (TemplateParameterList *TemplateParams = 11418 MatchTemplateParametersToScopeSpecifier( 11419 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11420 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11421 if (Kind == TTK_Enum) { 11422 Diag(KWLoc, diag::err_enum_template); 11423 return nullptr; 11424 } 11425 11426 if (TemplateParams->size() > 0) { 11427 // This is a declaration or definition of a class template (which may 11428 // be a member of another template). 11429 11430 if (Invalid) 11431 return nullptr; 11432 11433 OwnedDecl = false; 11434 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11435 SS, Name, NameLoc, Attr, 11436 TemplateParams, AS, 11437 ModulePrivateLoc, 11438 /*FriendLoc*/SourceLocation(), 11439 TemplateParameterLists.size()-1, 11440 TemplateParameterLists.data(), 11441 SkipBody); 11442 return Result.get(); 11443 } else { 11444 // The "template<>" header is extraneous. 11445 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11446 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11447 isExplicitSpecialization = true; 11448 } 11449 } 11450 } 11451 11452 // Figure out the underlying type if this a enum declaration. We need to do 11453 // this early, because it's needed to detect if this is an incompatible 11454 // redeclaration. 11455 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 11456 11457 if (Kind == TTK_Enum) { 11458 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 11459 // No underlying type explicitly specified, or we failed to parse the 11460 // type, default to int. 11461 EnumUnderlying = Context.IntTy.getTypePtr(); 11462 else if (UnderlyingType.get()) { 11463 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 11464 // integral type; any cv-qualification is ignored. 11465 TypeSourceInfo *TI = nullptr; 11466 GetTypeFromParser(UnderlyingType.get(), &TI); 11467 EnumUnderlying = TI; 11468 11469 if (CheckEnumUnderlyingType(TI)) 11470 // Recover by falling back to int. 11471 EnumUnderlying = Context.IntTy.getTypePtr(); 11472 11473 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 11474 UPPC_FixedUnderlyingType)) 11475 EnumUnderlying = Context.IntTy.getTypePtr(); 11476 11477 } else if (getLangOpts().MSVCCompat) 11478 // Microsoft enums are always of int type. 11479 EnumUnderlying = Context.IntTy.getTypePtr(); 11480 } 11481 11482 DeclContext *SearchDC = CurContext; 11483 DeclContext *DC = CurContext; 11484 bool isStdBadAlloc = false; 11485 11486 RedeclarationKind Redecl = ForRedeclaration; 11487 if (TUK == TUK_Friend || TUK == TUK_Reference) 11488 Redecl = NotForRedeclaration; 11489 11490 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 11491 if (Name && SS.isNotEmpty()) { 11492 // We have a nested-name tag ('struct foo::bar'). 11493 11494 // Check for invalid 'foo::'. 11495 if (SS.isInvalid()) { 11496 Name = nullptr; 11497 goto CreateNewDecl; 11498 } 11499 11500 // If this is a friend or a reference to a class in a dependent 11501 // context, don't try to make a decl for it. 11502 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11503 DC = computeDeclContext(SS, false); 11504 if (!DC) { 11505 IsDependent = true; 11506 return nullptr; 11507 } 11508 } else { 11509 DC = computeDeclContext(SS, true); 11510 if (!DC) { 11511 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 11512 << SS.getRange(); 11513 return nullptr; 11514 } 11515 } 11516 11517 if (RequireCompleteDeclContext(SS, DC)) 11518 return nullptr; 11519 11520 SearchDC = DC; 11521 // Look-up name inside 'foo::'. 11522 LookupQualifiedName(Previous, DC); 11523 11524 if (Previous.isAmbiguous()) 11525 return nullptr; 11526 11527 if (Previous.empty()) { 11528 // Name lookup did not find anything. However, if the 11529 // nested-name-specifier refers to the current instantiation, 11530 // and that current instantiation has any dependent base 11531 // classes, we might find something at instantiation time: treat 11532 // this as a dependent elaborated-type-specifier. 11533 // But this only makes any sense for reference-like lookups. 11534 if (Previous.wasNotFoundInCurrentInstantiation() && 11535 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11536 IsDependent = true; 11537 return nullptr; 11538 } 11539 11540 // A tag 'foo::bar' must already exist. 11541 Diag(NameLoc, diag::err_not_tag_in_scope) 11542 << Kind << Name << DC << SS.getRange(); 11543 Name = nullptr; 11544 Invalid = true; 11545 goto CreateNewDecl; 11546 } 11547 } else if (Name) { 11548 // If this is a named struct, check to see if there was a previous forward 11549 // declaration or definition. 11550 // FIXME: We're looking into outer scopes here, even when we 11551 // shouldn't be. Doing so can result in ambiguities that we 11552 // shouldn't be diagnosing. 11553 LookupName(Previous, S); 11554 11555 // When declaring or defining a tag, ignore ambiguities introduced 11556 // by types using'ed into this scope. 11557 if (Previous.isAmbiguous() && 11558 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 11559 LookupResult::Filter F = Previous.makeFilter(); 11560 while (F.hasNext()) { 11561 NamedDecl *ND = F.next(); 11562 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 11563 F.erase(); 11564 } 11565 F.done(); 11566 } 11567 11568 // C++11 [namespace.memdef]p3: 11569 // If the name in a friend declaration is neither qualified nor 11570 // a template-id and the declaration is a function or an 11571 // elaborated-type-specifier, the lookup to determine whether 11572 // the entity has been previously declared shall not consider 11573 // any scopes outside the innermost enclosing namespace. 11574 // 11575 // MSVC doesn't implement the above rule for types, so a friend tag 11576 // declaration may be a redeclaration of a type declared in an enclosing 11577 // scope. They do implement this rule for friend functions. 11578 // 11579 // Does it matter that this should be by scope instead of by 11580 // semantic context? 11581 if (!Previous.empty() && TUK == TUK_Friend) { 11582 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 11583 LookupResult::Filter F = Previous.makeFilter(); 11584 bool FriendSawTagOutsideEnclosingNamespace = false; 11585 while (F.hasNext()) { 11586 NamedDecl *ND = F.next(); 11587 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11588 if (DC->isFileContext() && 11589 !EnclosingNS->Encloses(ND->getDeclContext())) { 11590 if (getLangOpts().MSVCCompat) 11591 FriendSawTagOutsideEnclosingNamespace = true; 11592 else 11593 F.erase(); 11594 } 11595 } 11596 F.done(); 11597 11598 // Diagnose this MSVC extension in the easy case where lookup would have 11599 // unambiguously found something outside the enclosing namespace. 11600 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 11601 NamedDecl *ND = Previous.getFoundDecl(); 11602 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 11603 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 11604 } 11605 } 11606 11607 // Note: there used to be some attempt at recovery here. 11608 if (Previous.isAmbiguous()) 11609 return nullptr; 11610 11611 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 11612 // FIXME: This makes sure that we ignore the contexts associated 11613 // with C structs, unions, and enums when looking for a matching 11614 // tag declaration or definition. See the similar lookup tweak 11615 // in Sema::LookupName; is there a better way to deal with this? 11616 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 11617 SearchDC = SearchDC->getParent(); 11618 } 11619 } 11620 11621 if (Previous.isSingleResult() && 11622 Previous.getFoundDecl()->isTemplateParameter()) { 11623 // Maybe we will complain about the shadowed template parameter. 11624 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 11625 // Just pretend that we didn't see the previous declaration. 11626 Previous.clear(); 11627 } 11628 11629 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 11630 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 11631 // This is a declaration of or a reference to "std::bad_alloc". 11632 isStdBadAlloc = true; 11633 11634 if (Previous.empty() && StdBadAlloc) { 11635 // std::bad_alloc has been implicitly declared (but made invisible to 11636 // name lookup). Fill in this implicit declaration as the previous 11637 // declaration, so that the declarations get chained appropriately. 11638 Previous.addDecl(getStdBadAlloc()); 11639 } 11640 } 11641 11642 // If we didn't find a previous declaration, and this is a reference 11643 // (or friend reference), move to the correct scope. In C++, we 11644 // also need to do a redeclaration lookup there, just in case 11645 // there's a shadow friend decl. 11646 if (Name && Previous.empty() && 11647 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11648 if (Invalid) goto CreateNewDecl; 11649 assert(SS.isEmpty()); 11650 11651 if (TUK == TUK_Reference) { 11652 // C++ [basic.scope.pdecl]p5: 11653 // -- for an elaborated-type-specifier of the form 11654 // 11655 // class-key identifier 11656 // 11657 // if the elaborated-type-specifier is used in the 11658 // decl-specifier-seq or parameter-declaration-clause of a 11659 // function defined in namespace scope, the identifier is 11660 // declared as a class-name in the namespace that contains 11661 // the declaration; otherwise, except as a friend 11662 // declaration, the identifier is declared in the smallest 11663 // non-class, non-function-prototype scope that contains the 11664 // declaration. 11665 // 11666 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 11667 // C structs and unions. 11668 // 11669 // It is an error in C++ to declare (rather than define) an enum 11670 // type, including via an elaborated type specifier. We'll 11671 // diagnose that later; for now, declare the enum in the same 11672 // scope as we would have picked for any other tag type. 11673 // 11674 // GNU C also supports this behavior as part of its incomplete 11675 // enum types extension, while GNU C++ does not. 11676 // 11677 // Find the context where we'll be declaring the tag. 11678 // FIXME: We would like to maintain the current DeclContext as the 11679 // lexical context, 11680 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 11681 SearchDC = SearchDC->getParent(); 11682 11683 // Find the scope where we'll be declaring the tag. 11684 while (S->isClassScope() || 11685 (getLangOpts().CPlusPlus && 11686 S->isFunctionPrototypeScope()) || 11687 ((S->getFlags() & Scope::DeclScope) == 0) || 11688 (S->getEntity() && S->getEntity()->isTransparentContext())) 11689 S = S->getParent(); 11690 } else { 11691 assert(TUK == TUK_Friend); 11692 // C++ [namespace.memdef]p3: 11693 // If a friend declaration in a non-local class first declares a 11694 // class or function, the friend class or function is a member of 11695 // the innermost enclosing namespace. 11696 SearchDC = SearchDC->getEnclosingNamespaceContext(); 11697 } 11698 11699 // In C++, we need to do a redeclaration lookup to properly 11700 // diagnose some problems. 11701 if (getLangOpts().CPlusPlus) { 11702 Previous.setRedeclarationKind(ForRedeclaration); 11703 LookupQualifiedName(Previous, SearchDC); 11704 } 11705 } 11706 11707 // If we have a known previous declaration to use, then use it. 11708 if (Previous.empty() && SkipBody && SkipBody->Previous) 11709 Previous.addDecl(SkipBody->Previous); 11710 11711 if (!Previous.empty()) { 11712 NamedDecl *PrevDecl = Previous.getFoundDecl(); 11713 NamedDecl *DirectPrevDecl = 11714 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 11715 11716 // It's okay to have a tag decl in the same scope as a typedef 11717 // which hides a tag decl in the same scope. Finding this 11718 // insanity with a redeclaration lookup can only actually happen 11719 // in C++. 11720 // 11721 // This is also okay for elaborated-type-specifiers, which is 11722 // technically forbidden by the current standard but which is 11723 // okay according to the likely resolution of an open issue; 11724 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 11725 if (getLangOpts().CPlusPlus) { 11726 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11727 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 11728 TagDecl *Tag = TT->getDecl(); 11729 if (Tag->getDeclName() == Name && 11730 Tag->getDeclContext()->getRedeclContext() 11731 ->Equals(TD->getDeclContext()->getRedeclContext())) { 11732 PrevDecl = Tag; 11733 Previous.clear(); 11734 Previous.addDecl(Tag); 11735 Previous.resolveKind(); 11736 } 11737 } 11738 } 11739 } 11740 11741 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 11742 // If this is a use of a previous tag, or if the tag is already declared 11743 // in the same scope (so that the definition/declaration completes or 11744 // rementions the tag), reuse the decl. 11745 if (TUK == TUK_Reference || TUK == TUK_Friend || 11746 isDeclInScope(DirectPrevDecl, SearchDC, S, 11747 SS.isNotEmpty() || isExplicitSpecialization)) { 11748 // Make sure that this wasn't declared as an enum and now used as a 11749 // struct or something similar. 11750 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 11751 TUK == TUK_Definition, KWLoc, 11752 *Name)) { 11753 bool SafeToContinue 11754 = (PrevTagDecl->getTagKind() != TTK_Enum && 11755 Kind != TTK_Enum); 11756 if (SafeToContinue) 11757 Diag(KWLoc, diag::err_use_with_wrong_tag) 11758 << Name 11759 << FixItHint::CreateReplacement(SourceRange(KWLoc), 11760 PrevTagDecl->getKindName()); 11761 else 11762 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 11763 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 11764 11765 if (SafeToContinue) 11766 Kind = PrevTagDecl->getTagKind(); 11767 else { 11768 // Recover by making this an anonymous redefinition. 11769 Name = nullptr; 11770 Previous.clear(); 11771 Invalid = true; 11772 } 11773 } 11774 11775 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 11776 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 11777 11778 // If this is an elaborated-type-specifier for a scoped enumeration, 11779 // the 'class' keyword is not necessary and not permitted. 11780 if (TUK == TUK_Reference || TUK == TUK_Friend) { 11781 if (ScopedEnum) 11782 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 11783 << PrevEnum->isScoped() 11784 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 11785 return PrevTagDecl; 11786 } 11787 11788 QualType EnumUnderlyingTy; 11789 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11790 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 11791 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 11792 EnumUnderlyingTy = QualType(T, 0); 11793 11794 // All conflicts with previous declarations are recovered by 11795 // returning the previous declaration, unless this is a definition, 11796 // in which case we want the caller to bail out. 11797 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11798 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11799 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11800 } 11801 11802 // C++11 [class.mem]p1: 11803 // A member shall not be declared twice in the member-specification, 11804 // except that a nested class or member class template can be declared 11805 // and then later defined. 11806 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11807 S->isDeclScope(PrevDecl)) { 11808 Diag(NameLoc, diag::ext_member_redeclared); 11809 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11810 } 11811 11812 if (!Invalid) { 11813 // If this is a use, just return the declaration we found, unless 11814 // we have attributes. 11815 11816 // FIXME: In the future, return a variant or some other clue 11817 // for the consumer of this Decl to know it doesn't own it. 11818 // For our current ASTs this shouldn't be a problem, but will 11819 // need to be changed with DeclGroups. 11820 if (!Attr && 11821 ((TUK == TUK_Reference && 11822 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11823 || TUK == TUK_Friend)) 11824 return PrevTagDecl; 11825 11826 // Diagnose attempts to redefine a tag. 11827 if (TUK == TUK_Definition) { 11828 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 11829 // If we're defining a specialization and the previous definition 11830 // is from an implicit instantiation, don't emit an error 11831 // here; we'll catch this in the general case below. 11832 bool IsExplicitSpecializationAfterInstantiation = false; 11833 if (isExplicitSpecialization) { 11834 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11835 IsExplicitSpecializationAfterInstantiation = 11836 RD->getTemplateSpecializationKind() != 11837 TSK_ExplicitSpecialization; 11838 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11839 IsExplicitSpecializationAfterInstantiation = 11840 ED->getTemplateSpecializationKind() != 11841 TSK_ExplicitSpecialization; 11842 } 11843 11844 NamedDecl *Hidden = nullptr; 11845 if (SkipBody && getLangOpts().CPlusPlus && 11846 !hasVisibleDefinition(Def, &Hidden)) { 11847 // There is a definition of this tag, but it is not visible. We 11848 // explicitly make use of C++'s one definition rule here, and 11849 // assume that this definition is identical to the hidden one 11850 // we already have. Make the existing definition visible and 11851 // use it in place of this one. 11852 SkipBody->ShouldSkip = true; 11853 makeMergedDefinitionVisible(Hidden, KWLoc); 11854 return Def; 11855 } else if (!IsExplicitSpecializationAfterInstantiation) { 11856 // A redeclaration in function prototype scope in C isn't 11857 // visible elsewhere, so merely issue a warning. 11858 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11859 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11860 else 11861 Diag(NameLoc, diag::err_redefinition) << Name; 11862 Diag(Def->getLocation(), diag::note_previous_definition); 11863 // If this is a redefinition, recover by making this 11864 // struct be anonymous, which will make any later 11865 // references get the previous definition. 11866 Name = nullptr; 11867 Previous.clear(); 11868 Invalid = true; 11869 } 11870 } else { 11871 // If the type is currently being defined, complain 11872 // about a nested redefinition. 11873 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 11874 if (TD->isBeingDefined()) { 11875 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11876 Diag(PrevTagDecl->getLocation(), 11877 diag::note_previous_definition); 11878 Name = nullptr; 11879 Previous.clear(); 11880 Invalid = true; 11881 } 11882 } 11883 11884 // Okay, this is definition of a previously declared or referenced 11885 // tag. We're going to create a new Decl for it. 11886 } 11887 11888 // Okay, we're going to make a redeclaration. If this is some kind 11889 // of reference, make sure we build the redeclaration in the same DC 11890 // as the original, and ignore the current access specifier. 11891 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11892 SearchDC = PrevTagDecl->getDeclContext(); 11893 AS = AS_none; 11894 } 11895 } 11896 // If we get here we have (another) forward declaration or we 11897 // have a definition. Just create a new decl. 11898 11899 } else { 11900 // If we get here, this is a definition of a new tag type in a nested 11901 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11902 // new decl/type. We set PrevDecl to NULL so that the entities 11903 // have distinct types. 11904 Previous.clear(); 11905 } 11906 // If we get here, we're going to create a new Decl. If PrevDecl 11907 // is non-NULL, it's a definition of the tag declared by 11908 // PrevDecl. If it's NULL, we have a new definition. 11909 11910 11911 // Otherwise, PrevDecl is not a tag, but was found with tag 11912 // lookup. This is only actually possible in C++, where a few 11913 // things like templates still live in the tag namespace. 11914 } else { 11915 // Use a better diagnostic if an elaborated-type-specifier 11916 // found the wrong kind of type on the first 11917 // (non-redeclaration) lookup. 11918 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11919 !Previous.isForRedeclaration()) { 11920 unsigned Kind = 0; 11921 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11922 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11923 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11924 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11925 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11926 Invalid = true; 11927 11928 // Otherwise, only diagnose if the declaration is in scope. 11929 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11930 SS.isNotEmpty() || isExplicitSpecialization)) { 11931 // do nothing 11932 11933 // Diagnose implicit declarations introduced by elaborated types. 11934 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11935 unsigned Kind = 0; 11936 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11937 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11938 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11939 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11940 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11941 Invalid = true; 11942 11943 // Otherwise it's a declaration. Call out a particularly common 11944 // case here. 11945 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11946 unsigned Kind = 0; 11947 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11948 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11949 << Name << Kind << TND->getUnderlyingType(); 11950 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11951 Invalid = true; 11952 11953 // Otherwise, diagnose. 11954 } else { 11955 // The tag name clashes with something else in the target scope, 11956 // issue an error and recover by making this tag be anonymous. 11957 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11958 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11959 Name = nullptr; 11960 Invalid = true; 11961 } 11962 11963 // The existing declaration isn't relevant to us; we're in a 11964 // new scope, so clear out the previous declaration. 11965 Previous.clear(); 11966 } 11967 } 11968 11969 CreateNewDecl: 11970 11971 TagDecl *PrevDecl = nullptr; 11972 if (Previous.isSingleResult()) 11973 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11974 11975 // If there is an identifier, use the location of the identifier as the 11976 // location of the decl, otherwise use the location of the struct/union 11977 // keyword. 11978 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11979 11980 // Otherwise, create a new declaration. If there is a previous 11981 // declaration of the same entity, the two will be linked via 11982 // PrevDecl. 11983 TagDecl *New; 11984 11985 bool IsForwardReference = false; 11986 if (Kind == TTK_Enum) { 11987 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11988 // enum X { A, B, C } D; D should chain to X. 11989 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11990 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11991 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11992 // If this is an undefined enum, warn. 11993 if (TUK != TUK_Definition && !Invalid) { 11994 TagDecl *Def; 11995 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11996 cast<EnumDecl>(New)->isFixed()) { 11997 // C++0x: 7.2p2: opaque-enum-declaration. 11998 // Conflicts are diagnosed above. Do nothing. 11999 } 12000 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 12001 Diag(Loc, diag::ext_forward_ref_enum_def) 12002 << New; 12003 Diag(Def->getLocation(), diag::note_previous_definition); 12004 } else { 12005 unsigned DiagID = diag::ext_forward_ref_enum; 12006 if (getLangOpts().MSVCCompat) 12007 DiagID = diag::ext_ms_forward_ref_enum; 12008 else if (getLangOpts().CPlusPlus) 12009 DiagID = diag::err_forward_ref_enum; 12010 Diag(Loc, DiagID); 12011 12012 // If this is a forward-declared reference to an enumeration, make a 12013 // note of it; we won't actually be introducing the declaration into 12014 // the declaration context. 12015 if (TUK == TUK_Reference) 12016 IsForwardReference = true; 12017 } 12018 } 12019 12020 if (EnumUnderlying) { 12021 EnumDecl *ED = cast<EnumDecl>(New); 12022 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12023 ED->setIntegerTypeSourceInfo(TI); 12024 else 12025 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 12026 ED->setPromotionType(ED->getIntegerType()); 12027 } 12028 12029 } else { 12030 // struct/union/class 12031 12032 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 12033 // struct X { int A; } D; D should chain to X. 12034 if (getLangOpts().CPlusPlus) { 12035 // FIXME: Look for a way to use RecordDecl for simple structs. 12036 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12037 cast_or_null<CXXRecordDecl>(PrevDecl)); 12038 12039 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 12040 StdBadAlloc = cast<CXXRecordDecl>(New); 12041 } else 12042 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12043 cast_or_null<RecordDecl>(PrevDecl)); 12044 } 12045 12046 // C++11 [dcl.type]p3: 12047 // A type-specifier-seq shall not define a class or enumeration [...]. 12048 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 12049 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 12050 << Context.getTagDeclType(New); 12051 Invalid = true; 12052 } 12053 12054 // Maybe add qualifier info. 12055 if (SS.isNotEmpty()) { 12056 if (SS.isSet()) { 12057 // If this is either a declaration or a definition, check the 12058 // nested-name-specifier against the current context. We don't do this 12059 // for explicit specializations, because they have similar checking 12060 // (with more specific diagnostics) in the call to 12061 // CheckMemberSpecialization, below. 12062 if (!isExplicitSpecialization && 12063 (TUK == TUK_Definition || TUK == TUK_Declaration) && 12064 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 12065 Invalid = true; 12066 12067 New->setQualifierInfo(SS.getWithLocInContext(Context)); 12068 if (TemplateParameterLists.size() > 0) { 12069 New->setTemplateParameterListsInfo(Context, 12070 TemplateParameterLists.size(), 12071 TemplateParameterLists.data()); 12072 } 12073 } 12074 else 12075 Invalid = true; 12076 } 12077 12078 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 12079 // Add alignment attributes if necessary; these attributes are checked when 12080 // the ASTContext lays out the structure. 12081 // 12082 // It is important for implementing the correct semantics that this 12083 // happen here (in act on tag decl). The #pragma pack stack is 12084 // maintained as a result of parser callbacks which can occur at 12085 // many points during the parsing of a struct declaration (because 12086 // the #pragma tokens are effectively skipped over during the 12087 // parsing of the struct). 12088 if (TUK == TUK_Definition) { 12089 AddAlignmentAttributesForRecord(RD); 12090 AddMsStructLayoutForRecord(RD); 12091 } 12092 } 12093 12094 if (ModulePrivateLoc.isValid()) { 12095 if (isExplicitSpecialization) 12096 Diag(New->getLocation(), diag::err_module_private_specialization) 12097 << 2 12098 << FixItHint::CreateRemoval(ModulePrivateLoc); 12099 // __module_private__ does not apply to local classes. However, we only 12100 // diagnose this as an error when the declaration specifiers are 12101 // freestanding. Here, we just ignore the __module_private__. 12102 else if (!SearchDC->isFunctionOrMethod()) 12103 New->setModulePrivate(); 12104 } 12105 12106 // If this is a specialization of a member class (of a class template), 12107 // check the specialization. 12108 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 12109 Invalid = true; 12110 12111 // If we're declaring or defining a tag in function prototype scope in C, 12112 // note that this type can only be used within the function and add it to 12113 // the list of decls to inject into the function definition scope. 12114 if ((Name || Kind == TTK_Enum) && 12115 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 12116 if (getLangOpts().CPlusPlus) { 12117 // C++ [dcl.fct]p6: 12118 // Types shall not be defined in return or parameter types. 12119 if (TUK == TUK_Definition && !IsTypeSpecifier) { 12120 Diag(Loc, diag::err_type_defined_in_param_type) 12121 << Name; 12122 Invalid = true; 12123 } 12124 } else { 12125 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 12126 } 12127 DeclsInPrototypeScope.push_back(New); 12128 } 12129 12130 if (Invalid) 12131 New->setInvalidDecl(); 12132 12133 if (Attr) 12134 ProcessDeclAttributeList(S, New, Attr); 12135 12136 // Set the lexical context. If the tag has a C++ scope specifier, the 12137 // lexical context will be different from the semantic context. 12138 New->setLexicalDeclContext(CurContext); 12139 12140 // Mark this as a friend decl if applicable. 12141 // In Microsoft mode, a friend declaration also acts as a forward 12142 // declaration so we always pass true to setObjectOfFriendDecl to make 12143 // the tag name visible. 12144 if (TUK == TUK_Friend) 12145 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 12146 12147 // Set the access specifier. 12148 if (!Invalid && SearchDC->isRecord()) 12149 SetMemberAccessSpecifier(New, PrevDecl, AS); 12150 12151 if (TUK == TUK_Definition) 12152 New->startDefinition(); 12153 12154 // If this has an identifier, add it to the scope stack. 12155 if (TUK == TUK_Friend) { 12156 // We might be replacing an existing declaration in the lookup tables; 12157 // if so, borrow its access specifier. 12158 if (PrevDecl) 12159 New->setAccess(PrevDecl->getAccess()); 12160 12161 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 12162 DC->makeDeclVisibleInContext(New); 12163 if (Name) // can be null along some error paths 12164 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12165 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 12166 } else if (Name) { 12167 S = getNonFieldDeclScope(S); 12168 PushOnScopeChains(New, S, !IsForwardReference); 12169 if (IsForwardReference) 12170 SearchDC->makeDeclVisibleInContext(New); 12171 12172 } else { 12173 CurContext->addDecl(New); 12174 } 12175 12176 // If this is the C FILE type, notify the AST context. 12177 if (IdentifierInfo *II = New->getIdentifier()) 12178 if (!New->isInvalidDecl() && 12179 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 12180 II->isStr("FILE")) 12181 Context.setFILEDecl(New); 12182 12183 if (PrevDecl) 12184 mergeDeclAttributes(New, PrevDecl); 12185 12186 // If there's a #pragma GCC visibility in scope, set the visibility of this 12187 // record. 12188 AddPushedVisibilityAttribute(New); 12189 12190 OwnedDecl = true; 12191 // In C++, don't return an invalid declaration. We can't recover well from 12192 // the cases where we make the type anonymous. 12193 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 12194 } 12195 12196 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 12197 AdjustDeclIfTemplate(TagD); 12198 TagDecl *Tag = cast<TagDecl>(TagD); 12199 12200 // Enter the tag context. 12201 PushDeclContext(S, Tag); 12202 12203 ActOnDocumentableDecl(TagD); 12204 12205 // If there's a #pragma GCC visibility in scope, set the visibility of this 12206 // record. 12207 AddPushedVisibilityAttribute(Tag); 12208 } 12209 12210 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 12211 assert(isa<ObjCContainerDecl>(IDecl) && 12212 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 12213 DeclContext *OCD = cast<DeclContext>(IDecl); 12214 assert(getContainingDC(OCD) == CurContext && 12215 "The next DeclContext should be lexically contained in the current one."); 12216 CurContext = OCD; 12217 return IDecl; 12218 } 12219 12220 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 12221 SourceLocation FinalLoc, 12222 bool IsFinalSpelledSealed, 12223 SourceLocation LBraceLoc) { 12224 AdjustDeclIfTemplate(TagD); 12225 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 12226 12227 FieldCollector->StartClass(); 12228 12229 if (!Record->getIdentifier()) 12230 return; 12231 12232 if (FinalLoc.isValid()) 12233 Record->addAttr(new (Context) 12234 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 12235 12236 // C++ [class]p2: 12237 // [...] The class-name is also inserted into the scope of the 12238 // class itself; this is known as the injected-class-name. For 12239 // purposes of access checking, the injected-class-name is treated 12240 // as if it were a public member name. 12241 CXXRecordDecl *InjectedClassName 12242 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 12243 Record->getLocStart(), Record->getLocation(), 12244 Record->getIdentifier(), 12245 /*PrevDecl=*/nullptr, 12246 /*DelayTypeCreation=*/true); 12247 Context.getTypeDeclType(InjectedClassName, Record); 12248 InjectedClassName->setImplicit(); 12249 InjectedClassName->setAccess(AS_public); 12250 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 12251 InjectedClassName->setDescribedClassTemplate(Template); 12252 PushOnScopeChains(InjectedClassName, S); 12253 assert(InjectedClassName->isInjectedClassName() && 12254 "Broken injected-class-name"); 12255 } 12256 12257 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 12258 SourceLocation RBraceLoc) { 12259 AdjustDeclIfTemplate(TagD); 12260 TagDecl *Tag = cast<TagDecl>(TagD); 12261 Tag->setRBraceLoc(RBraceLoc); 12262 12263 // Make sure we "complete" the definition even it is invalid. 12264 if (Tag->isBeingDefined()) { 12265 assert(Tag->isInvalidDecl() && "We should already have completed it"); 12266 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12267 RD->completeDefinition(); 12268 } 12269 12270 if (isa<CXXRecordDecl>(Tag)) 12271 FieldCollector->FinishClass(); 12272 12273 // Exit this scope of this tag's definition. 12274 PopDeclContext(); 12275 12276 if (getCurLexicalContext()->isObjCContainer() && 12277 Tag->getDeclContext()->isFileContext()) 12278 Tag->setTopLevelDeclInObjCContainer(); 12279 12280 // Notify the consumer that we've defined a tag. 12281 if (!Tag->isInvalidDecl()) 12282 Consumer.HandleTagDeclDefinition(Tag); 12283 } 12284 12285 void Sema::ActOnObjCContainerFinishDefinition() { 12286 // Exit this scope of this interface definition. 12287 PopDeclContext(); 12288 } 12289 12290 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 12291 assert(DC == CurContext && "Mismatch of container contexts"); 12292 OriginalLexicalContext = DC; 12293 ActOnObjCContainerFinishDefinition(); 12294 } 12295 12296 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 12297 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 12298 OriginalLexicalContext = nullptr; 12299 } 12300 12301 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 12302 AdjustDeclIfTemplate(TagD); 12303 TagDecl *Tag = cast<TagDecl>(TagD); 12304 Tag->setInvalidDecl(); 12305 12306 // Make sure we "complete" the definition even it is invalid. 12307 if (Tag->isBeingDefined()) { 12308 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12309 RD->completeDefinition(); 12310 } 12311 12312 // We're undoing ActOnTagStartDefinition here, not 12313 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 12314 // the FieldCollector. 12315 12316 PopDeclContext(); 12317 } 12318 12319 // Note that FieldName may be null for anonymous bitfields. 12320 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 12321 IdentifierInfo *FieldName, 12322 QualType FieldTy, bool IsMsStruct, 12323 Expr *BitWidth, bool *ZeroWidth) { 12324 // Default to true; that shouldn't confuse checks for emptiness 12325 if (ZeroWidth) 12326 *ZeroWidth = true; 12327 12328 // C99 6.7.2.1p4 - verify the field type. 12329 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 12330 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 12331 // Handle incomplete types with specific error. 12332 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12333 return ExprError(); 12334 if (FieldName) 12335 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12336 << FieldName << FieldTy << BitWidth->getSourceRange(); 12337 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12338 << FieldTy << BitWidth->getSourceRange(); 12339 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12340 UPPC_BitFieldWidth)) 12341 return ExprError(); 12342 12343 // If the bit-width is type- or value-dependent, don't try to check 12344 // it now. 12345 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12346 return BitWidth; 12347 12348 llvm::APSInt Value; 12349 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12350 if (ICE.isInvalid()) 12351 return ICE; 12352 BitWidth = ICE.get(); 12353 12354 if (Value != 0 && ZeroWidth) 12355 *ZeroWidth = false; 12356 12357 // Zero-width bitfield is ok for anonymous field. 12358 if (Value == 0 && FieldName) 12359 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12360 12361 if (Value.isSigned() && Value.isNegative()) { 12362 if (FieldName) 12363 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12364 << FieldName << Value.toString(10); 12365 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12366 << Value.toString(10); 12367 } 12368 12369 if (!FieldTy->isDependentType()) { 12370 uint64_t TypeSize = Context.getTypeSize(FieldTy); 12371 if (Value.getZExtValue() > TypeSize) { 12372 if (!getLangOpts().CPlusPlus || IsMsStruct || 12373 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12374 if (FieldName) 12375 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 12376 << FieldName << (unsigned)Value.getZExtValue() 12377 << (unsigned)TypeSize; 12378 12379 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 12380 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12381 } 12382 12383 if (FieldName) 12384 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 12385 << FieldName << (unsigned)Value.getZExtValue() 12386 << (unsigned)TypeSize; 12387 else 12388 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 12389 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12390 } 12391 } 12392 12393 return BitWidth; 12394 } 12395 12396 /// ActOnField - Each field of a C struct/union is passed into this in order 12397 /// to create a FieldDecl object for it. 12398 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 12399 Declarator &D, Expr *BitfieldWidth) { 12400 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 12401 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 12402 /*InitStyle=*/ICIS_NoInit, AS_public); 12403 return Res; 12404 } 12405 12406 /// HandleField - Analyze a field of a C struct or a C++ data member. 12407 /// 12408 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 12409 SourceLocation DeclStart, 12410 Declarator &D, Expr *BitWidth, 12411 InClassInitStyle InitStyle, 12412 AccessSpecifier AS) { 12413 IdentifierInfo *II = D.getIdentifier(); 12414 SourceLocation Loc = DeclStart; 12415 if (II) Loc = D.getIdentifierLoc(); 12416 12417 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12418 QualType T = TInfo->getType(); 12419 if (getLangOpts().CPlusPlus) { 12420 CheckExtraCXXDefaultArguments(D); 12421 12422 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12423 UPPC_DataMemberType)) { 12424 D.setInvalidType(); 12425 T = Context.IntTy; 12426 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12427 } 12428 } 12429 12430 // TR 18037 does not allow fields to be declared with address spaces. 12431 if (T.getQualifiers().hasAddressSpace()) { 12432 Diag(Loc, diag::err_field_with_address_space); 12433 D.setInvalidType(); 12434 } 12435 12436 // OpenCL 1.2 spec, s6.9 r: 12437 // The event type cannot be used to declare a structure or union field. 12438 if (LangOpts.OpenCL && T->isEventT()) { 12439 Diag(Loc, diag::err_event_t_struct_field); 12440 D.setInvalidType(); 12441 } 12442 12443 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12444 12445 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12446 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12447 diag::err_invalid_thread) 12448 << DeclSpec::getSpecifierName(TSCS); 12449 12450 // Check to see if this name was declared as a member previously 12451 NamedDecl *PrevDecl = nullptr; 12452 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12453 LookupName(Previous, S); 12454 switch (Previous.getResultKind()) { 12455 case LookupResult::Found: 12456 case LookupResult::FoundUnresolvedValue: 12457 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12458 break; 12459 12460 case LookupResult::FoundOverloaded: 12461 PrevDecl = Previous.getRepresentativeDecl(); 12462 break; 12463 12464 case LookupResult::NotFound: 12465 case LookupResult::NotFoundInCurrentInstantiation: 12466 case LookupResult::Ambiguous: 12467 break; 12468 } 12469 Previous.suppressDiagnostics(); 12470 12471 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12472 // Maybe we will complain about the shadowed template parameter. 12473 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12474 // Just pretend that we didn't see the previous declaration. 12475 PrevDecl = nullptr; 12476 } 12477 12478 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12479 PrevDecl = nullptr; 12480 12481 bool Mutable 12482 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 12483 SourceLocation TSSL = D.getLocStart(); 12484 FieldDecl *NewFD 12485 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 12486 TSSL, AS, PrevDecl, &D); 12487 12488 if (NewFD->isInvalidDecl()) 12489 Record->setInvalidDecl(); 12490 12491 if (D.getDeclSpec().isModulePrivateSpecified()) 12492 NewFD->setModulePrivate(); 12493 12494 if (NewFD->isInvalidDecl() && PrevDecl) { 12495 // Don't introduce NewFD into scope; there's already something 12496 // with the same name in the same scope. 12497 } else if (II) { 12498 PushOnScopeChains(NewFD, S); 12499 } else 12500 Record->addDecl(NewFD); 12501 12502 return NewFD; 12503 } 12504 12505 /// \brief Build a new FieldDecl and check its well-formedness. 12506 /// 12507 /// This routine builds a new FieldDecl given the fields name, type, 12508 /// record, etc. \p PrevDecl should refer to any previous declaration 12509 /// with the same name and in the same scope as the field to be 12510 /// created. 12511 /// 12512 /// \returns a new FieldDecl. 12513 /// 12514 /// \todo The Declarator argument is a hack. It will be removed once 12515 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 12516 TypeSourceInfo *TInfo, 12517 RecordDecl *Record, SourceLocation Loc, 12518 bool Mutable, Expr *BitWidth, 12519 InClassInitStyle InitStyle, 12520 SourceLocation TSSL, 12521 AccessSpecifier AS, NamedDecl *PrevDecl, 12522 Declarator *D) { 12523 IdentifierInfo *II = Name.getAsIdentifierInfo(); 12524 bool InvalidDecl = false; 12525 if (D) InvalidDecl = D->isInvalidType(); 12526 12527 // If we receive a broken type, recover by assuming 'int' and 12528 // marking this declaration as invalid. 12529 if (T.isNull()) { 12530 InvalidDecl = true; 12531 T = Context.IntTy; 12532 } 12533 12534 QualType EltTy = Context.getBaseElementType(T); 12535 if (!EltTy->isDependentType()) { 12536 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 12537 // Fields of incomplete type force their record to be invalid. 12538 Record->setInvalidDecl(); 12539 InvalidDecl = true; 12540 } else { 12541 NamedDecl *Def; 12542 EltTy->isIncompleteType(&Def); 12543 if (Def && Def->isInvalidDecl()) { 12544 Record->setInvalidDecl(); 12545 InvalidDecl = true; 12546 } 12547 } 12548 } 12549 12550 // OpenCL v1.2 s6.9.c: bitfields are not supported. 12551 if (BitWidth && getLangOpts().OpenCL) { 12552 Diag(Loc, diag::err_opencl_bitfields); 12553 InvalidDecl = true; 12554 } 12555 12556 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12557 // than a variably modified type. 12558 if (!InvalidDecl && T->isVariablyModifiedType()) { 12559 bool SizeIsNegative; 12560 llvm::APSInt Oversized; 12561 12562 TypeSourceInfo *FixedTInfo = 12563 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 12564 SizeIsNegative, 12565 Oversized); 12566 if (FixedTInfo) { 12567 Diag(Loc, diag::warn_illegal_constant_array_size); 12568 TInfo = FixedTInfo; 12569 T = FixedTInfo->getType(); 12570 } else { 12571 if (SizeIsNegative) 12572 Diag(Loc, diag::err_typecheck_negative_array_size); 12573 else if (Oversized.getBoolValue()) 12574 Diag(Loc, diag::err_array_too_large) 12575 << Oversized.toString(10); 12576 else 12577 Diag(Loc, diag::err_typecheck_field_variable_size); 12578 InvalidDecl = true; 12579 } 12580 } 12581 12582 // Fields can not have abstract class types 12583 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 12584 diag::err_abstract_type_in_decl, 12585 AbstractFieldType)) 12586 InvalidDecl = true; 12587 12588 bool ZeroWidth = false; 12589 if (InvalidDecl) 12590 BitWidth = nullptr; 12591 // If this is declared as a bit-field, check the bit-field. 12592 if (BitWidth) { 12593 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 12594 &ZeroWidth).get(); 12595 if (!BitWidth) { 12596 InvalidDecl = true; 12597 BitWidth = nullptr; 12598 ZeroWidth = false; 12599 } 12600 } 12601 12602 // Check that 'mutable' is consistent with the type of the declaration. 12603 if (!InvalidDecl && Mutable) { 12604 unsigned DiagID = 0; 12605 if (T->isReferenceType()) 12606 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 12607 : diag::err_mutable_reference; 12608 else if (T.isConstQualified()) 12609 DiagID = diag::err_mutable_const; 12610 12611 if (DiagID) { 12612 SourceLocation ErrLoc = Loc; 12613 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 12614 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 12615 Diag(ErrLoc, DiagID); 12616 if (DiagID != diag::ext_mutable_reference) { 12617 Mutable = false; 12618 InvalidDecl = true; 12619 } 12620 } 12621 } 12622 12623 // C++11 [class.union]p8 (DR1460): 12624 // At most one variant member of a union may have a 12625 // brace-or-equal-initializer. 12626 if (InitStyle != ICIS_NoInit) 12627 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 12628 12629 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 12630 BitWidth, Mutable, InitStyle); 12631 if (InvalidDecl) 12632 NewFD->setInvalidDecl(); 12633 12634 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 12635 Diag(Loc, diag::err_duplicate_member) << II; 12636 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12637 NewFD->setInvalidDecl(); 12638 } 12639 12640 if (!InvalidDecl && getLangOpts().CPlusPlus) { 12641 if (Record->isUnion()) { 12642 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12643 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12644 if (RDecl->getDefinition()) { 12645 // C++ [class.union]p1: An object of a class with a non-trivial 12646 // constructor, a non-trivial copy constructor, a non-trivial 12647 // destructor, or a non-trivial copy assignment operator 12648 // cannot be a member of a union, nor can an array of such 12649 // objects. 12650 if (CheckNontrivialField(NewFD)) 12651 NewFD->setInvalidDecl(); 12652 } 12653 } 12654 12655 // C++ [class.union]p1: If a union contains a member of reference type, 12656 // the program is ill-formed, except when compiling with MSVC extensions 12657 // enabled. 12658 if (EltTy->isReferenceType()) { 12659 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 12660 diag::ext_union_member_of_reference_type : 12661 diag::err_union_member_of_reference_type) 12662 << NewFD->getDeclName() << EltTy; 12663 if (!getLangOpts().MicrosoftExt) 12664 NewFD->setInvalidDecl(); 12665 } 12666 } 12667 } 12668 12669 // FIXME: We need to pass in the attributes given an AST 12670 // representation, not a parser representation. 12671 if (D) { 12672 // FIXME: The current scope is almost... but not entirely... correct here. 12673 ProcessDeclAttributes(getCurScope(), NewFD, *D); 12674 12675 if (NewFD->hasAttrs()) 12676 CheckAlignasUnderalignment(NewFD); 12677 } 12678 12679 // In auto-retain/release, infer strong retension for fields of 12680 // retainable type. 12681 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 12682 NewFD->setInvalidDecl(); 12683 12684 if (T.isObjCGCWeak()) 12685 Diag(Loc, diag::warn_attribute_weak_on_field); 12686 12687 NewFD->setAccess(AS); 12688 return NewFD; 12689 } 12690 12691 bool Sema::CheckNontrivialField(FieldDecl *FD) { 12692 assert(FD); 12693 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 12694 12695 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 12696 return false; 12697 12698 QualType EltTy = Context.getBaseElementType(FD->getType()); 12699 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12700 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12701 if (RDecl->getDefinition()) { 12702 // We check for copy constructors before constructors 12703 // because otherwise we'll never get complaints about 12704 // copy constructors. 12705 12706 CXXSpecialMember member = CXXInvalid; 12707 // We're required to check for any non-trivial constructors. Since the 12708 // implicit default constructor is suppressed if there are any 12709 // user-declared constructors, we just need to check that there is a 12710 // trivial default constructor and a trivial copy constructor. (We don't 12711 // worry about move constructors here, since this is a C++98 check.) 12712 if (RDecl->hasNonTrivialCopyConstructor()) 12713 member = CXXCopyConstructor; 12714 else if (!RDecl->hasTrivialDefaultConstructor()) 12715 member = CXXDefaultConstructor; 12716 else if (RDecl->hasNonTrivialCopyAssignment()) 12717 member = CXXCopyAssignment; 12718 else if (RDecl->hasNonTrivialDestructor()) 12719 member = CXXDestructor; 12720 12721 if (member != CXXInvalid) { 12722 if (!getLangOpts().CPlusPlus11 && 12723 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 12724 // Objective-C++ ARC: it is an error to have a non-trivial field of 12725 // a union. However, system headers in Objective-C programs 12726 // occasionally have Objective-C lifetime objects within unions, 12727 // and rather than cause the program to fail, we make those 12728 // members unavailable. 12729 SourceLocation Loc = FD->getLocation(); 12730 if (getSourceManager().isInSystemHeader(Loc)) { 12731 if (!FD->hasAttr<UnavailableAttr>()) 12732 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12733 "this system field has retaining ownership", 12734 Loc)); 12735 return false; 12736 } 12737 } 12738 12739 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 12740 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 12741 diag::err_illegal_union_or_anon_struct_member) 12742 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 12743 DiagnoseNontrivial(RDecl, member); 12744 return !getLangOpts().CPlusPlus11; 12745 } 12746 } 12747 } 12748 12749 return false; 12750 } 12751 12752 /// TranslateIvarVisibility - Translate visibility from a token ID to an 12753 /// AST enum value. 12754 static ObjCIvarDecl::AccessControl 12755 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 12756 switch (ivarVisibility) { 12757 default: llvm_unreachable("Unknown visitibility kind"); 12758 case tok::objc_private: return ObjCIvarDecl::Private; 12759 case tok::objc_public: return ObjCIvarDecl::Public; 12760 case tok::objc_protected: return ObjCIvarDecl::Protected; 12761 case tok::objc_package: return ObjCIvarDecl::Package; 12762 } 12763 } 12764 12765 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 12766 /// in order to create an IvarDecl object for it. 12767 Decl *Sema::ActOnIvar(Scope *S, 12768 SourceLocation DeclStart, 12769 Declarator &D, Expr *BitfieldWidth, 12770 tok::ObjCKeywordKind Visibility) { 12771 12772 IdentifierInfo *II = D.getIdentifier(); 12773 Expr *BitWidth = (Expr*)BitfieldWidth; 12774 SourceLocation Loc = DeclStart; 12775 if (II) Loc = D.getIdentifierLoc(); 12776 12777 // FIXME: Unnamed fields can be handled in various different ways, for 12778 // example, unnamed unions inject all members into the struct namespace! 12779 12780 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12781 QualType T = TInfo->getType(); 12782 12783 if (BitWidth) { 12784 // 6.7.2.1p3, 6.7.2.1p4 12785 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 12786 if (!BitWidth) 12787 D.setInvalidType(); 12788 } else { 12789 // Not a bitfield. 12790 12791 // validate II. 12792 12793 } 12794 if (T->isReferenceType()) { 12795 Diag(Loc, diag::err_ivar_reference_type); 12796 D.setInvalidType(); 12797 } 12798 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12799 // than a variably modified type. 12800 else if (T->isVariablyModifiedType()) { 12801 Diag(Loc, diag::err_typecheck_ivar_variable_size); 12802 D.setInvalidType(); 12803 } 12804 12805 // Get the visibility (access control) for this ivar. 12806 ObjCIvarDecl::AccessControl ac = 12807 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 12808 : ObjCIvarDecl::None; 12809 // Must set ivar's DeclContext to its enclosing interface. 12810 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 12811 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 12812 return nullptr; 12813 ObjCContainerDecl *EnclosingContext; 12814 if (ObjCImplementationDecl *IMPDecl = 12815 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12816 if (LangOpts.ObjCRuntime.isFragile()) { 12817 // Case of ivar declared in an implementation. Context is that of its class. 12818 EnclosingContext = IMPDecl->getClassInterface(); 12819 assert(EnclosingContext && "Implementation has no class interface!"); 12820 } 12821 else 12822 EnclosingContext = EnclosingDecl; 12823 } else { 12824 if (ObjCCategoryDecl *CDecl = 12825 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12826 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12827 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12828 return nullptr; 12829 } 12830 } 12831 EnclosingContext = EnclosingDecl; 12832 } 12833 12834 // Construct the decl. 12835 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12836 DeclStart, Loc, II, T, 12837 TInfo, ac, (Expr *)BitfieldWidth); 12838 12839 if (II) { 12840 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12841 ForRedeclaration); 12842 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12843 && !isa<TagDecl>(PrevDecl)) { 12844 Diag(Loc, diag::err_duplicate_member) << II; 12845 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12846 NewID->setInvalidDecl(); 12847 } 12848 } 12849 12850 // Process attributes attached to the ivar. 12851 ProcessDeclAttributes(S, NewID, D); 12852 12853 if (D.isInvalidType()) 12854 NewID->setInvalidDecl(); 12855 12856 // In ARC, infer 'retaining' for ivars of retainable type. 12857 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12858 NewID->setInvalidDecl(); 12859 12860 if (D.getDeclSpec().isModulePrivateSpecified()) 12861 NewID->setModulePrivate(); 12862 12863 if (II) { 12864 // FIXME: When interfaces are DeclContexts, we'll need to add 12865 // these to the interface. 12866 S->AddDecl(NewID); 12867 IdResolver.AddDecl(NewID); 12868 } 12869 12870 if (LangOpts.ObjCRuntime.isNonFragile() && 12871 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12872 Diag(Loc, diag::warn_ivars_in_interface); 12873 12874 return NewID; 12875 } 12876 12877 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12878 /// class and class extensions. For every class \@interface and class 12879 /// extension \@interface, if the last ivar is a bitfield of any type, 12880 /// then add an implicit `char :0` ivar to the end of that interface. 12881 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12882 SmallVectorImpl<Decl *> &AllIvarDecls) { 12883 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12884 return; 12885 12886 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12887 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12888 12889 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12890 return; 12891 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12892 if (!ID) { 12893 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12894 if (!CD->IsClassExtension()) 12895 return; 12896 } 12897 // No need to add this to end of @implementation. 12898 else 12899 return; 12900 } 12901 // All conditions are met. Add a new bitfield to the tail end of ivars. 12902 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12903 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12904 12905 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12906 DeclLoc, DeclLoc, nullptr, 12907 Context.CharTy, 12908 Context.getTrivialTypeSourceInfo(Context.CharTy, 12909 DeclLoc), 12910 ObjCIvarDecl::Private, BW, 12911 true); 12912 AllIvarDecls.push_back(Ivar); 12913 } 12914 12915 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12916 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12917 SourceLocation RBrac, AttributeList *Attr) { 12918 assert(EnclosingDecl && "missing record or interface decl"); 12919 12920 // If this is an Objective-C @implementation or category and we have 12921 // new fields here we should reset the layout of the interface since 12922 // it will now change. 12923 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12924 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12925 switch (DC->getKind()) { 12926 default: break; 12927 case Decl::ObjCCategory: 12928 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12929 break; 12930 case Decl::ObjCImplementation: 12931 Context. 12932 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12933 break; 12934 } 12935 } 12936 12937 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12938 12939 // Start counting up the number of named members; make sure to include 12940 // members of anonymous structs and unions in the total. 12941 unsigned NumNamedMembers = 0; 12942 if (Record) { 12943 for (const auto *I : Record->decls()) { 12944 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12945 if (IFD->getDeclName()) 12946 ++NumNamedMembers; 12947 } 12948 } 12949 12950 // Verify that all the fields are okay. 12951 SmallVector<FieldDecl*, 32> RecFields; 12952 12953 bool ARCErrReported = false; 12954 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12955 i != end; ++i) { 12956 FieldDecl *FD = cast<FieldDecl>(*i); 12957 12958 // Get the type for the field. 12959 const Type *FDTy = FD->getType().getTypePtr(); 12960 12961 if (!FD->isAnonymousStructOrUnion()) { 12962 // Remember all fields written by the user. 12963 RecFields.push_back(FD); 12964 } 12965 12966 // If the field is already invalid for some reason, don't emit more 12967 // diagnostics about it. 12968 if (FD->isInvalidDecl()) { 12969 EnclosingDecl->setInvalidDecl(); 12970 continue; 12971 } 12972 12973 // C99 6.7.2.1p2: 12974 // A structure or union shall not contain a member with 12975 // incomplete or function type (hence, a structure shall not 12976 // contain an instance of itself, but may contain a pointer to 12977 // an instance of itself), except that the last member of a 12978 // structure with more than one named member may have incomplete 12979 // array type; such a structure (and any union containing, 12980 // possibly recursively, a member that is such a structure) 12981 // shall not be a member of a structure or an element of an 12982 // array. 12983 if (FDTy->isFunctionType()) { 12984 // Field declared as a function. 12985 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12986 << FD->getDeclName(); 12987 FD->setInvalidDecl(); 12988 EnclosingDecl->setInvalidDecl(); 12989 continue; 12990 } else if (FDTy->isIncompleteArrayType() && Record && 12991 ((i + 1 == Fields.end() && !Record->isUnion()) || 12992 ((getLangOpts().MicrosoftExt || 12993 getLangOpts().CPlusPlus) && 12994 (i + 1 == Fields.end() || Record->isUnion())))) { 12995 // Flexible array member. 12996 // Microsoft and g++ is more permissive regarding flexible array. 12997 // It will accept flexible array in union and also 12998 // as the sole element of a struct/class. 12999 unsigned DiagID = 0; 13000 if (Record->isUnion()) 13001 DiagID = getLangOpts().MicrosoftExt 13002 ? diag::ext_flexible_array_union_ms 13003 : getLangOpts().CPlusPlus 13004 ? diag::ext_flexible_array_union_gnu 13005 : diag::err_flexible_array_union; 13006 else if (Fields.size() == 1) 13007 DiagID = getLangOpts().MicrosoftExt 13008 ? diag::ext_flexible_array_empty_aggregate_ms 13009 : getLangOpts().CPlusPlus 13010 ? diag::ext_flexible_array_empty_aggregate_gnu 13011 : NumNamedMembers < 1 13012 ? diag::err_flexible_array_empty_aggregate 13013 : 0; 13014 13015 if (DiagID) 13016 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 13017 << Record->getTagKind(); 13018 // While the layout of types that contain virtual bases is not specified 13019 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 13020 // virtual bases after the derived members. This would make a flexible 13021 // array member declared at the end of an object not adjacent to the end 13022 // of the type. 13023 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 13024 if (RD->getNumVBases() != 0) 13025 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 13026 << FD->getDeclName() << Record->getTagKind(); 13027 if (!getLangOpts().C99) 13028 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 13029 << FD->getDeclName() << Record->getTagKind(); 13030 13031 // If the element type has a non-trivial destructor, we would not 13032 // implicitly destroy the elements, so disallow it for now. 13033 // 13034 // FIXME: GCC allows this. We should probably either implicitly delete 13035 // the destructor of the containing class, or just allow this. 13036 QualType BaseElem = Context.getBaseElementType(FD->getType()); 13037 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 13038 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 13039 << FD->getDeclName() << FD->getType(); 13040 FD->setInvalidDecl(); 13041 EnclosingDecl->setInvalidDecl(); 13042 continue; 13043 } 13044 // Okay, we have a legal flexible array member at the end of the struct. 13045 Record->setHasFlexibleArrayMember(true); 13046 } else if (!FDTy->isDependentType() && 13047 RequireCompleteType(FD->getLocation(), FD->getType(), 13048 diag::err_field_incomplete)) { 13049 // Incomplete type 13050 FD->setInvalidDecl(); 13051 EnclosingDecl->setInvalidDecl(); 13052 continue; 13053 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 13054 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 13055 // A type which contains a flexible array member is considered to be a 13056 // flexible array member. 13057 Record->setHasFlexibleArrayMember(true); 13058 if (!Record->isUnion()) { 13059 // If this is a struct/class and this is not the last element, reject 13060 // it. Note that GCC supports variable sized arrays in the middle of 13061 // structures. 13062 if (i + 1 != Fields.end()) 13063 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 13064 << FD->getDeclName() << FD->getType(); 13065 else { 13066 // We support flexible arrays at the end of structs in 13067 // other structs as an extension. 13068 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 13069 << FD->getDeclName(); 13070 } 13071 } 13072 } 13073 if (isa<ObjCContainerDecl>(EnclosingDecl) && 13074 RequireNonAbstractType(FD->getLocation(), FD->getType(), 13075 diag::err_abstract_type_in_decl, 13076 AbstractIvarType)) { 13077 // Ivars can not have abstract class types 13078 FD->setInvalidDecl(); 13079 } 13080 if (Record && FDTTy->getDecl()->hasObjectMember()) 13081 Record->setHasObjectMember(true); 13082 if (Record && FDTTy->getDecl()->hasVolatileMember()) 13083 Record->setHasVolatileMember(true); 13084 } else if (FDTy->isObjCObjectType()) { 13085 /// A field cannot be an Objective-c object 13086 Diag(FD->getLocation(), diag::err_statically_allocated_object) 13087 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 13088 QualType T = Context.getObjCObjectPointerType(FD->getType()); 13089 FD->setType(T); 13090 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 13091 (!getLangOpts().CPlusPlus || Record->isUnion())) { 13092 // It's an error in ARC if a field has lifetime. 13093 // We don't want to report this in a system header, though, 13094 // so we just make the field unavailable. 13095 // FIXME: that's really not sufficient; we need to make the type 13096 // itself invalid to, say, initialize or copy. 13097 QualType T = FD->getType(); 13098 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 13099 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 13100 SourceLocation loc = FD->getLocation(); 13101 if (getSourceManager().isInSystemHeader(loc)) { 13102 if (!FD->hasAttr<UnavailableAttr>()) { 13103 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 13104 "this system field has retaining ownership", 13105 loc)); 13106 } 13107 } else { 13108 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 13109 << T->isBlockPointerType() << Record->getTagKind(); 13110 } 13111 ARCErrReported = true; 13112 } 13113 } else if (getLangOpts().ObjC1 && 13114 getLangOpts().getGC() != LangOptions::NonGC && 13115 Record && !Record->hasObjectMember()) { 13116 if (FD->getType()->isObjCObjectPointerType() || 13117 FD->getType().isObjCGCStrong()) 13118 Record->setHasObjectMember(true); 13119 else if (Context.getAsArrayType(FD->getType())) { 13120 QualType BaseType = Context.getBaseElementType(FD->getType()); 13121 if (BaseType->isRecordType() && 13122 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 13123 Record->setHasObjectMember(true); 13124 else if (BaseType->isObjCObjectPointerType() || 13125 BaseType.isObjCGCStrong()) 13126 Record->setHasObjectMember(true); 13127 } 13128 } 13129 if (Record && FD->getType().isVolatileQualified()) 13130 Record->setHasVolatileMember(true); 13131 // Keep track of the number of named members. 13132 if (FD->getIdentifier()) 13133 ++NumNamedMembers; 13134 } 13135 13136 // Okay, we successfully defined 'Record'. 13137 if (Record) { 13138 bool Completed = false; 13139 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 13140 if (!CXXRecord->isInvalidDecl()) { 13141 // Set access bits correctly on the directly-declared conversions. 13142 for (CXXRecordDecl::conversion_iterator 13143 I = CXXRecord->conversion_begin(), 13144 E = CXXRecord->conversion_end(); I != E; ++I) 13145 I.setAccess((*I)->getAccess()); 13146 13147 if (!CXXRecord->isDependentType()) { 13148 if (CXXRecord->hasUserDeclaredDestructor()) { 13149 // Adjust user-defined destructor exception spec. 13150 if (getLangOpts().CPlusPlus11) 13151 AdjustDestructorExceptionSpec(CXXRecord, 13152 CXXRecord->getDestructor()); 13153 } 13154 13155 // Add any implicitly-declared members to this class. 13156 AddImplicitlyDeclaredMembersToClass(CXXRecord); 13157 13158 // If we have virtual base classes, we may end up finding multiple 13159 // final overriders for a given virtual function. Check for this 13160 // problem now. 13161 if (CXXRecord->getNumVBases()) { 13162 CXXFinalOverriderMap FinalOverriders; 13163 CXXRecord->getFinalOverriders(FinalOverriders); 13164 13165 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 13166 MEnd = FinalOverriders.end(); 13167 M != MEnd; ++M) { 13168 for (OverridingMethods::iterator SO = M->second.begin(), 13169 SOEnd = M->second.end(); 13170 SO != SOEnd; ++SO) { 13171 assert(SO->second.size() > 0 && 13172 "Virtual function without overridding functions?"); 13173 if (SO->second.size() == 1) 13174 continue; 13175 13176 // C++ [class.virtual]p2: 13177 // In a derived class, if a virtual member function of a base 13178 // class subobject has more than one final overrider the 13179 // program is ill-formed. 13180 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 13181 << (const NamedDecl *)M->first << Record; 13182 Diag(M->first->getLocation(), 13183 diag::note_overridden_virtual_function); 13184 for (OverridingMethods::overriding_iterator 13185 OM = SO->second.begin(), 13186 OMEnd = SO->second.end(); 13187 OM != OMEnd; ++OM) 13188 Diag(OM->Method->getLocation(), diag::note_final_overrider) 13189 << (const NamedDecl *)M->first << OM->Method->getParent(); 13190 13191 Record->setInvalidDecl(); 13192 } 13193 } 13194 CXXRecord->completeDefinition(&FinalOverriders); 13195 Completed = true; 13196 } 13197 } 13198 } 13199 } 13200 13201 if (!Completed) 13202 Record->completeDefinition(); 13203 13204 if (Record->hasAttrs()) { 13205 CheckAlignasUnderalignment(Record); 13206 13207 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 13208 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 13209 IA->getRange(), IA->getBestCase(), 13210 IA->getSemanticSpelling()); 13211 } 13212 13213 // Check if the structure/union declaration is a type that can have zero 13214 // size in C. For C this is a language extension, for C++ it may cause 13215 // compatibility problems. 13216 bool CheckForZeroSize; 13217 if (!getLangOpts().CPlusPlus) { 13218 CheckForZeroSize = true; 13219 } else { 13220 // For C++ filter out types that cannot be referenced in C code. 13221 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 13222 CheckForZeroSize = 13223 CXXRecord->getLexicalDeclContext()->isExternCContext() && 13224 !CXXRecord->isDependentType() && 13225 CXXRecord->isCLike(); 13226 } 13227 if (CheckForZeroSize) { 13228 bool ZeroSize = true; 13229 bool IsEmpty = true; 13230 unsigned NonBitFields = 0; 13231 for (RecordDecl::field_iterator I = Record->field_begin(), 13232 E = Record->field_end(); 13233 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 13234 IsEmpty = false; 13235 if (I->isUnnamedBitfield()) { 13236 if (I->getBitWidthValue(Context) > 0) 13237 ZeroSize = false; 13238 } else { 13239 ++NonBitFields; 13240 QualType FieldType = I->getType(); 13241 if (FieldType->isIncompleteType() || 13242 !Context.getTypeSizeInChars(FieldType).isZero()) 13243 ZeroSize = false; 13244 } 13245 } 13246 13247 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 13248 // allowed in C++, but warn if its declaration is inside 13249 // extern "C" block. 13250 if (ZeroSize) { 13251 Diag(RecLoc, getLangOpts().CPlusPlus ? 13252 diag::warn_zero_size_struct_union_in_extern_c : 13253 diag::warn_zero_size_struct_union_compat) 13254 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 13255 } 13256 13257 // Structs without named members are extension in C (C99 6.7.2.1p7), 13258 // but are accepted by GCC. 13259 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 13260 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 13261 diag::ext_no_named_members_in_struct_union) 13262 << Record->isUnion(); 13263 } 13264 } 13265 } else { 13266 ObjCIvarDecl **ClsFields = 13267 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 13268 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 13269 ID->setEndOfDefinitionLoc(RBrac); 13270 // Add ivar's to class's DeclContext. 13271 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13272 ClsFields[i]->setLexicalDeclContext(ID); 13273 ID->addDecl(ClsFields[i]); 13274 } 13275 // Must enforce the rule that ivars in the base classes may not be 13276 // duplicates. 13277 if (ID->getSuperClass()) 13278 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 13279 } else if (ObjCImplementationDecl *IMPDecl = 13280 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13281 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 13282 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 13283 // Ivar declared in @implementation never belongs to the implementation. 13284 // Only it is in implementation's lexical context. 13285 ClsFields[I]->setLexicalDeclContext(IMPDecl); 13286 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 13287 IMPDecl->setIvarLBraceLoc(LBrac); 13288 IMPDecl->setIvarRBraceLoc(RBrac); 13289 } else if (ObjCCategoryDecl *CDecl = 13290 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13291 // case of ivars in class extension; all other cases have been 13292 // reported as errors elsewhere. 13293 // FIXME. Class extension does not have a LocEnd field. 13294 // CDecl->setLocEnd(RBrac); 13295 // Add ivar's to class extension's DeclContext. 13296 // Diagnose redeclaration of private ivars. 13297 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 13298 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13299 if (IDecl) { 13300 if (const ObjCIvarDecl *ClsIvar = 13301 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 13302 Diag(ClsFields[i]->getLocation(), 13303 diag::err_duplicate_ivar_declaration); 13304 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 13305 continue; 13306 } 13307 for (const auto *Ext : IDecl->known_extensions()) { 13308 if (const ObjCIvarDecl *ClsExtIvar 13309 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 13310 Diag(ClsFields[i]->getLocation(), 13311 diag::err_duplicate_ivar_declaration); 13312 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 13313 continue; 13314 } 13315 } 13316 } 13317 ClsFields[i]->setLexicalDeclContext(CDecl); 13318 CDecl->addDecl(ClsFields[i]); 13319 } 13320 CDecl->setIvarLBraceLoc(LBrac); 13321 CDecl->setIvarRBraceLoc(RBrac); 13322 } 13323 } 13324 13325 if (Attr) 13326 ProcessDeclAttributeList(S, Record, Attr); 13327 } 13328 13329 /// \brief Determine whether the given integral value is representable within 13330 /// the given type T. 13331 static bool isRepresentableIntegerValue(ASTContext &Context, 13332 llvm::APSInt &Value, 13333 QualType T) { 13334 assert(T->isIntegralType(Context) && "Integral type required!"); 13335 unsigned BitWidth = Context.getIntWidth(T); 13336 13337 if (Value.isUnsigned() || Value.isNonNegative()) { 13338 if (T->isSignedIntegerOrEnumerationType()) 13339 --BitWidth; 13340 return Value.getActiveBits() <= BitWidth; 13341 } 13342 return Value.getMinSignedBits() <= BitWidth; 13343 } 13344 13345 // \brief Given an integral type, return the next larger integral type 13346 // (or a NULL type of no such type exists). 13347 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13348 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13349 // enum checking below. 13350 assert(T->isIntegralType(Context) && "Integral type required!"); 13351 const unsigned NumTypes = 4; 13352 QualType SignedIntegralTypes[NumTypes] = { 13353 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13354 }; 13355 QualType UnsignedIntegralTypes[NumTypes] = { 13356 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13357 Context.UnsignedLongLongTy 13358 }; 13359 13360 unsigned BitWidth = Context.getTypeSize(T); 13361 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13362 : UnsignedIntegralTypes; 13363 for (unsigned I = 0; I != NumTypes; ++I) 13364 if (Context.getTypeSize(Types[I]) > BitWidth) 13365 return Types[I]; 13366 13367 return QualType(); 13368 } 13369 13370 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13371 EnumConstantDecl *LastEnumConst, 13372 SourceLocation IdLoc, 13373 IdentifierInfo *Id, 13374 Expr *Val) { 13375 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13376 llvm::APSInt EnumVal(IntWidth); 13377 QualType EltTy; 13378 13379 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13380 Val = nullptr; 13381 13382 if (Val) 13383 Val = DefaultLvalueConversion(Val).get(); 13384 13385 if (Val) { 13386 if (Enum->isDependentType() || Val->isTypeDependent()) 13387 EltTy = Context.DependentTy; 13388 else { 13389 SourceLocation ExpLoc; 13390 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 13391 !getLangOpts().MSVCCompat) { 13392 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 13393 // constant-expression in the enumerator-definition shall be a converted 13394 // constant expression of the underlying type. 13395 EltTy = Enum->getIntegerType(); 13396 ExprResult Converted = 13397 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 13398 CCEK_Enumerator); 13399 if (Converted.isInvalid()) 13400 Val = nullptr; 13401 else 13402 Val = Converted.get(); 13403 } else if (!Val->isValueDependent() && 13404 !(Val = VerifyIntegerConstantExpression(Val, 13405 &EnumVal).get())) { 13406 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 13407 } else { 13408 if (Enum->isFixed()) { 13409 EltTy = Enum->getIntegerType(); 13410 13411 // In Obj-C and Microsoft mode, require the enumeration value to be 13412 // representable in the underlying type of the enumeration. In C++11, 13413 // we perform a non-narrowing conversion as part of converted constant 13414 // expression checking. 13415 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13416 if (getLangOpts().MSVCCompat) { 13417 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 13418 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13419 } else 13420 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 13421 } else 13422 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13423 } else if (getLangOpts().CPlusPlus) { 13424 // C++11 [dcl.enum]p5: 13425 // If the underlying type is not fixed, the type of each enumerator 13426 // is the type of its initializing value: 13427 // - If an initializer is specified for an enumerator, the 13428 // initializing value has the same type as the expression. 13429 EltTy = Val->getType(); 13430 } else { 13431 // C99 6.7.2.2p2: 13432 // The expression that defines the value of an enumeration constant 13433 // shall be an integer constant expression that has a value 13434 // representable as an int. 13435 13436 // Complain if the value is not representable in an int. 13437 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 13438 Diag(IdLoc, diag::ext_enum_value_not_int) 13439 << EnumVal.toString(10) << Val->getSourceRange() 13440 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 13441 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 13442 // Force the type of the expression to 'int'. 13443 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 13444 } 13445 EltTy = Val->getType(); 13446 } 13447 } 13448 } 13449 } 13450 13451 if (!Val) { 13452 if (Enum->isDependentType()) 13453 EltTy = Context.DependentTy; 13454 else if (!LastEnumConst) { 13455 // C++0x [dcl.enum]p5: 13456 // If the underlying type is not fixed, the type of each enumerator 13457 // is the type of its initializing value: 13458 // - If no initializer is specified for the first enumerator, the 13459 // initializing value has an unspecified integral type. 13460 // 13461 // GCC uses 'int' for its unspecified integral type, as does 13462 // C99 6.7.2.2p3. 13463 if (Enum->isFixed()) { 13464 EltTy = Enum->getIntegerType(); 13465 } 13466 else { 13467 EltTy = Context.IntTy; 13468 } 13469 } else { 13470 // Assign the last value + 1. 13471 EnumVal = LastEnumConst->getInitVal(); 13472 ++EnumVal; 13473 EltTy = LastEnumConst->getType(); 13474 13475 // Check for overflow on increment. 13476 if (EnumVal < LastEnumConst->getInitVal()) { 13477 // C++0x [dcl.enum]p5: 13478 // If the underlying type is not fixed, the type of each enumerator 13479 // is the type of its initializing value: 13480 // 13481 // - Otherwise the type of the initializing value is the same as 13482 // the type of the initializing value of the preceding enumerator 13483 // unless the incremented value is not representable in that type, 13484 // in which case the type is an unspecified integral type 13485 // sufficient to contain the incremented value. If no such type 13486 // exists, the program is ill-formed. 13487 QualType T = getNextLargerIntegralType(Context, EltTy); 13488 if (T.isNull() || Enum->isFixed()) { 13489 // There is no integral type larger enough to represent this 13490 // value. Complain, then allow the value to wrap around. 13491 EnumVal = LastEnumConst->getInitVal(); 13492 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 13493 ++EnumVal; 13494 if (Enum->isFixed()) 13495 // When the underlying type is fixed, this is ill-formed. 13496 Diag(IdLoc, diag::err_enumerator_wrapped) 13497 << EnumVal.toString(10) 13498 << EltTy; 13499 else 13500 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 13501 << EnumVal.toString(10); 13502 } else { 13503 EltTy = T; 13504 } 13505 13506 // Retrieve the last enumerator's value, extent that type to the 13507 // type that is supposed to be large enough to represent the incremented 13508 // value, then increment. 13509 EnumVal = LastEnumConst->getInitVal(); 13510 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13511 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 13512 ++EnumVal; 13513 13514 // If we're not in C++, diagnose the overflow of enumerator values, 13515 // which in C99 means that the enumerator value is not representable in 13516 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 13517 // permits enumerator values that are representable in some larger 13518 // integral type. 13519 if (!getLangOpts().CPlusPlus && !T.isNull()) 13520 Diag(IdLoc, diag::warn_enum_value_overflow); 13521 } else if (!getLangOpts().CPlusPlus && 13522 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13523 // Enforce C99 6.7.2.2p2 even when we compute the next value. 13524 Diag(IdLoc, diag::ext_enum_value_not_int) 13525 << EnumVal.toString(10) << 1; 13526 } 13527 } 13528 } 13529 13530 if (!EltTy->isDependentType()) { 13531 // Make the enumerator value match the signedness and size of the 13532 // enumerator's type. 13533 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 13534 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13535 } 13536 13537 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 13538 Val, EnumVal); 13539 } 13540 13541 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 13542 SourceLocation IILoc) { 13543 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 13544 !getLangOpts().CPlusPlus) 13545 return SkipBodyInfo(); 13546 13547 // We have an anonymous enum definition. Look up the first enumerator to 13548 // determine if we should merge the definition with an existing one and 13549 // skip the body. 13550 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 13551 ForRedeclaration); 13552 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 13553 NamedDecl *Hidden; 13554 if (PrevECD && 13555 !hasVisibleDefinition(cast<NamedDecl>(PrevECD->getDeclContext()), 13556 &Hidden)) { 13557 SkipBodyInfo Skip; 13558 Skip.Previous = Hidden; 13559 return Skip; 13560 } 13561 13562 return SkipBodyInfo(); 13563 } 13564 13565 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 13566 SourceLocation IdLoc, IdentifierInfo *Id, 13567 AttributeList *Attr, 13568 SourceLocation EqualLoc, Expr *Val) { 13569 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 13570 EnumConstantDecl *LastEnumConst = 13571 cast_or_null<EnumConstantDecl>(lastEnumConst); 13572 13573 // The scope passed in may not be a decl scope. Zip up the scope tree until 13574 // we find one that is. 13575 S = getNonFieldDeclScope(S); 13576 13577 // Verify that there isn't already something declared with this name in this 13578 // scope. 13579 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 13580 ForRedeclaration); 13581 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13582 // Maybe we will complain about the shadowed template parameter. 13583 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 13584 // Just pretend that we didn't see the previous declaration. 13585 PrevDecl = nullptr; 13586 } 13587 13588 if (PrevDecl) { 13589 // When in C++, we may get a TagDecl with the same name; in this case the 13590 // enum constant will 'hide' the tag. 13591 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 13592 "Received TagDecl when not in C++!"); 13593 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 13594 if (isa<EnumConstantDecl>(PrevDecl)) 13595 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 13596 else 13597 Diag(IdLoc, diag::err_redefinition) << Id; 13598 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13599 return nullptr; 13600 } 13601 } 13602 13603 // C++ [class.mem]p15: 13604 // If T is the name of a class, then each of the following shall have a name 13605 // different from T: 13606 // - every enumerator of every member of class T that is an unscoped 13607 // enumerated type 13608 if (CXXRecordDecl *Record 13609 = dyn_cast<CXXRecordDecl>( 13610 TheEnumDecl->getDeclContext()->getRedeclContext())) 13611 if (!TheEnumDecl->isScoped() && 13612 Record->getIdentifier() && Record->getIdentifier() == Id) 13613 Diag(IdLoc, diag::err_member_name_of_class) << Id; 13614 13615 EnumConstantDecl *New = 13616 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 13617 13618 if (New) { 13619 // Process attributes. 13620 if (Attr) ProcessDeclAttributeList(S, New, Attr); 13621 13622 // Register this decl in the current scope stack. 13623 New->setAccess(TheEnumDecl->getAccess()); 13624 PushOnScopeChains(New, S); 13625 } 13626 13627 ActOnDocumentableDecl(New); 13628 13629 return New; 13630 } 13631 13632 // Returns true when the enum initial expression does not trigger the 13633 // duplicate enum warning. A few common cases are exempted as follows: 13634 // Element2 = Element1 13635 // Element2 = Element1 + 1 13636 // Element2 = Element1 - 1 13637 // Where Element2 and Element1 are from the same enum. 13638 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 13639 Expr *InitExpr = ECD->getInitExpr(); 13640 if (!InitExpr) 13641 return true; 13642 InitExpr = InitExpr->IgnoreImpCasts(); 13643 13644 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 13645 if (!BO->isAdditiveOp()) 13646 return true; 13647 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 13648 if (!IL) 13649 return true; 13650 if (IL->getValue() != 1) 13651 return true; 13652 13653 InitExpr = BO->getLHS(); 13654 } 13655 13656 // This checks if the elements are from the same enum. 13657 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 13658 if (!DRE) 13659 return true; 13660 13661 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 13662 if (!EnumConstant) 13663 return true; 13664 13665 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 13666 Enum) 13667 return true; 13668 13669 return false; 13670 } 13671 13672 struct DupKey { 13673 int64_t val; 13674 bool isTombstoneOrEmptyKey; 13675 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 13676 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 13677 }; 13678 13679 static DupKey GetDupKey(const llvm::APSInt& Val) { 13680 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 13681 false); 13682 } 13683 13684 struct DenseMapInfoDupKey { 13685 static DupKey getEmptyKey() { return DupKey(0, true); } 13686 static DupKey getTombstoneKey() { return DupKey(1, true); } 13687 static unsigned getHashValue(const DupKey Key) { 13688 return (unsigned)(Key.val * 37); 13689 } 13690 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 13691 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 13692 LHS.val == RHS.val; 13693 } 13694 }; 13695 13696 // Emits a warning when an element is implicitly set a value that 13697 // a previous element has already been set to. 13698 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 13699 EnumDecl *Enum, 13700 QualType EnumType) { 13701 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 13702 return; 13703 // Avoid anonymous enums 13704 if (!Enum->getIdentifier()) 13705 return; 13706 13707 // Only check for small enums. 13708 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 13709 return; 13710 13711 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 13712 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 13713 13714 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 13715 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 13716 ValueToVectorMap; 13717 13718 DuplicatesVector DupVector; 13719 ValueToVectorMap EnumMap; 13720 13721 // Populate the EnumMap with all values represented by enum constants without 13722 // an initialier. 13723 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13724 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13725 13726 // Null EnumConstantDecl means a previous diagnostic has been emitted for 13727 // this constant. Skip this enum since it may be ill-formed. 13728 if (!ECD) { 13729 return; 13730 } 13731 13732 if (ECD->getInitExpr()) 13733 continue; 13734 13735 DupKey Key = GetDupKey(ECD->getInitVal()); 13736 DeclOrVector &Entry = EnumMap[Key]; 13737 13738 // First time encountering this value. 13739 if (Entry.isNull()) 13740 Entry = ECD; 13741 } 13742 13743 // Create vectors for any values that has duplicates. 13744 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13745 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 13746 if (!ValidDuplicateEnum(ECD, Enum)) 13747 continue; 13748 13749 DupKey Key = GetDupKey(ECD->getInitVal()); 13750 13751 DeclOrVector& Entry = EnumMap[Key]; 13752 if (Entry.isNull()) 13753 continue; 13754 13755 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 13756 // Ensure constants are different. 13757 if (D == ECD) 13758 continue; 13759 13760 // Create new vector and push values onto it. 13761 ECDVector *Vec = new ECDVector(); 13762 Vec->push_back(D); 13763 Vec->push_back(ECD); 13764 13765 // Update entry to point to the duplicates vector. 13766 Entry = Vec; 13767 13768 // Store the vector somewhere we can consult later for quick emission of 13769 // diagnostics. 13770 DupVector.push_back(Vec); 13771 continue; 13772 } 13773 13774 ECDVector *Vec = Entry.get<ECDVector*>(); 13775 // Make sure constants are not added more than once. 13776 if (*Vec->begin() == ECD) 13777 continue; 13778 13779 Vec->push_back(ECD); 13780 } 13781 13782 // Emit diagnostics. 13783 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 13784 DupVectorEnd = DupVector.end(); 13785 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 13786 ECDVector *Vec = *DupVectorIter; 13787 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 13788 13789 // Emit warning for one enum constant. 13790 ECDVector::iterator I = Vec->begin(); 13791 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 13792 << (*I)->getName() << (*I)->getInitVal().toString(10) 13793 << (*I)->getSourceRange(); 13794 ++I; 13795 13796 // Emit one note for each of the remaining enum constants with 13797 // the same value. 13798 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 13799 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 13800 << (*I)->getName() << (*I)->getInitVal().toString(10) 13801 << (*I)->getSourceRange(); 13802 delete Vec; 13803 } 13804 } 13805 13806 bool 13807 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 13808 bool AllowMask) const { 13809 FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>(); 13810 assert(FEAttr && "looking for value in non-flag enum"); 13811 13812 llvm::APInt FlagMask = ~FEAttr->getFlagBits(); 13813 unsigned Width = FlagMask.getBitWidth(); 13814 13815 // We will try a zero-extended value for the regular check first. 13816 llvm::APInt ExtVal = Val.zextOrSelf(Width); 13817 13818 // A value is in a flag enum if either its bits are a subset of the enum's 13819 // flag bits (the first condition) or we are allowing masks and the same is 13820 // true of its complement (the second condition). When masks are allowed, we 13821 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 13822 // 13823 // While it's true that any value could be used as a mask, the assumption is 13824 // that a mask will have all of the insignificant bits set. Anything else is 13825 // likely a logic error. 13826 if (!(FlagMask & ExtVal)) 13827 return true; 13828 13829 if (AllowMask) { 13830 // Try a one-extended value instead. This can happen if the enum is wider 13831 // than the constant used, in C with extensions to allow for wider enums. 13832 // The mask will still have the correct behaviour, so we give the user the 13833 // benefit of the doubt. 13834 // 13835 // FIXME: This heuristic can cause weird results if the enum was extended 13836 // to a larger type and is signed, because then bit-masks of smaller types 13837 // that get extended will fall out of range (e.g. ~0x1u). We currently don't 13838 // detect that case and will get a false positive for it. In most cases, 13839 // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may 13840 // be fine just to accept this as a warning. 13841 ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth()); 13842 if (!(FlagMask & ~ExtVal)) 13843 return true; 13844 } 13845 13846 return false; 13847 } 13848 13849 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 13850 SourceLocation RBraceLoc, Decl *EnumDeclX, 13851 ArrayRef<Decl *> Elements, 13852 Scope *S, AttributeList *Attr) { 13853 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 13854 QualType EnumType = Context.getTypeDeclType(Enum); 13855 13856 if (Attr) 13857 ProcessDeclAttributeList(S, Enum, Attr); 13858 13859 if (Enum->isDependentType()) { 13860 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13861 EnumConstantDecl *ECD = 13862 cast_or_null<EnumConstantDecl>(Elements[i]); 13863 if (!ECD) continue; 13864 13865 ECD->setType(EnumType); 13866 } 13867 13868 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 13869 return; 13870 } 13871 13872 // TODO: If the result value doesn't fit in an int, it must be a long or long 13873 // long value. ISO C does not support this, but GCC does as an extension, 13874 // emit a warning. 13875 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13876 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 13877 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 13878 13879 // Verify that all the values are okay, compute the size of the values, and 13880 // reverse the list. 13881 unsigned NumNegativeBits = 0; 13882 unsigned NumPositiveBits = 0; 13883 13884 // Keep track of whether all elements have type int. 13885 bool AllElementsInt = true; 13886 13887 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13888 EnumConstantDecl *ECD = 13889 cast_or_null<EnumConstantDecl>(Elements[i]); 13890 if (!ECD) continue; // Already issued a diagnostic. 13891 13892 const llvm::APSInt &InitVal = ECD->getInitVal(); 13893 13894 // Keep track of the size of positive and negative values. 13895 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13896 NumPositiveBits = std::max(NumPositiveBits, 13897 (unsigned)InitVal.getActiveBits()); 13898 else 13899 NumNegativeBits = std::max(NumNegativeBits, 13900 (unsigned)InitVal.getMinSignedBits()); 13901 13902 // Keep track of whether every enum element has type int (very commmon). 13903 if (AllElementsInt) 13904 AllElementsInt = ECD->getType() == Context.IntTy; 13905 } 13906 13907 // Figure out the type that should be used for this enum. 13908 QualType BestType; 13909 unsigned BestWidth; 13910 13911 // C++0x N3000 [conv.prom]p3: 13912 // An rvalue of an unscoped enumeration type whose underlying 13913 // type is not fixed can be converted to an rvalue of the first 13914 // of the following types that can represent all the values of 13915 // the enumeration: int, unsigned int, long int, unsigned long 13916 // int, long long int, or unsigned long long int. 13917 // C99 6.4.4.3p2: 13918 // An identifier declared as an enumeration constant has type int. 13919 // The C99 rule is modified by a gcc extension 13920 QualType BestPromotionType; 13921 13922 bool Packed = Enum->hasAttr<PackedAttr>(); 13923 // -fshort-enums is the equivalent to specifying the packed attribute on all 13924 // enum definitions. 13925 if (LangOpts.ShortEnums) 13926 Packed = true; 13927 13928 if (Enum->isFixed()) { 13929 BestType = Enum->getIntegerType(); 13930 if (BestType->isPromotableIntegerType()) 13931 BestPromotionType = Context.getPromotedIntegerType(BestType); 13932 else 13933 BestPromotionType = BestType; 13934 13935 BestWidth = Context.getIntWidth(BestType); 13936 } 13937 else if (NumNegativeBits) { 13938 // If there is a negative value, figure out the smallest integer type (of 13939 // int/long/longlong) that fits. 13940 // If it's packed, check also if it fits a char or a short. 13941 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13942 BestType = Context.SignedCharTy; 13943 BestWidth = CharWidth; 13944 } else if (Packed && NumNegativeBits <= ShortWidth && 13945 NumPositiveBits < ShortWidth) { 13946 BestType = Context.ShortTy; 13947 BestWidth = ShortWidth; 13948 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13949 BestType = Context.IntTy; 13950 BestWidth = IntWidth; 13951 } else { 13952 BestWidth = Context.getTargetInfo().getLongWidth(); 13953 13954 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13955 BestType = Context.LongTy; 13956 } else { 13957 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13958 13959 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13960 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13961 BestType = Context.LongLongTy; 13962 } 13963 } 13964 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13965 } else { 13966 // If there is no negative value, figure out the smallest type that fits 13967 // all of the enumerator values. 13968 // If it's packed, check also if it fits a char or a short. 13969 if (Packed && NumPositiveBits <= CharWidth) { 13970 BestType = Context.UnsignedCharTy; 13971 BestPromotionType = Context.IntTy; 13972 BestWidth = CharWidth; 13973 } else if (Packed && NumPositiveBits <= ShortWidth) { 13974 BestType = Context.UnsignedShortTy; 13975 BestPromotionType = Context.IntTy; 13976 BestWidth = ShortWidth; 13977 } else if (NumPositiveBits <= IntWidth) { 13978 BestType = Context.UnsignedIntTy; 13979 BestWidth = IntWidth; 13980 BestPromotionType 13981 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13982 ? Context.UnsignedIntTy : Context.IntTy; 13983 } else if (NumPositiveBits <= 13984 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13985 BestType = Context.UnsignedLongTy; 13986 BestPromotionType 13987 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13988 ? Context.UnsignedLongTy : Context.LongTy; 13989 } else { 13990 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13991 assert(NumPositiveBits <= BestWidth && 13992 "How could an initializer get larger than ULL?"); 13993 BestType = Context.UnsignedLongLongTy; 13994 BestPromotionType 13995 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13996 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13997 } 13998 } 13999 14000 FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>(); 14001 if (FEAttr) 14002 FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0); 14003 14004 // Loop over all of the enumerator constants, changing their types to match 14005 // the type of the enum if needed. If we have a flag type, we also prepare the 14006 // FlagBits cache. 14007 for (auto *D : Elements) { 14008 auto *ECD = cast_or_null<EnumConstantDecl>(D); 14009 if (!ECD) continue; // Already issued a diagnostic. 14010 14011 // Standard C says the enumerators have int type, but we allow, as an 14012 // extension, the enumerators to be larger than int size. If each 14013 // enumerator value fits in an int, type it as an int, otherwise type it the 14014 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 14015 // that X has type 'int', not 'unsigned'. 14016 14017 // Determine whether the value fits into an int. 14018 llvm::APSInt InitVal = ECD->getInitVal(); 14019 14020 // If it fits into an integer type, force it. Otherwise force it to match 14021 // the enum decl type. 14022 QualType NewTy; 14023 unsigned NewWidth; 14024 bool NewSign; 14025 if (!getLangOpts().CPlusPlus && 14026 !Enum->isFixed() && 14027 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 14028 NewTy = Context.IntTy; 14029 NewWidth = IntWidth; 14030 NewSign = true; 14031 } else if (ECD->getType() == BestType) { 14032 // Already the right type! 14033 if (getLangOpts().CPlusPlus) 14034 // C++ [dcl.enum]p4: Following the closing brace of an 14035 // enum-specifier, each enumerator has the type of its 14036 // enumeration. 14037 ECD->setType(EnumType); 14038 goto flagbits; 14039 } else { 14040 NewTy = BestType; 14041 NewWidth = BestWidth; 14042 NewSign = BestType->isSignedIntegerOrEnumerationType(); 14043 } 14044 14045 // Adjust the APSInt value. 14046 InitVal = InitVal.extOrTrunc(NewWidth); 14047 InitVal.setIsSigned(NewSign); 14048 ECD->setInitVal(InitVal); 14049 14050 // Adjust the Expr initializer and type. 14051 if (ECD->getInitExpr() && 14052 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 14053 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 14054 CK_IntegralCast, 14055 ECD->getInitExpr(), 14056 /*base paths*/ nullptr, 14057 VK_RValue)); 14058 if (getLangOpts().CPlusPlus) 14059 // C++ [dcl.enum]p4: Following the closing brace of an 14060 // enum-specifier, each enumerator has the type of its 14061 // enumeration. 14062 ECD->setType(EnumType); 14063 else 14064 ECD->setType(NewTy); 14065 14066 flagbits: 14067 // Check to see if we have a constant with exactly one bit set. Note that x 14068 // & (x - 1) will be nonzero if and only if x has more than one bit set. 14069 if (FEAttr) { 14070 llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth); 14071 if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) { 14072 FEAttr->getFlagBits() |= ExtVal; 14073 } 14074 } 14075 } 14076 14077 if (FEAttr) { 14078 for (Decl *D : Elements) { 14079 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 14080 if (!ECD) continue; // Already issued a diagnostic. 14081 14082 llvm::APSInt InitVal = ECD->getInitVal(); 14083 if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true)) 14084 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 14085 << ECD << Enum; 14086 } 14087 } 14088 14089 14090 14091 Enum->completeDefinition(BestType, BestPromotionType, 14092 NumPositiveBits, NumNegativeBits); 14093 14094 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 14095 14096 // Now that the enum type is defined, ensure it's not been underaligned. 14097 if (Enum->hasAttrs()) 14098 CheckAlignasUnderalignment(Enum); 14099 } 14100 14101 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 14102 SourceLocation StartLoc, 14103 SourceLocation EndLoc) { 14104 StringLiteral *AsmString = cast<StringLiteral>(expr); 14105 14106 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 14107 AsmString, StartLoc, 14108 EndLoc); 14109 CurContext->addDecl(New); 14110 return New; 14111 } 14112 14113 static void checkModuleImportContext(Sema &S, Module *M, 14114 SourceLocation ImportLoc, 14115 DeclContext *DC) { 14116 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 14117 switch (LSD->getLanguage()) { 14118 case LinkageSpecDecl::lang_c: 14119 if (!M->IsExternC) { 14120 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 14121 << M->getFullModuleName(); 14122 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 14123 return; 14124 } 14125 break; 14126 case LinkageSpecDecl::lang_cxx: 14127 break; 14128 } 14129 DC = LSD->getParent(); 14130 } 14131 14132 while (isa<LinkageSpecDecl>(DC)) 14133 DC = DC->getParent(); 14134 if (!isa<TranslationUnitDecl>(DC)) { 14135 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 14136 << M->getFullModuleName() << DC; 14137 S.Diag(cast<Decl>(DC)->getLocStart(), 14138 diag::note_module_import_not_at_top_level) 14139 << DC; 14140 } 14141 } 14142 14143 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 14144 SourceLocation ImportLoc, 14145 ModuleIdPath Path) { 14146 Module *Mod = 14147 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 14148 /*IsIncludeDirective=*/false); 14149 if (!Mod) 14150 return true; 14151 14152 VisibleModules.setVisible(Mod, ImportLoc); 14153 14154 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 14155 14156 // FIXME: we should support importing a submodule within a different submodule 14157 // of the same top-level module. Until we do, make it an error rather than 14158 // silently ignoring the import. 14159 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 14160 Diag(ImportLoc, diag::err_module_self_import) 14161 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 14162 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule) 14163 Diag(ImportLoc, diag::err_module_import_in_implementation) 14164 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule; 14165 14166 SmallVector<SourceLocation, 2> IdentifierLocs; 14167 Module *ModCheck = Mod; 14168 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 14169 // If we've run out of module parents, just drop the remaining identifiers. 14170 // We need the length to be consistent. 14171 if (!ModCheck) 14172 break; 14173 ModCheck = ModCheck->Parent; 14174 14175 IdentifierLocs.push_back(Path[I].second); 14176 } 14177 14178 ImportDecl *Import = ImportDecl::Create(Context, 14179 Context.getTranslationUnitDecl(), 14180 AtLoc.isValid()? AtLoc : ImportLoc, 14181 Mod, IdentifierLocs); 14182 Context.getTranslationUnitDecl()->addDecl(Import); 14183 return Import; 14184 } 14185 14186 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 14187 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14188 14189 // Determine whether we're in the #include buffer for a module. The #includes 14190 // in that buffer do not qualify as module imports; they're just an 14191 // implementation detail of us building the module. 14192 // 14193 // FIXME: Should we even get ActOnModuleInclude calls for those? 14194 bool IsInModuleIncludes = 14195 TUKind == TU_Module && 14196 getSourceManager().isWrittenInMainFile(DirectiveLoc); 14197 14198 // If this module import was due to an inclusion directive, create an 14199 // implicit import declaration to capture it in the AST. 14200 if (!IsInModuleIncludes) { 14201 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14202 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14203 DirectiveLoc, Mod, 14204 DirectiveLoc); 14205 TU->addDecl(ImportD); 14206 Consumer.HandleImplicitImportDecl(ImportD); 14207 } 14208 14209 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 14210 VisibleModules.setVisible(Mod, DirectiveLoc); 14211 } 14212 14213 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 14214 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14215 14216 if (getLangOpts().ModulesLocalVisibility) 14217 VisibleModulesStack.push_back(std::move(VisibleModules)); 14218 VisibleModules.setVisible(Mod, DirectiveLoc); 14219 } 14220 14221 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) { 14222 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14223 14224 if (getLangOpts().ModulesLocalVisibility) { 14225 VisibleModules = std::move(VisibleModulesStack.back()); 14226 VisibleModulesStack.pop_back(); 14227 VisibleModules.setVisible(Mod, DirectiveLoc); 14228 } 14229 } 14230 14231 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 14232 Module *Mod) { 14233 // Bail if we're not allowed to implicitly import a module here. 14234 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 14235 return; 14236 14237 // Create the implicit import declaration. 14238 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14239 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14240 Loc, Mod, Loc); 14241 TU->addDecl(ImportD); 14242 Consumer.HandleImplicitImportDecl(ImportD); 14243 14244 // Make the module visible. 14245 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 14246 VisibleModules.setVisible(Mod, Loc); 14247 } 14248 14249 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 14250 IdentifierInfo* AliasName, 14251 SourceLocation PragmaLoc, 14252 SourceLocation NameLoc, 14253 SourceLocation AliasNameLoc) { 14254 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 14255 LookupOrdinaryName); 14256 AsmLabelAttr *Attr = 14257 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 14258 14259 // If a declaration that: 14260 // 1) declares a function or a variable 14261 // 2) has external linkage 14262 // already exists, add a label attribute to it. 14263 if (PrevDecl && 14264 (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)) && 14265 PrevDecl->hasExternalFormalLinkage()) 14266 PrevDecl->addAttr(Attr); 14267 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 14268 else 14269 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 14270 } 14271 14272 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 14273 SourceLocation PragmaLoc, 14274 SourceLocation NameLoc) { 14275 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 14276 14277 if (PrevDecl) { 14278 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 14279 } else { 14280 (void)WeakUndeclaredIdentifiers.insert( 14281 std::pair<IdentifierInfo*,WeakInfo> 14282 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 14283 } 14284 } 14285 14286 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 14287 IdentifierInfo* AliasName, 14288 SourceLocation PragmaLoc, 14289 SourceLocation NameLoc, 14290 SourceLocation AliasNameLoc) { 14291 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 14292 LookupOrdinaryName); 14293 WeakInfo W = WeakInfo(Name, NameLoc); 14294 14295 if (PrevDecl) { 14296 if (!PrevDecl->hasAttr<AliasAttr>()) 14297 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 14298 DeclApplyPragmaWeak(TUScope, ND, W); 14299 } else { 14300 (void)WeakUndeclaredIdentifiers.insert( 14301 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 14302 } 14303 } 14304 14305 Decl *Sema::getObjCDeclContext() const { 14306 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 14307 } 14308 14309 AvailabilityResult Sema::getCurContextAvailability() const { 14310 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 14311 if (!D) 14312 return AR_Available; 14313 14314 // If we are within an Objective-C method, we should consult 14315 // both the availability of the method as well as the 14316 // enclosing class. If the class is (say) deprecated, 14317 // the entire method is considered deprecated from the 14318 // purpose of checking if the current context is deprecated. 14319 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 14320 AvailabilityResult R = MD->getAvailability(); 14321 if (R != AR_Available) 14322 return R; 14323 D = MD->getClassInterface(); 14324 } 14325 // If we are within an Objective-c @implementation, it 14326 // gets the same availability context as the @interface. 14327 else if (const ObjCImplementationDecl *ID = 14328 dyn_cast<ObjCImplementationDecl>(D)) { 14329 D = ID->getClassInterface(); 14330 } 14331 // Recover from user error. 14332 return D ? D->getAvailability() : AR_Available; 14333 } 14334