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 } 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 case tok::kw___auto_type: 115 return true; 116 117 case tok::annot_typename: 118 case tok::kw_char16_t: 119 case tok::kw_char32_t: 120 case tok::kw_typeof: 121 case tok::annot_decltype: 122 case tok::kw_decltype: 123 return getLangOpts().CPlusPlus; 124 125 default: 126 break; 127 } 128 129 return false; 130 } 131 132 namespace { 133 enum class UnqualifiedTypeNameLookupResult { 134 NotFound, 135 FoundNonType, 136 FoundType 137 }; 138 } // namespace 139 140 /// \brief Tries to perform unqualified lookup of the type decls in bases for 141 /// dependent class. 142 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 143 /// type decl, \a FoundType if only type decls are found. 144 static UnqualifiedTypeNameLookupResult 145 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 146 SourceLocation NameLoc, 147 const CXXRecordDecl *RD) { 148 if (!RD->hasDefinition()) 149 return UnqualifiedTypeNameLookupResult::NotFound; 150 // Look for type decls in base classes. 151 UnqualifiedTypeNameLookupResult FoundTypeDecl = 152 UnqualifiedTypeNameLookupResult::NotFound; 153 for (const auto &Base : RD->bases()) { 154 const CXXRecordDecl *BaseRD = nullptr; 155 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 156 BaseRD = BaseTT->getAsCXXRecordDecl(); 157 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 158 // Look for type decls in dependent base classes that have known primary 159 // templates. 160 if (!TST || !TST->isDependentType()) 161 continue; 162 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 163 if (!TD) 164 continue; 165 auto *BasePrimaryTemplate = 166 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl()); 167 if (!BasePrimaryTemplate) 168 continue; 169 BaseRD = BasePrimaryTemplate; 170 } 171 if (BaseRD) { 172 for (NamedDecl *ND : BaseRD->lookup(&II)) { 173 if (!isa<TypeDecl>(ND)) 174 return UnqualifiedTypeNameLookupResult::FoundNonType; 175 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 176 } 177 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 178 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 179 case UnqualifiedTypeNameLookupResult::FoundNonType: 180 return UnqualifiedTypeNameLookupResult::FoundNonType; 181 case UnqualifiedTypeNameLookupResult::FoundType: 182 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 183 break; 184 case UnqualifiedTypeNameLookupResult::NotFound: 185 break; 186 } 187 } 188 } 189 } 190 191 return FoundTypeDecl; 192 } 193 194 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 195 const IdentifierInfo &II, 196 SourceLocation NameLoc) { 197 // Lookup in the parent class template context, if any. 198 const CXXRecordDecl *RD = nullptr; 199 UnqualifiedTypeNameLookupResult FoundTypeDecl = 200 UnqualifiedTypeNameLookupResult::NotFound; 201 for (DeclContext *DC = S.CurContext; 202 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 203 DC = DC->getParent()) { 204 // Look for type decls in dependent base classes that have known primary 205 // templates. 206 RD = dyn_cast<CXXRecordDecl>(DC); 207 if (RD && RD->getDescribedClassTemplate()) 208 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 209 } 210 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 211 return ParsedType(); 212 213 // We found some types in dependent base classes. Recover as if the user 214 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 215 // lookup during template instantiation. 216 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 217 218 ASTContext &Context = S.Context; 219 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 220 cast<Type>(Context.getRecordType(RD))); 221 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 222 223 CXXScopeSpec SS; 224 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 225 226 TypeLocBuilder Builder; 227 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 228 DepTL.setNameLoc(NameLoc); 229 DepTL.setElaboratedKeywordLoc(SourceLocation()); 230 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 231 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 232 } 233 234 /// \brief If the identifier refers to a type name within this scope, 235 /// return the declaration of that type. 236 /// 237 /// This routine performs ordinary name lookup of the identifier II 238 /// within the given scope, with optional C++ scope specifier SS, to 239 /// determine whether the name refers to a type. If so, returns an 240 /// opaque pointer (actually a QualType) corresponding to that 241 /// type. Otherwise, returns NULL. 242 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 243 Scope *S, CXXScopeSpec *SS, 244 bool isClassName, bool HasTrailingDot, 245 ParsedType ObjectTypePtr, 246 bool IsCtorOrDtorName, 247 bool WantNontrivialTypeSourceInfo, 248 IdentifierInfo **CorrectedII) { 249 // Determine where we will perform name lookup. 250 DeclContext *LookupCtx = nullptr; 251 if (ObjectTypePtr) { 252 QualType ObjectType = ObjectTypePtr.get(); 253 if (ObjectType->isRecordType()) 254 LookupCtx = computeDeclContext(ObjectType); 255 } else if (SS && SS->isNotEmpty()) { 256 LookupCtx = computeDeclContext(*SS, false); 257 258 if (!LookupCtx) { 259 if (isDependentScopeSpecifier(*SS)) { 260 // C++ [temp.res]p3: 261 // A qualified-id that refers to a type and in which the 262 // nested-name-specifier depends on a template-parameter (14.6.2) 263 // shall be prefixed by the keyword typename to indicate that the 264 // qualified-id denotes a type, forming an 265 // elaborated-type-specifier (7.1.5.3). 266 // 267 // We therefore do not perform any name lookup if the result would 268 // refer to a member of an unknown specialization. 269 if (!isClassName && !IsCtorOrDtorName) 270 return ParsedType(); 271 272 // We know from the grammar that this name refers to a type, 273 // so build a dependent node to describe the type. 274 if (WantNontrivialTypeSourceInfo) 275 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 276 277 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 278 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 279 II, NameLoc); 280 return ParsedType::make(T); 281 } 282 283 return ParsedType(); 284 } 285 286 if (!LookupCtx->isDependentContext() && 287 RequireCompleteDeclContext(*SS, LookupCtx)) 288 return ParsedType(); 289 } 290 291 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 292 // lookup for class-names. 293 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 294 LookupOrdinaryName; 295 LookupResult Result(*this, &II, NameLoc, Kind); 296 if (LookupCtx) { 297 // Perform "qualified" name lookup into the declaration context we 298 // computed, which is either the type of the base of a member access 299 // expression or the declaration context associated with a prior 300 // nested-name-specifier. 301 LookupQualifiedName(Result, LookupCtx); 302 303 if (ObjectTypePtr && Result.empty()) { 304 // C++ [basic.lookup.classref]p3: 305 // If the unqualified-id is ~type-name, the type-name is looked up 306 // in the context of the entire postfix-expression. If the type T of 307 // the object expression is of a class type C, the type-name is also 308 // looked up in the scope of class C. At least one of the lookups shall 309 // find a name that refers to (possibly cv-qualified) T. 310 LookupName(Result, S); 311 } 312 } else { 313 // Perform unqualified name lookup. 314 LookupName(Result, S); 315 316 // For unqualified lookup in a class template in MSVC mode, look into 317 // dependent base classes where the primary class template is known. 318 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 319 if (ParsedType TypeInBase = 320 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 321 return TypeInBase; 322 } 323 } 324 325 NamedDecl *IIDecl = nullptr; 326 switch (Result.getResultKind()) { 327 case LookupResult::NotFound: 328 case LookupResult::NotFoundInCurrentInstantiation: 329 if (CorrectedII) { 330 TypoCorrection Correction = CorrectTypo( 331 Result.getLookupNameInfo(), Kind, S, SS, 332 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName), 333 CTK_ErrorRecovery); 334 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 335 TemplateTy Template; 336 bool MemberOfUnknownSpecialization; 337 UnqualifiedId TemplateName; 338 TemplateName.setIdentifier(NewII, NameLoc); 339 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 340 CXXScopeSpec NewSS, *NewSSPtr = SS; 341 if (SS && NNS) { 342 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 343 NewSSPtr = &NewSS; 344 } 345 if (Correction && (NNS || NewII != &II) && 346 // Ignore a correction to a template type as the to-be-corrected 347 // identifier is not a template (typo correction for template names 348 // is handled elsewhere). 349 !(getLangOpts().CPlusPlus && NewSSPtr && 350 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 351 false, Template, MemberOfUnknownSpecialization))) { 352 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 353 isClassName, HasTrailingDot, ObjectTypePtr, 354 IsCtorOrDtorName, 355 WantNontrivialTypeSourceInfo); 356 if (Ty) { 357 diagnoseTypo(Correction, 358 PDiag(diag::err_unknown_type_or_class_name_suggest) 359 << Result.getLookupName() << isClassName); 360 if (SS && NNS) 361 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 362 *CorrectedII = NewII; 363 return Ty; 364 } 365 } 366 } 367 // If typo correction failed or was not performed, fall through 368 case LookupResult::FoundOverloaded: 369 case LookupResult::FoundUnresolvedValue: 370 Result.suppressDiagnostics(); 371 return ParsedType(); 372 373 case LookupResult::Ambiguous: 374 // Recover from type-hiding ambiguities by hiding the type. We'll 375 // do the lookup again when looking for an object, and we can 376 // diagnose the error then. If we don't do this, then the error 377 // about hiding the type will be immediately followed by an error 378 // that only makes sense if the identifier was treated like a type. 379 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 380 Result.suppressDiagnostics(); 381 return ParsedType(); 382 } 383 384 // Look to see if we have a type anywhere in the list of results. 385 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 386 Res != ResEnd; ++Res) { 387 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 388 if (!IIDecl || 389 (*Res)->getLocation().getRawEncoding() < 390 IIDecl->getLocation().getRawEncoding()) 391 IIDecl = *Res; 392 } 393 } 394 395 if (!IIDecl) { 396 // None of the entities we found is a type, so there is no way 397 // to even assume that the result is a type. In this case, don't 398 // complain about the ambiguity. The parser will either try to 399 // perform this lookup again (e.g., as an object name), which 400 // will produce the ambiguity, or will complain that it expected 401 // a type name. 402 Result.suppressDiagnostics(); 403 return ParsedType(); 404 } 405 406 // We found a type within the ambiguous lookup; diagnose the 407 // ambiguity and then return that type. This might be the right 408 // answer, or it might not be, but it suppresses any attempt to 409 // perform the name lookup again. 410 break; 411 412 case LookupResult::Found: 413 IIDecl = Result.getFoundDecl(); 414 break; 415 } 416 417 assert(IIDecl && "Didn't find decl"); 418 419 QualType T; 420 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 421 DiagnoseUseOfDecl(IIDecl, NameLoc); 422 423 T = Context.getTypeDeclType(TD); 424 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 425 426 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 427 // constructor or destructor name (in such a case, the scope specifier 428 // will be attached to the enclosing Expr or Decl node). 429 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 430 if (WantNontrivialTypeSourceInfo) { 431 // Construct a type with type-source information. 432 TypeLocBuilder Builder; 433 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 434 435 T = getElaboratedType(ETK_None, *SS, T); 436 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 437 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 438 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 439 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 440 } else { 441 T = getElaboratedType(ETK_None, *SS, T); 442 } 443 } 444 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 445 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 446 if (!HasTrailingDot) 447 T = Context.getObjCInterfaceType(IDecl); 448 } 449 450 if (T.isNull()) { 451 // If it's not plausibly a type, suppress diagnostics. 452 Result.suppressDiagnostics(); 453 return ParsedType(); 454 } 455 return ParsedType::make(T); 456 } 457 458 // Builds a fake NNS for the given decl context. 459 static NestedNameSpecifier * 460 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 461 for (;; DC = DC->getLookupParent()) { 462 DC = DC->getPrimaryContext(); 463 auto *ND = dyn_cast<NamespaceDecl>(DC); 464 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 465 return NestedNameSpecifier::Create(Context, nullptr, ND); 466 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 467 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 468 RD->getTypeForDecl()); 469 else if (isa<TranslationUnitDecl>(DC)) 470 return NestedNameSpecifier::GlobalSpecifier(Context); 471 } 472 llvm_unreachable("something isn't in TU scope?"); 473 } 474 475 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 476 SourceLocation NameLoc) { 477 // Accepting an undeclared identifier as a default argument for a template 478 // type parameter is a Microsoft extension. 479 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 480 481 // Build a fake DependentNameType that will perform lookup into CurContext at 482 // instantiation time. The name specifier isn't dependent, so template 483 // instantiation won't transform it. It will retry the lookup, however. 484 NestedNameSpecifier *NNS = 485 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 486 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 487 488 // Build type location information. We synthesized the qualifier, so we have 489 // to build a fake NestedNameSpecifierLoc. 490 NestedNameSpecifierLocBuilder NNSLocBuilder; 491 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 492 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 493 494 TypeLocBuilder Builder; 495 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 496 DepTL.setNameLoc(NameLoc); 497 DepTL.setElaboratedKeywordLoc(SourceLocation()); 498 DepTL.setQualifierLoc(QualifierLoc); 499 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 500 } 501 502 /// isTagName() - This method is called *for error recovery purposes only* 503 /// to determine if the specified name is a valid tag name ("struct foo"). If 504 /// so, this returns the TST for the tag corresponding to it (TST_enum, 505 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 506 /// cases in C where the user forgot to specify the tag. 507 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 508 // Do a tag name lookup in this scope. 509 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 510 LookupName(R, S, false); 511 R.suppressDiagnostics(); 512 if (R.getResultKind() == LookupResult::Found) 513 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 514 switch (TD->getTagKind()) { 515 case TTK_Struct: return DeclSpec::TST_struct; 516 case TTK_Interface: return DeclSpec::TST_interface; 517 case TTK_Union: return DeclSpec::TST_union; 518 case TTK_Class: return DeclSpec::TST_class; 519 case TTK_Enum: return DeclSpec::TST_enum; 520 } 521 } 522 523 return DeclSpec::TST_unspecified; 524 } 525 526 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 527 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 528 /// then downgrade the missing typename error to a warning. 529 /// This is needed for MSVC compatibility; Example: 530 /// @code 531 /// template<class T> class A { 532 /// public: 533 /// typedef int TYPE; 534 /// }; 535 /// template<class T> class B : public A<T> { 536 /// public: 537 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 538 /// }; 539 /// @endcode 540 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 541 if (CurContext->isRecord()) { 542 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 543 return true; 544 545 const Type *Ty = SS->getScopeRep()->getAsType(); 546 547 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 548 for (const auto &Base : RD->bases()) 549 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 550 return true; 551 return S->isFunctionPrototypeScope(); 552 } 553 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 554 } 555 556 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 557 SourceLocation IILoc, 558 Scope *S, 559 CXXScopeSpec *SS, 560 ParsedType &SuggestedType, 561 bool AllowClassTemplates) { 562 // We don't have anything to suggest (yet). 563 SuggestedType = ParsedType(); 564 565 // There may have been a typo in the name of the type. Look up typo 566 // results, in case we have something that we can suggest. 567 if (TypoCorrection Corrected = 568 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 569 llvm::make_unique<TypeNameValidatorCCC>( 570 false, false, AllowClassTemplates), 571 CTK_ErrorRecovery)) { 572 if (Corrected.isKeyword()) { 573 // We corrected to a keyword. 574 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 575 II = Corrected.getCorrectionAsIdentifierInfo(); 576 } else { 577 // We found a similarly-named type or interface; suggest that. 578 if (!SS || !SS->isSet()) { 579 diagnoseTypo(Corrected, 580 PDiag(diag::err_unknown_typename_suggest) << II); 581 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 582 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 583 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 584 II->getName().equals(CorrectedStr); 585 diagnoseTypo(Corrected, 586 PDiag(diag::err_unknown_nested_typename_suggest) 587 << II << DC << DroppedSpecifier << SS->getRange()); 588 } else { 589 llvm_unreachable("could not have corrected a typo here"); 590 } 591 592 CXXScopeSpec tmpSS; 593 if (Corrected.getCorrectionSpecifier()) 594 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 595 SourceRange(IILoc)); 596 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 597 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 598 false, ParsedType(), 599 /*IsCtorOrDtorName=*/false, 600 /*NonTrivialTypeSourceInfo=*/true); 601 } 602 return; 603 } 604 605 if (getLangOpts().CPlusPlus) { 606 // See if II is a class template that the user forgot to pass arguments to. 607 UnqualifiedId Name; 608 Name.setIdentifier(II, IILoc); 609 CXXScopeSpec EmptySS; 610 TemplateTy TemplateResult; 611 bool MemberOfUnknownSpecialization; 612 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 613 Name, ParsedType(), true, TemplateResult, 614 MemberOfUnknownSpecialization) == TNK_Type_template) { 615 TemplateName TplName = TemplateResult.get(); 616 Diag(IILoc, diag::err_template_missing_args) << TplName; 617 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 618 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 619 << TplDecl->getTemplateParameters()->getSourceRange(); 620 } 621 return; 622 } 623 } 624 625 // FIXME: Should we move the logic that tries to recover from a missing tag 626 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 627 628 if (!SS || (!SS->isSet() && !SS->isInvalid())) 629 Diag(IILoc, diag::err_unknown_typename) << II; 630 else if (DeclContext *DC = computeDeclContext(*SS, false)) 631 Diag(IILoc, diag::err_typename_nested_not_found) 632 << II << DC << SS->getRange(); 633 else if (isDependentScopeSpecifier(*SS)) { 634 unsigned DiagID = diag::err_typename_missing; 635 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 636 DiagID = diag::ext_typename_missing; 637 638 Diag(SS->getRange().getBegin(), DiagID) 639 << SS->getScopeRep() << II->getName() 640 << SourceRange(SS->getRange().getBegin(), IILoc) 641 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 642 SuggestedType = ActOnTypenameType(S, SourceLocation(), 643 *SS, *II, IILoc).get(); 644 } else { 645 assert(SS && SS->isInvalid() && 646 "Invalid scope specifier has already been diagnosed"); 647 } 648 } 649 650 /// \brief Determine whether the given result set contains either a type name 651 /// or 652 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 653 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 654 NextToken.is(tok::less); 655 656 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 657 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 658 return true; 659 660 if (CheckTemplate && isa<TemplateDecl>(*I)) 661 return true; 662 } 663 664 return false; 665 } 666 667 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 668 Scope *S, CXXScopeSpec &SS, 669 IdentifierInfo *&Name, 670 SourceLocation NameLoc) { 671 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 672 SemaRef.LookupParsedName(R, S, &SS); 673 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 674 StringRef FixItTagName; 675 switch (Tag->getTagKind()) { 676 case TTK_Class: 677 FixItTagName = "class "; 678 break; 679 680 case TTK_Enum: 681 FixItTagName = "enum "; 682 break; 683 684 case TTK_Struct: 685 FixItTagName = "struct "; 686 break; 687 688 case TTK_Interface: 689 FixItTagName = "__interface "; 690 break; 691 692 case TTK_Union: 693 FixItTagName = "union "; 694 break; 695 } 696 697 StringRef TagName = FixItTagName.drop_back(); 698 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 699 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 700 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 701 702 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 703 I != IEnd; ++I) 704 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 705 << Name << TagName; 706 707 // Replace lookup results with just the tag decl. 708 Result.clear(Sema::LookupTagName); 709 SemaRef.LookupParsedName(Result, S, &SS); 710 return true; 711 } 712 713 return false; 714 } 715 716 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 717 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 718 QualType T, SourceLocation NameLoc) { 719 ASTContext &Context = S.Context; 720 721 TypeLocBuilder Builder; 722 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 723 724 T = S.getElaboratedType(ETK_None, SS, T); 725 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 726 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 727 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 728 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 729 } 730 731 Sema::NameClassification 732 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 733 SourceLocation NameLoc, const Token &NextToken, 734 bool IsAddressOfOperand, 735 std::unique_ptr<CorrectionCandidateCallback> CCC) { 736 DeclarationNameInfo NameInfo(Name, NameLoc); 737 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 738 739 if (NextToken.is(tok::coloncolon)) { 740 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 741 QualType(), false, SS, nullptr, false); 742 } 743 744 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 745 LookupParsedName(Result, S, &SS, !CurMethod); 746 747 // For unqualified lookup in a class template in MSVC mode, look into 748 // dependent base classes where the primary class template is known. 749 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 750 if (ParsedType TypeInBase = 751 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 752 return TypeInBase; 753 } 754 755 // Perform lookup for Objective-C instance variables (including automatically 756 // synthesized instance variables), if we're in an Objective-C method. 757 // FIXME: This lookup really, really needs to be folded in to the normal 758 // unqualified lookup mechanism. 759 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 760 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 761 if (E.get() || E.isInvalid()) 762 return E; 763 } 764 765 bool SecondTry = false; 766 bool IsFilteredTemplateName = false; 767 768 Corrected: 769 switch (Result.getResultKind()) { 770 case LookupResult::NotFound: 771 // If an unqualified-id is followed by a '(', then we have a function 772 // call. 773 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 774 // In C++, this is an ADL-only call. 775 // FIXME: Reference? 776 if (getLangOpts().CPlusPlus) 777 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 778 779 // C90 6.3.2.2: 780 // If the expression that precedes the parenthesized argument list in a 781 // function call consists solely of an identifier, and if no 782 // declaration is visible for this identifier, the identifier is 783 // implicitly declared exactly as if, in the innermost block containing 784 // the function call, the declaration 785 // 786 // extern int identifier (); 787 // 788 // appeared. 789 // 790 // We also allow this in C99 as an extension. 791 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 792 Result.addDecl(D); 793 Result.resolveKind(); 794 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 795 } 796 } 797 798 // In C, we first see whether there is a tag type by the same name, in 799 // which case it's likely that the user just forget to write "enum", 800 // "struct", or "union". 801 if (!getLangOpts().CPlusPlus && !SecondTry && 802 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 803 break; 804 } 805 806 // Perform typo correction to determine if there is another name that is 807 // close to this name. 808 if (!SecondTry && CCC) { 809 SecondTry = true; 810 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 811 Result.getLookupKind(), S, 812 &SS, std::move(CCC), 813 CTK_ErrorRecovery)) { 814 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 815 unsigned QualifiedDiag = diag::err_no_member_suggest; 816 817 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 818 NamedDecl *UnderlyingFirstDecl 819 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr; 820 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 821 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 822 UnqualifiedDiag = diag::err_no_template_suggest; 823 QualifiedDiag = diag::err_no_member_template_suggest; 824 } else if (UnderlyingFirstDecl && 825 (isa<TypeDecl>(UnderlyingFirstDecl) || 826 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 827 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 828 UnqualifiedDiag = diag::err_unknown_typename_suggest; 829 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 830 } 831 832 if (SS.isEmpty()) { 833 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 834 } else {// FIXME: is this even reachable? Test it. 835 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 836 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 837 Name->getName().equals(CorrectedStr); 838 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 839 << Name << computeDeclContext(SS, false) 840 << DroppedSpecifier << SS.getRange()); 841 } 842 843 // Update the name, so that the caller has the new name. 844 Name = Corrected.getCorrectionAsIdentifierInfo(); 845 846 // Typo correction corrected to a keyword. 847 if (Corrected.isKeyword()) 848 return Name; 849 850 // Also update the LookupResult... 851 // FIXME: This should probably go away at some point 852 Result.clear(); 853 Result.setLookupName(Corrected.getCorrection()); 854 if (FirstDecl) 855 Result.addDecl(FirstDecl); 856 857 // If we found an Objective-C instance variable, let 858 // LookupInObjCMethod build the appropriate expression to 859 // reference the ivar. 860 // FIXME: This is a gross hack. 861 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 862 Result.clear(); 863 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 864 return E; 865 } 866 867 goto Corrected; 868 } 869 } 870 871 // We failed to correct; just fall through and let the parser deal with it. 872 Result.suppressDiagnostics(); 873 return NameClassification::Unknown(); 874 875 case LookupResult::NotFoundInCurrentInstantiation: { 876 // We performed name lookup into the current instantiation, and there were 877 // dependent bases, so we treat this result the same way as any other 878 // dependent nested-name-specifier. 879 880 // C++ [temp.res]p2: 881 // A name used in a template declaration or definition and that is 882 // dependent on a template-parameter is assumed not to name a type 883 // unless the applicable name lookup finds a type name or the name is 884 // qualified by the keyword typename. 885 // 886 // FIXME: If the next token is '<', we might want to ask the parser to 887 // perform some heroics to see if we actually have a 888 // template-argument-list, which would indicate a missing 'template' 889 // keyword here. 890 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 891 NameInfo, IsAddressOfOperand, 892 /*TemplateArgs=*/nullptr); 893 } 894 895 case LookupResult::Found: 896 case LookupResult::FoundOverloaded: 897 case LookupResult::FoundUnresolvedValue: 898 break; 899 900 case LookupResult::Ambiguous: 901 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 902 hasAnyAcceptableTemplateNames(Result)) { 903 // C++ [temp.local]p3: 904 // A lookup that finds an injected-class-name (10.2) can result in an 905 // ambiguity in certain cases (for example, if it is found in more than 906 // one base class). If all of the injected-class-names that are found 907 // refer to specializations of the same class template, and if the name 908 // is followed by a template-argument-list, the reference refers to the 909 // class template itself and not a specialization thereof, and is not 910 // ambiguous. 911 // 912 // This filtering can make an ambiguous result into an unambiguous one, 913 // so try again after filtering out template names. 914 FilterAcceptableTemplateNames(Result); 915 if (!Result.isAmbiguous()) { 916 IsFilteredTemplateName = true; 917 break; 918 } 919 } 920 921 // Diagnose the ambiguity and return an error. 922 return NameClassification::Error(); 923 } 924 925 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 926 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 927 // C++ [temp.names]p3: 928 // After name lookup (3.4) finds that a name is a template-name or that 929 // an operator-function-id or a literal- operator-id refers to a set of 930 // overloaded functions any member of which is a function template if 931 // this is followed by a <, the < is always taken as the delimiter of a 932 // template-argument-list and never as the less-than operator. 933 if (!IsFilteredTemplateName) 934 FilterAcceptableTemplateNames(Result); 935 936 if (!Result.empty()) { 937 bool IsFunctionTemplate; 938 bool IsVarTemplate; 939 TemplateName Template; 940 if (Result.end() - Result.begin() > 1) { 941 IsFunctionTemplate = true; 942 Template = Context.getOverloadedTemplateName(Result.begin(), 943 Result.end()); 944 } else { 945 TemplateDecl *TD 946 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 947 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 948 IsVarTemplate = isa<VarTemplateDecl>(TD); 949 950 if (SS.isSet() && !SS.isInvalid()) 951 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 952 /*TemplateKeyword=*/false, 953 TD); 954 else 955 Template = TemplateName(TD); 956 } 957 958 if (IsFunctionTemplate) { 959 // Function templates always go through overload resolution, at which 960 // point we'll perform the various checks (e.g., accessibility) we need 961 // to based on which function we selected. 962 Result.suppressDiagnostics(); 963 964 return NameClassification::FunctionTemplate(Template); 965 } 966 967 return IsVarTemplate ? NameClassification::VarTemplate(Template) 968 : NameClassification::TypeTemplate(Template); 969 } 970 } 971 972 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 973 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 974 DiagnoseUseOfDecl(Type, NameLoc); 975 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 976 QualType T = Context.getTypeDeclType(Type); 977 if (SS.isNotEmpty()) 978 return buildNestedType(*this, SS, T, NameLoc); 979 return ParsedType::make(T); 980 } 981 982 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 983 if (!Class) { 984 // FIXME: It's unfortunate that we don't have a Type node for handling this. 985 if (ObjCCompatibleAliasDecl *Alias = 986 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 987 Class = Alias->getClassInterface(); 988 } 989 990 if (Class) { 991 DiagnoseUseOfDecl(Class, NameLoc); 992 993 if (NextToken.is(tok::period)) { 994 // Interface. <something> is parsed as a property reference expression. 995 // Just return "unknown" as a fall-through for now. 996 Result.suppressDiagnostics(); 997 return NameClassification::Unknown(); 998 } 999 1000 QualType T = Context.getObjCInterfaceType(Class); 1001 return ParsedType::make(T); 1002 } 1003 1004 // We can have a type template here if we're classifying a template argument. 1005 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 1006 return NameClassification::TypeTemplate( 1007 TemplateName(cast<TemplateDecl>(FirstDecl))); 1008 1009 // Check for a tag type hidden by a non-type decl in a few cases where it 1010 // seems likely a type is wanted instead of the non-type that was found. 1011 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star); 1012 if ((NextToken.is(tok::identifier) || 1013 (NextIsOp && 1014 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1015 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1016 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1017 DiagnoseUseOfDecl(Type, NameLoc); 1018 QualType T = Context.getTypeDeclType(Type); 1019 if (SS.isNotEmpty()) 1020 return buildNestedType(*this, SS, T, NameLoc); 1021 return ParsedType::make(T); 1022 } 1023 1024 if (FirstDecl->isCXXClassMember()) 1025 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1026 nullptr, S); 1027 1028 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1029 return BuildDeclarationNameExpr(SS, Result, ADL); 1030 } 1031 1032 // Determines the context to return to after temporarily entering a 1033 // context. This depends in an unnecessarily complicated way on the 1034 // exact ordering of callbacks from the parser. 1035 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1036 1037 // Functions defined inline within classes aren't parsed until we've 1038 // finished parsing the top-level class, so the top-level class is 1039 // the context we'll need to return to. 1040 // A Lambda call operator whose parent is a class must not be treated 1041 // as an inline member function. A Lambda can be used legally 1042 // either as an in-class member initializer or a default argument. These 1043 // are parsed once the class has been marked complete and so the containing 1044 // context would be the nested class (when the lambda is defined in one); 1045 // If the class is not complete, then the lambda is being used in an 1046 // ill-formed fashion (such as to specify the width of a bit-field, or 1047 // in an array-bound) - in which case we still want to return the 1048 // lexically containing DC (which could be a nested class). 1049 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1050 DC = DC->getLexicalParent(); 1051 1052 // A function not defined within a class will always return to its 1053 // lexical context. 1054 if (!isa<CXXRecordDecl>(DC)) 1055 return DC; 1056 1057 // A C++ inline method/friend is parsed *after* the topmost class 1058 // it was declared in is fully parsed ("complete"); the topmost 1059 // class is the context we need to return to. 1060 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1061 DC = RD; 1062 1063 // Return the declaration context of the topmost class the inline method is 1064 // declared in. 1065 return DC; 1066 } 1067 1068 return DC->getLexicalParent(); 1069 } 1070 1071 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1072 assert(getContainingDC(DC) == CurContext && 1073 "The next DeclContext should be lexically contained in the current one."); 1074 CurContext = DC; 1075 S->setEntity(DC); 1076 } 1077 1078 void Sema::PopDeclContext() { 1079 assert(CurContext && "DeclContext imbalance!"); 1080 1081 CurContext = getContainingDC(CurContext); 1082 assert(CurContext && "Popped translation unit!"); 1083 } 1084 1085 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S, 1086 Decl *D) { 1087 // Unlike PushDeclContext, the context to which we return is not necessarily 1088 // the containing DC of TD, because the new context will be some pre-existing 1089 // TagDecl definition instead of a fresh one. 1090 auto Result = static_cast<SkippedDefinitionContext>(CurContext); 1091 CurContext = cast<TagDecl>(D)->getDefinition(); 1092 assert(CurContext && "skipping definition of undefined tag"); 1093 // Start lookups from the parent of the current context; we don't want to look 1094 // into the pre-existing complete definition. 1095 S->setEntity(CurContext->getLookupParent()); 1096 return Result; 1097 } 1098 1099 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) { 1100 CurContext = static_cast<decltype(CurContext)>(Context); 1101 } 1102 1103 /// EnterDeclaratorContext - Used when we must lookup names in the context 1104 /// of a declarator's nested name specifier. 1105 /// 1106 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1107 // C++0x [basic.lookup.unqual]p13: 1108 // A name used in the definition of a static data member of class 1109 // X (after the qualified-id of the static member) is looked up as 1110 // if the name was used in a member function of X. 1111 // C++0x [basic.lookup.unqual]p14: 1112 // If a variable member of a namespace is defined outside of the 1113 // scope of its namespace then any name used in the definition of 1114 // the variable member (after the declarator-id) is looked up as 1115 // if the definition of the variable member occurred in its 1116 // namespace. 1117 // Both of these imply that we should push a scope whose context 1118 // is the semantic context of the declaration. We can't use 1119 // PushDeclContext here because that context is not necessarily 1120 // lexically contained in the current context. Fortunately, 1121 // the containing scope should have the appropriate information. 1122 1123 assert(!S->getEntity() && "scope already has entity"); 1124 1125 #ifndef NDEBUG 1126 Scope *Ancestor = S->getParent(); 1127 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1128 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1129 #endif 1130 1131 CurContext = DC; 1132 S->setEntity(DC); 1133 } 1134 1135 void Sema::ExitDeclaratorContext(Scope *S) { 1136 assert(S->getEntity() == CurContext && "Context imbalance!"); 1137 1138 // Switch back to the lexical context. The safety of this is 1139 // enforced by an assert in EnterDeclaratorContext. 1140 Scope *Ancestor = S->getParent(); 1141 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1142 CurContext = Ancestor->getEntity(); 1143 1144 // We don't need to do anything with the scope, which is going to 1145 // disappear. 1146 } 1147 1148 1149 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1150 // We assume that the caller has already called 1151 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1152 FunctionDecl *FD = D->getAsFunction(); 1153 if (!FD) 1154 return; 1155 1156 // Same implementation as PushDeclContext, but enters the context 1157 // from the lexical parent, rather than the top-level class. 1158 assert(CurContext == FD->getLexicalParent() && 1159 "The next DeclContext should be lexically contained in the current one."); 1160 CurContext = FD; 1161 S->setEntity(CurContext); 1162 1163 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1164 ParmVarDecl *Param = FD->getParamDecl(P); 1165 // If the parameter has an identifier, then add it to the scope 1166 if (Param->getIdentifier()) { 1167 S->AddDecl(Param); 1168 IdResolver.AddDecl(Param); 1169 } 1170 } 1171 } 1172 1173 1174 void Sema::ActOnExitFunctionContext() { 1175 // Same implementation as PopDeclContext, but returns to the lexical parent, 1176 // rather than the top-level class. 1177 assert(CurContext && "DeclContext imbalance!"); 1178 CurContext = CurContext->getLexicalParent(); 1179 assert(CurContext && "Popped translation unit!"); 1180 } 1181 1182 1183 /// \brief Determine whether we allow overloading of the function 1184 /// PrevDecl with another declaration. 1185 /// 1186 /// This routine determines whether overloading is possible, not 1187 /// whether some new function is actually an overload. It will return 1188 /// true in C++ (where we can always provide overloads) or, as an 1189 /// extension, in C when the previous function is already an 1190 /// overloaded function declaration or has the "overloadable" 1191 /// attribute. 1192 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1193 ASTContext &Context) { 1194 if (Context.getLangOpts().CPlusPlus) 1195 return true; 1196 1197 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1198 return true; 1199 1200 return (Previous.getResultKind() == LookupResult::Found 1201 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1202 } 1203 1204 /// Add this decl to the scope shadowed decl chains. 1205 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1206 // Move up the scope chain until we find the nearest enclosing 1207 // non-transparent context. The declaration will be introduced into this 1208 // scope. 1209 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1210 S = S->getParent(); 1211 1212 // Add scoped declarations into their context, so that they can be 1213 // found later. Declarations without a context won't be inserted 1214 // into any context. 1215 if (AddToContext) 1216 CurContext->addDecl(D); 1217 1218 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1219 // are function-local declarations. 1220 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1221 !D->getDeclContext()->getRedeclContext()->Equals( 1222 D->getLexicalDeclContext()->getRedeclContext()) && 1223 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1224 return; 1225 1226 // Template instantiations should also not be pushed into scope. 1227 if (isa<FunctionDecl>(D) && 1228 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1229 return; 1230 1231 // If this replaces anything in the current scope, 1232 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1233 IEnd = IdResolver.end(); 1234 for (; I != IEnd; ++I) { 1235 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1236 S->RemoveDecl(*I); 1237 IdResolver.RemoveDecl(*I); 1238 1239 // Should only need to replace one decl. 1240 break; 1241 } 1242 } 1243 1244 S->AddDecl(D); 1245 1246 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1247 // Implicitly-generated labels may end up getting generated in an order that 1248 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1249 // the label at the appropriate place in the identifier chain. 1250 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1251 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1252 if (IDC == CurContext) { 1253 if (!S->isDeclScope(*I)) 1254 continue; 1255 } else if (IDC->Encloses(CurContext)) 1256 break; 1257 } 1258 1259 IdResolver.InsertDeclAfter(I, D); 1260 } else { 1261 IdResolver.AddDecl(D); 1262 } 1263 } 1264 1265 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1266 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1267 TUScope->AddDecl(D); 1268 } 1269 1270 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1271 bool AllowInlineNamespace) { 1272 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1273 } 1274 1275 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1276 DeclContext *TargetDC = DC->getPrimaryContext(); 1277 do { 1278 if (DeclContext *ScopeDC = S->getEntity()) 1279 if (ScopeDC->getPrimaryContext() == TargetDC) 1280 return S; 1281 } while ((S = S->getParent())); 1282 1283 return nullptr; 1284 } 1285 1286 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1287 DeclContext*, 1288 ASTContext&); 1289 1290 /// Filters out lookup results that don't fall within the given scope 1291 /// as determined by isDeclInScope. 1292 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1293 bool ConsiderLinkage, 1294 bool AllowInlineNamespace) { 1295 LookupResult::Filter F = R.makeFilter(); 1296 while (F.hasNext()) { 1297 NamedDecl *D = F.next(); 1298 1299 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1300 continue; 1301 1302 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1303 continue; 1304 1305 F.erase(); 1306 } 1307 1308 F.done(); 1309 } 1310 1311 static bool isUsingDecl(NamedDecl *D) { 1312 return isa<UsingShadowDecl>(D) || 1313 isa<UnresolvedUsingTypenameDecl>(D) || 1314 isa<UnresolvedUsingValueDecl>(D); 1315 } 1316 1317 /// Removes using shadow declarations from the lookup results. 1318 static void RemoveUsingDecls(LookupResult &R) { 1319 LookupResult::Filter F = R.makeFilter(); 1320 while (F.hasNext()) 1321 if (isUsingDecl(F.next())) 1322 F.erase(); 1323 1324 F.done(); 1325 } 1326 1327 /// \brief Check for this common pattern: 1328 /// @code 1329 /// class S { 1330 /// S(const S&); // DO NOT IMPLEMENT 1331 /// void operator=(const S&); // DO NOT IMPLEMENT 1332 /// }; 1333 /// @endcode 1334 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1335 // FIXME: Should check for private access too but access is set after we get 1336 // the decl here. 1337 if (D->doesThisDeclarationHaveABody()) 1338 return false; 1339 1340 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1341 return CD->isCopyConstructor(); 1342 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1343 return Method->isCopyAssignmentOperator(); 1344 return false; 1345 } 1346 1347 // We need this to handle 1348 // 1349 // typedef struct { 1350 // void *foo() { return 0; } 1351 // } A; 1352 // 1353 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1354 // for example. If 'A', foo will have external linkage. If we have '*A', 1355 // foo will have no linkage. Since we can't know until we get to the end 1356 // of the typedef, this function finds out if D might have non-external linkage. 1357 // Callers should verify at the end of the TU if it D has external linkage or 1358 // not. 1359 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1360 const DeclContext *DC = D->getDeclContext(); 1361 while (!DC->isTranslationUnit()) { 1362 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1363 if (!RD->hasNameForLinkage()) 1364 return true; 1365 } 1366 DC = DC->getParent(); 1367 } 1368 1369 return !D->isExternallyVisible(); 1370 } 1371 1372 // FIXME: This needs to be refactored; some other isInMainFile users want 1373 // these semantics. 1374 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1375 if (S.TUKind != TU_Complete) 1376 return false; 1377 return S.SourceMgr.isInMainFile(Loc); 1378 } 1379 1380 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1381 assert(D); 1382 1383 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1384 return false; 1385 1386 // Ignore all entities declared within templates, and out-of-line definitions 1387 // of members of class templates. 1388 if (D->getDeclContext()->isDependentContext() || 1389 D->getLexicalDeclContext()->isDependentContext()) 1390 return false; 1391 1392 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1393 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1394 return false; 1395 1396 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1397 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1398 return false; 1399 } else { 1400 // 'static inline' functions are defined in headers; don't warn. 1401 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1402 return false; 1403 } 1404 1405 if (FD->doesThisDeclarationHaveABody() && 1406 Context.DeclMustBeEmitted(FD)) 1407 return false; 1408 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1409 // Constants and utility variables are defined in headers with internal 1410 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1411 // like "inline".) 1412 if (!isMainFileLoc(*this, VD->getLocation())) 1413 return false; 1414 1415 if (Context.DeclMustBeEmitted(VD)) 1416 return false; 1417 1418 if (VD->isStaticDataMember() && 1419 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1420 return false; 1421 } else { 1422 return false; 1423 } 1424 1425 // Only warn for unused decls internal to the translation unit. 1426 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1427 // for inline functions defined in the main source file, for instance. 1428 return mightHaveNonExternalLinkage(D); 1429 } 1430 1431 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1432 if (!D) 1433 return; 1434 1435 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1436 const FunctionDecl *First = FD->getFirstDecl(); 1437 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1438 return; // First should already be in the vector. 1439 } 1440 1441 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1442 const VarDecl *First = VD->getFirstDecl(); 1443 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1444 return; // First should already be in the vector. 1445 } 1446 1447 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1448 UnusedFileScopedDecls.push_back(D); 1449 } 1450 1451 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1452 if (D->isInvalidDecl()) 1453 return false; 1454 1455 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1456 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1457 return false; 1458 1459 if (isa<LabelDecl>(D)) 1460 return true; 1461 1462 // Except for labels, we only care about unused decls that are local to 1463 // functions. 1464 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1465 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1466 // For dependent types, the diagnostic is deferred. 1467 WithinFunction = 1468 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1469 if (!WithinFunction) 1470 return false; 1471 1472 if (isa<TypedefNameDecl>(D)) 1473 return true; 1474 1475 // White-list anything that isn't a local variable. 1476 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1477 return false; 1478 1479 // Types of valid local variables should be complete, so this should succeed. 1480 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1481 1482 // White-list anything with an __attribute__((unused)) type. 1483 QualType Ty = VD->getType(); 1484 1485 // Only look at the outermost level of typedef. 1486 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1487 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1488 return false; 1489 } 1490 1491 // If we failed to complete the type for some reason, or if the type is 1492 // dependent, don't diagnose the variable. 1493 if (Ty->isIncompleteType() || Ty->isDependentType()) 1494 return false; 1495 1496 if (const TagType *TT = Ty->getAs<TagType>()) { 1497 const TagDecl *Tag = TT->getDecl(); 1498 if (Tag->hasAttr<UnusedAttr>()) 1499 return false; 1500 1501 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1502 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1503 return false; 1504 1505 if (const Expr *Init = VD->getInit()) { 1506 if (const ExprWithCleanups *Cleanups = 1507 dyn_cast<ExprWithCleanups>(Init)) 1508 Init = Cleanups->getSubExpr(); 1509 const CXXConstructExpr *Construct = 1510 dyn_cast<CXXConstructExpr>(Init); 1511 if (Construct && !Construct->isElidable()) { 1512 CXXConstructorDecl *CD = Construct->getConstructor(); 1513 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1514 return false; 1515 } 1516 } 1517 } 1518 } 1519 1520 // TODO: __attribute__((unused)) templates? 1521 } 1522 1523 return true; 1524 } 1525 1526 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1527 FixItHint &Hint) { 1528 if (isa<LabelDecl>(D)) { 1529 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1530 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1531 if (AfterColon.isInvalid()) 1532 return; 1533 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1534 getCharRange(D->getLocStart(), AfterColon)); 1535 } 1536 return; 1537 } 1538 1539 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1540 if (D->getTypeForDecl()->isDependentType()) 1541 return; 1542 1543 for (auto *TmpD : D->decls()) { 1544 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1545 DiagnoseUnusedDecl(T); 1546 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1547 DiagnoseUnusedNestedTypedefs(R); 1548 } 1549 } 1550 1551 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1552 /// unless they are marked attr(unused). 1553 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1554 if (!ShouldDiagnoseUnusedDecl(D)) 1555 return; 1556 1557 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1558 // typedefs can be referenced later on, so the diagnostics are emitted 1559 // at end-of-translation-unit. 1560 UnusedLocalTypedefNameCandidates.insert(TD); 1561 return; 1562 } 1563 1564 FixItHint Hint; 1565 GenerateFixForUnusedDecl(D, Context, Hint); 1566 1567 unsigned DiagID; 1568 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1569 DiagID = diag::warn_unused_exception_param; 1570 else if (isa<LabelDecl>(D)) 1571 DiagID = diag::warn_unused_label; 1572 else 1573 DiagID = diag::warn_unused_variable; 1574 1575 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1576 } 1577 1578 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1579 // Verify that we have no forward references left. If so, there was a goto 1580 // or address of a label taken, but no definition of it. Label fwd 1581 // definitions are indicated with a null substmt which is also not a resolved 1582 // MS inline assembly label name. 1583 bool Diagnose = false; 1584 if (L->isMSAsmLabel()) 1585 Diagnose = !L->isResolvedMSAsmLabel(); 1586 else 1587 Diagnose = L->getStmt() == nullptr; 1588 if (Diagnose) 1589 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1590 } 1591 1592 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1593 S->mergeNRVOIntoParent(); 1594 1595 if (S->decl_empty()) return; 1596 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1597 "Scope shouldn't contain decls!"); 1598 1599 for (auto *TmpD : S->decls()) { 1600 assert(TmpD && "This decl didn't get pushed??"); 1601 1602 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1603 NamedDecl *D = cast<NamedDecl>(TmpD); 1604 1605 if (!D->getDeclName()) continue; 1606 1607 // Diagnose unused variables in this scope. 1608 if (!S->hasUnrecoverableErrorOccurred()) { 1609 DiagnoseUnusedDecl(D); 1610 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1611 DiagnoseUnusedNestedTypedefs(RD); 1612 } 1613 1614 // If this was a forward reference to a label, verify it was defined. 1615 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1616 CheckPoppedLabel(LD, *this); 1617 1618 // Remove this name from our lexical scope. 1619 IdResolver.RemoveDecl(D); 1620 } 1621 } 1622 1623 /// \brief Look for an Objective-C class in the translation unit. 1624 /// 1625 /// \param Id The name of the Objective-C class we're looking for. If 1626 /// typo-correction fixes this name, the Id will be updated 1627 /// to the fixed name. 1628 /// 1629 /// \param IdLoc The location of the name in the translation unit. 1630 /// 1631 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1632 /// if there is no class with the given name. 1633 /// 1634 /// \returns The declaration of the named Objective-C class, or NULL if the 1635 /// class could not be found. 1636 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1637 SourceLocation IdLoc, 1638 bool DoTypoCorrection) { 1639 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1640 // creation from this context. 1641 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1642 1643 if (!IDecl && DoTypoCorrection) { 1644 // Perform typo correction at the given location, but only if we 1645 // find an Objective-C class name. 1646 if (TypoCorrection C = CorrectTypo( 1647 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1648 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1649 CTK_ErrorRecovery)) { 1650 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1651 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1652 Id = IDecl->getIdentifier(); 1653 } 1654 } 1655 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1656 // This routine must always return a class definition, if any. 1657 if (Def && Def->getDefinition()) 1658 Def = Def->getDefinition(); 1659 return Def; 1660 } 1661 1662 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1663 /// from S, where a non-field would be declared. This routine copes 1664 /// with the difference between C and C++ scoping rules in structs and 1665 /// unions. For example, the following code is well-formed in C but 1666 /// ill-formed in C++: 1667 /// @code 1668 /// struct S6 { 1669 /// enum { BAR } e; 1670 /// }; 1671 /// 1672 /// void test_S6() { 1673 /// struct S6 a; 1674 /// a.e = BAR; 1675 /// } 1676 /// @endcode 1677 /// For the declaration of BAR, this routine will return a different 1678 /// scope. The scope S will be the scope of the unnamed enumeration 1679 /// within S6. In C++, this routine will return the scope associated 1680 /// with S6, because the enumeration's scope is a transparent 1681 /// context but structures can contain non-field names. In C, this 1682 /// routine will return the translation unit scope, since the 1683 /// enumeration's scope is a transparent context and structures cannot 1684 /// contain non-field names. 1685 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1686 while (((S->getFlags() & Scope::DeclScope) == 0) || 1687 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1688 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1689 S = S->getParent(); 1690 return S; 1691 } 1692 1693 /// \brief Looks up the declaration of "struct objc_super" and 1694 /// saves it for later use in building builtin declaration of 1695 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1696 /// pre-existing declaration exists no action takes place. 1697 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1698 IdentifierInfo *II) { 1699 if (!II->isStr("objc_msgSendSuper")) 1700 return; 1701 ASTContext &Context = ThisSema.Context; 1702 1703 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1704 SourceLocation(), Sema::LookupTagName); 1705 ThisSema.LookupName(Result, S); 1706 if (Result.getResultKind() == LookupResult::Found) 1707 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1708 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1709 } 1710 1711 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1712 switch (Error) { 1713 case ASTContext::GE_None: 1714 return ""; 1715 case ASTContext::GE_Missing_stdio: 1716 return "stdio.h"; 1717 case ASTContext::GE_Missing_setjmp: 1718 return "setjmp.h"; 1719 case ASTContext::GE_Missing_ucontext: 1720 return "ucontext.h"; 1721 } 1722 llvm_unreachable("unhandled error kind"); 1723 } 1724 1725 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1726 /// file scope. lazily create a decl for it. ForRedeclaration is true 1727 /// if we're creating this built-in in anticipation of redeclaring the 1728 /// built-in. 1729 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1730 Scope *S, bool ForRedeclaration, 1731 SourceLocation Loc) { 1732 LookupPredefedObjCSuperType(*this, S, II); 1733 1734 ASTContext::GetBuiltinTypeError Error; 1735 QualType R = Context.GetBuiltinType(ID, Error); 1736 if (Error) { 1737 if (ForRedeclaration) 1738 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1739 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID); 1740 return nullptr; 1741 } 1742 1743 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1744 Diag(Loc, diag::ext_implicit_lib_function_decl) 1745 << Context.BuiltinInfo.getName(ID) << R; 1746 if (Context.BuiltinInfo.getHeaderName(ID) && 1747 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1748 Diag(Loc, diag::note_include_header_or_declare) 1749 << Context.BuiltinInfo.getHeaderName(ID) 1750 << Context.BuiltinInfo.getName(ID); 1751 } 1752 1753 DeclContext *Parent = Context.getTranslationUnitDecl(); 1754 if (getLangOpts().CPlusPlus) { 1755 LinkageSpecDecl *CLinkageDecl = 1756 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1757 LinkageSpecDecl::lang_c, false); 1758 CLinkageDecl->setImplicit(); 1759 Parent->addDecl(CLinkageDecl); 1760 Parent = CLinkageDecl; 1761 } 1762 1763 FunctionDecl *New = FunctionDecl::Create(Context, 1764 Parent, 1765 Loc, Loc, II, R, /*TInfo=*/nullptr, 1766 SC_Extern, 1767 false, 1768 R->isFunctionProtoType()); 1769 New->setImplicit(); 1770 1771 // Create Decl objects for each parameter, adding them to the 1772 // FunctionDecl. 1773 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1774 SmallVector<ParmVarDecl*, 16> Params; 1775 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1776 ParmVarDecl *parm = 1777 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1778 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1779 SC_None, nullptr); 1780 parm->setScopeInfo(0, i); 1781 Params.push_back(parm); 1782 } 1783 New->setParams(Params); 1784 } 1785 1786 AddKnownFunctionAttributes(New); 1787 RegisterLocallyScopedExternCDecl(New, S); 1788 1789 // TUScope is the translation-unit scope to insert this function into. 1790 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1791 // relate Scopes to DeclContexts, and probably eliminate CurContext 1792 // entirely, but we're not there yet. 1793 DeclContext *SavedContext = CurContext; 1794 CurContext = Parent; 1795 PushOnScopeChains(New, TUScope); 1796 CurContext = SavedContext; 1797 return New; 1798 } 1799 1800 /// Typedef declarations don't have linkage, but they still denote the same 1801 /// entity if their types are the same. 1802 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1803 /// isSameEntity. 1804 static void filterNonConflictingPreviousTypedefDecls(Sema &S, 1805 TypedefNameDecl *Decl, 1806 LookupResult &Previous) { 1807 // This is only interesting when modules are enabled. 1808 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility) 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 // Declarations of the same entity are not ignored, even if they have 1824 // different linkages. 1825 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1826 if (S.Context.hasSameType(OldTD->getUnderlyingType(), 1827 Decl->getUnderlyingType())) 1828 continue; 1829 1830 // If both declarations give a tag declaration a typedef name for linkage 1831 // purposes, then they declare the same entity. 1832 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) && 1833 Decl->getAnonDeclWithTypedefName()) 1834 continue; 1835 } 1836 1837 if (!Old->isExternallyVisible()) 1838 Filter.erase(); 1839 } 1840 1841 Filter.done(); 1842 } 1843 1844 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1845 QualType OldType; 1846 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1847 OldType = OldTypedef->getUnderlyingType(); 1848 else 1849 OldType = Context.getTypeDeclType(Old); 1850 QualType NewType = New->getUnderlyingType(); 1851 1852 if (NewType->isVariablyModifiedType()) { 1853 // Must not redefine a typedef with a variably-modified type. 1854 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1855 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1856 << Kind << NewType; 1857 if (Old->getLocation().isValid()) 1858 Diag(Old->getLocation(), diag::note_previous_definition); 1859 New->setInvalidDecl(); 1860 return true; 1861 } 1862 1863 if (OldType != NewType && 1864 !OldType->isDependentType() && 1865 !NewType->isDependentType() && 1866 !Context.hasSameType(OldType, NewType)) { 1867 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1868 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1869 << Kind << NewType << OldType; 1870 if (Old->getLocation().isValid()) 1871 Diag(Old->getLocation(), diag::note_previous_definition); 1872 New->setInvalidDecl(); 1873 return true; 1874 } 1875 return false; 1876 } 1877 1878 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1879 /// same name and scope as a previous declaration 'Old'. Figure out 1880 /// how to resolve this situation, merging decls or emitting 1881 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1882 /// 1883 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1884 // If the new decl is known invalid already, don't bother doing any 1885 // merging checks. 1886 if (New->isInvalidDecl()) return; 1887 1888 // Allow multiple definitions for ObjC built-in typedefs. 1889 // FIXME: Verify the underlying types are equivalent! 1890 if (getLangOpts().ObjC1) { 1891 const IdentifierInfo *TypeID = New->getIdentifier(); 1892 switch (TypeID->getLength()) { 1893 default: break; 1894 case 2: 1895 { 1896 if (!TypeID->isStr("id")) 1897 break; 1898 QualType T = New->getUnderlyingType(); 1899 if (!T->isPointerType()) 1900 break; 1901 if (!T->isVoidPointerType()) { 1902 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1903 if (!PT->isStructureType()) 1904 break; 1905 } 1906 Context.setObjCIdRedefinitionType(T); 1907 // Install the built-in type for 'id', ignoring the current definition. 1908 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1909 return; 1910 } 1911 case 5: 1912 if (!TypeID->isStr("Class")) 1913 break; 1914 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1915 // Install the built-in type for 'Class', ignoring the current definition. 1916 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1917 return; 1918 case 3: 1919 if (!TypeID->isStr("SEL")) 1920 break; 1921 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1922 // Install the built-in type for 'SEL', ignoring the current definition. 1923 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1924 return; 1925 } 1926 // Fall through - the typedef name was not a builtin type. 1927 } 1928 1929 // Verify the old decl was also a type. 1930 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1931 if (!Old) { 1932 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1933 << New->getDeclName(); 1934 1935 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1936 if (OldD->getLocation().isValid()) 1937 Diag(OldD->getLocation(), diag::note_previous_definition); 1938 1939 return New->setInvalidDecl(); 1940 } 1941 1942 // If the old declaration is invalid, just give up here. 1943 if (Old->isInvalidDecl()) 1944 return New->setInvalidDecl(); 1945 1946 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) { 1947 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true); 1948 auto *NewTag = New->getAnonDeclWithTypedefName(); 1949 NamedDecl *Hidden = nullptr; 1950 if (getLangOpts().CPlusPlus && OldTag && NewTag && 1951 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() && 1952 !hasVisibleDefinition(OldTag, &Hidden)) { 1953 // There is a definition of this tag, but it is not visible. Use it 1954 // instead of our tag. 1955 New->setTypeForDecl(OldTD->getTypeForDecl()); 1956 if (OldTD->isModed()) 1957 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(), 1958 OldTD->getUnderlyingType()); 1959 else 1960 New->setTypeSourceInfo(OldTD->getTypeSourceInfo()); 1961 1962 // Make the old tag definition visible. 1963 makeMergedDefinitionVisible(Hidden, NewTag->getLocation()); 1964 } 1965 } 1966 1967 // If the typedef types are not identical, reject them in all languages and 1968 // with any extensions enabled. 1969 if (isIncompatibleTypedef(Old, New)) 1970 return; 1971 1972 // The types match. Link up the redeclaration chain and merge attributes if 1973 // the old declaration was a typedef. 1974 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1975 New->setPreviousDecl(Typedef); 1976 mergeDeclAttributes(New, Old); 1977 } 1978 1979 if (getLangOpts().MicrosoftExt) 1980 return; 1981 1982 if (getLangOpts().CPlusPlus) { 1983 // C++ [dcl.typedef]p2: 1984 // In a given non-class scope, a typedef specifier can be used to 1985 // redefine the name of any type declared in that scope to refer 1986 // to the type to which it already refers. 1987 if (!isa<CXXRecordDecl>(CurContext)) 1988 return; 1989 1990 // C++0x [dcl.typedef]p4: 1991 // In a given class scope, a typedef specifier can be used to redefine 1992 // any class-name declared in that scope that is not also a typedef-name 1993 // to refer to the type to which it already refers. 1994 // 1995 // This wording came in via DR424, which was a correction to the 1996 // wording in DR56, which accidentally banned code like: 1997 // 1998 // struct S { 1999 // typedef struct A { } A; 2000 // }; 2001 // 2002 // in the C++03 standard. We implement the C++0x semantics, which 2003 // allow the above but disallow 2004 // 2005 // struct S { 2006 // typedef int I; 2007 // typedef int I; 2008 // }; 2009 // 2010 // since that was the intent of DR56. 2011 if (!isa<TypedefNameDecl>(Old)) 2012 return; 2013 2014 Diag(New->getLocation(), diag::err_redefinition) 2015 << New->getDeclName(); 2016 Diag(Old->getLocation(), diag::note_previous_definition); 2017 return New->setInvalidDecl(); 2018 } 2019 2020 // Modules always permit redefinition of typedefs, as does C11. 2021 if (getLangOpts().Modules || getLangOpts().C11) 2022 return; 2023 2024 // If we have a redefinition of a typedef in C, emit a warning. This warning 2025 // is normally mapped to an error, but can be controlled with 2026 // -Wtypedef-redefinition. If either the original or the redefinition is 2027 // in a system header, don't emit this for compatibility with GCC. 2028 if (getDiagnostics().getSuppressSystemWarnings() && 2029 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2030 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2031 return; 2032 2033 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2034 << New->getDeclName(); 2035 Diag(Old->getLocation(), diag::note_previous_definition); 2036 } 2037 2038 /// DeclhasAttr - returns true if decl Declaration already has the target 2039 /// attribute. 2040 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2041 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2042 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2043 for (const auto *i : D->attrs()) 2044 if (i->getKind() == A->getKind()) { 2045 if (Ann) { 2046 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2047 return true; 2048 continue; 2049 } 2050 // FIXME: Don't hardcode this check 2051 if (OA && isa<OwnershipAttr>(i)) 2052 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2053 return true; 2054 } 2055 2056 return false; 2057 } 2058 2059 static bool isAttributeTargetADefinition(Decl *D) { 2060 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2061 return VD->isThisDeclarationADefinition(); 2062 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2063 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2064 return true; 2065 } 2066 2067 /// Merge alignment attributes from \p Old to \p New, taking into account the 2068 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2069 /// 2070 /// \return \c true if any attributes were added to \p New. 2071 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2072 // Look for alignas attributes on Old, and pick out whichever attribute 2073 // specifies the strictest alignment requirement. 2074 AlignedAttr *OldAlignasAttr = nullptr; 2075 AlignedAttr *OldStrictestAlignAttr = nullptr; 2076 unsigned OldAlign = 0; 2077 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2078 // FIXME: We have no way of representing inherited dependent alignments 2079 // in a case like: 2080 // template<int A, int B> struct alignas(A) X; 2081 // template<int A, int B> struct alignas(B) X {}; 2082 // For now, we just ignore any alignas attributes which are not on the 2083 // definition in such a case. 2084 if (I->isAlignmentDependent()) 2085 return false; 2086 2087 if (I->isAlignas()) 2088 OldAlignasAttr = I; 2089 2090 unsigned Align = I->getAlignment(S.Context); 2091 if (Align > OldAlign) { 2092 OldAlign = Align; 2093 OldStrictestAlignAttr = I; 2094 } 2095 } 2096 2097 // Look for alignas attributes on New. 2098 AlignedAttr *NewAlignasAttr = nullptr; 2099 unsigned NewAlign = 0; 2100 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2101 if (I->isAlignmentDependent()) 2102 return false; 2103 2104 if (I->isAlignas()) 2105 NewAlignasAttr = I; 2106 2107 unsigned Align = I->getAlignment(S.Context); 2108 if (Align > NewAlign) 2109 NewAlign = Align; 2110 } 2111 2112 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2113 // Both declarations have 'alignas' attributes. We require them to match. 2114 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2115 // fall short. (If two declarations both have alignas, they must both match 2116 // every definition, and so must match each other if there is a definition.) 2117 2118 // If either declaration only contains 'alignas(0)' specifiers, then it 2119 // specifies the natural alignment for the type. 2120 if (OldAlign == 0 || NewAlign == 0) { 2121 QualType Ty; 2122 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2123 Ty = VD->getType(); 2124 else 2125 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2126 2127 if (OldAlign == 0) 2128 OldAlign = S.Context.getTypeAlign(Ty); 2129 if (NewAlign == 0) 2130 NewAlign = S.Context.getTypeAlign(Ty); 2131 } 2132 2133 if (OldAlign != NewAlign) { 2134 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2135 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2136 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2137 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2138 } 2139 } 2140 2141 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2142 // C++11 [dcl.align]p6: 2143 // if any declaration of an entity has an alignment-specifier, 2144 // every defining declaration of that entity shall specify an 2145 // equivalent alignment. 2146 // C11 6.7.5/7: 2147 // If the definition of an object does not have an alignment 2148 // specifier, any other declaration of that object shall also 2149 // have no alignment specifier. 2150 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2151 << OldAlignasAttr; 2152 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2153 << OldAlignasAttr; 2154 } 2155 2156 bool AnyAdded = false; 2157 2158 // Ensure we have an attribute representing the strictest alignment. 2159 if (OldAlign > NewAlign) { 2160 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2161 Clone->setInherited(true); 2162 New->addAttr(Clone); 2163 AnyAdded = true; 2164 } 2165 2166 // Ensure we have an alignas attribute if the old declaration had one. 2167 if (OldAlignasAttr && !NewAlignasAttr && 2168 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2169 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2170 Clone->setInherited(true); 2171 New->addAttr(Clone); 2172 AnyAdded = true; 2173 } 2174 2175 return AnyAdded; 2176 } 2177 2178 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2179 const InheritableAttr *Attr, 2180 Sema::AvailabilityMergeKind AMK) { 2181 InheritableAttr *NewAttr = nullptr; 2182 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2183 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2184 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2185 AA->getIntroduced(), AA->getDeprecated(), 2186 AA->getObsoleted(), AA->getUnavailable(), 2187 AA->getMessage(), AMK, 2188 AttrSpellingListIndex); 2189 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2190 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2191 AttrSpellingListIndex); 2192 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2193 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2194 AttrSpellingListIndex); 2195 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2196 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2197 AttrSpellingListIndex); 2198 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2199 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2200 AttrSpellingListIndex); 2201 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2202 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2203 FA->getFormatIdx(), FA->getFirstArg(), 2204 AttrSpellingListIndex); 2205 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2206 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2207 AttrSpellingListIndex); 2208 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2209 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2210 AttrSpellingListIndex, 2211 IA->getSemanticSpelling()); 2212 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2213 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2214 &S.Context.Idents.get(AA->getSpelling()), 2215 AttrSpellingListIndex); 2216 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2217 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2218 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2219 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2220 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr)) 2221 NewAttr = S.mergeInternalLinkageAttr( 2222 D, InternalLinkageA->getRange(), 2223 &S.Context.Idents.get(InternalLinkageA->getSpelling()), 2224 AttrSpellingListIndex); 2225 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr)) 2226 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(), 2227 &S.Context.Idents.get(CommonA->getSpelling()), 2228 AttrSpellingListIndex); 2229 else if (isa<AlignedAttr>(Attr)) 2230 // AlignedAttrs are handled separately, because we need to handle all 2231 // such attributes on a declaration at the same time. 2232 NewAttr = nullptr; 2233 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) && 2234 (AMK == Sema::AMK_Override || 2235 AMK == Sema::AMK_ProtocolImplementation)) 2236 NewAttr = nullptr; 2237 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2238 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2239 2240 if (NewAttr) { 2241 NewAttr->setInherited(true); 2242 D->addAttr(NewAttr); 2243 return true; 2244 } 2245 2246 return false; 2247 } 2248 2249 static const Decl *getDefinition(const Decl *D) { 2250 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2251 return TD->getDefinition(); 2252 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2253 const VarDecl *Def = VD->getDefinition(); 2254 if (Def) 2255 return Def; 2256 return VD->getActingDefinition(); 2257 } 2258 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2259 const FunctionDecl* Def; 2260 if (FD->isDefined(Def)) 2261 return Def; 2262 } 2263 return nullptr; 2264 } 2265 2266 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2267 for (const auto *Attribute : D->attrs()) 2268 if (Attribute->getKind() == Kind) 2269 return true; 2270 return false; 2271 } 2272 2273 /// checkNewAttributesAfterDef - If we already have a definition, check that 2274 /// there are no new attributes in this declaration. 2275 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2276 if (!New->hasAttrs()) 2277 return; 2278 2279 const Decl *Def = getDefinition(Old); 2280 if (!Def || Def == New) 2281 return; 2282 2283 AttrVec &NewAttributes = New->getAttrs(); 2284 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2285 const Attr *NewAttribute = NewAttributes[I]; 2286 2287 if (isa<AliasAttr>(NewAttribute)) { 2288 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) { 2289 Sema::SkipBodyInfo SkipBody; 2290 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody); 2291 2292 // If we're skipping this definition, drop the "alias" attribute. 2293 if (SkipBody.ShouldSkip) { 2294 NewAttributes.erase(NewAttributes.begin() + I); 2295 --E; 2296 continue; 2297 } 2298 } else { 2299 VarDecl *VD = cast<VarDecl>(New); 2300 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2301 VarDecl::TentativeDefinition 2302 ? diag::err_alias_after_tentative 2303 : diag::err_redefinition; 2304 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2305 S.Diag(Def->getLocation(), diag::note_previous_definition); 2306 VD->setInvalidDecl(); 2307 } 2308 ++I; 2309 continue; 2310 } 2311 2312 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2313 // Tentative definitions are only interesting for the alias check above. 2314 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2315 ++I; 2316 continue; 2317 } 2318 } 2319 2320 if (hasAttribute(Def, NewAttribute->getKind())) { 2321 ++I; 2322 continue; // regular attr merging will take care of validating this. 2323 } 2324 2325 if (isa<C11NoReturnAttr>(NewAttribute)) { 2326 // C's _Noreturn is allowed to be added to a function after it is defined. 2327 ++I; 2328 continue; 2329 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2330 if (AA->isAlignas()) { 2331 // C++11 [dcl.align]p6: 2332 // if any declaration of an entity has an alignment-specifier, 2333 // every defining declaration of that entity shall specify an 2334 // equivalent alignment. 2335 // C11 6.7.5/7: 2336 // If the definition of an object does not have an alignment 2337 // specifier, any other declaration of that object shall also 2338 // have no alignment specifier. 2339 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2340 << AA; 2341 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2342 << AA; 2343 NewAttributes.erase(NewAttributes.begin() + I); 2344 --E; 2345 continue; 2346 } 2347 } 2348 2349 S.Diag(NewAttribute->getLocation(), 2350 diag::warn_attribute_precede_definition); 2351 S.Diag(Def->getLocation(), diag::note_previous_definition); 2352 NewAttributes.erase(NewAttributes.begin() + I); 2353 --E; 2354 } 2355 } 2356 2357 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2358 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2359 AvailabilityMergeKind AMK) { 2360 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2361 UsedAttr *NewAttr = OldAttr->clone(Context); 2362 NewAttr->setInherited(true); 2363 New->addAttr(NewAttr); 2364 } 2365 2366 if (!Old->hasAttrs() && !New->hasAttrs()) 2367 return; 2368 2369 // attributes declared post-definition are currently ignored 2370 checkNewAttributesAfterDef(*this, New, Old); 2371 2372 if (!Old->hasAttrs()) 2373 return; 2374 2375 bool foundAny = New->hasAttrs(); 2376 2377 // Ensure that any moving of objects within the allocated map is done before 2378 // we process them. 2379 if (!foundAny) New->setAttrs(AttrVec()); 2380 2381 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2382 // Ignore deprecated/unavailable/availability attributes if requested. 2383 AvailabilityMergeKind LocalAMK = AMK_None; 2384 if (isa<DeprecatedAttr>(I) || 2385 isa<UnavailableAttr>(I) || 2386 isa<AvailabilityAttr>(I)) { 2387 switch (AMK) { 2388 case AMK_None: 2389 continue; 2390 2391 case AMK_Redeclaration: 2392 case AMK_Override: 2393 case AMK_ProtocolImplementation: 2394 LocalAMK = AMK; 2395 break; 2396 } 2397 } 2398 2399 // Already handled. 2400 if (isa<UsedAttr>(I)) 2401 continue; 2402 2403 if (mergeDeclAttribute(*this, New, I, LocalAMK)) 2404 foundAny = true; 2405 } 2406 2407 if (mergeAlignedAttrs(*this, New, Old)) 2408 foundAny = true; 2409 2410 if (!foundAny) New->dropAttrs(); 2411 } 2412 2413 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2414 /// to the new one. 2415 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2416 const ParmVarDecl *oldDecl, 2417 Sema &S) { 2418 // C++11 [dcl.attr.depend]p2: 2419 // The first declaration of a function shall specify the 2420 // carries_dependency attribute for its declarator-id if any declaration 2421 // of the function specifies the carries_dependency attribute. 2422 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2423 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2424 S.Diag(CDA->getLocation(), 2425 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2426 // Find the first declaration of the parameter. 2427 // FIXME: Should we build redeclaration chains for function parameters? 2428 const FunctionDecl *FirstFD = 2429 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2430 const ParmVarDecl *FirstVD = 2431 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2432 S.Diag(FirstVD->getLocation(), 2433 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2434 } 2435 2436 if (!oldDecl->hasAttrs()) 2437 return; 2438 2439 bool foundAny = newDecl->hasAttrs(); 2440 2441 // Ensure that any moving of objects within the allocated map is 2442 // done before we process them. 2443 if (!foundAny) newDecl->setAttrs(AttrVec()); 2444 2445 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2446 if (!DeclHasAttr(newDecl, I)) { 2447 InheritableAttr *newAttr = 2448 cast<InheritableParamAttr>(I->clone(S.Context)); 2449 newAttr->setInherited(true); 2450 newDecl->addAttr(newAttr); 2451 foundAny = true; 2452 } 2453 } 2454 2455 if (!foundAny) newDecl->dropAttrs(); 2456 } 2457 2458 static void mergeParamDeclTypes(ParmVarDecl *NewParam, 2459 const ParmVarDecl *OldParam, 2460 Sema &S) { 2461 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) { 2462 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) { 2463 if (*Oldnullability != *Newnullability) { 2464 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr) 2465 << DiagNullabilityKind( 2466 *Newnullability, 2467 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2468 != 0)) 2469 << DiagNullabilityKind( 2470 *Oldnullability, 2471 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2472 != 0)); 2473 S.Diag(OldParam->getLocation(), diag::note_previous_declaration); 2474 } 2475 } else { 2476 QualType NewT = NewParam->getType(); 2477 NewT = S.Context.getAttributedType( 2478 AttributedType::getNullabilityAttrKind(*Oldnullability), 2479 NewT, NewT); 2480 NewParam->setType(NewT); 2481 } 2482 } 2483 } 2484 2485 namespace { 2486 2487 /// Used in MergeFunctionDecl to keep track of function parameters in 2488 /// C. 2489 struct GNUCompatibleParamWarning { 2490 ParmVarDecl *OldParm; 2491 ParmVarDecl *NewParm; 2492 QualType PromotedType; 2493 }; 2494 2495 } 2496 2497 /// getSpecialMember - get the special member enum for a method. 2498 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2499 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2500 if (Ctor->isDefaultConstructor()) 2501 return Sema::CXXDefaultConstructor; 2502 2503 if (Ctor->isCopyConstructor()) 2504 return Sema::CXXCopyConstructor; 2505 2506 if (Ctor->isMoveConstructor()) 2507 return Sema::CXXMoveConstructor; 2508 } else if (isa<CXXDestructorDecl>(MD)) { 2509 return Sema::CXXDestructor; 2510 } else if (MD->isCopyAssignmentOperator()) { 2511 return Sema::CXXCopyAssignment; 2512 } else if (MD->isMoveAssignmentOperator()) { 2513 return Sema::CXXMoveAssignment; 2514 } 2515 2516 return Sema::CXXInvalid; 2517 } 2518 2519 // Determine whether the previous declaration was a definition, implicit 2520 // declaration, or a declaration. 2521 template <typename T> 2522 static std::pair<diag::kind, SourceLocation> 2523 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2524 diag::kind PrevDiag; 2525 SourceLocation OldLocation = Old->getLocation(); 2526 if (Old->isThisDeclarationADefinition()) 2527 PrevDiag = diag::note_previous_definition; 2528 else if (Old->isImplicit()) { 2529 PrevDiag = diag::note_previous_implicit_declaration; 2530 if (OldLocation.isInvalid()) 2531 OldLocation = New->getLocation(); 2532 } else 2533 PrevDiag = diag::note_previous_declaration; 2534 return std::make_pair(PrevDiag, OldLocation); 2535 } 2536 2537 /// canRedefineFunction - checks if a function can be redefined. Currently, 2538 /// only extern inline functions can be redefined, and even then only in 2539 /// GNU89 mode. 2540 static bool canRedefineFunction(const FunctionDecl *FD, 2541 const LangOptions& LangOpts) { 2542 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2543 !LangOpts.CPlusPlus && 2544 FD->isInlineSpecified() && 2545 FD->getStorageClass() == SC_Extern); 2546 } 2547 2548 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2549 const AttributedType *AT = T->getAs<AttributedType>(); 2550 while (AT && !AT->isCallingConv()) 2551 AT = AT->getModifiedType()->getAs<AttributedType>(); 2552 return AT; 2553 } 2554 2555 template <typename T> 2556 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2557 const DeclContext *DC = Old->getDeclContext(); 2558 if (DC->isRecord()) 2559 return false; 2560 2561 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2562 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2563 return true; 2564 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2565 return true; 2566 return false; 2567 } 2568 2569 template<typename T> static bool isExternC(T *D) { return D->isExternC(); } 2570 static bool isExternC(VarTemplateDecl *) { return false; } 2571 2572 /// \brief Check whether a redeclaration of an entity introduced by a 2573 /// using-declaration is valid, given that we know it's not an overload 2574 /// (nor a hidden tag declaration). 2575 template<typename ExpectedDecl> 2576 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, 2577 ExpectedDecl *New) { 2578 // C++11 [basic.scope.declarative]p4: 2579 // Given a set of declarations in a single declarative region, each of 2580 // which specifies the same unqualified name, 2581 // -- they shall all refer to the same entity, or all refer to functions 2582 // and function templates; or 2583 // -- exactly one declaration shall declare a class name or enumeration 2584 // name that is not a typedef name and the other declarations shall all 2585 // refer to the same variable or enumerator, or all refer to functions 2586 // and function templates; in this case the class name or enumeration 2587 // name is hidden (3.3.10). 2588 2589 // C++11 [namespace.udecl]p14: 2590 // If a function declaration in namespace scope or block scope has the 2591 // same name and the same parameter-type-list as a function introduced 2592 // by a using-declaration, and the declarations do not declare the same 2593 // function, the program is ill-formed. 2594 2595 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl()); 2596 if (Old && 2597 !Old->getDeclContext()->getRedeclContext()->Equals( 2598 New->getDeclContext()->getRedeclContext()) && 2599 !(isExternC(Old) && isExternC(New))) 2600 Old = nullptr; 2601 2602 if (!Old) { 2603 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2604 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target); 2605 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2606 return true; 2607 } 2608 return false; 2609 } 2610 2611 /// MergeFunctionDecl - We just parsed a function 'New' from 2612 /// declarator D which has the same name and scope as a previous 2613 /// declaration 'Old'. Figure out how to resolve this situation, 2614 /// merging decls or emitting diagnostics as appropriate. 2615 /// 2616 /// In C++, New and Old must be declarations that are not 2617 /// overloaded. Use IsOverload to determine whether New and Old are 2618 /// overloaded, and to select the Old declaration that New should be 2619 /// merged with. 2620 /// 2621 /// Returns true if there was an error, false otherwise. 2622 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2623 Scope *S, bool MergeTypeWithOld) { 2624 // Verify the old decl was also a function. 2625 FunctionDecl *Old = OldD->getAsFunction(); 2626 if (!Old) { 2627 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2628 if (New->getFriendObjectKind()) { 2629 Diag(New->getLocation(), diag::err_using_decl_friend); 2630 Diag(Shadow->getTargetDecl()->getLocation(), 2631 diag::note_using_decl_target); 2632 Diag(Shadow->getUsingDecl()->getLocation(), 2633 diag::note_using_decl) << 0; 2634 return true; 2635 } 2636 2637 // Check whether the two declarations might declare the same function. 2638 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New)) 2639 return true; 2640 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl()); 2641 } else { 2642 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2643 << New->getDeclName(); 2644 Diag(OldD->getLocation(), diag::note_previous_definition); 2645 return true; 2646 } 2647 } 2648 2649 // If the old declaration is invalid, just give up here. 2650 if (Old->isInvalidDecl()) 2651 return true; 2652 2653 diag::kind PrevDiag; 2654 SourceLocation OldLocation; 2655 std::tie(PrevDiag, OldLocation) = 2656 getNoteDiagForInvalidRedeclaration(Old, New); 2657 2658 // Don't complain about this if we're in GNU89 mode and the old function 2659 // is an extern inline function. 2660 // Don't complain about specializations. They are not supposed to have 2661 // storage classes. 2662 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2663 New->getStorageClass() == SC_Static && 2664 Old->hasExternalFormalLinkage() && 2665 !New->getTemplateSpecializationInfo() && 2666 !canRedefineFunction(Old, getLangOpts())) { 2667 if (getLangOpts().MicrosoftExt) { 2668 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2669 Diag(OldLocation, PrevDiag); 2670 } else { 2671 Diag(New->getLocation(), diag::err_static_non_static) << New; 2672 Diag(OldLocation, PrevDiag); 2673 return true; 2674 } 2675 } 2676 2677 if (New->hasAttr<InternalLinkageAttr>() && 2678 !Old->hasAttr<InternalLinkageAttr>()) { 2679 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 2680 << New->getDeclName(); 2681 Diag(Old->getLocation(), diag::note_previous_definition); 2682 New->dropAttr<InternalLinkageAttr>(); 2683 } 2684 2685 // If a function is first declared with a calling convention, but is later 2686 // declared or defined without one, all following decls assume the calling 2687 // convention of the first. 2688 // 2689 // It's OK if a function is first declared without a calling convention, 2690 // but is later declared or defined with the default calling convention. 2691 // 2692 // To test if either decl has an explicit calling convention, we look for 2693 // AttributedType sugar nodes on the type as written. If they are missing or 2694 // were canonicalized away, we assume the calling convention was implicit. 2695 // 2696 // Note also that we DO NOT return at this point, because we still have 2697 // other tests to run. 2698 QualType OldQType = Context.getCanonicalType(Old->getType()); 2699 QualType NewQType = Context.getCanonicalType(New->getType()); 2700 const FunctionType *OldType = cast<FunctionType>(OldQType); 2701 const FunctionType *NewType = cast<FunctionType>(NewQType); 2702 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2703 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2704 bool RequiresAdjustment = false; 2705 2706 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2707 FunctionDecl *First = Old->getFirstDecl(); 2708 const FunctionType *FT = 2709 First->getType().getCanonicalType()->castAs<FunctionType>(); 2710 FunctionType::ExtInfo FI = FT->getExtInfo(); 2711 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2712 if (!NewCCExplicit) { 2713 // Inherit the CC from the previous declaration if it was specified 2714 // there but not here. 2715 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2716 RequiresAdjustment = true; 2717 } else { 2718 // Calling conventions aren't compatible, so complain. 2719 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2720 Diag(New->getLocation(), diag::err_cconv_change) 2721 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2722 << !FirstCCExplicit 2723 << (!FirstCCExplicit ? "" : 2724 FunctionType::getNameForCallConv(FI.getCC())); 2725 2726 // Put the note on the first decl, since it is the one that matters. 2727 Diag(First->getLocation(), diag::note_previous_declaration); 2728 return true; 2729 } 2730 } 2731 2732 // FIXME: diagnose the other way around? 2733 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2734 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2735 RequiresAdjustment = true; 2736 } 2737 2738 // Merge regparm attribute. 2739 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2740 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2741 if (NewTypeInfo.getHasRegParm()) { 2742 Diag(New->getLocation(), diag::err_regparm_mismatch) 2743 << NewType->getRegParmType() 2744 << OldType->getRegParmType(); 2745 Diag(OldLocation, diag::note_previous_declaration); 2746 return true; 2747 } 2748 2749 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2750 RequiresAdjustment = true; 2751 } 2752 2753 // Merge ns_returns_retained attribute. 2754 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2755 if (NewTypeInfo.getProducesResult()) { 2756 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2757 Diag(OldLocation, diag::note_previous_declaration); 2758 return true; 2759 } 2760 2761 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2762 RequiresAdjustment = true; 2763 } 2764 2765 if (RequiresAdjustment) { 2766 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2767 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2768 New->setType(QualType(AdjustedType, 0)); 2769 NewQType = Context.getCanonicalType(New->getType()); 2770 NewType = cast<FunctionType>(NewQType); 2771 } 2772 2773 // If this redeclaration makes the function inline, we may need to add it to 2774 // UndefinedButUsed. 2775 if (!Old->isInlined() && New->isInlined() && 2776 !New->hasAttr<GNUInlineAttr>() && 2777 !getLangOpts().GNUInline && 2778 Old->isUsed(false) && 2779 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2780 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2781 SourceLocation())); 2782 2783 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2784 // about it. 2785 if (New->hasAttr<GNUInlineAttr>() && 2786 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2787 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2788 } 2789 2790 if (getLangOpts().CPlusPlus) { 2791 // (C++98 13.1p2): 2792 // Certain function declarations cannot be overloaded: 2793 // -- Function declarations that differ only in the return type 2794 // cannot be overloaded. 2795 2796 // Go back to the type source info to compare the declared return types, 2797 // per C++1y [dcl.type.auto]p13: 2798 // Redeclarations or specializations of a function or function template 2799 // with a declared return type that uses a placeholder type shall also 2800 // use that placeholder, not a deduced type. 2801 QualType OldDeclaredReturnType = 2802 (Old->getTypeSourceInfo() 2803 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2804 : OldType)->getReturnType(); 2805 QualType NewDeclaredReturnType = 2806 (New->getTypeSourceInfo() 2807 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2808 : NewType)->getReturnType(); 2809 QualType ResQT; 2810 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2811 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2812 New->isLocalExternDecl())) { 2813 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2814 OldDeclaredReturnType->isObjCObjectPointerType()) 2815 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2816 if (ResQT.isNull()) { 2817 if (New->isCXXClassMember() && New->isOutOfLine()) 2818 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2819 << New << New->getReturnTypeSourceRange(); 2820 else 2821 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2822 << New->getReturnTypeSourceRange(); 2823 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2824 << Old->getReturnTypeSourceRange(); 2825 return true; 2826 } 2827 else 2828 NewQType = ResQT; 2829 } 2830 2831 QualType OldReturnType = OldType->getReturnType(); 2832 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2833 if (OldReturnType != NewReturnType) { 2834 // If this function has a deduced return type and has already been 2835 // defined, copy the deduced value from the old declaration. 2836 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2837 if (OldAT && OldAT->isDeduced()) { 2838 New->setType( 2839 SubstAutoType(New->getType(), 2840 OldAT->isDependentType() ? Context.DependentTy 2841 : OldAT->getDeducedType())); 2842 NewQType = Context.getCanonicalType( 2843 SubstAutoType(NewQType, 2844 OldAT->isDependentType() ? Context.DependentTy 2845 : OldAT->getDeducedType())); 2846 } 2847 } 2848 2849 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2850 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2851 if (OldMethod && NewMethod) { 2852 // Preserve triviality. 2853 NewMethod->setTrivial(OldMethod->isTrivial()); 2854 2855 // MSVC allows explicit template specialization at class scope: 2856 // 2 CXXMethodDecls referring to the same function will be injected. 2857 // We don't want a redeclaration error. 2858 bool IsClassScopeExplicitSpecialization = 2859 OldMethod->isFunctionTemplateSpecialization() && 2860 NewMethod->isFunctionTemplateSpecialization(); 2861 bool isFriend = NewMethod->getFriendObjectKind(); 2862 2863 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2864 !IsClassScopeExplicitSpecialization) { 2865 // -- Member function declarations with the same name and the 2866 // same parameter types cannot be overloaded if any of them 2867 // is a static member function declaration. 2868 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2869 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2870 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2871 return true; 2872 } 2873 2874 // C++ [class.mem]p1: 2875 // [...] A member shall not be declared twice in the 2876 // member-specification, except that a nested class or member 2877 // class template can be declared and then later defined. 2878 if (ActiveTemplateInstantiations.empty()) { 2879 unsigned NewDiag; 2880 if (isa<CXXConstructorDecl>(OldMethod)) 2881 NewDiag = diag::err_constructor_redeclared; 2882 else if (isa<CXXDestructorDecl>(NewMethod)) 2883 NewDiag = diag::err_destructor_redeclared; 2884 else if (isa<CXXConversionDecl>(NewMethod)) 2885 NewDiag = diag::err_conv_function_redeclared; 2886 else 2887 NewDiag = diag::err_member_redeclared; 2888 2889 Diag(New->getLocation(), NewDiag); 2890 } else { 2891 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2892 << New << New->getType(); 2893 } 2894 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2895 return true; 2896 2897 // Complain if this is an explicit declaration of a special 2898 // member that was initially declared implicitly. 2899 // 2900 // As an exception, it's okay to befriend such methods in order 2901 // to permit the implicit constructor/destructor/operator calls. 2902 } else if (OldMethod->isImplicit()) { 2903 if (isFriend) { 2904 NewMethod->setImplicit(); 2905 } else { 2906 Diag(NewMethod->getLocation(), 2907 diag::err_definition_of_implicitly_declared_member) 2908 << New << getSpecialMember(OldMethod); 2909 return true; 2910 } 2911 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2912 Diag(NewMethod->getLocation(), 2913 diag::err_definition_of_explicitly_defaulted_member) 2914 << getSpecialMember(OldMethod); 2915 return true; 2916 } 2917 } 2918 2919 // C++11 [dcl.attr.noreturn]p1: 2920 // The first declaration of a function shall specify the noreturn 2921 // attribute if any declaration of that function specifies the noreturn 2922 // attribute. 2923 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2924 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2925 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2926 Diag(Old->getFirstDecl()->getLocation(), 2927 diag::note_noreturn_missing_first_decl); 2928 } 2929 2930 // C++11 [dcl.attr.depend]p2: 2931 // The first declaration of a function shall specify the 2932 // carries_dependency attribute for its declarator-id if any declaration 2933 // of the function specifies the carries_dependency attribute. 2934 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2935 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2936 Diag(CDA->getLocation(), 2937 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2938 Diag(Old->getFirstDecl()->getLocation(), 2939 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2940 } 2941 2942 // (C++98 8.3.5p3): 2943 // All declarations for a function shall agree exactly in both the 2944 // return type and the parameter-type-list. 2945 // We also want to respect all the extended bits except noreturn. 2946 2947 // noreturn should now match unless the old type info didn't have it. 2948 QualType OldQTypeForComparison = OldQType; 2949 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2950 assert(OldQType == QualType(OldType, 0)); 2951 const FunctionType *OldTypeForComparison 2952 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2953 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2954 assert(OldQTypeForComparison.isCanonical()); 2955 } 2956 2957 if (haveIncompatibleLanguageLinkages(Old, New)) { 2958 // As a special case, retain the language linkage from previous 2959 // declarations of a friend function as an extension. 2960 // 2961 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2962 // and is useful because there's otherwise no way to specify language 2963 // linkage within class scope. 2964 // 2965 // Check cautiously as the friend object kind isn't yet complete. 2966 if (New->getFriendObjectKind() != Decl::FOK_None) { 2967 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2968 Diag(OldLocation, PrevDiag); 2969 } else { 2970 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2971 Diag(OldLocation, PrevDiag); 2972 return true; 2973 } 2974 } 2975 2976 if (OldQTypeForComparison == NewQType) 2977 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2978 2979 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2980 New->isLocalExternDecl()) { 2981 // It's OK if we couldn't merge types for a local function declaraton 2982 // if either the old or new type is dependent. We'll merge the types 2983 // when we instantiate the function. 2984 return false; 2985 } 2986 2987 // Fall through for conflicting redeclarations and redefinitions. 2988 } 2989 2990 // C: Function types need to be compatible, not identical. This handles 2991 // duplicate function decls like "void f(int); void f(enum X);" properly. 2992 if (!getLangOpts().CPlusPlus && 2993 Context.typesAreCompatible(OldQType, NewQType)) { 2994 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2995 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2996 const FunctionProtoType *OldProto = nullptr; 2997 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2998 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2999 // The old declaration provided a function prototype, but the 3000 // new declaration does not. Merge in the prototype. 3001 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 3002 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 3003 NewQType = 3004 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 3005 OldProto->getExtProtoInfo()); 3006 New->setType(NewQType); 3007 New->setHasInheritedPrototype(); 3008 3009 // Synthesize parameters with the same types. 3010 SmallVector<ParmVarDecl*, 16> Params; 3011 for (const auto &ParamType : OldProto->param_types()) { 3012 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 3013 SourceLocation(), nullptr, 3014 ParamType, /*TInfo=*/nullptr, 3015 SC_None, nullptr); 3016 Param->setScopeInfo(0, Params.size()); 3017 Param->setImplicit(); 3018 Params.push_back(Param); 3019 } 3020 3021 New->setParams(Params); 3022 } 3023 3024 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3025 } 3026 3027 // GNU C permits a K&R definition to follow a prototype declaration 3028 // if the declared types of the parameters in the K&R definition 3029 // match the types in the prototype declaration, even when the 3030 // promoted types of the parameters from the K&R definition differ 3031 // from the types in the prototype. GCC then keeps the types from 3032 // the prototype. 3033 // 3034 // If a variadic prototype is followed by a non-variadic K&R definition, 3035 // the K&R definition becomes variadic. This is sort of an edge case, but 3036 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 3037 // C99 6.9.1p8. 3038 if (!getLangOpts().CPlusPlus && 3039 Old->hasPrototype() && !New->hasPrototype() && 3040 New->getType()->getAs<FunctionProtoType>() && 3041 Old->getNumParams() == New->getNumParams()) { 3042 SmallVector<QualType, 16> ArgTypes; 3043 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 3044 const FunctionProtoType *OldProto 3045 = Old->getType()->getAs<FunctionProtoType>(); 3046 const FunctionProtoType *NewProto 3047 = New->getType()->getAs<FunctionProtoType>(); 3048 3049 // Determine whether this is the GNU C extension. 3050 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 3051 NewProto->getReturnType()); 3052 bool LooseCompatible = !MergedReturn.isNull(); 3053 for (unsigned Idx = 0, End = Old->getNumParams(); 3054 LooseCompatible && Idx != End; ++Idx) { 3055 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 3056 ParmVarDecl *NewParm = New->getParamDecl(Idx); 3057 if (Context.typesAreCompatible(OldParm->getType(), 3058 NewProto->getParamType(Idx))) { 3059 ArgTypes.push_back(NewParm->getType()); 3060 } else if (Context.typesAreCompatible(OldParm->getType(), 3061 NewParm->getType(), 3062 /*CompareUnqualified=*/true)) { 3063 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 3064 NewProto->getParamType(Idx) }; 3065 Warnings.push_back(Warn); 3066 ArgTypes.push_back(NewParm->getType()); 3067 } else 3068 LooseCompatible = false; 3069 } 3070 3071 if (LooseCompatible) { 3072 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 3073 Diag(Warnings[Warn].NewParm->getLocation(), 3074 diag::ext_param_promoted_not_compatible_with_prototype) 3075 << Warnings[Warn].PromotedType 3076 << Warnings[Warn].OldParm->getType(); 3077 if (Warnings[Warn].OldParm->getLocation().isValid()) 3078 Diag(Warnings[Warn].OldParm->getLocation(), 3079 diag::note_previous_declaration); 3080 } 3081 3082 if (MergeTypeWithOld) 3083 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 3084 OldProto->getExtProtoInfo())); 3085 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 3086 } 3087 3088 // Fall through to diagnose conflicting types. 3089 } 3090 3091 // A function that has already been declared has been redeclared or 3092 // defined with a different type; show an appropriate diagnostic. 3093 3094 // If the previous declaration was an implicitly-generated builtin 3095 // declaration, then at the very least we should use a specialized note. 3096 unsigned BuiltinID; 3097 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3098 // If it's actually a library-defined builtin function like 'malloc' 3099 // or 'printf', just warn about the incompatible redeclaration. 3100 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3101 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3102 Diag(OldLocation, diag::note_previous_builtin_declaration) 3103 << Old << Old->getType(); 3104 3105 // If this is a global redeclaration, just forget hereafter 3106 // about the "builtin-ness" of the function. 3107 // 3108 // Doing this for local extern declarations is problematic. If 3109 // the builtin declaration remains visible, a second invalid 3110 // local declaration will produce a hard error; if it doesn't 3111 // remain visible, a single bogus local redeclaration (which is 3112 // actually only a warning) could break all the downstream code. 3113 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3114 New->getIdentifier()->revertBuiltin(); 3115 3116 return false; 3117 } 3118 3119 PrevDiag = diag::note_previous_builtin_declaration; 3120 } 3121 3122 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3123 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3124 return true; 3125 } 3126 3127 /// \brief Completes the merge of two function declarations that are 3128 /// known to be compatible. 3129 /// 3130 /// This routine handles the merging of attributes and other 3131 /// properties of function declarations from the old declaration to 3132 /// the new declaration, once we know that New is in fact a 3133 /// redeclaration of Old. 3134 /// 3135 /// \returns false 3136 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3137 Scope *S, bool MergeTypeWithOld) { 3138 // Merge the attributes 3139 mergeDeclAttributes(New, Old); 3140 3141 // Merge "pure" flag. 3142 if (Old->isPure()) 3143 New->setPure(); 3144 3145 // Merge "used" flag. 3146 if (Old->getMostRecentDecl()->isUsed(false)) 3147 New->setIsUsed(); 3148 3149 // Merge attributes from the parameters. These can mismatch with K&R 3150 // declarations. 3151 if (New->getNumParams() == Old->getNumParams()) 3152 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) { 3153 ParmVarDecl *NewParam = New->getParamDecl(i); 3154 ParmVarDecl *OldParam = Old->getParamDecl(i); 3155 mergeParamDeclAttributes(NewParam, OldParam, *this); 3156 mergeParamDeclTypes(NewParam, OldParam, *this); 3157 } 3158 3159 if (getLangOpts().CPlusPlus) 3160 return MergeCXXFunctionDecl(New, Old, S); 3161 3162 // Merge the function types so the we get the composite types for the return 3163 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3164 // was visible. 3165 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3166 if (!Merged.isNull() && MergeTypeWithOld) 3167 New->setType(Merged); 3168 3169 return false; 3170 } 3171 3172 3173 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3174 ObjCMethodDecl *oldMethod) { 3175 3176 // Merge the attributes, including deprecated/unavailable 3177 AvailabilityMergeKind MergeKind = 3178 isa<ObjCProtocolDecl>(oldMethod->getDeclContext()) 3179 ? AMK_ProtocolImplementation 3180 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3181 : AMK_Override; 3182 3183 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3184 3185 // Merge attributes from the parameters. 3186 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3187 oe = oldMethod->param_end(); 3188 for (ObjCMethodDecl::param_iterator 3189 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3190 ni != ne && oi != oe; ++ni, ++oi) 3191 mergeParamDeclAttributes(*ni, *oi, *this); 3192 3193 CheckObjCMethodOverride(newMethod, oldMethod); 3194 } 3195 3196 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3197 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3198 /// emitting diagnostics as appropriate. 3199 /// 3200 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3201 /// to here in AddInitializerToDecl. We can't check them before the initializer 3202 /// is attached. 3203 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3204 bool MergeTypeWithOld) { 3205 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3206 return; 3207 3208 QualType MergedT; 3209 if (getLangOpts().CPlusPlus) { 3210 if (New->getType()->isUndeducedType()) { 3211 // We don't know what the new type is until the initializer is attached. 3212 return; 3213 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3214 // These could still be something that needs exception specs checked. 3215 return MergeVarDeclExceptionSpecs(New, Old); 3216 } 3217 // C++ [basic.link]p10: 3218 // [...] the types specified by all declarations referring to a given 3219 // object or function shall be identical, except that declarations for an 3220 // array object can specify array types that differ by the presence or 3221 // absence of a major array bound (8.3.4). 3222 else if (Old->getType()->isIncompleteArrayType() && 3223 New->getType()->isArrayType()) { 3224 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3225 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3226 if (Context.hasSameType(OldArray->getElementType(), 3227 NewArray->getElementType())) 3228 MergedT = New->getType(); 3229 } else if (Old->getType()->isArrayType() && 3230 New->getType()->isIncompleteArrayType()) { 3231 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3232 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3233 if (Context.hasSameType(OldArray->getElementType(), 3234 NewArray->getElementType())) 3235 MergedT = Old->getType(); 3236 } else if (New->getType()->isObjCObjectPointerType() && 3237 Old->getType()->isObjCObjectPointerType()) { 3238 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3239 Old->getType()); 3240 } 3241 } else { 3242 // C 6.2.7p2: 3243 // All declarations that refer to the same object or function shall have 3244 // compatible type. 3245 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3246 } 3247 if (MergedT.isNull()) { 3248 // It's OK if we couldn't merge types if either type is dependent, for a 3249 // block-scope variable. In other cases (static data members of class 3250 // templates, variable templates, ...), we require the types to be 3251 // equivalent. 3252 // FIXME: The C++ standard doesn't say anything about this. 3253 if ((New->getType()->isDependentType() || 3254 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3255 // If the old type was dependent, we can't merge with it, so the new type 3256 // becomes dependent for now. We'll reproduce the original type when we 3257 // instantiate the TypeSourceInfo for the variable. 3258 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3259 New->setType(Context.DependentTy); 3260 return; 3261 } 3262 3263 // FIXME: Even if this merging succeeds, some other non-visible declaration 3264 // of this variable might have an incompatible type. For instance: 3265 // 3266 // extern int arr[]; 3267 // void f() { extern int arr[2]; } 3268 // void g() { extern int arr[3]; } 3269 // 3270 // Neither C nor C++ requires a diagnostic for this, but we should still try 3271 // to diagnose it. 3272 Diag(New->getLocation(), New->isThisDeclarationADefinition() 3273 ? diag::err_redefinition_different_type 3274 : diag::err_redeclaration_different_type) 3275 << New->getDeclName() << New->getType() << Old->getType(); 3276 3277 diag::kind PrevDiag; 3278 SourceLocation OldLocation; 3279 std::tie(PrevDiag, OldLocation) = 3280 getNoteDiagForInvalidRedeclaration(Old, New); 3281 Diag(OldLocation, PrevDiag); 3282 return New->setInvalidDecl(); 3283 } 3284 3285 // Don't actually update the type on the new declaration if the old 3286 // declaration was an extern declaration in a different scope. 3287 if (MergeTypeWithOld) 3288 New->setType(MergedT); 3289 } 3290 3291 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3292 LookupResult &Previous) { 3293 // C11 6.2.7p4: 3294 // For an identifier with internal or external linkage declared 3295 // in a scope in which a prior declaration of that identifier is 3296 // visible, if the prior declaration specifies internal or 3297 // external linkage, the type of the identifier at the later 3298 // declaration becomes the composite type. 3299 // 3300 // If the variable isn't visible, we do not merge with its type. 3301 if (Previous.isShadowed()) 3302 return false; 3303 3304 if (S.getLangOpts().CPlusPlus) { 3305 // C++11 [dcl.array]p3: 3306 // If there is a preceding declaration of the entity in the same 3307 // scope in which the bound was specified, an omitted array bound 3308 // is taken to be the same as in that earlier declaration. 3309 return NewVD->isPreviousDeclInSameBlockScope() || 3310 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3311 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3312 } else { 3313 // If the old declaration was function-local, don't merge with its 3314 // type unless we're in the same function. 3315 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3316 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3317 } 3318 } 3319 3320 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3321 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3322 /// situation, merging decls or emitting diagnostics as appropriate. 3323 /// 3324 /// Tentative definition rules (C99 6.9.2p2) are checked by 3325 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3326 /// definitions here, since the initializer hasn't been attached. 3327 /// 3328 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3329 // If the new decl is already invalid, don't do any other checking. 3330 if (New->isInvalidDecl()) 3331 return; 3332 3333 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3334 3335 // Verify the old decl was also a variable or variable template. 3336 VarDecl *Old = nullptr; 3337 VarTemplateDecl *OldTemplate = nullptr; 3338 if (Previous.isSingleResult()) { 3339 if (NewTemplate) { 3340 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3341 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3342 3343 if (auto *Shadow = 3344 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3345 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate)) 3346 return New->setInvalidDecl(); 3347 } else { 3348 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3349 3350 if (auto *Shadow = 3351 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl())) 3352 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New)) 3353 return New->setInvalidDecl(); 3354 } 3355 } 3356 if (!Old) { 3357 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3358 << New->getDeclName(); 3359 Diag(Previous.getRepresentativeDecl()->getLocation(), 3360 diag::note_previous_definition); 3361 return New->setInvalidDecl(); 3362 } 3363 3364 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3365 return; 3366 3367 // Ensure the template parameters are compatible. 3368 if (NewTemplate && 3369 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3370 OldTemplate->getTemplateParameters(), 3371 /*Complain=*/true, TPL_TemplateMatch)) 3372 return New->setInvalidDecl(); 3373 3374 // C++ [class.mem]p1: 3375 // A member shall not be declared twice in the member-specification [...] 3376 // 3377 // Here, we need only consider static data members. 3378 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3379 Diag(New->getLocation(), diag::err_duplicate_member) 3380 << New->getIdentifier(); 3381 Diag(Old->getLocation(), diag::note_previous_declaration); 3382 New->setInvalidDecl(); 3383 } 3384 3385 mergeDeclAttributes(New, Old); 3386 // Warn if an already-declared variable is made a weak_import in a subsequent 3387 // declaration 3388 if (New->hasAttr<WeakImportAttr>() && 3389 Old->getStorageClass() == SC_None && 3390 !Old->hasAttr<WeakImportAttr>()) { 3391 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3392 Diag(Old->getLocation(), diag::note_previous_definition); 3393 // Remove weak_import attribute on new declaration. 3394 New->dropAttr<WeakImportAttr>(); 3395 } 3396 3397 if (New->hasAttr<InternalLinkageAttr>() && 3398 !Old->hasAttr<InternalLinkageAttr>()) { 3399 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration) 3400 << New->getDeclName(); 3401 Diag(Old->getLocation(), diag::note_previous_definition); 3402 New->dropAttr<InternalLinkageAttr>(); 3403 } 3404 3405 // Merge the types. 3406 VarDecl *MostRecent = Old->getMostRecentDecl(); 3407 if (MostRecent != Old) { 3408 MergeVarDeclTypes(New, MostRecent, 3409 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3410 if (New->isInvalidDecl()) 3411 return; 3412 } 3413 3414 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3415 if (New->isInvalidDecl()) 3416 return; 3417 3418 diag::kind PrevDiag; 3419 SourceLocation OldLocation; 3420 std::tie(PrevDiag, OldLocation) = 3421 getNoteDiagForInvalidRedeclaration(Old, New); 3422 3423 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3424 if (New->getStorageClass() == SC_Static && 3425 !New->isStaticDataMember() && 3426 Old->hasExternalFormalLinkage()) { 3427 if (getLangOpts().MicrosoftExt) { 3428 Diag(New->getLocation(), diag::ext_static_non_static) 3429 << New->getDeclName(); 3430 Diag(OldLocation, PrevDiag); 3431 } else { 3432 Diag(New->getLocation(), diag::err_static_non_static) 3433 << New->getDeclName(); 3434 Diag(OldLocation, PrevDiag); 3435 return New->setInvalidDecl(); 3436 } 3437 } 3438 // C99 6.2.2p4: 3439 // For an identifier declared with the storage-class specifier 3440 // extern in a scope in which a prior declaration of that 3441 // identifier is visible,23) if the prior declaration specifies 3442 // internal or external linkage, the linkage of the identifier at 3443 // the later declaration is the same as the linkage specified at 3444 // the prior declaration. If no prior declaration is visible, or 3445 // if the prior declaration specifies no linkage, then the 3446 // identifier has external linkage. 3447 if (New->hasExternalStorage() && Old->hasLinkage()) 3448 /* Okay */; 3449 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3450 !New->isStaticDataMember() && 3451 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3452 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3453 Diag(OldLocation, PrevDiag); 3454 return New->setInvalidDecl(); 3455 } 3456 3457 // Check if extern is followed by non-extern and vice-versa. 3458 if (New->hasExternalStorage() && 3459 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3460 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3461 Diag(OldLocation, PrevDiag); 3462 return New->setInvalidDecl(); 3463 } 3464 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3465 !New->hasExternalStorage()) { 3466 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3467 Diag(OldLocation, PrevDiag); 3468 return New->setInvalidDecl(); 3469 } 3470 3471 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3472 3473 // FIXME: The test for external storage here seems wrong? We still 3474 // need to check for mismatches. 3475 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3476 // Don't complain about out-of-line definitions of static members. 3477 !(Old->getLexicalDeclContext()->isRecord() && 3478 !New->getLexicalDeclContext()->isRecord())) { 3479 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3480 Diag(OldLocation, PrevDiag); 3481 return New->setInvalidDecl(); 3482 } 3483 3484 if (New->getTLSKind() != Old->getTLSKind()) { 3485 if (!Old->getTLSKind()) { 3486 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3487 Diag(OldLocation, PrevDiag); 3488 } else if (!New->getTLSKind()) { 3489 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3490 Diag(OldLocation, PrevDiag); 3491 } else { 3492 // Do not allow redeclaration to change the variable between requiring 3493 // static and dynamic initialization. 3494 // FIXME: GCC allows this, but uses the TLS keyword on the first 3495 // declaration to determine the kind. Do we need to be compatible here? 3496 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3497 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3498 Diag(OldLocation, PrevDiag); 3499 } 3500 } 3501 3502 // C++ doesn't have tentative definitions, so go right ahead and check here. 3503 VarDecl *Def; 3504 if (getLangOpts().CPlusPlus && 3505 New->isThisDeclarationADefinition() == VarDecl::Definition && 3506 (Def = Old->getDefinition())) { 3507 NamedDecl *Hidden = nullptr; 3508 if (!hasVisibleDefinition(Def, &Hidden) && 3509 (New->getFormalLinkage() == InternalLinkage || 3510 New->getDescribedVarTemplate() || 3511 New->getNumTemplateParameterLists() || 3512 New->getDeclContext()->isDependentContext())) { 3513 // The previous definition is hidden, and multiple definitions are 3514 // permitted (in separate TUs). Form another definition of it. 3515 } else { 3516 Diag(New->getLocation(), diag::err_redefinition) << New; 3517 Diag(Def->getLocation(), diag::note_previous_definition); 3518 New->setInvalidDecl(); 3519 return; 3520 } 3521 } 3522 3523 if (haveIncompatibleLanguageLinkages(Old, New)) { 3524 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3525 Diag(OldLocation, PrevDiag); 3526 New->setInvalidDecl(); 3527 return; 3528 } 3529 3530 // Merge "used" flag. 3531 if (Old->getMostRecentDecl()->isUsed(false)) 3532 New->setIsUsed(); 3533 3534 // Keep a chain of previous declarations. 3535 New->setPreviousDecl(Old); 3536 if (NewTemplate) 3537 NewTemplate->setPreviousDecl(OldTemplate); 3538 3539 // Inherit access appropriately. 3540 New->setAccess(Old->getAccess()); 3541 if (NewTemplate) 3542 NewTemplate->setAccess(New->getAccess()); 3543 } 3544 3545 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3546 /// no declarator (e.g. "struct foo;") is parsed. 3547 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3548 DeclSpec &DS) { 3549 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3550 } 3551 3552 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3553 // disambiguate entities defined in different scopes. 3554 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3555 // compatibility. 3556 // We will pick our mangling number depending on which version of MSVC is being 3557 // targeted. 3558 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3559 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015) 3560 ? S->getMSCurManglingNumber() 3561 : S->getMSLastManglingNumber(); 3562 } 3563 3564 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3565 if (!Context.getLangOpts().CPlusPlus) 3566 return; 3567 3568 if (isa<CXXRecordDecl>(Tag->getParent())) { 3569 // If this tag is the direct child of a class, number it if 3570 // it is anonymous. 3571 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3572 return; 3573 MangleNumberingContext &MCtx = 3574 Context.getManglingNumberContext(Tag->getParent()); 3575 Context.setManglingNumber( 3576 Tag, MCtx.getManglingNumber( 3577 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3578 return; 3579 } 3580 3581 // If this tag isn't a direct child of a class, number it if it is local. 3582 Decl *ManglingContextDecl; 3583 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3584 Tag->getDeclContext(), ManglingContextDecl)) { 3585 Context.setManglingNumber( 3586 Tag, MCtx->getManglingNumber( 3587 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3588 } 3589 } 3590 3591 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3592 TypedefNameDecl *NewTD) { 3593 if (TagFromDeclSpec->isInvalidDecl()) 3594 return; 3595 3596 // Do nothing if the tag already has a name for linkage purposes. 3597 if (TagFromDeclSpec->hasNameForLinkage()) 3598 return; 3599 3600 // A well-formed anonymous tag must always be a TUK_Definition. 3601 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3602 3603 // The type must match the tag exactly; no qualifiers allowed. 3604 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3605 Context.getTagDeclType(TagFromDeclSpec))) { 3606 if (getLangOpts().CPlusPlus) 3607 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD); 3608 return; 3609 } 3610 3611 // If we've already computed linkage for the anonymous tag, then 3612 // adding a typedef name for the anonymous decl can change that 3613 // linkage, which might be a serious problem. Diagnose this as 3614 // unsupported and ignore the typedef name. TODO: we should 3615 // pursue this as a language defect and establish a formal rule 3616 // for how to handle it. 3617 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3618 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3619 3620 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3621 tagLoc = getLocForEndOfToken(tagLoc); 3622 3623 llvm::SmallString<40> textToInsert; 3624 textToInsert += ' '; 3625 textToInsert += NewTD->getIdentifier()->getName(); 3626 Diag(tagLoc, diag::note_typedef_changes_linkage) 3627 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3628 return; 3629 } 3630 3631 // Otherwise, set this is the anon-decl typedef for the tag. 3632 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3633 } 3634 3635 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) { 3636 switch (T) { 3637 case DeclSpec::TST_class: 3638 return 0; 3639 case DeclSpec::TST_struct: 3640 return 1; 3641 case DeclSpec::TST_interface: 3642 return 2; 3643 case DeclSpec::TST_union: 3644 return 3; 3645 case DeclSpec::TST_enum: 3646 return 4; 3647 default: 3648 llvm_unreachable("unexpected type specifier"); 3649 } 3650 } 3651 3652 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3653 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3654 /// parameters to cope with template friend declarations. 3655 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3656 DeclSpec &DS, 3657 MultiTemplateParamsArg TemplateParams, 3658 bool IsExplicitInstantiation) { 3659 Decl *TagD = nullptr; 3660 TagDecl *Tag = nullptr; 3661 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3662 DS.getTypeSpecType() == DeclSpec::TST_struct || 3663 DS.getTypeSpecType() == DeclSpec::TST_interface || 3664 DS.getTypeSpecType() == DeclSpec::TST_union || 3665 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3666 TagD = DS.getRepAsDecl(); 3667 3668 if (!TagD) // We probably had an error 3669 return nullptr; 3670 3671 // Note that the above type specs guarantee that the 3672 // type rep is a Decl, whereas in many of the others 3673 // it's a Type. 3674 if (isa<TagDecl>(TagD)) 3675 Tag = cast<TagDecl>(TagD); 3676 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3677 Tag = CTD->getTemplatedDecl(); 3678 } 3679 3680 if (Tag) { 3681 handleTagNumbering(Tag, S); 3682 Tag->setFreeStanding(); 3683 if (Tag->isInvalidDecl()) 3684 return Tag; 3685 } 3686 3687 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3688 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3689 // or incomplete types shall not be restrict-qualified." 3690 if (TypeQuals & DeclSpec::TQ_restrict) 3691 Diag(DS.getRestrictSpecLoc(), 3692 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3693 << DS.getSourceRange(); 3694 } 3695 3696 if (DS.isConstexprSpecified()) { 3697 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3698 // and definitions of functions and variables. 3699 if (Tag) 3700 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3701 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()); 3702 else 3703 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3704 // Don't emit warnings after this error. 3705 return TagD; 3706 } 3707 3708 if (DS.isConceptSpecified()) { 3709 // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to 3710 // either a function concept and its definition or a variable concept and 3711 // its initializer. 3712 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 3713 return TagD; 3714 } 3715 3716 DiagnoseFunctionSpecifiers(DS); 3717 3718 if (DS.isFriendSpecified()) { 3719 // If we're dealing with a decl but not a TagDecl, assume that 3720 // whatever routines created it handled the friendship aspect. 3721 if (TagD && !Tag) 3722 return nullptr; 3723 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3724 } 3725 3726 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3727 bool IsExplicitSpecialization = 3728 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3729 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3730 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3731 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3732 // nested-name-specifier unless it is an explicit instantiation 3733 // or an explicit specialization. 3734 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3735 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3736 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange(); 3737 return nullptr; 3738 } 3739 3740 // Track whether this decl-specifier declares anything. 3741 bool DeclaresAnything = true; 3742 3743 // Handle anonymous struct definitions. 3744 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3745 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3746 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3747 if (getLangOpts().CPlusPlus || 3748 Record->getDeclContext()->isRecord()) 3749 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3750 Context.getPrintingPolicy()); 3751 3752 DeclaresAnything = false; 3753 } 3754 } 3755 3756 // C11 6.7.2.1p2: 3757 // A struct-declaration that does not declare an anonymous structure or 3758 // anonymous union shall contain a struct-declarator-list. 3759 // 3760 // This rule also existed in C89 and C99; the grammar for struct-declaration 3761 // did not permit a struct-declaration without a struct-declarator-list. 3762 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3763 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3764 // Check for Microsoft C extension: anonymous struct/union member. 3765 // Handle 2 kinds of anonymous struct/union: 3766 // struct STRUCT; 3767 // union UNION; 3768 // and 3769 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3770 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3771 if ((Tag && Tag->getDeclName()) || 3772 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3773 RecordDecl *Record = nullptr; 3774 if (Tag) 3775 Record = dyn_cast<RecordDecl>(Tag); 3776 else if (const RecordType *RT = 3777 DS.getRepAsType().get()->getAsStructureType()) 3778 Record = RT->getDecl(); 3779 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3780 Record = UT->getDecl(); 3781 3782 if (Record && getLangOpts().MicrosoftExt) { 3783 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3784 << Record->isUnion() << DS.getSourceRange(); 3785 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3786 } 3787 3788 DeclaresAnything = false; 3789 } 3790 } 3791 3792 // Skip all the checks below if we have a type error. 3793 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3794 (TagD && TagD->isInvalidDecl())) 3795 return TagD; 3796 3797 if (getLangOpts().CPlusPlus && 3798 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3799 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3800 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3801 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3802 DeclaresAnything = false; 3803 3804 if (!DS.isMissingDeclaratorOk()) { 3805 // Customize diagnostic for a typedef missing a name. 3806 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3807 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3808 << DS.getSourceRange(); 3809 else 3810 DeclaresAnything = false; 3811 } 3812 3813 if (DS.isModulePrivateSpecified() && 3814 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3815 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3816 << Tag->getTagKind() 3817 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3818 3819 ActOnDocumentableDecl(TagD); 3820 3821 // C 6.7/2: 3822 // A declaration [...] shall declare at least a declarator [...], a tag, 3823 // or the members of an enumeration. 3824 // C++ [dcl.dcl]p3: 3825 // [If there are no declarators], and except for the declaration of an 3826 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3827 // names into the program, or shall redeclare a name introduced by a 3828 // previous declaration. 3829 if (!DeclaresAnything) { 3830 // In C, we allow this as a (popular) extension / bug. Don't bother 3831 // producing further diagnostics for redundant qualifiers after this. 3832 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3833 return TagD; 3834 } 3835 3836 // C++ [dcl.stc]p1: 3837 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3838 // init-declarator-list of the declaration shall not be empty. 3839 // C++ [dcl.fct.spec]p1: 3840 // If a cv-qualifier appears in a decl-specifier-seq, the 3841 // init-declarator-list of the declaration shall not be empty. 3842 // 3843 // Spurious qualifiers here appear to be valid in C. 3844 unsigned DiagID = diag::warn_standalone_specifier; 3845 if (getLangOpts().CPlusPlus) 3846 DiagID = diag::ext_standalone_specifier; 3847 3848 // Note that a linkage-specification sets a storage class, but 3849 // 'extern "C" struct foo;' is actually valid and not theoretically 3850 // useless. 3851 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3852 if (SCS == DeclSpec::SCS_mutable) 3853 // Since mutable is not a viable storage class specifier in C, there is 3854 // no reason to treat it as an extension. Instead, diagnose as an error. 3855 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3856 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3857 Diag(DS.getStorageClassSpecLoc(), DiagID) 3858 << DeclSpec::getSpecifierName(SCS); 3859 } 3860 3861 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3862 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3863 << DeclSpec::getSpecifierName(TSCS); 3864 if (DS.getTypeQualifiers()) { 3865 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3866 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3867 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3868 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3869 // Restrict is covered above. 3870 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3871 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3872 } 3873 3874 // Warn about ignored type attributes, for example: 3875 // __attribute__((aligned)) struct A; 3876 // Attributes should be placed after tag to apply to type declaration. 3877 if (!DS.getAttributes().empty()) { 3878 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3879 if (TypeSpecType == DeclSpec::TST_class || 3880 TypeSpecType == DeclSpec::TST_struct || 3881 TypeSpecType == DeclSpec::TST_interface || 3882 TypeSpecType == DeclSpec::TST_union || 3883 TypeSpecType == DeclSpec::TST_enum) { 3884 for (AttributeList* attrs = DS.getAttributes().getList(); attrs; 3885 attrs = attrs->getNext()) 3886 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3887 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType); 3888 } 3889 } 3890 3891 return TagD; 3892 } 3893 3894 /// We are trying to inject an anonymous member into the given scope; 3895 /// check if there's an existing declaration that can't be overloaded. 3896 /// 3897 /// \return true if this is a forbidden redeclaration 3898 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3899 Scope *S, 3900 DeclContext *Owner, 3901 DeclarationName Name, 3902 SourceLocation NameLoc, 3903 unsigned diagnostic) { 3904 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3905 Sema::ForRedeclaration); 3906 if (!SemaRef.LookupName(R, S)) return false; 3907 3908 if (R.getAsSingle<TagDecl>()) 3909 return false; 3910 3911 // Pick a representative declaration. 3912 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3913 assert(PrevDecl && "Expected a non-null Decl"); 3914 3915 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3916 return false; 3917 3918 SemaRef.Diag(NameLoc, diagnostic) << Name; 3919 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3920 3921 return true; 3922 } 3923 3924 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3925 /// anonymous struct or union AnonRecord into the owning context Owner 3926 /// and scope S. This routine will be invoked just after we realize 3927 /// that an unnamed union or struct is actually an anonymous union or 3928 /// struct, e.g., 3929 /// 3930 /// @code 3931 /// union { 3932 /// int i; 3933 /// float f; 3934 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3935 /// // f into the surrounding scope.x 3936 /// @endcode 3937 /// 3938 /// This routine is recursive, injecting the names of nested anonymous 3939 /// structs/unions into the owning context and scope as well. 3940 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3941 DeclContext *Owner, 3942 RecordDecl *AnonRecord, 3943 AccessSpecifier AS, 3944 SmallVectorImpl<NamedDecl *> &Chaining, 3945 bool MSAnonStruct) { 3946 unsigned diagKind 3947 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3948 : diag::err_anonymous_struct_member_redecl; 3949 3950 bool Invalid = false; 3951 3952 // Look every FieldDecl and IndirectFieldDecl with a name. 3953 for (auto *D : AnonRecord->decls()) { 3954 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3955 cast<NamedDecl>(D)->getDeclName()) { 3956 ValueDecl *VD = cast<ValueDecl>(D); 3957 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3958 VD->getLocation(), diagKind)) { 3959 // C++ [class.union]p2: 3960 // The names of the members of an anonymous union shall be 3961 // distinct from the names of any other entity in the 3962 // scope in which the anonymous union is declared. 3963 Invalid = true; 3964 } else { 3965 // C++ [class.union]p2: 3966 // For the purpose of name lookup, after the anonymous union 3967 // definition, the members of the anonymous union are 3968 // considered to have been defined in the scope in which the 3969 // anonymous union is declared. 3970 unsigned OldChainingSize = Chaining.size(); 3971 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3972 Chaining.append(IF->chain_begin(), IF->chain_end()); 3973 else 3974 Chaining.push_back(VD); 3975 3976 assert(Chaining.size() >= 2); 3977 NamedDecl **NamedChain = 3978 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3979 for (unsigned i = 0; i < Chaining.size(); i++) 3980 NamedChain[i] = Chaining[i]; 3981 3982 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 3983 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 3984 VD->getType(), NamedChain, Chaining.size()); 3985 3986 for (const auto *Attr : VD->attrs()) 3987 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 3988 3989 IndirectField->setAccess(AS); 3990 IndirectField->setImplicit(); 3991 SemaRef.PushOnScopeChains(IndirectField, S); 3992 3993 // That includes picking up the appropriate access specifier. 3994 if (AS != AS_none) IndirectField->setAccess(AS); 3995 3996 Chaining.resize(OldChainingSize); 3997 } 3998 } 3999 } 4000 4001 return Invalid; 4002 } 4003 4004 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 4005 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 4006 /// illegal input values are mapped to SC_None. 4007 static StorageClass 4008 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 4009 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 4010 assert(StorageClassSpec != DeclSpec::SCS_typedef && 4011 "Parser allowed 'typedef' as storage class VarDecl."); 4012 switch (StorageClassSpec) { 4013 case DeclSpec::SCS_unspecified: return SC_None; 4014 case DeclSpec::SCS_extern: 4015 if (DS.isExternInLinkageSpec()) 4016 return SC_None; 4017 return SC_Extern; 4018 case DeclSpec::SCS_static: return SC_Static; 4019 case DeclSpec::SCS_auto: return SC_Auto; 4020 case DeclSpec::SCS_register: return SC_Register; 4021 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 4022 // Illegal SCSs map to None: error reporting is up to the caller. 4023 case DeclSpec::SCS_mutable: // Fall through. 4024 case DeclSpec::SCS_typedef: return SC_None; 4025 } 4026 llvm_unreachable("unknown storage class specifier"); 4027 } 4028 4029 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 4030 assert(Record->hasInClassInitializer()); 4031 4032 for (const auto *I : Record->decls()) { 4033 const auto *FD = dyn_cast<FieldDecl>(I); 4034 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 4035 FD = IFD->getAnonField(); 4036 if (FD && FD->hasInClassInitializer()) 4037 return FD->getLocation(); 4038 } 4039 4040 llvm_unreachable("couldn't find in-class initializer"); 4041 } 4042 4043 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4044 SourceLocation DefaultInitLoc) { 4045 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4046 return; 4047 4048 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 4049 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 4050 } 4051 4052 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 4053 CXXRecordDecl *AnonUnion) { 4054 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 4055 return; 4056 4057 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 4058 } 4059 4060 /// BuildAnonymousStructOrUnion - Handle the declaration of an 4061 /// anonymous structure or union. Anonymous unions are a C++ feature 4062 /// (C++ [class.union]) and a C11 feature; anonymous structures 4063 /// are a C11 feature and GNU C++ extension. 4064 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 4065 AccessSpecifier AS, 4066 RecordDecl *Record, 4067 const PrintingPolicy &Policy) { 4068 DeclContext *Owner = Record->getDeclContext(); 4069 4070 // Diagnose whether this anonymous struct/union is an extension. 4071 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 4072 Diag(Record->getLocation(), diag::ext_anonymous_union); 4073 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 4074 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 4075 else if (!Record->isUnion() && !getLangOpts().C11) 4076 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 4077 4078 // C and C++ require different kinds of checks for anonymous 4079 // structs/unions. 4080 bool Invalid = false; 4081 if (getLangOpts().CPlusPlus) { 4082 const char *PrevSpec = nullptr; 4083 unsigned DiagID; 4084 if (Record->isUnion()) { 4085 // C++ [class.union]p6: 4086 // Anonymous unions declared in a named namespace or in the 4087 // global namespace shall be declared static. 4088 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 4089 (isa<TranslationUnitDecl>(Owner) || 4090 (isa<NamespaceDecl>(Owner) && 4091 cast<NamespaceDecl>(Owner)->getDeclName()))) { 4092 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 4093 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 4094 4095 // Recover by adding 'static'. 4096 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 4097 PrevSpec, DiagID, Policy); 4098 } 4099 // C++ [class.union]p6: 4100 // A storage class is not allowed in a declaration of an 4101 // anonymous union in a class scope. 4102 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 4103 isa<RecordDecl>(Owner)) { 4104 Diag(DS.getStorageClassSpecLoc(), 4105 diag::err_anonymous_union_with_storage_spec) 4106 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 4107 4108 // Recover by removing the storage specifier. 4109 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 4110 SourceLocation(), 4111 PrevSpec, DiagID, Context.getPrintingPolicy()); 4112 } 4113 } 4114 4115 // Ignore const/volatile/restrict qualifiers. 4116 if (DS.getTypeQualifiers()) { 4117 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 4118 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 4119 << Record->isUnion() << "const" 4120 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 4121 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 4122 Diag(DS.getVolatileSpecLoc(), 4123 diag::ext_anonymous_struct_union_qualified) 4124 << Record->isUnion() << "volatile" 4125 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 4126 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 4127 Diag(DS.getRestrictSpecLoc(), 4128 diag::ext_anonymous_struct_union_qualified) 4129 << Record->isUnion() << "restrict" 4130 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 4131 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 4132 Diag(DS.getAtomicSpecLoc(), 4133 diag::ext_anonymous_struct_union_qualified) 4134 << Record->isUnion() << "_Atomic" 4135 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 4136 4137 DS.ClearTypeQualifiers(); 4138 } 4139 4140 // C++ [class.union]p2: 4141 // The member-specification of an anonymous union shall only 4142 // define non-static data members. [Note: nested types and 4143 // functions cannot be declared within an anonymous union. ] 4144 for (auto *Mem : Record->decls()) { 4145 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 4146 // C++ [class.union]p3: 4147 // An anonymous union shall not have private or protected 4148 // members (clause 11). 4149 assert(FD->getAccess() != AS_none); 4150 if (FD->getAccess() != AS_public) { 4151 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4152 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 4153 Invalid = true; 4154 } 4155 4156 // C++ [class.union]p1 4157 // An object of a class with a non-trivial constructor, a non-trivial 4158 // copy constructor, a non-trivial destructor, or a non-trivial copy 4159 // assignment operator cannot be a member of a union, nor can an 4160 // array of such objects. 4161 if (CheckNontrivialField(FD)) 4162 Invalid = true; 4163 } else if (Mem->isImplicit()) { 4164 // Any implicit members are fine. 4165 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4166 // This is a type that showed up in an 4167 // elaborated-type-specifier inside the anonymous struct or 4168 // union, but which actually declares a type outside of the 4169 // anonymous struct or union. It's okay. 4170 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4171 if (!MemRecord->isAnonymousStructOrUnion() && 4172 MemRecord->getDeclName()) { 4173 // Visual C++ allows type definition in anonymous struct or union. 4174 if (getLangOpts().MicrosoftExt) 4175 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4176 << (int)Record->isUnion(); 4177 else { 4178 // This is a nested type declaration. 4179 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4180 << (int)Record->isUnion(); 4181 Invalid = true; 4182 } 4183 } else { 4184 // This is an anonymous type definition within another anonymous type. 4185 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4186 // not part of standard C++. 4187 Diag(MemRecord->getLocation(), 4188 diag::ext_anonymous_record_with_anonymous_type) 4189 << (int)Record->isUnion(); 4190 } 4191 } else if (isa<AccessSpecDecl>(Mem)) { 4192 // Any access specifier is fine. 4193 } else if (isa<StaticAssertDecl>(Mem)) { 4194 // In C++1z, static_assert declarations are also fine. 4195 } else { 4196 // We have something that isn't a non-static data 4197 // member. Complain about it. 4198 unsigned DK = diag::err_anonymous_record_bad_member; 4199 if (isa<TypeDecl>(Mem)) 4200 DK = diag::err_anonymous_record_with_type; 4201 else if (isa<FunctionDecl>(Mem)) 4202 DK = diag::err_anonymous_record_with_function; 4203 else if (isa<VarDecl>(Mem)) 4204 DK = diag::err_anonymous_record_with_static; 4205 4206 // Visual C++ allows type definition in anonymous struct or union. 4207 if (getLangOpts().MicrosoftExt && 4208 DK == diag::err_anonymous_record_with_type) 4209 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4210 << (int)Record->isUnion(); 4211 else { 4212 Diag(Mem->getLocation(), DK) 4213 << (int)Record->isUnion(); 4214 Invalid = true; 4215 } 4216 } 4217 } 4218 4219 // C++11 [class.union]p8 (DR1460): 4220 // At most one variant member of a union may have a 4221 // brace-or-equal-initializer. 4222 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4223 Owner->isRecord()) 4224 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4225 cast<CXXRecordDecl>(Record)); 4226 } 4227 4228 if (!Record->isUnion() && !Owner->isRecord()) { 4229 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4230 << (int)getLangOpts().CPlusPlus; 4231 Invalid = true; 4232 } 4233 4234 // Mock up a declarator. 4235 Declarator Dc(DS, Declarator::MemberContext); 4236 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4237 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4238 4239 // Create a declaration for this anonymous struct/union. 4240 NamedDecl *Anon = nullptr; 4241 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4242 Anon = FieldDecl::Create(Context, OwningClass, 4243 DS.getLocStart(), 4244 Record->getLocation(), 4245 /*IdentifierInfo=*/nullptr, 4246 Context.getTypeDeclType(Record), 4247 TInfo, 4248 /*BitWidth=*/nullptr, /*Mutable=*/false, 4249 /*InitStyle=*/ICIS_NoInit); 4250 Anon->setAccess(AS); 4251 if (getLangOpts().CPlusPlus) 4252 FieldCollector->Add(cast<FieldDecl>(Anon)); 4253 } else { 4254 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4255 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4256 if (SCSpec == DeclSpec::SCS_mutable) { 4257 // mutable can only appear on non-static class members, so it's always 4258 // an error here 4259 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4260 Invalid = true; 4261 SC = SC_None; 4262 } 4263 4264 Anon = VarDecl::Create(Context, Owner, 4265 DS.getLocStart(), 4266 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4267 Context.getTypeDeclType(Record), 4268 TInfo, SC); 4269 4270 // Default-initialize the implicit variable. This initialization will be 4271 // trivial in almost all cases, except if a union member has an in-class 4272 // initializer: 4273 // union { int n = 0; }; 4274 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4275 } 4276 Anon->setImplicit(); 4277 4278 // Mark this as an anonymous struct/union type. 4279 Record->setAnonymousStructOrUnion(true); 4280 4281 // Add the anonymous struct/union object to the current 4282 // context. We'll be referencing this object when we refer to one of 4283 // its members. 4284 Owner->addDecl(Anon); 4285 4286 // Inject the members of the anonymous struct/union into the owning 4287 // context and into the identifier resolver chain for name lookup 4288 // purposes. 4289 SmallVector<NamedDecl*, 2> Chain; 4290 Chain.push_back(Anon); 4291 4292 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 4293 Chain, false)) 4294 Invalid = true; 4295 4296 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4297 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4298 Decl *ManglingContextDecl; 4299 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4300 NewVD->getDeclContext(), ManglingContextDecl)) { 4301 Context.setManglingNumber( 4302 NewVD, MCtx->getManglingNumber( 4303 NewVD, getMSManglingNumber(getLangOpts(), S))); 4304 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4305 } 4306 } 4307 } 4308 4309 if (Invalid) 4310 Anon->setInvalidDecl(); 4311 4312 return Anon; 4313 } 4314 4315 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4316 /// Microsoft C anonymous structure. 4317 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4318 /// Example: 4319 /// 4320 /// struct A { int a; }; 4321 /// struct B { struct A; int b; }; 4322 /// 4323 /// void foo() { 4324 /// B var; 4325 /// var.a = 3; 4326 /// } 4327 /// 4328 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4329 RecordDecl *Record) { 4330 assert(Record && "expected a record!"); 4331 4332 // Mock up a declarator. 4333 Declarator Dc(DS, Declarator::TypeNameContext); 4334 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4335 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4336 4337 auto *ParentDecl = cast<RecordDecl>(CurContext); 4338 QualType RecTy = Context.getTypeDeclType(Record); 4339 4340 // Create a declaration for this anonymous struct. 4341 NamedDecl *Anon = FieldDecl::Create(Context, 4342 ParentDecl, 4343 DS.getLocStart(), 4344 DS.getLocStart(), 4345 /*IdentifierInfo=*/nullptr, 4346 RecTy, 4347 TInfo, 4348 /*BitWidth=*/nullptr, /*Mutable=*/false, 4349 /*InitStyle=*/ICIS_NoInit); 4350 Anon->setImplicit(); 4351 4352 // Add the anonymous struct object to the current context. 4353 CurContext->addDecl(Anon); 4354 4355 // Inject the members of the anonymous struct into the current 4356 // context and into the identifier resolver chain for name lookup 4357 // purposes. 4358 SmallVector<NamedDecl*, 2> Chain; 4359 Chain.push_back(Anon); 4360 4361 RecordDecl *RecordDef = Record->getDefinition(); 4362 if (RequireCompleteType(Anon->getLocation(), RecTy, 4363 diag::err_field_incomplete) || 4364 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4365 AS_none, Chain, true)) { 4366 Anon->setInvalidDecl(); 4367 ParentDecl->setInvalidDecl(); 4368 } 4369 4370 return Anon; 4371 } 4372 4373 /// GetNameForDeclarator - Determine the full declaration name for the 4374 /// given Declarator. 4375 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4376 return GetNameFromUnqualifiedId(D.getName()); 4377 } 4378 4379 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4380 DeclarationNameInfo 4381 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4382 DeclarationNameInfo NameInfo; 4383 NameInfo.setLoc(Name.StartLocation); 4384 4385 switch (Name.getKind()) { 4386 4387 case UnqualifiedId::IK_ImplicitSelfParam: 4388 case UnqualifiedId::IK_Identifier: 4389 NameInfo.setName(Name.Identifier); 4390 NameInfo.setLoc(Name.StartLocation); 4391 return NameInfo; 4392 4393 case UnqualifiedId::IK_OperatorFunctionId: 4394 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4395 Name.OperatorFunctionId.Operator)); 4396 NameInfo.setLoc(Name.StartLocation); 4397 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4398 = Name.OperatorFunctionId.SymbolLocations[0]; 4399 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4400 = Name.EndLocation.getRawEncoding(); 4401 return NameInfo; 4402 4403 case UnqualifiedId::IK_LiteralOperatorId: 4404 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4405 Name.Identifier)); 4406 NameInfo.setLoc(Name.StartLocation); 4407 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4408 return NameInfo; 4409 4410 case UnqualifiedId::IK_ConversionFunctionId: { 4411 TypeSourceInfo *TInfo; 4412 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4413 if (Ty.isNull()) 4414 return DeclarationNameInfo(); 4415 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4416 Context.getCanonicalType(Ty))); 4417 NameInfo.setLoc(Name.StartLocation); 4418 NameInfo.setNamedTypeInfo(TInfo); 4419 return NameInfo; 4420 } 4421 4422 case UnqualifiedId::IK_ConstructorName: { 4423 TypeSourceInfo *TInfo; 4424 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4425 if (Ty.isNull()) 4426 return DeclarationNameInfo(); 4427 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4428 Context.getCanonicalType(Ty))); 4429 NameInfo.setLoc(Name.StartLocation); 4430 NameInfo.setNamedTypeInfo(TInfo); 4431 return NameInfo; 4432 } 4433 4434 case UnqualifiedId::IK_ConstructorTemplateId: { 4435 // In well-formed code, we can only have a constructor 4436 // template-id that refers to the current context, so go there 4437 // to find the actual type being constructed. 4438 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4439 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4440 return DeclarationNameInfo(); 4441 4442 // Determine the type of the class being constructed. 4443 QualType CurClassType = Context.getTypeDeclType(CurClass); 4444 4445 // FIXME: Check two things: that the template-id names the same type as 4446 // CurClassType, and that the template-id does not occur when the name 4447 // was qualified. 4448 4449 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4450 Context.getCanonicalType(CurClassType))); 4451 NameInfo.setLoc(Name.StartLocation); 4452 // FIXME: should we retrieve TypeSourceInfo? 4453 NameInfo.setNamedTypeInfo(nullptr); 4454 return NameInfo; 4455 } 4456 4457 case UnqualifiedId::IK_DestructorName: { 4458 TypeSourceInfo *TInfo; 4459 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4460 if (Ty.isNull()) 4461 return DeclarationNameInfo(); 4462 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4463 Context.getCanonicalType(Ty))); 4464 NameInfo.setLoc(Name.StartLocation); 4465 NameInfo.setNamedTypeInfo(TInfo); 4466 return NameInfo; 4467 } 4468 4469 case UnqualifiedId::IK_TemplateId: { 4470 TemplateName TName = Name.TemplateId->Template.get(); 4471 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4472 return Context.getNameForTemplate(TName, TNameLoc); 4473 } 4474 4475 } // switch (Name.getKind()) 4476 4477 llvm_unreachable("Unknown name kind"); 4478 } 4479 4480 static QualType getCoreType(QualType Ty) { 4481 do { 4482 if (Ty->isPointerType() || Ty->isReferenceType()) 4483 Ty = Ty->getPointeeType(); 4484 else if (Ty->isArrayType()) 4485 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4486 else 4487 return Ty.withoutLocalFastQualifiers(); 4488 } while (true); 4489 } 4490 4491 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4492 /// and Definition have "nearly" matching parameters. This heuristic is 4493 /// used to improve diagnostics in the case where an out-of-line function 4494 /// definition doesn't match any declaration within the class or namespace. 4495 /// Also sets Params to the list of indices to the parameters that differ 4496 /// between the declaration and the definition. If hasSimilarParameters 4497 /// returns true and Params is empty, then all of the parameters match. 4498 static bool hasSimilarParameters(ASTContext &Context, 4499 FunctionDecl *Declaration, 4500 FunctionDecl *Definition, 4501 SmallVectorImpl<unsigned> &Params) { 4502 Params.clear(); 4503 if (Declaration->param_size() != Definition->param_size()) 4504 return false; 4505 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4506 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4507 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4508 4509 // The parameter types are identical 4510 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4511 continue; 4512 4513 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4514 QualType DefParamBaseTy = getCoreType(DefParamTy); 4515 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4516 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4517 4518 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4519 (DeclTyName && DeclTyName == DefTyName)) 4520 Params.push_back(Idx); 4521 else // The two parameters aren't even close 4522 return false; 4523 } 4524 4525 return true; 4526 } 4527 4528 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4529 /// declarator needs to be rebuilt in the current instantiation. 4530 /// Any bits of declarator which appear before the name are valid for 4531 /// consideration here. That's specifically the type in the decl spec 4532 /// and the base type in any member-pointer chunks. 4533 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4534 DeclarationName Name) { 4535 // The types we specifically need to rebuild are: 4536 // - typenames, typeofs, and decltypes 4537 // - types which will become injected class names 4538 // Of course, we also need to rebuild any type referencing such a 4539 // type. It's safest to just say "dependent", but we call out a 4540 // few cases here. 4541 4542 DeclSpec &DS = D.getMutableDeclSpec(); 4543 switch (DS.getTypeSpecType()) { 4544 case DeclSpec::TST_typename: 4545 case DeclSpec::TST_typeofType: 4546 case DeclSpec::TST_underlyingType: 4547 case DeclSpec::TST_atomic: { 4548 // Grab the type from the parser. 4549 TypeSourceInfo *TSI = nullptr; 4550 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4551 if (T.isNull() || !T->isDependentType()) break; 4552 4553 // Make sure there's a type source info. This isn't really much 4554 // of a waste; most dependent types should have type source info 4555 // attached already. 4556 if (!TSI) 4557 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4558 4559 // Rebuild the type in the current instantiation. 4560 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4561 if (!TSI) return true; 4562 4563 // Store the new type back in the decl spec. 4564 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4565 DS.UpdateTypeRep(LocType); 4566 break; 4567 } 4568 4569 case DeclSpec::TST_decltype: 4570 case DeclSpec::TST_typeofExpr: { 4571 Expr *E = DS.getRepAsExpr(); 4572 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4573 if (Result.isInvalid()) return true; 4574 DS.UpdateExprRep(Result.get()); 4575 break; 4576 } 4577 4578 default: 4579 // Nothing to do for these decl specs. 4580 break; 4581 } 4582 4583 // It doesn't matter what order we do this in. 4584 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4585 DeclaratorChunk &Chunk = D.getTypeObject(I); 4586 4587 // The only type information in the declarator which can come 4588 // before the declaration name is the base type of a member 4589 // pointer. 4590 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4591 continue; 4592 4593 // Rebuild the scope specifier in-place. 4594 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4595 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4596 return true; 4597 } 4598 4599 return false; 4600 } 4601 4602 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4603 D.setFunctionDefinitionKind(FDK_Declaration); 4604 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4605 4606 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4607 Dcl && Dcl->getDeclContext()->isFileContext()) 4608 Dcl->setTopLevelDeclInObjCContainer(); 4609 4610 return Dcl; 4611 } 4612 4613 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4614 /// If T is the name of a class, then each of the following shall have a 4615 /// name different from T: 4616 /// - every static data member of class T; 4617 /// - every member function of class T 4618 /// - every member of class T that is itself a type; 4619 /// \returns true if the declaration name violates these rules. 4620 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4621 DeclarationNameInfo NameInfo) { 4622 DeclarationName Name = NameInfo.getName(); 4623 4624 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4625 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4626 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4627 return true; 4628 } 4629 4630 return false; 4631 } 4632 4633 /// \brief Diagnose a declaration whose declarator-id has the given 4634 /// nested-name-specifier. 4635 /// 4636 /// \param SS The nested-name-specifier of the declarator-id. 4637 /// 4638 /// \param DC The declaration context to which the nested-name-specifier 4639 /// resolves. 4640 /// 4641 /// \param Name The name of the entity being declared. 4642 /// 4643 /// \param Loc The location of the name of the entity being declared. 4644 /// 4645 /// \returns true if we cannot safely recover from this error, false otherwise. 4646 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4647 DeclarationName Name, 4648 SourceLocation Loc) { 4649 DeclContext *Cur = CurContext; 4650 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4651 Cur = Cur->getParent(); 4652 4653 // If the user provided a superfluous scope specifier that refers back to the 4654 // class in which the entity is already declared, diagnose and ignore it. 4655 // 4656 // class X { 4657 // void X::f(); 4658 // }; 4659 // 4660 // Note, it was once ill-formed to give redundant qualification in all 4661 // contexts, but that rule was removed by DR482. 4662 if (Cur->Equals(DC)) { 4663 if (Cur->isRecord()) { 4664 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4665 : diag::err_member_extra_qualification) 4666 << Name << FixItHint::CreateRemoval(SS.getRange()); 4667 SS.clear(); 4668 } else { 4669 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4670 } 4671 return false; 4672 } 4673 4674 // Check whether the qualifying scope encloses the scope of the original 4675 // declaration. 4676 if (!Cur->Encloses(DC)) { 4677 if (Cur->isRecord()) 4678 Diag(Loc, diag::err_member_qualification) 4679 << Name << SS.getRange(); 4680 else if (isa<TranslationUnitDecl>(DC)) 4681 Diag(Loc, diag::err_invalid_declarator_global_scope) 4682 << Name << SS.getRange(); 4683 else if (isa<FunctionDecl>(Cur)) 4684 Diag(Loc, diag::err_invalid_declarator_in_function) 4685 << Name << SS.getRange(); 4686 else if (isa<BlockDecl>(Cur)) 4687 Diag(Loc, diag::err_invalid_declarator_in_block) 4688 << Name << SS.getRange(); 4689 else 4690 Diag(Loc, diag::err_invalid_declarator_scope) 4691 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4692 4693 return true; 4694 } 4695 4696 if (Cur->isRecord()) { 4697 // Cannot qualify members within a class. 4698 Diag(Loc, diag::err_member_qualification) 4699 << Name << SS.getRange(); 4700 SS.clear(); 4701 4702 // C++ constructors and destructors with incorrect scopes can break 4703 // our AST invariants by having the wrong underlying types. If 4704 // that's the case, then drop this declaration entirely. 4705 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4706 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4707 !Context.hasSameType(Name.getCXXNameType(), 4708 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4709 return true; 4710 4711 return false; 4712 } 4713 4714 // C++11 [dcl.meaning]p1: 4715 // [...] "The nested-name-specifier of the qualified declarator-id shall 4716 // not begin with a decltype-specifer" 4717 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4718 while (SpecLoc.getPrefix()) 4719 SpecLoc = SpecLoc.getPrefix(); 4720 if (dyn_cast_or_null<DecltypeType>( 4721 SpecLoc.getNestedNameSpecifier()->getAsType())) 4722 Diag(Loc, diag::err_decltype_in_declarator) 4723 << SpecLoc.getTypeLoc().getSourceRange(); 4724 4725 return false; 4726 } 4727 4728 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4729 MultiTemplateParamsArg TemplateParamLists) { 4730 // TODO: consider using NameInfo for diagnostic. 4731 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4732 DeclarationName Name = NameInfo.getName(); 4733 4734 // All of these full declarators require an identifier. If it doesn't have 4735 // one, the ParsedFreeStandingDeclSpec action should be used. 4736 if (!Name) { 4737 if (!D.isInvalidType()) // Reject this if we think it is valid. 4738 Diag(D.getDeclSpec().getLocStart(), 4739 diag::err_declarator_need_ident) 4740 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4741 return nullptr; 4742 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4743 return nullptr; 4744 4745 // The scope passed in may not be a decl scope. Zip up the scope tree until 4746 // we find one that is. 4747 while ((S->getFlags() & Scope::DeclScope) == 0 || 4748 (S->getFlags() & Scope::TemplateParamScope) != 0) 4749 S = S->getParent(); 4750 4751 DeclContext *DC = CurContext; 4752 if (D.getCXXScopeSpec().isInvalid()) 4753 D.setInvalidType(); 4754 else if (D.getCXXScopeSpec().isSet()) { 4755 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4756 UPPC_DeclarationQualifier)) 4757 return nullptr; 4758 4759 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4760 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4761 if (!DC || isa<EnumDecl>(DC)) { 4762 // If we could not compute the declaration context, it's because the 4763 // declaration context is dependent but does not refer to a class, 4764 // class template, or class template partial specialization. Complain 4765 // and return early, to avoid the coming semantic disaster. 4766 Diag(D.getIdentifierLoc(), 4767 diag::err_template_qualified_declarator_no_match) 4768 << D.getCXXScopeSpec().getScopeRep() 4769 << D.getCXXScopeSpec().getRange(); 4770 return nullptr; 4771 } 4772 bool IsDependentContext = DC->isDependentContext(); 4773 4774 if (!IsDependentContext && 4775 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4776 return nullptr; 4777 4778 // If a class is incomplete, do not parse entities inside it. 4779 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4780 Diag(D.getIdentifierLoc(), 4781 diag::err_member_def_undefined_record) 4782 << Name << DC << D.getCXXScopeSpec().getRange(); 4783 return nullptr; 4784 } 4785 if (!D.getDeclSpec().isFriendSpecified()) { 4786 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4787 Name, D.getIdentifierLoc())) { 4788 if (DC->isRecord()) 4789 return nullptr; 4790 4791 D.setInvalidType(); 4792 } 4793 } 4794 4795 // Check whether we need to rebuild the type of the given 4796 // declaration in the current instantiation. 4797 if (EnteringContext && IsDependentContext && 4798 TemplateParamLists.size() != 0) { 4799 ContextRAII SavedContext(*this, DC); 4800 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4801 D.setInvalidType(); 4802 } 4803 } 4804 4805 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4806 QualType R = TInfo->getType(); 4807 4808 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo)) 4809 // If this is a typedef, we'll end up spewing multiple diagnostics. 4810 // Just return early; it's safer. If this is a function, let the 4811 // "constructor cannot have a return type" diagnostic handle it. 4812 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4813 return nullptr; 4814 4815 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4816 UPPC_DeclarationType)) 4817 D.setInvalidType(); 4818 4819 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4820 ForRedeclaration); 4821 4822 // If we're hiding internal-linkage symbols in modules from redeclaration 4823 // lookup, let name lookup know. 4824 if ((getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) && 4825 getLangOpts().ModulesHideInternalLinkage && 4826 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4827 Previous.setAllowHiddenInternal(false); 4828 4829 // See if this is a redefinition of a variable in the same scope. 4830 if (!D.getCXXScopeSpec().isSet()) { 4831 bool IsLinkageLookup = false; 4832 bool CreateBuiltins = false; 4833 4834 // If the declaration we're planning to build will be a function 4835 // or object with linkage, then look for another declaration with 4836 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4837 // 4838 // If the declaration we're planning to build will be declared with 4839 // external linkage in the translation unit, create any builtin with 4840 // the same name. 4841 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4842 /* Do nothing*/; 4843 else if (CurContext->isFunctionOrMethod() && 4844 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4845 R->isFunctionType())) { 4846 IsLinkageLookup = true; 4847 CreateBuiltins = 4848 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4849 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4850 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4851 CreateBuiltins = true; 4852 4853 if (IsLinkageLookup) 4854 Previous.clear(LookupRedeclarationWithLinkage); 4855 4856 LookupName(Previous, S, CreateBuiltins); 4857 } else { // Something like "int foo::x;" 4858 LookupQualifiedName(Previous, DC); 4859 4860 // C++ [dcl.meaning]p1: 4861 // When the declarator-id is qualified, the declaration shall refer to a 4862 // previously declared member of the class or namespace to which the 4863 // qualifier refers (or, in the case of a namespace, of an element of the 4864 // inline namespace set of that namespace (7.3.1)) or to a specialization 4865 // thereof; [...] 4866 // 4867 // Note that we already checked the context above, and that we do not have 4868 // enough information to make sure that Previous contains the declaration 4869 // we want to match. For example, given: 4870 // 4871 // class X { 4872 // void f(); 4873 // void f(float); 4874 // }; 4875 // 4876 // void X::f(int) { } // ill-formed 4877 // 4878 // In this case, Previous will point to the overload set 4879 // containing the two f's declared in X, but neither of them 4880 // matches. 4881 4882 // C++ [dcl.meaning]p1: 4883 // [...] the member shall not merely have been introduced by a 4884 // using-declaration in the scope of the class or namespace nominated by 4885 // the nested-name-specifier of the declarator-id. 4886 RemoveUsingDecls(Previous); 4887 } 4888 4889 if (Previous.isSingleResult() && 4890 Previous.getFoundDecl()->isTemplateParameter()) { 4891 // Maybe we will complain about the shadowed template parameter. 4892 if (!D.isInvalidType()) 4893 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4894 Previous.getFoundDecl()); 4895 4896 // Just pretend that we didn't see the previous declaration. 4897 Previous.clear(); 4898 } 4899 4900 // In C++, the previous declaration we find might be a tag type 4901 // (class or enum). In this case, the new declaration will hide the 4902 // tag type. Note that this does does not apply if we're declaring a 4903 // typedef (C++ [dcl.typedef]p4). 4904 if (Previous.isSingleTagDecl() && 4905 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4906 Previous.clear(); 4907 4908 // Check that there are no default arguments other than in the parameters 4909 // of a function declaration (C++ only). 4910 if (getLangOpts().CPlusPlus) 4911 CheckExtraCXXDefaultArguments(D); 4912 4913 if (D.getDeclSpec().isConceptSpecified()) { 4914 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 4915 // applied only to the definition of a function template or variable 4916 // template, declared in namespace scope 4917 if (!TemplateParamLists.size()) { 4918 Diag(D.getDeclSpec().getConceptSpecLoc(), 4919 diag:: err_concept_wrong_decl_kind); 4920 return nullptr; 4921 } 4922 4923 if (!DC->getRedeclContext()->isFileContext()) { 4924 Diag(D.getIdentifierLoc(), 4925 diag::err_concept_decls_may_only_appear_in_namespace_scope); 4926 return nullptr; 4927 } 4928 } 4929 4930 NamedDecl *New; 4931 4932 bool AddToScope = true; 4933 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4934 if (TemplateParamLists.size()) { 4935 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4936 return nullptr; 4937 } 4938 4939 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4940 } else if (R->isFunctionType()) { 4941 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4942 TemplateParamLists, 4943 AddToScope); 4944 } else { 4945 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4946 AddToScope); 4947 } 4948 4949 if (!New) 4950 return nullptr; 4951 4952 // If this has an identifier and is not an invalid redeclaration or 4953 // function template specialization, add it to the scope stack. 4954 if (New->getDeclName() && AddToScope && 4955 !(D.isRedeclaration() && New->isInvalidDecl())) { 4956 // Only make a locally-scoped extern declaration visible if it is the first 4957 // declaration of this entity. Qualified lookup for such an entity should 4958 // only find this declaration if there is no visible declaration of it. 4959 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4960 PushOnScopeChains(New, S, AddToContext); 4961 if (!AddToContext) 4962 CurContext->addHiddenDecl(New); 4963 } 4964 4965 return New; 4966 } 4967 4968 /// Helper method to turn variable array types into constant array 4969 /// types in certain situations which would otherwise be errors (for 4970 /// GCC compatibility). 4971 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4972 ASTContext &Context, 4973 bool &SizeIsNegative, 4974 llvm::APSInt &Oversized) { 4975 // This method tries to turn a variable array into a constant 4976 // array even when the size isn't an ICE. This is necessary 4977 // for compatibility with code that depends on gcc's buggy 4978 // constant expression folding, like struct {char x[(int)(char*)2];} 4979 SizeIsNegative = false; 4980 Oversized = 0; 4981 4982 if (T->isDependentType()) 4983 return QualType(); 4984 4985 QualifierCollector Qs; 4986 const Type *Ty = Qs.strip(T); 4987 4988 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4989 QualType Pointee = PTy->getPointeeType(); 4990 QualType FixedType = 4991 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4992 Oversized); 4993 if (FixedType.isNull()) return FixedType; 4994 FixedType = Context.getPointerType(FixedType); 4995 return Qs.apply(Context, FixedType); 4996 } 4997 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4998 QualType Inner = PTy->getInnerType(); 4999 QualType FixedType = 5000 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 5001 Oversized); 5002 if (FixedType.isNull()) return FixedType; 5003 FixedType = Context.getParenType(FixedType); 5004 return Qs.apply(Context, FixedType); 5005 } 5006 5007 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 5008 if (!VLATy) 5009 return QualType(); 5010 // FIXME: We should probably handle this case 5011 if (VLATy->getElementType()->isVariablyModifiedType()) 5012 return QualType(); 5013 5014 llvm::APSInt Res; 5015 if (!VLATy->getSizeExpr() || 5016 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 5017 return QualType(); 5018 5019 // Check whether the array size is negative. 5020 if (Res.isSigned() && Res.isNegative()) { 5021 SizeIsNegative = true; 5022 return QualType(); 5023 } 5024 5025 // Check whether the array is too large to be addressed. 5026 unsigned ActiveSizeBits 5027 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 5028 Res); 5029 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 5030 Oversized = Res; 5031 return QualType(); 5032 } 5033 5034 return Context.getConstantArrayType(VLATy->getElementType(), 5035 Res, ArrayType::Normal, 0); 5036 } 5037 5038 static void 5039 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 5040 SrcTL = SrcTL.getUnqualifiedLoc(); 5041 DstTL = DstTL.getUnqualifiedLoc(); 5042 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 5043 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 5044 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 5045 DstPTL.getPointeeLoc()); 5046 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 5047 return; 5048 } 5049 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 5050 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 5051 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 5052 DstPTL.getInnerLoc()); 5053 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 5054 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 5055 return; 5056 } 5057 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 5058 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 5059 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 5060 TypeLoc DstElemTL = DstATL.getElementLoc(); 5061 DstElemTL.initializeFullCopy(SrcElemTL); 5062 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 5063 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 5064 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 5065 } 5066 5067 /// Helper method to turn variable array types into constant array 5068 /// types in certain situations which would otherwise be errors (for 5069 /// GCC compatibility). 5070 static TypeSourceInfo* 5071 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 5072 ASTContext &Context, 5073 bool &SizeIsNegative, 5074 llvm::APSInt &Oversized) { 5075 QualType FixedTy 5076 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 5077 SizeIsNegative, Oversized); 5078 if (FixedTy.isNull()) 5079 return nullptr; 5080 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 5081 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 5082 FixedTInfo->getTypeLoc()); 5083 return FixedTInfo; 5084 } 5085 5086 /// \brief Register the given locally-scoped extern "C" declaration so 5087 /// that it can be found later for redeclarations. We include any extern "C" 5088 /// declaration that is not visible in the translation unit here, not just 5089 /// function-scope declarations. 5090 void 5091 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 5092 if (!getLangOpts().CPlusPlus && 5093 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 5094 // Don't need to track declarations in the TU in C. 5095 return; 5096 5097 // Note that we have a locally-scoped external with this name. 5098 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 5099 } 5100 5101 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 5102 // FIXME: We can have multiple results via __attribute__((overloadable)). 5103 auto Result = Context.getExternCContextDecl()->lookup(Name); 5104 return Result.empty() ? nullptr : *Result.begin(); 5105 } 5106 5107 /// \brief Diagnose function specifiers on a declaration of an identifier that 5108 /// does not identify a function. 5109 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 5110 // FIXME: We should probably indicate the identifier in question to avoid 5111 // confusion for constructs like "inline int a(), b;" 5112 if (DS.isInlineSpecified()) 5113 Diag(DS.getInlineSpecLoc(), 5114 diag::err_inline_non_function); 5115 5116 if (DS.isVirtualSpecified()) 5117 Diag(DS.getVirtualSpecLoc(), 5118 diag::err_virtual_non_function); 5119 5120 if (DS.isExplicitSpecified()) 5121 Diag(DS.getExplicitSpecLoc(), 5122 diag::err_explicit_non_function); 5123 5124 if (DS.isNoreturnSpecified()) 5125 Diag(DS.getNoreturnSpecLoc(), 5126 diag::err_noreturn_non_function); 5127 } 5128 5129 NamedDecl* 5130 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 5131 TypeSourceInfo *TInfo, LookupResult &Previous) { 5132 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 5133 if (D.getCXXScopeSpec().isSet()) { 5134 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 5135 << D.getCXXScopeSpec().getRange(); 5136 D.setInvalidType(); 5137 // Pretend we didn't see the scope specifier. 5138 DC = CurContext; 5139 Previous.clear(); 5140 } 5141 5142 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5143 5144 if (D.getDeclSpec().isConstexprSpecified()) 5145 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 5146 << 1; 5147 if (D.getDeclSpec().isConceptSpecified()) 5148 Diag(D.getDeclSpec().getConceptSpecLoc(), 5149 diag::err_concept_wrong_decl_kind); 5150 5151 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 5152 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 5153 << D.getName().getSourceRange(); 5154 return nullptr; 5155 } 5156 5157 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 5158 if (!NewTD) return nullptr; 5159 5160 // Handle attributes prior to checking for duplicates in MergeVarDecl 5161 ProcessDeclAttributes(S, NewTD, D); 5162 5163 CheckTypedefForVariablyModifiedType(S, NewTD); 5164 5165 bool Redeclaration = D.isRedeclaration(); 5166 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 5167 D.setRedeclaration(Redeclaration); 5168 return ND; 5169 } 5170 5171 void 5172 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 5173 // C99 6.7.7p2: If a typedef name specifies a variably modified type 5174 // then it shall have block scope. 5175 // Note that variably modified types must be fixed before merging the decl so 5176 // that redeclarations will match. 5177 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 5178 QualType T = TInfo->getType(); 5179 if (T->isVariablyModifiedType()) { 5180 getCurFunction()->setHasBranchProtectedScope(); 5181 5182 if (S->getFnParent() == nullptr) { 5183 bool SizeIsNegative; 5184 llvm::APSInt Oversized; 5185 TypeSourceInfo *FixedTInfo = 5186 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5187 SizeIsNegative, 5188 Oversized); 5189 if (FixedTInfo) { 5190 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5191 NewTD->setTypeSourceInfo(FixedTInfo); 5192 } else { 5193 if (SizeIsNegative) 5194 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5195 else if (T->isVariableArrayType()) 5196 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5197 else if (Oversized.getBoolValue()) 5198 Diag(NewTD->getLocation(), diag::err_array_too_large) 5199 << Oversized.toString(10); 5200 else 5201 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5202 NewTD->setInvalidDecl(); 5203 } 5204 } 5205 } 5206 } 5207 5208 5209 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5210 /// declares a typedef-name, either using the 'typedef' type specifier or via 5211 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5212 NamedDecl* 5213 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5214 LookupResult &Previous, bool &Redeclaration) { 5215 // Merge the decl with the existing one if appropriate. If the decl is 5216 // in an outer scope, it isn't the same thing. 5217 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5218 /*AllowInlineNamespace*/false); 5219 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous); 5220 if (!Previous.empty()) { 5221 Redeclaration = true; 5222 MergeTypedefNameDecl(NewTD, Previous); 5223 } 5224 5225 // If this is the C FILE type, notify the AST context. 5226 if (IdentifierInfo *II = NewTD->getIdentifier()) 5227 if (!NewTD->isInvalidDecl() && 5228 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5229 if (II->isStr("FILE")) 5230 Context.setFILEDecl(NewTD); 5231 else if (II->isStr("jmp_buf")) 5232 Context.setjmp_bufDecl(NewTD); 5233 else if (II->isStr("sigjmp_buf")) 5234 Context.setsigjmp_bufDecl(NewTD); 5235 else if (II->isStr("ucontext_t")) 5236 Context.setucontext_tDecl(NewTD); 5237 } 5238 5239 return NewTD; 5240 } 5241 5242 /// \brief Determines whether the given declaration is an out-of-scope 5243 /// previous declaration. 5244 /// 5245 /// This routine should be invoked when name lookup has found a 5246 /// previous declaration (PrevDecl) that is not in the scope where a 5247 /// new declaration by the same name is being introduced. If the new 5248 /// declaration occurs in a local scope, previous declarations with 5249 /// linkage may still be considered previous declarations (C99 5250 /// 6.2.2p4-5, C++ [basic.link]p6). 5251 /// 5252 /// \param PrevDecl the previous declaration found by name 5253 /// lookup 5254 /// 5255 /// \param DC the context in which the new declaration is being 5256 /// declared. 5257 /// 5258 /// \returns true if PrevDecl is an out-of-scope previous declaration 5259 /// for a new delcaration with the same name. 5260 static bool 5261 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5262 ASTContext &Context) { 5263 if (!PrevDecl) 5264 return false; 5265 5266 if (!PrevDecl->hasLinkage()) 5267 return false; 5268 5269 if (Context.getLangOpts().CPlusPlus) { 5270 // C++ [basic.link]p6: 5271 // If there is a visible declaration of an entity with linkage 5272 // having the same name and type, ignoring entities declared 5273 // outside the innermost enclosing namespace scope, the block 5274 // scope declaration declares that same entity and receives the 5275 // linkage of the previous declaration. 5276 DeclContext *OuterContext = DC->getRedeclContext(); 5277 if (!OuterContext->isFunctionOrMethod()) 5278 // This rule only applies to block-scope declarations. 5279 return false; 5280 5281 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5282 if (PrevOuterContext->isRecord()) 5283 // We found a member function: ignore it. 5284 return false; 5285 5286 // Find the innermost enclosing namespace for the new and 5287 // previous declarations. 5288 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5289 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5290 5291 // The previous declaration is in a different namespace, so it 5292 // isn't the same function. 5293 if (!OuterContext->Equals(PrevOuterContext)) 5294 return false; 5295 } 5296 5297 return true; 5298 } 5299 5300 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5301 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5302 if (!SS.isSet()) return; 5303 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5304 } 5305 5306 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5307 QualType type = decl->getType(); 5308 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5309 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5310 // Various kinds of declaration aren't allowed to be __autoreleasing. 5311 unsigned kind = -1U; 5312 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5313 if (var->hasAttr<BlocksAttr>()) 5314 kind = 0; // __block 5315 else if (!var->hasLocalStorage()) 5316 kind = 1; // global 5317 } else if (isa<ObjCIvarDecl>(decl)) { 5318 kind = 3; // ivar 5319 } else if (isa<FieldDecl>(decl)) { 5320 kind = 2; // field 5321 } 5322 5323 if (kind != -1U) { 5324 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5325 << kind; 5326 } 5327 } else if (lifetime == Qualifiers::OCL_None) { 5328 // Try to infer lifetime. 5329 if (!type->isObjCLifetimeType()) 5330 return false; 5331 5332 lifetime = type->getObjCARCImplicitLifetime(); 5333 type = Context.getLifetimeQualifiedType(type, lifetime); 5334 decl->setType(type); 5335 } 5336 5337 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5338 // Thread-local variables cannot have lifetime. 5339 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5340 var->getTLSKind()) { 5341 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5342 << var->getType(); 5343 return true; 5344 } 5345 } 5346 5347 return false; 5348 } 5349 5350 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5351 // Ensure that an auto decl is deduced otherwise the checks below might cache 5352 // the wrong linkage. 5353 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5354 5355 // 'weak' only applies to declarations with external linkage. 5356 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5357 if (!ND.isExternallyVisible()) { 5358 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5359 ND.dropAttr<WeakAttr>(); 5360 } 5361 } 5362 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5363 if (ND.isExternallyVisible()) { 5364 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5365 ND.dropAttr<WeakRefAttr>(); 5366 ND.dropAttr<AliasAttr>(); 5367 } 5368 } 5369 5370 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5371 if (VD->hasInit()) { 5372 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5373 assert(VD->isThisDeclarationADefinition() && 5374 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5375 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD; 5376 VD->dropAttr<AliasAttr>(); 5377 } 5378 } 5379 } 5380 5381 // 'selectany' only applies to externally visible variable declarations. 5382 // It does not apply to functions. 5383 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5384 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5385 S.Diag(Attr->getLocation(), 5386 diag::err_attribute_selectany_non_extern_data); 5387 ND.dropAttr<SelectAnyAttr>(); 5388 } 5389 } 5390 5391 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5392 // dll attributes require external linkage. Static locals may have external 5393 // linkage but still cannot be explicitly imported or exported. 5394 auto *VD = dyn_cast<VarDecl>(&ND); 5395 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) { 5396 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5397 << &ND << Attr; 5398 ND.setInvalidDecl(); 5399 } 5400 } 5401 5402 // Virtual functions cannot be marked as 'notail'. 5403 if (auto *Attr = ND.getAttr<NotTailCalledAttr>()) 5404 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND)) 5405 if (MD->isVirtual()) { 5406 S.Diag(ND.getLocation(), 5407 diag::err_invalid_attribute_on_virtual_function) 5408 << Attr; 5409 ND.dropAttr<NotTailCalledAttr>(); 5410 } 5411 } 5412 5413 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5414 NamedDecl *NewDecl, 5415 bool IsSpecialization) { 5416 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5417 OldDecl = OldTD->getTemplatedDecl(); 5418 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5419 NewDecl = NewTD->getTemplatedDecl(); 5420 5421 if (!OldDecl || !NewDecl) 5422 return; 5423 5424 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5425 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5426 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5427 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5428 5429 // dllimport and dllexport are inheritable attributes so we have to exclude 5430 // inherited attribute instances. 5431 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5432 (NewExportAttr && !NewExportAttr->isInherited()); 5433 5434 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5435 // the only exception being explicit specializations. 5436 // Implicitly generated declarations are also excluded for now because there 5437 // is no other way to switch these to use dllimport or dllexport. 5438 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5439 5440 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5441 // Allow with a warning for free functions and global variables. 5442 bool JustWarn = false; 5443 if (!OldDecl->isCXXClassMember()) { 5444 auto *VD = dyn_cast<VarDecl>(OldDecl); 5445 if (VD && !VD->getDescribedVarTemplate()) 5446 JustWarn = true; 5447 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5448 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5449 JustWarn = true; 5450 } 5451 5452 // We cannot change a declaration that's been used because IR has already 5453 // been emitted. Dllimported functions will still work though (modulo 5454 // address equality) as they can use the thunk. 5455 if (OldDecl->isUsed()) 5456 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr) 5457 JustWarn = false; 5458 5459 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5460 : diag::err_attribute_dll_redeclaration; 5461 S.Diag(NewDecl->getLocation(), DiagID) 5462 << NewDecl 5463 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5464 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5465 if (!JustWarn) { 5466 NewDecl->setInvalidDecl(); 5467 return; 5468 } 5469 } 5470 5471 // A redeclaration is not allowed to drop a dllimport attribute, the only 5472 // exceptions being inline function definitions, local extern declarations, 5473 // and qualified friend declarations. 5474 // NB: MSVC converts such a declaration to dllexport. 5475 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5476 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5477 // Ignore static data because out-of-line definitions are diagnosed 5478 // separately. 5479 IsStaticDataMember = VD->isStaticDataMember(); 5480 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5481 IsInline = FD->isInlined(); 5482 IsQualifiedFriend = FD->getQualifier() && 5483 FD->getFriendObjectKind() == Decl::FOK_Declared; 5484 } 5485 5486 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5487 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5488 S.Diag(NewDecl->getLocation(), 5489 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5490 << NewDecl << OldImportAttr; 5491 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5492 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5493 OldDecl->dropAttr<DLLImportAttr>(); 5494 NewDecl->dropAttr<DLLImportAttr>(); 5495 } else if (IsInline && OldImportAttr && 5496 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5497 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5498 OldDecl->dropAttr<DLLImportAttr>(); 5499 NewDecl->dropAttr<DLLImportAttr>(); 5500 S.Diag(NewDecl->getLocation(), 5501 diag::warn_dllimport_dropped_from_inline_function) 5502 << NewDecl << OldImportAttr; 5503 } 5504 } 5505 5506 /// Given that we are within the definition of the given function, 5507 /// will that definition behave like C99's 'inline', where the 5508 /// definition is discarded except for optimization purposes? 5509 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5510 // Try to avoid calling GetGVALinkageForFunction. 5511 5512 // All cases of this require the 'inline' keyword. 5513 if (!FD->isInlined()) return false; 5514 5515 // This is only possible in C++ with the gnu_inline attribute. 5516 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5517 return false; 5518 5519 // Okay, go ahead and call the relatively-more-expensive function. 5520 5521 #ifndef NDEBUG 5522 // AST quite reasonably asserts that it's working on a function 5523 // definition. We don't really have a way to tell it that we're 5524 // currently defining the function, so just lie to it in +Asserts 5525 // builds. This is an awful hack. 5526 FD->setLazyBody(1); 5527 #endif 5528 5529 bool isC99Inline = 5530 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5531 5532 #ifndef NDEBUG 5533 FD->setLazyBody(0); 5534 #endif 5535 5536 return isC99Inline; 5537 } 5538 5539 /// Determine whether a variable is extern "C" prior to attaching 5540 /// an initializer. We can't just call isExternC() here, because that 5541 /// will also compute and cache whether the declaration is externally 5542 /// visible, which might change when we attach the initializer. 5543 /// 5544 /// This can only be used if the declaration is known to not be a 5545 /// redeclaration of an internal linkage declaration. 5546 /// 5547 /// For instance: 5548 /// 5549 /// auto x = []{}; 5550 /// 5551 /// Attaching the initializer here makes this declaration not externally 5552 /// visible, because its type has internal linkage. 5553 /// 5554 /// FIXME: This is a hack. 5555 template<typename T> 5556 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5557 if (S.getLangOpts().CPlusPlus) { 5558 // In C++, the overloadable attribute negates the effects of extern "C". 5559 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5560 return false; 5561 5562 // So do CUDA's host/device attributes if overloading is enabled. 5563 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 5564 (D->template hasAttr<CUDADeviceAttr>() || 5565 D->template hasAttr<CUDAHostAttr>())) 5566 return false; 5567 } 5568 return D->isExternC(); 5569 } 5570 5571 static bool shouldConsiderLinkage(const VarDecl *VD) { 5572 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5573 if (DC->isFunctionOrMethod()) 5574 return VD->hasExternalStorage(); 5575 if (DC->isFileContext()) 5576 return true; 5577 if (DC->isRecord()) 5578 return false; 5579 llvm_unreachable("Unexpected context"); 5580 } 5581 5582 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5583 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5584 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5585 return true; 5586 if (DC->isRecord()) 5587 return false; 5588 llvm_unreachable("Unexpected context"); 5589 } 5590 5591 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5592 AttributeList::Kind Kind) { 5593 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5594 if (L->getKind() == Kind) 5595 return true; 5596 return false; 5597 } 5598 5599 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5600 AttributeList::Kind Kind) { 5601 // Check decl attributes on the DeclSpec. 5602 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5603 return true; 5604 5605 // Walk the declarator structure, checking decl attributes that were in a type 5606 // position to the decl itself. 5607 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5608 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5609 return true; 5610 } 5611 5612 // Finally, check attributes on the decl itself. 5613 return hasParsedAttr(S, PD.getAttributes(), Kind); 5614 } 5615 5616 /// Adjust the \c DeclContext for a function or variable that might be a 5617 /// function-local external declaration. 5618 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5619 if (!DC->isFunctionOrMethod()) 5620 return false; 5621 5622 // If this is a local extern function or variable declared within a function 5623 // template, don't add it into the enclosing namespace scope until it is 5624 // instantiated; it might have a dependent type right now. 5625 if (DC->isDependentContext()) 5626 return true; 5627 5628 // C++11 [basic.link]p7: 5629 // When a block scope declaration of an entity with linkage is not found to 5630 // refer to some other declaration, then that entity is a member of the 5631 // innermost enclosing namespace. 5632 // 5633 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5634 // semantically-enclosing namespace, not a lexically-enclosing one. 5635 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5636 DC = DC->getParent(); 5637 return true; 5638 } 5639 5640 /// \brief Returns true if given declaration has external C language linkage. 5641 static bool isDeclExternC(const Decl *D) { 5642 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 5643 return FD->isExternC(); 5644 if (const auto *VD = dyn_cast<VarDecl>(D)) 5645 return VD->isExternC(); 5646 5647 llvm_unreachable("Unknown type of decl!"); 5648 } 5649 5650 NamedDecl * 5651 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5652 TypeSourceInfo *TInfo, LookupResult &Previous, 5653 MultiTemplateParamsArg TemplateParamLists, 5654 bool &AddToScope) { 5655 QualType R = TInfo->getType(); 5656 DeclarationName Name = GetNameForDeclarator(D).getName(); 5657 5658 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5659 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5660 5661 // dllimport globals without explicit storage class are treated as extern. We 5662 // have to change the storage class this early to get the right DeclContext. 5663 if (SC == SC_None && !DC->isRecord() && 5664 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5665 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5666 SC = SC_Extern; 5667 5668 DeclContext *OriginalDC = DC; 5669 bool IsLocalExternDecl = SC == SC_Extern && 5670 adjustContextForLocalExternDecl(DC); 5671 5672 if (getLangOpts().OpenCL) { 5673 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5674 QualType NR = R; 5675 while (NR->isPointerType()) { 5676 if (NR->isFunctionPointerType()) { 5677 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5678 D.setInvalidType(); 5679 break; 5680 } 5681 NR = NR->getPointeeType(); 5682 } 5683 5684 if (!getOpenCLOptions().cl_khr_fp16) { 5685 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5686 // half array type (unless the cl_khr_fp16 extension is enabled). 5687 if (Context.getBaseElementType(R)->isHalfType()) { 5688 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5689 D.setInvalidType(); 5690 } 5691 } 5692 } 5693 5694 if (SCSpec == DeclSpec::SCS_mutable) { 5695 // mutable can only appear on non-static class members, so it's always 5696 // an error here 5697 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5698 D.setInvalidType(); 5699 SC = SC_None; 5700 } 5701 5702 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5703 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5704 D.getDeclSpec().getStorageClassSpecLoc())) { 5705 // In C++11, the 'register' storage class specifier is deprecated. 5706 // Suppress the warning in system macros, it's used in macros in some 5707 // popular C system headers, such as in glibc's htonl() macro. 5708 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5709 diag::warn_deprecated_register) 5710 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5711 } 5712 5713 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5714 if (!II) { 5715 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5716 << Name; 5717 return nullptr; 5718 } 5719 5720 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5721 5722 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5723 // C99 6.9p2: The storage-class specifiers auto and register shall not 5724 // appear in the declaration specifiers in an external declaration. 5725 // Global Register+Asm is a GNU extension we support. 5726 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5727 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5728 D.setInvalidType(); 5729 } 5730 } 5731 5732 if (getLangOpts().OpenCL) { 5733 // OpenCL v1.2 s6.9.b p4: 5734 // The sampler type cannot be used with the __local and __global address 5735 // space qualifiers. 5736 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5737 R.getAddressSpace() == LangAS::opencl_global)) { 5738 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5739 } 5740 5741 // OpenCL 1.2 spec, p6.9 r: 5742 // The event type cannot be used to declare a program scope variable. 5743 // The event type cannot be used with the __local, __constant and __global 5744 // address space qualifiers. 5745 if (R->isEventT()) { 5746 if (S->getParent() == nullptr) { 5747 Diag(D.getLocStart(), diag::err_event_t_global_var); 5748 D.setInvalidType(); 5749 } 5750 5751 if (R.getAddressSpace()) { 5752 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5753 D.setInvalidType(); 5754 } 5755 } 5756 } 5757 5758 bool IsExplicitSpecialization = false; 5759 bool IsVariableTemplateSpecialization = false; 5760 bool IsPartialSpecialization = false; 5761 bool IsVariableTemplate = false; 5762 VarDecl *NewVD = nullptr; 5763 VarTemplateDecl *NewTemplate = nullptr; 5764 TemplateParameterList *TemplateParams = nullptr; 5765 if (!getLangOpts().CPlusPlus) { 5766 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5767 D.getIdentifierLoc(), II, 5768 R, TInfo, SC); 5769 5770 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5771 ParsingInitForAutoVars.insert(NewVD); 5772 5773 if (D.isInvalidType()) 5774 NewVD->setInvalidDecl(); 5775 } else { 5776 bool Invalid = false; 5777 5778 if (DC->isRecord() && !CurContext->isRecord()) { 5779 // This is an out-of-line definition of a static data member. 5780 switch (SC) { 5781 case SC_None: 5782 break; 5783 case SC_Static: 5784 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5785 diag::err_static_out_of_line) 5786 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5787 break; 5788 case SC_Auto: 5789 case SC_Register: 5790 case SC_Extern: 5791 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5792 // to names of variables declared in a block or to function parameters. 5793 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5794 // of class members 5795 5796 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5797 diag::err_storage_class_for_static_member) 5798 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5799 break; 5800 case SC_PrivateExtern: 5801 llvm_unreachable("C storage class in c++!"); 5802 } 5803 } 5804 5805 if (SC == SC_Static && CurContext->isRecord()) { 5806 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5807 if (RD->isLocalClass()) 5808 Diag(D.getIdentifierLoc(), 5809 diag::err_static_data_member_not_allowed_in_local_class) 5810 << Name << RD->getDeclName(); 5811 5812 // C++98 [class.union]p1: If a union contains a static data member, 5813 // the program is ill-formed. C++11 drops this restriction. 5814 if (RD->isUnion()) 5815 Diag(D.getIdentifierLoc(), 5816 getLangOpts().CPlusPlus11 5817 ? diag::warn_cxx98_compat_static_data_member_in_union 5818 : diag::ext_static_data_member_in_union) << Name; 5819 // We conservatively disallow static data members in anonymous structs. 5820 else if (!RD->getDeclName()) 5821 Diag(D.getIdentifierLoc(), 5822 diag::err_static_data_member_not_allowed_in_anon_struct) 5823 << Name << RD->isUnion(); 5824 } 5825 } 5826 5827 // Match up the template parameter lists with the scope specifier, then 5828 // determine whether we have a template or a template specialization. 5829 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5830 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5831 D.getCXXScopeSpec(), 5832 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5833 ? D.getName().TemplateId 5834 : nullptr, 5835 TemplateParamLists, 5836 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5837 5838 if (TemplateParams) { 5839 if (!TemplateParams->size() && 5840 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5841 // There is an extraneous 'template<>' for this variable. Complain 5842 // about it, but allow the declaration of the variable. 5843 Diag(TemplateParams->getTemplateLoc(), 5844 diag::err_template_variable_noparams) 5845 << II 5846 << SourceRange(TemplateParams->getTemplateLoc(), 5847 TemplateParams->getRAngleLoc()); 5848 TemplateParams = nullptr; 5849 } else { 5850 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5851 // This is an explicit specialization or a partial specialization. 5852 // FIXME: Check that we can declare a specialization here. 5853 IsVariableTemplateSpecialization = true; 5854 IsPartialSpecialization = TemplateParams->size() > 0; 5855 } else { // if (TemplateParams->size() > 0) 5856 // This is a template declaration. 5857 IsVariableTemplate = true; 5858 5859 // Check that we can declare a template here. 5860 if (CheckTemplateDeclScope(S, TemplateParams)) 5861 return nullptr; 5862 5863 // Only C++1y supports variable templates (N3651). 5864 Diag(D.getIdentifierLoc(), 5865 getLangOpts().CPlusPlus14 5866 ? diag::warn_cxx11_compat_variable_template 5867 : diag::ext_variable_template); 5868 } 5869 } 5870 } else { 5871 assert( 5872 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 5873 "should have a 'template<>' for this decl"); 5874 } 5875 5876 if (IsVariableTemplateSpecialization) { 5877 SourceLocation TemplateKWLoc = 5878 TemplateParamLists.size() > 0 5879 ? TemplateParamLists[0]->getTemplateLoc() 5880 : SourceLocation(); 5881 DeclResult Res = ActOnVarTemplateSpecialization( 5882 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5883 IsPartialSpecialization); 5884 if (Res.isInvalid()) 5885 return nullptr; 5886 NewVD = cast<VarDecl>(Res.get()); 5887 AddToScope = false; 5888 } else 5889 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5890 D.getIdentifierLoc(), II, R, TInfo, SC); 5891 5892 // If this is supposed to be a variable template, create it as such. 5893 if (IsVariableTemplate) { 5894 NewTemplate = 5895 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5896 TemplateParams, NewVD); 5897 NewVD->setDescribedVarTemplate(NewTemplate); 5898 } 5899 5900 // If this decl has an auto type in need of deduction, make a note of the 5901 // Decl so we can diagnose uses of it in its own initializer. 5902 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5903 ParsingInitForAutoVars.insert(NewVD); 5904 5905 if (D.isInvalidType() || Invalid) { 5906 NewVD->setInvalidDecl(); 5907 if (NewTemplate) 5908 NewTemplate->setInvalidDecl(); 5909 } 5910 5911 SetNestedNameSpecifier(NewVD, D); 5912 5913 // If we have any template parameter lists that don't directly belong to 5914 // the variable (matching the scope specifier), store them. 5915 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5916 if (TemplateParamLists.size() > VDTemplateParamLists) 5917 NewVD->setTemplateParameterListsInfo( 5918 Context, TemplateParamLists.drop_back(VDTemplateParamLists)); 5919 5920 if (D.getDeclSpec().isConstexprSpecified()) 5921 NewVD->setConstexpr(true); 5922 5923 if (D.getDeclSpec().isConceptSpecified()) { 5924 NewVD->setConcept(true); 5925 5926 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 5927 // be declared with the thread_local, inline, friend, or constexpr 5928 // specifiers, [...] 5929 if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) { 5930 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5931 diag::err_concept_decl_invalid_specifiers) 5932 << 0 << 0; 5933 NewVD->setInvalidDecl(true); 5934 } 5935 5936 if (D.getDeclSpec().isConstexprSpecified()) { 5937 Diag(D.getDeclSpec().getConstexprSpecLoc(), 5938 diag::err_concept_decl_invalid_specifiers) 5939 << 0 << 3; 5940 NewVD->setInvalidDecl(true); 5941 } 5942 } 5943 } 5944 5945 // Set the lexical context. If the declarator has a C++ scope specifier, the 5946 // lexical context will be different from the semantic context. 5947 NewVD->setLexicalDeclContext(CurContext); 5948 if (NewTemplate) 5949 NewTemplate->setLexicalDeclContext(CurContext); 5950 5951 if (IsLocalExternDecl) 5952 NewVD->setLocalExternDecl(); 5953 5954 bool EmitTLSUnsupportedError = false; 5955 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5956 // C++11 [dcl.stc]p4: 5957 // When thread_local is applied to a variable of block scope the 5958 // storage-class-specifier static is implied if it does not appear 5959 // explicitly. 5960 // Core issue: 'static' is not implied if the variable is declared 5961 // 'extern'. 5962 if (NewVD->hasLocalStorage() && 5963 (SCSpec != DeclSpec::SCS_unspecified || 5964 TSCS != DeclSpec::TSCS_thread_local || 5965 !DC->isFunctionOrMethod())) 5966 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5967 diag::err_thread_non_global) 5968 << DeclSpec::getSpecifierName(TSCS); 5969 else if (!Context.getTargetInfo().isTLSSupported()) { 5970 if (getLangOpts().CUDA) { 5971 // Postpone error emission until we've collected attributes required to 5972 // figure out whether it's a host or device variable and whether the 5973 // error should be ignored. 5974 EmitTLSUnsupportedError = true; 5975 // We still need to mark the variable as TLS so it shows up in AST with 5976 // proper storage class for other tools to use even if we're not going 5977 // to emit any code for it. 5978 NewVD->setTSCSpec(TSCS); 5979 } else 5980 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5981 diag::err_thread_unsupported); 5982 } else 5983 NewVD->setTSCSpec(TSCS); 5984 } 5985 5986 // C99 6.7.4p3 5987 // An inline definition of a function with external linkage shall 5988 // not contain a definition of a modifiable object with static or 5989 // thread storage duration... 5990 // We only apply this when the function is required to be defined 5991 // elsewhere, i.e. when the function is not 'extern inline'. Note 5992 // that a local variable with thread storage duration still has to 5993 // be marked 'static'. Also note that it's possible to get these 5994 // semantics in C++ using __attribute__((gnu_inline)). 5995 if (SC == SC_Static && S->getFnParent() != nullptr && 5996 !NewVD->getType().isConstQualified()) { 5997 FunctionDecl *CurFD = getCurFunctionDecl(); 5998 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5999 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6000 diag::warn_static_local_in_extern_inline); 6001 MaybeSuggestAddingStaticToDecl(CurFD); 6002 } 6003 } 6004 6005 if (D.getDeclSpec().isModulePrivateSpecified()) { 6006 if (IsVariableTemplateSpecialization) 6007 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6008 << (IsPartialSpecialization ? 1 : 0) 6009 << FixItHint::CreateRemoval( 6010 D.getDeclSpec().getModulePrivateSpecLoc()); 6011 else if (IsExplicitSpecialization) 6012 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 6013 << 2 6014 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6015 else if (NewVD->hasLocalStorage()) 6016 Diag(NewVD->getLocation(), diag::err_module_private_local) 6017 << 0 << NewVD->getDeclName() 6018 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 6019 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 6020 else { 6021 NewVD->setModulePrivate(); 6022 if (NewTemplate) 6023 NewTemplate->setModulePrivate(); 6024 } 6025 } 6026 6027 // Handle attributes prior to checking for duplicates in MergeVarDecl 6028 ProcessDeclAttributes(S, NewVD, D); 6029 6030 if (getLangOpts().CUDA) { 6031 if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6032 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6033 diag::err_thread_unsupported); 6034 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 6035 // storage [duration]." 6036 if (SC == SC_None && S->getFnParent() != nullptr && 6037 (NewVD->hasAttr<CUDASharedAttr>() || 6038 NewVD->hasAttr<CUDAConstantAttr>())) { 6039 NewVD->setStorageClass(SC_Static); 6040 } 6041 } 6042 6043 // Ensure that dllimport globals without explicit storage class are treated as 6044 // extern. The storage class is set above using parsed attributes. Now we can 6045 // check the VarDecl itself. 6046 assert(!NewVD->hasAttr<DLLImportAttr>() || 6047 NewVD->getAttr<DLLImportAttr>()->isInherited() || 6048 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 6049 6050 // In auto-retain/release, infer strong retension for variables of 6051 // retainable type. 6052 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 6053 NewVD->setInvalidDecl(); 6054 6055 // Handle GNU asm-label extension (encoded as an attribute). 6056 if (Expr *E = (Expr*)D.getAsmLabel()) { 6057 // The parser guarantees this is a string. 6058 StringLiteral *SE = cast<StringLiteral>(E); 6059 StringRef Label = SE->getString(); 6060 if (S->getFnParent() != nullptr) { 6061 switch (SC) { 6062 case SC_None: 6063 case SC_Auto: 6064 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 6065 break; 6066 case SC_Register: 6067 // Local Named register 6068 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6069 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) 6070 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6071 break; 6072 case SC_Static: 6073 case SC_Extern: 6074 case SC_PrivateExtern: 6075 break; 6076 } 6077 } else if (SC == SC_Register) { 6078 // Global Named register 6079 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) && 6080 DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) 6081 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 6082 if (!R->isIntegralType(Context) && !R->isPointerType()) { 6083 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 6084 NewVD->setInvalidDecl(true); 6085 } 6086 } 6087 6088 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 6089 Context, Label, 0)); 6090 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 6091 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 6092 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 6093 if (I != ExtnameUndeclaredIdentifiers.end()) { 6094 if (isDeclExternC(NewVD)) { 6095 NewVD->addAttr(I->second); 6096 ExtnameUndeclaredIdentifiers.erase(I); 6097 } else 6098 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied) 6099 << /*Variable*/1 << NewVD; 6100 } 6101 } 6102 6103 // Diagnose shadowed variables before filtering for scope. 6104 if (D.getCXXScopeSpec().isEmpty()) 6105 CheckShadow(S, NewVD, Previous); 6106 6107 // Don't consider existing declarations that are in a different 6108 // scope and are out-of-semantic-context declarations (if the new 6109 // declaration has linkage). 6110 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 6111 D.getCXXScopeSpec().isNotEmpty() || 6112 IsExplicitSpecialization || 6113 IsVariableTemplateSpecialization); 6114 6115 // Check whether the previous declaration is in the same block scope. This 6116 // affects whether we merge types with it, per C++11 [dcl.array]p3. 6117 if (getLangOpts().CPlusPlus && 6118 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 6119 NewVD->setPreviousDeclInSameBlockScope( 6120 Previous.isSingleResult() && !Previous.isShadowed() && 6121 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 6122 6123 if (!getLangOpts().CPlusPlus) { 6124 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6125 } else { 6126 // If this is an explicit specialization of a static data member, check it. 6127 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 6128 CheckMemberSpecialization(NewVD, Previous)) 6129 NewVD->setInvalidDecl(); 6130 6131 // Merge the decl with the existing one if appropriate. 6132 if (!Previous.empty()) { 6133 if (Previous.isSingleResult() && 6134 isa<FieldDecl>(Previous.getFoundDecl()) && 6135 D.getCXXScopeSpec().isSet()) { 6136 // The user tried to define a non-static data member 6137 // out-of-line (C++ [dcl.meaning]p1). 6138 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 6139 << D.getCXXScopeSpec().getRange(); 6140 Previous.clear(); 6141 NewVD->setInvalidDecl(); 6142 } 6143 } else if (D.getCXXScopeSpec().isSet()) { 6144 // No previous declaration in the qualifying scope. 6145 Diag(D.getIdentifierLoc(), diag::err_no_member) 6146 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 6147 << D.getCXXScopeSpec().getRange(); 6148 NewVD->setInvalidDecl(); 6149 } 6150 6151 if (!IsVariableTemplateSpecialization) 6152 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 6153 6154 if (NewTemplate) { 6155 VarTemplateDecl *PrevVarTemplate = 6156 NewVD->getPreviousDecl() 6157 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 6158 : nullptr; 6159 6160 // Check the template parameter list of this declaration, possibly 6161 // merging in the template parameter list from the previous variable 6162 // template declaration. 6163 if (CheckTemplateParameterList( 6164 TemplateParams, 6165 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 6166 : nullptr, 6167 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 6168 DC->isDependentContext()) 6169 ? TPC_ClassTemplateMember 6170 : TPC_VarTemplate)) 6171 NewVD->setInvalidDecl(); 6172 6173 // If we are providing an explicit specialization of a static variable 6174 // template, make a note of that. 6175 if (PrevVarTemplate && 6176 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 6177 PrevVarTemplate->setMemberSpecialization(); 6178 } 6179 } 6180 6181 ProcessPragmaWeak(S, NewVD); 6182 6183 // If this is the first declaration of an extern C variable, update 6184 // the map of such variables. 6185 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 6186 isIncompleteDeclExternC(*this, NewVD)) 6187 RegisterLocallyScopedExternCDecl(NewVD, S); 6188 6189 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 6190 Decl *ManglingContextDecl; 6191 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 6192 NewVD->getDeclContext(), ManglingContextDecl)) { 6193 Context.setManglingNumber( 6194 NewVD, MCtx->getManglingNumber( 6195 NewVD, getMSManglingNumber(getLangOpts(), S))); 6196 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 6197 } 6198 } 6199 6200 // Special handling of variable named 'main'. 6201 if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") && 6202 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() && 6203 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) { 6204 6205 // C++ [basic.start.main]p3 6206 // A program that declares a variable main at global scope is ill-formed. 6207 if (getLangOpts().CPlusPlus) 6208 Diag(D.getLocStart(), diag::err_main_global_variable); 6209 6210 // In C, and external-linkage variable named main results in undefined 6211 // behavior. 6212 else if (NewVD->hasExternalFormalLinkage()) 6213 Diag(D.getLocStart(), diag::warn_main_redefined); 6214 } 6215 6216 if (D.isRedeclaration() && !Previous.empty()) { 6217 checkDLLAttributeRedeclaration( 6218 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 6219 IsExplicitSpecialization); 6220 } 6221 6222 if (NewTemplate) { 6223 if (NewVD->isInvalidDecl()) 6224 NewTemplate->setInvalidDecl(); 6225 ActOnDocumentableDecl(NewTemplate); 6226 return NewTemplate; 6227 } 6228 6229 return NewVD; 6230 } 6231 6232 /// \brief Diagnose variable or built-in function shadowing. Implements 6233 /// -Wshadow. 6234 /// 6235 /// This method is called whenever a VarDecl is added to a "useful" 6236 /// scope. 6237 /// 6238 /// \param S the scope in which the shadowing name is being declared 6239 /// \param R the lookup of the name 6240 /// 6241 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 6242 // Return if warning is ignored. 6243 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 6244 return; 6245 6246 // Don't diagnose declarations at file scope. 6247 if (D->hasGlobalStorage()) 6248 return; 6249 6250 DeclContext *NewDC = D->getDeclContext(); 6251 6252 // Only diagnose if we're shadowing an unambiguous field or variable. 6253 if (R.getResultKind() != LookupResult::Found) 6254 return; 6255 6256 NamedDecl* ShadowedDecl = R.getFoundDecl(); 6257 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 6258 return; 6259 6260 // Fields are not shadowed by variables in C++ static methods. 6261 if (isa<FieldDecl>(ShadowedDecl)) 6262 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 6263 if (MD->isStatic()) 6264 return; 6265 6266 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6267 if (shadowedVar->isExternC()) { 6268 // For shadowing external vars, make sure that we point to the global 6269 // declaration, not a locally scoped extern declaration. 6270 for (auto I : shadowedVar->redecls()) 6271 if (I->isFileVarDecl()) { 6272 ShadowedDecl = I; 6273 break; 6274 } 6275 } 6276 6277 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6278 6279 // Only warn about certain kinds of shadowing for class members. 6280 if (NewDC && NewDC->isRecord()) { 6281 // In particular, don't warn about shadowing non-class members. 6282 if (!OldDC->isRecord()) 6283 return; 6284 6285 // TODO: should we warn about static data members shadowing 6286 // static data members from base classes? 6287 6288 // TODO: don't diagnose for inaccessible shadowed members. 6289 // This is hard to do perfectly because we might friend the 6290 // shadowing context, but that's just a false negative. 6291 } 6292 6293 // Determine what kind of declaration we're shadowing. 6294 unsigned Kind; 6295 if (isa<RecordDecl>(OldDC)) { 6296 if (isa<FieldDecl>(ShadowedDecl)) 6297 Kind = 3; // field 6298 else 6299 Kind = 2; // static data member 6300 } else if (OldDC->isFileContext()) 6301 Kind = 1; // global 6302 else 6303 Kind = 0; // local 6304 6305 DeclarationName Name = R.getLookupName(); 6306 6307 // Emit warning and note. 6308 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6309 return; 6310 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6311 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6312 } 6313 6314 /// \brief Check -Wshadow without the advantage of a previous lookup. 6315 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6316 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6317 return; 6318 6319 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6320 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6321 LookupName(R, S); 6322 CheckShadow(S, D, R); 6323 } 6324 6325 /// Check for conflict between this global or extern "C" declaration and 6326 /// previous global or extern "C" declarations. This is only used in C++. 6327 template<typename T> 6328 static bool checkGlobalOrExternCConflict( 6329 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6330 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6331 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6332 6333 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6334 // The common case: this global doesn't conflict with any extern "C" 6335 // declaration. 6336 return false; 6337 } 6338 6339 if (Prev) { 6340 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6341 // Both the old and new declarations have C language linkage. This is a 6342 // redeclaration. 6343 Previous.clear(); 6344 Previous.addDecl(Prev); 6345 return true; 6346 } 6347 6348 // This is a global, non-extern "C" declaration, and there is a previous 6349 // non-global extern "C" declaration. Diagnose if this is a variable 6350 // declaration. 6351 if (!isa<VarDecl>(ND)) 6352 return false; 6353 } else { 6354 // The declaration is extern "C". Check for any declaration in the 6355 // translation unit which might conflict. 6356 if (IsGlobal) { 6357 // We have already performed the lookup into the translation unit. 6358 IsGlobal = false; 6359 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6360 I != E; ++I) { 6361 if (isa<VarDecl>(*I)) { 6362 Prev = *I; 6363 break; 6364 } 6365 } 6366 } else { 6367 DeclContext::lookup_result R = 6368 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6369 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6370 I != E; ++I) { 6371 if (isa<VarDecl>(*I)) { 6372 Prev = *I; 6373 break; 6374 } 6375 // FIXME: If we have any other entity with this name in global scope, 6376 // the declaration is ill-formed, but that is a defect: it breaks the 6377 // 'stat' hack, for instance. Only variables can have mangled name 6378 // clashes with extern "C" declarations, so only they deserve a 6379 // diagnostic. 6380 } 6381 } 6382 6383 if (!Prev) 6384 return false; 6385 } 6386 6387 // Use the first declaration's location to ensure we point at something which 6388 // is lexically inside an extern "C" linkage-spec. 6389 assert(Prev && "should have found a previous declaration to diagnose"); 6390 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6391 Prev = FD->getFirstDecl(); 6392 else 6393 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6394 6395 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6396 << IsGlobal << ND; 6397 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6398 << IsGlobal; 6399 return false; 6400 } 6401 6402 /// Apply special rules for handling extern "C" declarations. Returns \c true 6403 /// if we have found that this is a redeclaration of some prior entity. 6404 /// 6405 /// Per C++ [dcl.link]p6: 6406 /// Two declarations [for a function or variable] with C language linkage 6407 /// with the same name that appear in different scopes refer to the same 6408 /// [entity]. An entity with C language linkage shall not be declared with 6409 /// the same name as an entity in global scope. 6410 template<typename T> 6411 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6412 LookupResult &Previous) { 6413 if (!S.getLangOpts().CPlusPlus) { 6414 // In C, when declaring a global variable, look for a corresponding 'extern' 6415 // variable declared in function scope. We don't need this in C++, because 6416 // we find local extern decls in the surrounding file-scope DeclContext. 6417 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6418 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6419 Previous.clear(); 6420 Previous.addDecl(Prev); 6421 return true; 6422 } 6423 } 6424 return false; 6425 } 6426 6427 // A declaration in the translation unit can conflict with an extern "C" 6428 // declaration. 6429 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6430 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6431 6432 // An extern "C" declaration can conflict with a declaration in the 6433 // translation unit or can be a redeclaration of an extern "C" declaration 6434 // in another scope. 6435 if (isIncompleteDeclExternC(S,ND)) 6436 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6437 6438 // Neither global nor extern "C": nothing to do. 6439 return false; 6440 } 6441 6442 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6443 // If the decl is already known invalid, don't check it. 6444 if (NewVD->isInvalidDecl()) 6445 return; 6446 6447 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6448 QualType T = TInfo->getType(); 6449 6450 // Defer checking an 'auto' type until its initializer is attached. 6451 if (T->isUndeducedType()) 6452 return; 6453 6454 if (NewVD->hasAttrs()) 6455 CheckAlignasUnderalignment(NewVD); 6456 6457 if (T->isObjCObjectType()) { 6458 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6459 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6460 T = Context.getObjCObjectPointerType(T); 6461 NewVD->setType(T); 6462 } 6463 6464 // Emit an error if an address space was applied to decl with local storage. 6465 // This includes arrays of objects with address space qualifiers, but not 6466 // automatic variables that point to other address spaces. 6467 // ISO/IEC TR 18037 S5.1.2 6468 if (!getLangOpts().OpenCL 6469 && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6470 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6471 NewVD->setInvalidDecl(); 6472 return; 6473 } 6474 6475 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6476 // scope. 6477 if (getLangOpts().OpenCLVersion == 120 && 6478 !getOpenCLOptions().cl_clang_storage_class_specifiers && 6479 NewVD->isStaticLocal()) { 6480 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6481 NewVD->setInvalidDecl(); 6482 return; 6483 } 6484 6485 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6486 // __constant address space. 6487 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6488 // variables inside a function can also be declared in the global 6489 // address space. 6490 if (getLangOpts().OpenCL) { 6491 if (NewVD->isFileVarDecl()) { 6492 if (!T->isSamplerT() && 6493 !(T.getAddressSpace() == LangAS::opencl_constant || 6494 (T.getAddressSpace() == LangAS::opencl_global && 6495 getLangOpts().OpenCLVersion == 200))) { 6496 if (getLangOpts().OpenCLVersion == 200) 6497 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6498 << "global or constant"; 6499 else 6500 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6501 << "constant"; 6502 NewVD->setInvalidDecl(); 6503 return; 6504 } 6505 } else { 6506 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static 6507 // variables inside a function can also be declared in the global 6508 // address space. 6509 if (NewVD->isStaticLocal() && 6510 !(T.getAddressSpace() == LangAS::opencl_constant || 6511 (T.getAddressSpace() == LangAS::opencl_global && 6512 getLangOpts().OpenCLVersion == 200))) { 6513 if (getLangOpts().OpenCLVersion == 200) 6514 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6515 << "global or constant"; 6516 else 6517 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space) 6518 << "constant"; 6519 NewVD->setInvalidDecl(); 6520 return; 6521 } 6522 // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables 6523 // in functions. 6524 if (T.getAddressSpace() == LangAS::opencl_constant || 6525 T.getAddressSpace() == LangAS::opencl_local) { 6526 FunctionDecl *FD = getCurFunctionDecl(); 6527 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) { 6528 if (T.getAddressSpace() == LangAS::opencl_constant) 6529 Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable) 6530 << "constant"; 6531 else 6532 Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable) 6533 << "local"; 6534 NewVD->setInvalidDecl(); 6535 return; 6536 } 6537 } 6538 } 6539 } 6540 6541 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6542 && !NewVD->hasAttr<BlocksAttr>()) { 6543 if (getLangOpts().getGC() != LangOptions::NonGC) 6544 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6545 else { 6546 assert(!getLangOpts().ObjCAutoRefCount); 6547 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6548 } 6549 } 6550 6551 bool isVM = T->isVariablyModifiedType(); 6552 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6553 NewVD->hasAttr<BlocksAttr>()) 6554 getCurFunction()->setHasBranchProtectedScope(); 6555 6556 if ((isVM && NewVD->hasLinkage()) || 6557 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6558 bool SizeIsNegative; 6559 llvm::APSInt Oversized; 6560 TypeSourceInfo *FixedTInfo = 6561 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6562 SizeIsNegative, Oversized); 6563 if (!FixedTInfo && T->isVariableArrayType()) { 6564 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6565 // FIXME: This won't give the correct result for 6566 // int a[10][n]; 6567 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6568 6569 if (NewVD->isFileVarDecl()) 6570 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6571 << SizeRange; 6572 else if (NewVD->isStaticLocal()) 6573 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6574 << SizeRange; 6575 else 6576 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6577 << SizeRange; 6578 NewVD->setInvalidDecl(); 6579 return; 6580 } 6581 6582 if (!FixedTInfo) { 6583 if (NewVD->isFileVarDecl()) 6584 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6585 else 6586 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6587 NewVD->setInvalidDecl(); 6588 return; 6589 } 6590 6591 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6592 NewVD->setType(FixedTInfo->getType()); 6593 NewVD->setTypeSourceInfo(FixedTInfo); 6594 } 6595 6596 if (T->isVoidType()) { 6597 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6598 // of objects and functions. 6599 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6600 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6601 << T; 6602 NewVD->setInvalidDecl(); 6603 return; 6604 } 6605 } 6606 6607 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6608 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6609 NewVD->setInvalidDecl(); 6610 return; 6611 } 6612 6613 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6614 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6615 NewVD->setInvalidDecl(); 6616 return; 6617 } 6618 6619 if (NewVD->isConstexpr() && !T->isDependentType() && 6620 RequireLiteralType(NewVD->getLocation(), T, 6621 diag::err_constexpr_var_non_literal)) { 6622 NewVD->setInvalidDecl(); 6623 return; 6624 } 6625 } 6626 6627 /// \brief Perform semantic checking on a newly-created variable 6628 /// declaration. 6629 /// 6630 /// This routine performs all of the type-checking required for a 6631 /// variable declaration once it has been built. It is used both to 6632 /// check variables after they have been parsed and their declarators 6633 /// have been translated into a declaration, and to check variables 6634 /// that have been instantiated from a template. 6635 /// 6636 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6637 /// 6638 /// Returns true if the variable declaration is a redeclaration. 6639 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6640 CheckVariableDeclarationType(NewVD); 6641 6642 // If the decl is already known invalid, don't check it. 6643 if (NewVD->isInvalidDecl()) 6644 return false; 6645 6646 // If we did not find anything by this name, look for a non-visible 6647 // extern "C" declaration with the same name. 6648 if (Previous.empty() && 6649 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6650 Previous.setShadowed(); 6651 6652 if (!Previous.empty()) { 6653 MergeVarDecl(NewVD, Previous); 6654 return true; 6655 } 6656 return false; 6657 } 6658 6659 namespace { 6660 struct FindOverriddenMethod { 6661 Sema *S; 6662 CXXMethodDecl *Method; 6663 6664 /// Member lookup function that determines whether a given C++ 6665 /// method overrides a method in a base class, to be used with 6666 /// CXXRecordDecl::lookupInBases(). 6667 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { 6668 RecordDecl *BaseRecord = 6669 Specifier->getType()->getAs<RecordType>()->getDecl(); 6670 6671 DeclarationName Name = Method->getDeclName(); 6672 6673 // FIXME: Do we care about other names here too? 6674 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6675 // We really want to find the base class destructor here. 6676 QualType T = S->Context.getTypeDeclType(BaseRecord); 6677 CanQualType CT = S->Context.getCanonicalType(T); 6678 6679 Name = S->Context.DeclarationNames.getCXXDestructorName(CT); 6680 } 6681 6682 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty(); 6683 Path.Decls = Path.Decls.slice(1)) { 6684 NamedDecl *D = Path.Decls.front(); 6685 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6686 if (MD->isVirtual() && !S->IsOverload(Method, MD, false)) 6687 return true; 6688 } 6689 } 6690 6691 return false; 6692 } 6693 }; 6694 6695 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6696 } // end anonymous namespace 6697 6698 /// \brief Report an error regarding overriding, along with any relevant 6699 /// overriden methods. 6700 /// 6701 /// \param DiagID the primary error to report. 6702 /// \param MD the overriding method. 6703 /// \param OEK which overrides to include as notes. 6704 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6705 OverrideErrorKind OEK = OEK_All) { 6706 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6707 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6708 E = MD->end_overridden_methods(); 6709 I != E; ++I) { 6710 // This check (& the OEK parameter) could be replaced by a predicate, but 6711 // without lambdas that would be overkill. This is still nicer than writing 6712 // out the diag loop 3 times. 6713 if ((OEK == OEK_All) || 6714 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6715 (OEK == OEK_Deleted && (*I)->isDeleted())) 6716 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6717 } 6718 } 6719 6720 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6721 /// and if so, check that it's a valid override and remember it. 6722 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6723 // Look for methods in base classes that this method might override. 6724 CXXBasePaths Paths; 6725 FindOverriddenMethod FOM; 6726 FOM.Method = MD; 6727 FOM.S = this; 6728 bool hasDeletedOverridenMethods = false; 6729 bool hasNonDeletedOverridenMethods = false; 6730 bool AddedAny = false; 6731 if (DC->lookupInBases(FOM, Paths)) { 6732 for (auto *I : Paths.found_decls()) { 6733 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6734 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6735 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6736 !CheckOverridingFunctionAttributes(MD, OldMD) && 6737 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6738 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6739 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6740 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6741 AddedAny = true; 6742 } 6743 } 6744 } 6745 } 6746 6747 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6748 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6749 } 6750 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6751 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6752 } 6753 6754 return AddedAny; 6755 } 6756 6757 namespace { 6758 // Struct for holding all of the extra arguments needed by 6759 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6760 struct ActOnFDArgs { 6761 Scope *S; 6762 Declarator &D; 6763 MultiTemplateParamsArg TemplateParamLists; 6764 bool AddToScope; 6765 }; 6766 } 6767 6768 namespace { 6769 6770 // Callback to only accept typo corrections that have a non-zero edit distance. 6771 // Also only accept corrections that have the same parent decl. 6772 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6773 public: 6774 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6775 CXXRecordDecl *Parent) 6776 : Context(Context), OriginalFD(TypoFD), 6777 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6778 6779 bool ValidateCandidate(const TypoCorrection &candidate) override { 6780 if (candidate.getEditDistance() == 0) 6781 return false; 6782 6783 SmallVector<unsigned, 1> MismatchedParams; 6784 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6785 CDeclEnd = candidate.end(); 6786 CDecl != CDeclEnd; ++CDecl) { 6787 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6788 6789 if (FD && !FD->hasBody() && 6790 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6791 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6792 CXXRecordDecl *Parent = MD->getParent(); 6793 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6794 return true; 6795 } else if (!ExpectedParent) { 6796 return true; 6797 } 6798 } 6799 } 6800 6801 return false; 6802 } 6803 6804 private: 6805 ASTContext &Context; 6806 FunctionDecl *OriginalFD; 6807 CXXRecordDecl *ExpectedParent; 6808 }; 6809 6810 } 6811 6812 /// \brief Generate diagnostics for an invalid function redeclaration. 6813 /// 6814 /// This routine handles generating the diagnostic messages for an invalid 6815 /// function redeclaration, including finding possible similar declarations 6816 /// or performing typo correction if there are no previous declarations with 6817 /// the same name. 6818 /// 6819 /// Returns a NamedDecl iff typo correction was performed and substituting in 6820 /// the new declaration name does not cause new errors. 6821 static NamedDecl *DiagnoseInvalidRedeclaration( 6822 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6823 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6824 DeclarationName Name = NewFD->getDeclName(); 6825 DeclContext *NewDC = NewFD->getDeclContext(); 6826 SmallVector<unsigned, 1> MismatchedParams; 6827 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6828 TypoCorrection Correction; 6829 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6830 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6831 : diag::err_member_decl_does_not_match; 6832 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6833 IsLocalFriend ? Sema::LookupLocalFriendName 6834 : Sema::LookupOrdinaryName, 6835 Sema::ForRedeclaration); 6836 6837 NewFD->setInvalidDecl(); 6838 if (IsLocalFriend) 6839 SemaRef.LookupName(Prev, S); 6840 else 6841 SemaRef.LookupQualifiedName(Prev, NewDC); 6842 assert(!Prev.isAmbiguous() && 6843 "Cannot have an ambiguity in previous-declaration lookup"); 6844 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6845 if (!Prev.empty()) { 6846 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6847 Func != FuncEnd; ++Func) { 6848 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6849 if (FD && 6850 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6851 // Add 1 to the index so that 0 can mean the mismatch didn't 6852 // involve a parameter 6853 unsigned ParamNum = 6854 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6855 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6856 } 6857 } 6858 // If the qualified name lookup yielded nothing, try typo correction 6859 } else if ((Correction = SemaRef.CorrectTypo( 6860 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6861 &ExtraArgs.D.getCXXScopeSpec(), 6862 llvm::make_unique<DifferentNameValidatorCCC>( 6863 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 6864 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6865 // Set up everything for the call to ActOnFunctionDeclarator 6866 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6867 ExtraArgs.D.getIdentifierLoc()); 6868 Previous.clear(); 6869 Previous.setLookupName(Correction.getCorrection()); 6870 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6871 CDeclEnd = Correction.end(); 6872 CDecl != CDeclEnd; ++CDecl) { 6873 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6874 if (FD && !FD->hasBody() && 6875 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6876 Previous.addDecl(FD); 6877 } 6878 } 6879 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6880 6881 NamedDecl *Result; 6882 // Retry building the function declaration with the new previous 6883 // declarations, and with errors suppressed. 6884 { 6885 // Trap errors. 6886 Sema::SFINAETrap Trap(SemaRef); 6887 6888 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6889 // pieces need to verify the typo-corrected C++ declaration and hopefully 6890 // eliminate the need for the parameter pack ExtraArgs. 6891 Result = SemaRef.ActOnFunctionDeclarator( 6892 ExtraArgs.S, ExtraArgs.D, 6893 Correction.getCorrectionDecl()->getDeclContext(), 6894 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6895 ExtraArgs.AddToScope); 6896 6897 if (Trap.hasErrorOccurred()) 6898 Result = nullptr; 6899 } 6900 6901 if (Result) { 6902 // Determine which correction we picked. 6903 Decl *Canonical = Result->getCanonicalDecl(); 6904 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6905 I != E; ++I) 6906 if ((*I)->getCanonicalDecl() == Canonical) 6907 Correction.setCorrectionDecl(*I); 6908 6909 SemaRef.diagnoseTypo( 6910 Correction, 6911 SemaRef.PDiag(IsLocalFriend 6912 ? diag::err_no_matching_local_friend_suggest 6913 : diag::err_member_decl_does_not_match_suggest) 6914 << Name << NewDC << IsDefinition); 6915 return Result; 6916 } 6917 6918 // Pretend the typo correction never occurred 6919 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6920 ExtraArgs.D.getIdentifierLoc()); 6921 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6922 Previous.clear(); 6923 Previous.setLookupName(Name); 6924 } 6925 6926 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6927 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6928 6929 bool NewFDisConst = false; 6930 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6931 NewFDisConst = NewMD->isConst(); 6932 6933 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6934 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6935 NearMatch != NearMatchEnd; ++NearMatch) { 6936 FunctionDecl *FD = NearMatch->first; 6937 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6938 bool FDisConst = MD && MD->isConst(); 6939 bool IsMember = MD || !IsLocalFriend; 6940 6941 // FIXME: These notes are poorly worded for the local friend case. 6942 if (unsigned Idx = NearMatch->second) { 6943 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6944 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6945 if (Loc.isInvalid()) Loc = FD->getLocation(); 6946 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6947 : diag::note_local_decl_close_param_match) 6948 << Idx << FDParam->getType() 6949 << NewFD->getParamDecl(Idx - 1)->getType(); 6950 } else if (FDisConst != NewFDisConst) { 6951 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6952 << NewFDisConst << FD->getSourceRange().getEnd(); 6953 } else 6954 SemaRef.Diag(FD->getLocation(), 6955 IsMember ? diag::note_member_def_close_match 6956 : diag::note_local_decl_close_match); 6957 } 6958 return nullptr; 6959 } 6960 6961 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 6962 switch (D.getDeclSpec().getStorageClassSpec()) { 6963 default: llvm_unreachable("Unknown storage class!"); 6964 case DeclSpec::SCS_auto: 6965 case DeclSpec::SCS_register: 6966 case DeclSpec::SCS_mutable: 6967 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6968 diag::err_typecheck_sclass_func); 6969 D.setInvalidType(); 6970 break; 6971 case DeclSpec::SCS_unspecified: break; 6972 case DeclSpec::SCS_extern: 6973 if (D.getDeclSpec().isExternInLinkageSpec()) 6974 return SC_None; 6975 return SC_Extern; 6976 case DeclSpec::SCS_static: { 6977 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6978 // C99 6.7.1p5: 6979 // The declaration of an identifier for a function that has 6980 // block scope shall have no explicit storage-class specifier 6981 // other than extern 6982 // See also (C++ [dcl.stc]p4). 6983 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6984 diag::err_static_block_func); 6985 break; 6986 } else 6987 return SC_Static; 6988 } 6989 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6990 } 6991 6992 // No explicit storage class has already been returned 6993 return SC_None; 6994 } 6995 6996 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6997 DeclContext *DC, QualType &R, 6998 TypeSourceInfo *TInfo, 6999 StorageClass SC, 7000 bool &IsVirtualOkay) { 7001 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 7002 DeclarationName Name = NameInfo.getName(); 7003 7004 FunctionDecl *NewFD = nullptr; 7005 bool isInline = D.getDeclSpec().isInlineSpecified(); 7006 7007 if (!SemaRef.getLangOpts().CPlusPlus) { 7008 // Determine whether the function was written with a 7009 // prototype. This true when: 7010 // - there is a prototype in the declarator, or 7011 // - the type R of the function is some kind of typedef or other reference 7012 // to a type name (which eventually refers to a function type). 7013 bool HasPrototype = 7014 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 7015 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 7016 7017 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 7018 D.getLocStart(), NameInfo, R, 7019 TInfo, SC, isInline, 7020 HasPrototype, false); 7021 if (D.isInvalidType()) 7022 NewFD->setInvalidDecl(); 7023 7024 return NewFD; 7025 } 7026 7027 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7028 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7029 7030 // Check that the return type is not an abstract class type. 7031 // For record types, this is done by the AbstractClassUsageDiagnoser once 7032 // the class has been completely parsed. 7033 if (!DC->isRecord() && 7034 SemaRef.RequireNonAbstractType( 7035 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 7036 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 7037 D.setInvalidType(); 7038 7039 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 7040 // This is a C++ constructor declaration. 7041 assert(DC->isRecord() && 7042 "Constructors can only be declared in a member context"); 7043 7044 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 7045 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7046 D.getLocStart(), NameInfo, 7047 R, TInfo, isExplicit, isInline, 7048 /*isImplicitlyDeclared=*/false, 7049 isConstexpr); 7050 7051 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7052 // This is a C++ destructor declaration. 7053 if (DC->isRecord()) { 7054 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 7055 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 7056 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 7057 SemaRef.Context, Record, 7058 D.getLocStart(), 7059 NameInfo, R, TInfo, isInline, 7060 /*isImplicitlyDeclared=*/false); 7061 7062 // If the class is complete, then we now create the implicit exception 7063 // specification. If the class is incomplete or dependent, we can't do 7064 // it yet. 7065 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 7066 Record->getDefinition() && !Record->isBeingDefined() && 7067 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 7068 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 7069 } 7070 7071 IsVirtualOkay = true; 7072 return NewDD; 7073 7074 } else { 7075 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 7076 D.setInvalidType(); 7077 7078 // Create a FunctionDecl to satisfy the function definition parsing 7079 // code path. 7080 return FunctionDecl::Create(SemaRef.Context, DC, 7081 D.getLocStart(), 7082 D.getIdentifierLoc(), Name, R, TInfo, 7083 SC, isInline, 7084 /*hasPrototype=*/true, isConstexpr); 7085 } 7086 7087 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 7088 if (!DC->isRecord()) { 7089 SemaRef.Diag(D.getIdentifierLoc(), 7090 diag::err_conv_function_not_member); 7091 return nullptr; 7092 } 7093 7094 SemaRef.CheckConversionDeclarator(D, R, SC); 7095 IsVirtualOkay = true; 7096 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 7097 D.getLocStart(), NameInfo, 7098 R, TInfo, isInline, isExplicit, 7099 isConstexpr, SourceLocation()); 7100 7101 } else if (DC->isRecord()) { 7102 // If the name of the function is the same as the name of the record, 7103 // then this must be an invalid constructor that has a return type. 7104 // (The parser checks for a return type and makes the declarator a 7105 // constructor if it has no return type). 7106 if (Name.getAsIdentifierInfo() && 7107 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 7108 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 7109 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 7110 << SourceRange(D.getIdentifierLoc()); 7111 return nullptr; 7112 } 7113 7114 // This is a C++ method declaration. 7115 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 7116 cast<CXXRecordDecl>(DC), 7117 D.getLocStart(), NameInfo, R, 7118 TInfo, SC, isInline, 7119 isConstexpr, SourceLocation()); 7120 IsVirtualOkay = !Ret->isStatic(); 7121 return Ret; 7122 } else { 7123 bool isFriend = 7124 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 7125 if (!isFriend && SemaRef.CurContext->isRecord()) 7126 return nullptr; 7127 7128 // Determine whether the function was written with a 7129 // prototype. This true when: 7130 // - we're in C++ (where every function has a prototype), 7131 return FunctionDecl::Create(SemaRef.Context, DC, 7132 D.getLocStart(), 7133 NameInfo, R, TInfo, SC, isInline, 7134 true/*HasPrototype*/, isConstexpr); 7135 } 7136 } 7137 7138 enum OpenCLParamType { 7139 ValidKernelParam, 7140 PtrPtrKernelParam, 7141 PtrKernelParam, 7142 PrivatePtrKernelParam, 7143 InvalidKernelParam, 7144 RecordKernelParam 7145 }; 7146 7147 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 7148 if (PT->isPointerType()) { 7149 QualType PointeeType = PT->getPointeeType(); 7150 if (PointeeType->isPointerType()) 7151 return PtrPtrKernelParam; 7152 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 7153 : PtrKernelParam; 7154 } 7155 7156 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 7157 // be used as builtin types. 7158 7159 if (PT->isImageType()) 7160 return PtrKernelParam; 7161 7162 if (PT->isBooleanType()) 7163 return InvalidKernelParam; 7164 7165 if (PT->isEventT()) 7166 return InvalidKernelParam; 7167 7168 if (PT->isHalfType()) 7169 return InvalidKernelParam; 7170 7171 if (PT->isRecordType()) 7172 return RecordKernelParam; 7173 7174 return ValidKernelParam; 7175 } 7176 7177 static void checkIsValidOpenCLKernelParameter( 7178 Sema &S, 7179 Declarator &D, 7180 ParmVarDecl *Param, 7181 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 7182 QualType PT = Param->getType(); 7183 7184 // Cache the valid types we encounter to avoid rechecking structs that are 7185 // used again 7186 if (ValidTypes.count(PT.getTypePtr())) 7187 return; 7188 7189 switch (getOpenCLKernelParameterType(PT)) { 7190 case PtrPtrKernelParam: 7191 // OpenCL v1.2 s6.9.a: 7192 // A kernel function argument cannot be declared as a 7193 // pointer to a pointer type. 7194 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 7195 D.setInvalidType(); 7196 return; 7197 7198 case PrivatePtrKernelParam: 7199 // OpenCL v1.2 s6.9.a: 7200 // A kernel function argument cannot be declared as a 7201 // pointer to the private address space. 7202 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 7203 D.setInvalidType(); 7204 return; 7205 7206 // OpenCL v1.2 s6.9.k: 7207 // Arguments to kernel functions in a program cannot be declared with the 7208 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 7209 // uintptr_t or a struct and/or union that contain fields declared to be 7210 // one of these built-in scalar types. 7211 7212 case InvalidKernelParam: 7213 // OpenCL v1.2 s6.8 n: 7214 // A kernel function argument cannot be declared 7215 // of event_t type. 7216 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7217 D.setInvalidType(); 7218 return; 7219 7220 case PtrKernelParam: 7221 case ValidKernelParam: 7222 ValidTypes.insert(PT.getTypePtr()); 7223 return; 7224 7225 case RecordKernelParam: 7226 break; 7227 } 7228 7229 // Track nested structs we will inspect 7230 SmallVector<const Decl *, 4> VisitStack; 7231 7232 // Track where we are in the nested structs. Items will migrate from 7233 // VisitStack to HistoryStack as we do the DFS for bad field. 7234 SmallVector<const FieldDecl *, 4> HistoryStack; 7235 HistoryStack.push_back(nullptr); 7236 7237 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 7238 VisitStack.push_back(PD); 7239 7240 assert(VisitStack.back() && "First decl null?"); 7241 7242 do { 7243 const Decl *Next = VisitStack.pop_back_val(); 7244 if (!Next) { 7245 assert(!HistoryStack.empty()); 7246 // Found a marker, we have gone up a level 7247 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 7248 ValidTypes.insert(Hist->getType().getTypePtr()); 7249 7250 continue; 7251 } 7252 7253 // Adds everything except the original parameter declaration (which is not a 7254 // field itself) to the history stack. 7255 const RecordDecl *RD; 7256 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 7257 HistoryStack.push_back(Field); 7258 RD = Field->getType()->castAs<RecordType>()->getDecl(); 7259 } else { 7260 RD = cast<RecordDecl>(Next); 7261 } 7262 7263 // Add a null marker so we know when we've gone back up a level 7264 VisitStack.push_back(nullptr); 7265 7266 for (const auto *FD : RD->fields()) { 7267 QualType QT = FD->getType(); 7268 7269 if (ValidTypes.count(QT.getTypePtr())) 7270 continue; 7271 7272 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 7273 if (ParamType == ValidKernelParam) 7274 continue; 7275 7276 if (ParamType == RecordKernelParam) { 7277 VisitStack.push_back(FD); 7278 continue; 7279 } 7280 7281 // OpenCL v1.2 s6.9.p: 7282 // Arguments to kernel functions that are declared to be a struct or union 7283 // do not allow OpenCL objects to be passed as elements of the struct or 7284 // union. 7285 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 7286 ParamType == PrivatePtrKernelParam) { 7287 S.Diag(Param->getLocation(), 7288 diag::err_record_with_pointers_kernel_param) 7289 << PT->isUnionType() 7290 << PT; 7291 } else { 7292 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 7293 } 7294 7295 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 7296 << PD->getDeclName(); 7297 7298 // We have an error, now let's go back up through history and show where 7299 // the offending field came from 7300 for (ArrayRef<const FieldDecl *>::const_iterator 7301 I = HistoryStack.begin() + 1, 7302 E = HistoryStack.end(); 7303 I != E; ++I) { 7304 const FieldDecl *OuterField = *I; 7305 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7306 << OuterField->getType(); 7307 } 7308 7309 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7310 << QT->isPointerType() 7311 << QT; 7312 D.setInvalidType(); 7313 return; 7314 } 7315 } while (!VisitStack.empty()); 7316 } 7317 7318 NamedDecl* 7319 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7320 TypeSourceInfo *TInfo, LookupResult &Previous, 7321 MultiTemplateParamsArg TemplateParamLists, 7322 bool &AddToScope) { 7323 QualType R = TInfo->getType(); 7324 7325 assert(R.getTypePtr()->isFunctionType()); 7326 7327 // TODO: consider using NameInfo for diagnostic. 7328 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7329 DeclarationName Name = NameInfo.getName(); 7330 StorageClass SC = getFunctionStorageClass(*this, D); 7331 7332 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7333 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7334 diag::err_invalid_thread) 7335 << DeclSpec::getSpecifierName(TSCS); 7336 7337 if (D.isFirstDeclarationOfMember()) 7338 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(), 7339 D.getIdentifierLoc()); 7340 7341 bool isFriend = false; 7342 FunctionTemplateDecl *FunctionTemplate = nullptr; 7343 bool isExplicitSpecialization = false; 7344 bool isFunctionTemplateSpecialization = false; 7345 7346 bool isDependentClassScopeExplicitSpecialization = false; 7347 bool HasExplicitTemplateArgs = false; 7348 TemplateArgumentListInfo TemplateArgs; 7349 7350 bool isVirtualOkay = false; 7351 7352 DeclContext *OriginalDC = DC; 7353 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7354 7355 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7356 isVirtualOkay); 7357 if (!NewFD) return nullptr; 7358 7359 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7360 NewFD->setTopLevelDeclInObjCContainer(); 7361 7362 // Set the lexical context. If this is a function-scope declaration, or has a 7363 // C++ scope specifier, or is the object of a friend declaration, the lexical 7364 // context will be different from the semantic context. 7365 NewFD->setLexicalDeclContext(CurContext); 7366 7367 if (IsLocalExternDecl) 7368 NewFD->setLocalExternDecl(); 7369 7370 if (getLangOpts().CPlusPlus) { 7371 bool isInline = D.getDeclSpec().isInlineSpecified(); 7372 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7373 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7374 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7375 bool isConcept = D.getDeclSpec().isConceptSpecified(); 7376 isFriend = D.getDeclSpec().isFriendSpecified(); 7377 if (isFriend && !isInline && D.isFunctionDefinition()) { 7378 // C++ [class.friend]p5 7379 // A function can be defined in a friend declaration of a 7380 // class . . . . Such a function is implicitly inline. 7381 NewFD->setImplicitlyInline(); 7382 } 7383 7384 // If this is a method defined in an __interface, and is not a constructor 7385 // or an overloaded operator, then set the pure flag (isVirtual will already 7386 // return true). 7387 if (const CXXRecordDecl *Parent = 7388 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7389 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7390 NewFD->setPure(true); 7391 7392 // C++ [class.union]p2 7393 // A union can have member functions, but not virtual functions. 7394 if (isVirtual && Parent->isUnion()) 7395 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union); 7396 } 7397 7398 SetNestedNameSpecifier(NewFD, D); 7399 isExplicitSpecialization = false; 7400 isFunctionTemplateSpecialization = false; 7401 if (D.isInvalidType()) 7402 NewFD->setInvalidDecl(); 7403 7404 // Match up the template parameter lists with the scope specifier, then 7405 // determine whether we have a template or a template specialization. 7406 bool Invalid = false; 7407 if (TemplateParameterList *TemplateParams = 7408 MatchTemplateParametersToScopeSpecifier( 7409 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7410 D.getCXXScopeSpec(), 7411 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7412 ? D.getName().TemplateId 7413 : nullptr, 7414 TemplateParamLists, isFriend, isExplicitSpecialization, 7415 Invalid)) { 7416 if (TemplateParams->size() > 0) { 7417 // This is a function template 7418 7419 // Check that we can declare a template here. 7420 if (CheckTemplateDeclScope(S, TemplateParams)) 7421 NewFD->setInvalidDecl(); 7422 7423 // A destructor cannot be a template. 7424 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7425 Diag(NewFD->getLocation(), diag::err_destructor_template); 7426 NewFD->setInvalidDecl(); 7427 } 7428 7429 // If we're adding a template to a dependent context, we may need to 7430 // rebuilding some of the types used within the template parameter list, 7431 // now that we know what the current instantiation is. 7432 if (DC->isDependentContext()) { 7433 ContextRAII SavedContext(*this, DC); 7434 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7435 Invalid = true; 7436 } 7437 7438 7439 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7440 NewFD->getLocation(), 7441 Name, TemplateParams, 7442 NewFD); 7443 FunctionTemplate->setLexicalDeclContext(CurContext); 7444 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7445 7446 // For source fidelity, store the other template param lists. 7447 if (TemplateParamLists.size() > 1) { 7448 NewFD->setTemplateParameterListsInfo(Context, 7449 TemplateParamLists.drop_back(1)); 7450 } 7451 } else { 7452 // This is a function template specialization. 7453 isFunctionTemplateSpecialization = true; 7454 // For source fidelity, store all the template param lists. 7455 if (TemplateParamLists.size() > 0) 7456 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7457 7458 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7459 if (isFriend) { 7460 // We want to remove the "template<>", found here. 7461 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7462 7463 // If we remove the template<> and the name is not a 7464 // template-id, we're actually silently creating a problem: 7465 // the friend declaration will refer to an untemplated decl, 7466 // and clearly the user wants a template specialization. So 7467 // we need to insert '<>' after the name. 7468 SourceLocation InsertLoc; 7469 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7470 InsertLoc = D.getName().getSourceRange().getEnd(); 7471 InsertLoc = getLocForEndOfToken(InsertLoc); 7472 } 7473 7474 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7475 << Name << RemoveRange 7476 << FixItHint::CreateRemoval(RemoveRange) 7477 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7478 } 7479 } 7480 } 7481 else { 7482 // All template param lists were matched against the scope specifier: 7483 // this is NOT (an explicit specialization of) a template. 7484 if (TemplateParamLists.size() > 0) 7485 // For source fidelity, store all the template param lists. 7486 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists); 7487 } 7488 7489 if (Invalid) { 7490 NewFD->setInvalidDecl(); 7491 if (FunctionTemplate) 7492 FunctionTemplate->setInvalidDecl(); 7493 } 7494 7495 // C++ [dcl.fct.spec]p5: 7496 // The virtual specifier shall only be used in declarations of 7497 // nonstatic class member functions that appear within a 7498 // member-specification of a class declaration; see 10.3. 7499 // 7500 if (isVirtual && !NewFD->isInvalidDecl()) { 7501 if (!isVirtualOkay) { 7502 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7503 diag::err_virtual_non_function); 7504 } else if (!CurContext->isRecord()) { 7505 // 'virtual' was specified outside of the class. 7506 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7507 diag::err_virtual_out_of_class) 7508 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7509 } else if (NewFD->getDescribedFunctionTemplate()) { 7510 // C++ [temp.mem]p3: 7511 // A member function template shall not be virtual. 7512 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7513 diag::err_virtual_member_function_template) 7514 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7515 } else { 7516 // Okay: Add virtual to the method. 7517 NewFD->setVirtualAsWritten(true); 7518 } 7519 7520 if (getLangOpts().CPlusPlus14 && 7521 NewFD->getReturnType()->isUndeducedType()) 7522 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7523 } 7524 7525 if (getLangOpts().CPlusPlus14 && 7526 (NewFD->isDependentContext() || 7527 (isFriend && CurContext->isDependentContext())) && 7528 NewFD->getReturnType()->isUndeducedType()) { 7529 // If the function template is referenced directly (for instance, as a 7530 // member of the current instantiation), pretend it has a dependent type. 7531 // This is not really justified by the standard, but is the only sane 7532 // thing to do. 7533 // FIXME: For a friend function, we have not marked the function as being 7534 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7535 const FunctionProtoType *FPT = 7536 NewFD->getType()->castAs<FunctionProtoType>(); 7537 QualType Result = 7538 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7539 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7540 FPT->getExtProtoInfo())); 7541 } 7542 7543 // C++ [dcl.fct.spec]p3: 7544 // The inline specifier shall not appear on a block scope function 7545 // declaration. 7546 if (isInline && !NewFD->isInvalidDecl()) { 7547 if (CurContext->isFunctionOrMethod()) { 7548 // 'inline' is not allowed on block scope function declaration. 7549 Diag(D.getDeclSpec().getInlineSpecLoc(), 7550 diag::err_inline_declaration_block_scope) << Name 7551 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7552 } 7553 } 7554 7555 // C++ [dcl.fct.spec]p6: 7556 // The explicit specifier shall be used only in the declaration of a 7557 // constructor or conversion function within its class definition; 7558 // see 12.3.1 and 12.3.2. 7559 if (isExplicit && !NewFD->isInvalidDecl()) { 7560 if (!CurContext->isRecord()) { 7561 // 'explicit' was specified outside of the class. 7562 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7563 diag::err_explicit_out_of_class) 7564 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7565 } else if (!isa<CXXConstructorDecl>(NewFD) && 7566 !isa<CXXConversionDecl>(NewFD)) { 7567 // 'explicit' was specified on a function that wasn't a constructor 7568 // or conversion function. 7569 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7570 diag::err_explicit_non_ctor_or_conv_function) 7571 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7572 } 7573 } 7574 7575 if (isConstexpr) { 7576 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7577 // are implicitly inline. 7578 NewFD->setImplicitlyInline(); 7579 7580 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7581 // be either constructors or to return a literal type. Therefore, 7582 // destructors cannot be declared constexpr. 7583 if (isa<CXXDestructorDecl>(NewFD)) 7584 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7585 } 7586 7587 if (isConcept) { 7588 // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be 7589 // applied only to the definition of a function template [...] 7590 if (!D.isFunctionDefinition()) { 7591 Diag(D.getDeclSpec().getConceptSpecLoc(), 7592 diag::err_function_concept_not_defined); 7593 NewFD->setInvalidDecl(); 7594 } 7595 7596 // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall 7597 // have no exception-specification and is treated as if it were specified 7598 // with noexcept(true) (15.4). [...] 7599 if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) { 7600 if (FPT->hasExceptionSpec()) { 7601 SourceRange Range; 7602 if (D.isFunctionDeclarator()) 7603 Range = D.getFunctionTypeInfo().getExceptionSpecRange(); 7604 Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec) 7605 << FixItHint::CreateRemoval(Range); 7606 NewFD->setInvalidDecl(); 7607 } else { 7608 Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept); 7609 } 7610 7611 // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the 7612 // following restrictions: 7613 // - The declaration's parameter list shall be equivalent to an empty 7614 // parameter list. 7615 if (FPT->getNumParams() > 0 || FPT->isVariadic()) 7616 Diag(NewFD->getLocation(), diag::err_function_concept_with_params); 7617 } 7618 7619 // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is 7620 // implicity defined to be a constexpr declaration (implicitly inline) 7621 NewFD->setImplicitlyInline(); 7622 7623 // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not 7624 // be declared with the thread_local, inline, friend, or constexpr 7625 // specifiers, [...] 7626 if (isInline) { 7627 Diag(D.getDeclSpec().getInlineSpecLoc(), 7628 diag::err_concept_decl_invalid_specifiers) 7629 << 1 << 1; 7630 NewFD->setInvalidDecl(true); 7631 } 7632 7633 if (isFriend) { 7634 Diag(D.getDeclSpec().getFriendSpecLoc(), 7635 diag::err_concept_decl_invalid_specifiers) 7636 << 1 << 2; 7637 NewFD->setInvalidDecl(true); 7638 } 7639 7640 if (isConstexpr) { 7641 Diag(D.getDeclSpec().getConstexprSpecLoc(), 7642 diag::err_concept_decl_invalid_specifiers) 7643 << 1 << 3; 7644 NewFD->setInvalidDecl(true); 7645 } 7646 } 7647 7648 // If __module_private__ was specified, mark the function accordingly. 7649 if (D.getDeclSpec().isModulePrivateSpecified()) { 7650 if (isFunctionTemplateSpecialization) { 7651 SourceLocation ModulePrivateLoc 7652 = D.getDeclSpec().getModulePrivateSpecLoc(); 7653 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7654 << 0 7655 << FixItHint::CreateRemoval(ModulePrivateLoc); 7656 } else { 7657 NewFD->setModulePrivate(); 7658 if (FunctionTemplate) 7659 FunctionTemplate->setModulePrivate(); 7660 } 7661 } 7662 7663 if (isFriend) { 7664 if (FunctionTemplate) { 7665 FunctionTemplate->setObjectOfFriendDecl(); 7666 FunctionTemplate->setAccess(AS_public); 7667 } 7668 NewFD->setObjectOfFriendDecl(); 7669 NewFD->setAccess(AS_public); 7670 } 7671 7672 // If a function is defined as defaulted or deleted, mark it as such now. 7673 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7674 // definition kind to FDK_Definition. 7675 switch (D.getFunctionDefinitionKind()) { 7676 case FDK_Declaration: 7677 case FDK_Definition: 7678 break; 7679 7680 case FDK_Defaulted: 7681 NewFD->setDefaulted(); 7682 break; 7683 7684 case FDK_Deleted: 7685 NewFD->setDeletedAsWritten(); 7686 break; 7687 } 7688 7689 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7690 D.isFunctionDefinition()) { 7691 // C++ [class.mfct]p2: 7692 // A member function may be defined (8.4) in its class definition, in 7693 // which case it is an inline member function (7.1.2) 7694 NewFD->setImplicitlyInline(); 7695 } 7696 7697 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7698 !CurContext->isRecord()) { 7699 // C++ [class.static]p1: 7700 // A data or function member of a class may be declared static 7701 // in a class definition, in which case it is a static member of 7702 // the class. 7703 7704 // Complain about the 'static' specifier if it's on an out-of-line 7705 // member function definition. 7706 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7707 diag::err_static_out_of_line) 7708 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7709 } 7710 7711 // C++11 [except.spec]p15: 7712 // A deallocation function with no exception-specification is treated 7713 // as if it were specified with noexcept(true). 7714 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7715 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7716 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7717 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7718 NewFD->setType(Context.getFunctionType( 7719 FPT->getReturnType(), FPT->getParamTypes(), 7720 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7721 } 7722 7723 // Filter out previous declarations that don't match the scope. 7724 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7725 D.getCXXScopeSpec().isNotEmpty() || 7726 isExplicitSpecialization || 7727 isFunctionTemplateSpecialization); 7728 7729 // Handle GNU asm-label extension (encoded as an attribute). 7730 if (Expr *E = (Expr*) D.getAsmLabel()) { 7731 // The parser guarantees this is a string. 7732 StringLiteral *SE = cast<StringLiteral>(E); 7733 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7734 SE->getString(), 0)); 7735 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7736 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7737 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7738 if (I != ExtnameUndeclaredIdentifiers.end()) { 7739 if (isDeclExternC(NewFD)) { 7740 NewFD->addAttr(I->second); 7741 ExtnameUndeclaredIdentifiers.erase(I); 7742 } else 7743 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied) 7744 << /*Variable*/0 << NewFD; 7745 } 7746 } 7747 7748 // Copy the parameter declarations from the declarator D to the function 7749 // declaration NewFD, if they are available. First scavenge them into Params. 7750 SmallVector<ParmVarDecl*, 16> Params; 7751 if (D.isFunctionDeclarator()) { 7752 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7753 7754 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7755 // function that takes no arguments, not a function that takes a 7756 // single void argument. 7757 // We let through "const void" here because Sema::GetTypeForDeclarator 7758 // already checks for that case. 7759 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7760 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7761 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7762 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7763 Param->setDeclContext(NewFD); 7764 Params.push_back(Param); 7765 7766 if (Param->isInvalidDecl()) 7767 NewFD->setInvalidDecl(); 7768 } 7769 } 7770 7771 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7772 // When we're declaring a function with a typedef, typeof, etc as in the 7773 // following example, we'll need to synthesize (unnamed) 7774 // parameters for use in the declaration. 7775 // 7776 // @code 7777 // typedef void fn(int); 7778 // fn f; 7779 // @endcode 7780 7781 // Synthesize a parameter for each argument type. 7782 for (const auto &AI : FT->param_types()) { 7783 ParmVarDecl *Param = 7784 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7785 Param->setScopeInfo(0, Params.size()); 7786 Params.push_back(Param); 7787 } 7788 } else { 7789 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7790 "Should not need args for typedef of non-prototype fn"); 7791 } 7792 7793 // Finally, we know we have the right number of parameters, install them. 7794 NewFD->setParams(Params); 7795 7796 // Find all anonymous symbols defined during the declaration of this function 7797 // and add to NewFD. This lets us track decls such 'enum Y' in: 7798 // 7799 // void f(enum Y {AA} x) {} 7800 // 7801 // which would otherwise incorrectly end up in the translation unit scope. 7802 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7803 DeclsInPrototypeScope.clear(); 7804 7805 if (D.getDeclSpec().isNoreturnSpecified()) 7806 NewFD->addAttr( 7807 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7808 Context, 0)); 7809 7810 // Functions returning a variably modified type violate C99 6.7.5.2p2 7811 // because all functions have linkage. 7812 if (!NewFD->isInvalidDecl() && 7813 NewFD->getReturnType()->isVariablyModifiedType()) { 7814 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7815 NewFD->setInvalidDecl(); 7816 } 7817 7818 // Apply an implicit SectionAttr if #pragma code_seg is active. 7819 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 7820 !NewFD->hasAttr<SectionAttr>()) { 7821 NewFD->addAttr( 7822 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7823 CodeSegStack.CurrentValue->getString(), 7824 CodeSegStack.CurrentPragmaLocation)); 7825 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7826 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 7827 ASTContext::PSF_Read, 7828 NewFD)) 7829 NewFD->dropAttr<SectionAttr>(); 7830 } 7831 7832 // Handle attributes. 7833 ProcessDeclAttributes(S, NewFD, D); 7834 7835 if (getLangOpts().OpenCL) { 7836 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7837 // type declaration will generate a compilation error. 7838 unsigned AddressSpace = NewFD->getReturnType().getAddressSpace(); 7839 if (AddressSpace == LangAS::opencl_local || 7840 AddressSpace == LangAS::opencl_global || 7841 AddressSpace == LangAS::opencl_constant) { 7842 Diag(NewFD->getLocation(), 7843 diag::err_opencl_return_value_with_address_space); 7844 NewFD->setInvalidDecl(); 7845 } 7846 } 7847 7848 if (!getLangOpts().CPlusPlus) { 7849 // Perform semantic checking on the function declaration. 7850 bool isExplicitSpecialization=false; 7851 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7852 CheckMain(NewFD, D.getDeclSpec()); 7853 7854 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7855 CheckMSVCRTEntryPoint(NewFD); 7856 7857 if (!NewFD->isInvalidDecl()) 7858 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7859 isExplicitSpecialization)); 7860 else if (!Previous.empty()) 7861 // Recover gracefully from an invalid redeclaration. 7862 D.setRedeclaration(true); 7863 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7864 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7865 "previous declaration set still overloaded"); 7866 7867 // Diagnose no-prototype function declarations with calling conventions that 7868 // don't support variadic calls. Only do this in C and do it after merging 7869 // possibly prototyped redeclarations. 7870 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 7871 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 7872 CallingConv CC = FT->getExtInfo().getCC(); 7873 if (!supportsVariadicCall(CC)) { 7874 // Windows system headers sometimes accidentally use stdcall without 7875 // (void) parameters, so we relax this to a warning. 7876 int DiagID = 7877 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 7878 Diag(NewFD->getLocation(), DiagID) 7879 << FunctionType::getNameForCallConv(CC); 7880 } 7881 } 7882 } else { 7883 // C++11 [replacement.functions]p3: 7884 // The program's definitions shall not be specified as inline. 7885 // 7886 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7887 // 7888 // Suppress the diagnostic if the function is __attribute__((used)), since 7889 // that forces an external definition to be emitted. 7890 if (D.getDeclSpec().isInlineSpecified() && 7891 NewFD->isReplaceableGlobalAllocationFunction() && 7892 !NewFD->hasAttr<UsedAttr>()) 7893 Diag(D.getDeclSpec().getInlineSpecLoc(), 7894 diag::ext_operator_new_delete_declared_inline) 7895 << NewFD->getDeclName(); 7896 7897 // If the declarator is a template-id, translate the parser's template 7898 // argument list into our AST format. 7899 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7900 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7901 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7902 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7903 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7904 TemplateId->NumArgs); 7905 translateTemplateArguments(TemplateArgsPtr, 7906 TemplateArgs); 7907 7908 HasExplicitTemplateArgs = true; 7909 7910 if (NewFD->isInvalidDecl()) { 7911 HasExplicitTemplateArgs = false; 7912 } else if (FunctionTemplate) { 7913 // Function template with explicit template arguments. 7914 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7915 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7916 7917 HasExplicitTemplateArgs = false; 7918 } else { 7919 assert((isFunctionTemplateSpecialization || 7920 D.getDeclSpec().isFriendSpecified()) && 7921 "should have a 'template<>' for this decl"); 7922 // "friend void foo<>(int);" is an implicit specialization decl. 7923 isFunctionTemplateSpecialization = true; 7924 } 7925 } else if (isFriend && isFunctionTemplateSpecialization) { 7926 // This combination is only possible in a recovery case; the user 7927 // wrote something like: 7928 // template <> friend void foo(int); 7929 // which we're recovering from as if the user had written: 7930 // friend void foo<>(int); 7931 // Go ahead and fake up a template id. 7932 HasExplicitTemplateArgs = true; 7933 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7934 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7935 } 7936 7937 // If it's a friend (and only if it's a friend), it's possible 7938 // that either the specialized function type or the specialized 7939 // template is dependent, and therefore matching will fail. In 7940 // this case, don't check the specialization yet. 7941 bool InstantiationDependent = false; 7942 if (isFunctionTemplateSpecialization && isFriend && 7943 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7944 TemplateSpecializationType::anyDependentTemplateArguments( 7945 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7946 InstantiationDependent))) { 7947 assert(HasExplicitTemplateArgs && 7948 "friend function specialization without template args"); 7949 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7950 Previous)) 7951 NewFD->setInvalidDecl(); 7952 } else if (isFunctionTemplateSpecialization) { 7953 if (CurContext->isDependentContext() && CurContext->isRecord() 7954 && !isFriend) { 7955 isDependentClassScopeExplicitSpecialization = true; 7956 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7957 diag::ext_function_specialization_in_class : 7958 diag::err_function_specialization_in_class) 7959 << NewFD->getDeclName(); 7960 } else if (CheckFunctionTemplateSpecialization(NewFD, 7961 (HasExplicitTemplateArgs ? &TemplateArgs 7962 : nullptr), 7963 Previous)) 7964 NewFD->setInvalidDecl(); 7965 7966 // C++ [dcl.stc]p1: 7967 // A storage-class-specifier shall not be specified in an explicit 7968 // specialization (14.7.3) 7969 FunctionTemplateSpecializationInfo *Info = 7970 NewFD->getTemplateSpecializationInfo(); 7971 if (Info && SC != SC_None) { 7972 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7973 Diag(NewFD->getLocation(), 7974 diag::err_explicit_specialization_inconsistent_storage_class) 7975 << SC 7976 << FixItHint::CreateRemoval( 7977 D.getDeclSpec().getStorageClassSpecLoc()); 7978 7979 else 7980 Diag(NewFD->getLocation(), 7981 diag::ext_explicit_specialization_storage_class) 7982 << FixItHint::CreateRemoval( 7983 D.getDeclSpec().getStorageClassSpecLoc()); 7984 } 7985 7986 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7987 if (CheckMemberSpecialization(NewFD, Previous)) 7988 NewFD->setInvalidDecl(); 7989 } 7990 7991 // Perform semantic checking on the function declaration. 7992 if (!isDependentClassScopeExplicitSpecialization) { 7993 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7994 CheckMain(NewFD, D.getDeclSpec()); 7995 7996 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7997 CheckMSVCRTEntryPoint(NewFD); 7998 7999 if (!NewFD->isInvalidDecl()) 8000 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 8001 isExplicitSpecialization)); 8002 else if (!Previous.empty()) 8003 // Recover gracefully from an invalid redeclaration. 8004 D.setRedeclaration(true); 8005 } 8006 8007 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 8008 Previous.getResultKind() != LookupResult::FoundOverloaded) && 8009 "previous declaration set still overloaded"); 8010 8011 NamedDecl *PrincipalDecl = (FunctionTemplate 8012 ? cast<NamedDecl>(FunctionTemplate) 8013 : NewFD); 8014 8015 if (isFriend && D.isRedeclaration()) { 8016 AccessSpecifier Access = AS_public; 8017 if (!NewFD->isInvalidDecl()) 8018 Access = NewFD->getPreviousDecl()->getAccess(); 8019 8020 NewFD->setAccess(Access); 8021 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 8022 } 8023 8024 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 8025 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 8026 PrincipalDecl->setNonMemberOperator(); 8027 8028 // If we have a function template, check the template parameter 8029 // list. This will check and merge default template arguments. 8030 if (FunctionTemplate) { 8031 FunctionTemplateDecl *PrevTemplate = 8032 FunctionTemplate->getPreviousDecl(); 8033 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 8034 PrevTemplate ? PrevTemplate->getTemplateParameters() 8035 : nullptr, 8036 D.getDeclSpec().isFriendSpecified() 8037 ? (D.isFunctionDefinition() 8038 ? TPC_FriendFunctionTemplateDefinition 8039 : TPC_FriendFunctionTemplate) 8040 : (D.getCXXScopeSpec().isSet() && 8041 DC && DC->isRecord() && 8042 DC->isDependentContext()) 8043 ? TPC_ClassTemplateMember 8044 : TPC_FunctionTemplate); 8045 } 8046 8047 if (NewFD->isInvalidDecl()) { 8048 // Ignore all the rest of this. 8049 } else if (!D.isRedeclaration()) { 8050 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 8051 AddToScope }; 8052 // Fake up an access specifier if it's supposed to be a class member. 8053 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 8054 NewFD->setAccess(AS_public); 8055 8056 // Qualified decls generally require a previous declaration. 8057 if (D.getCXXScopeSpec().isSet()) { 8058 // ...with the major exception of templated-scope or 8059 // dependent-scope friend declarations. 8060 8061 // TODO: we currently also suppress this check in dependent 8062 // contexts because (1) the parameter depth will be off when 8063 // matching friend templates and (2) we might actually be 8064 // selecting a friend based on a dependent factor. But there 8065 // are situations where these conditions don't apply and we 8066 // can actually do this check immediately. 8067 if (isFriend && 8068 (TemplateParamLists.size() || 8069 D.getCXXScopeSpec().getScopeRep()->isDependent() || 8070 CurContext->isDependentContext())) { 8071 // ignore these 8072 } else { 8073 // The user tried to provide an out-of-line definition for a 8074 // function that is a member of a class or namespace, but there 8075 // was no such member function declared (C++ [class.mfct]p2, 8076 // C++ [namespace.memdef]p2). For example: 8077 // 8078 // class X { 8079 // void f() const; 8080 // }; 8081 // 8082 // void X::f() { } // ill-formed 8083 // 8084 // Complain about this problem, and attempt to suggest close 8085 // matches (e.g., those that differ only in cv-qualifiers and 8086 // whether the parameter types are references). 8087 8088 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8089 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 8090 AddToScope = ExtraArgs.AddToScope; 8091 return Result; 8092 } 8093 } 8094 8095 // Unqualified local friend declarations are required to resolve 8096 // to something. 8097 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 8098 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 8099 *this, Previous, NewFD, ExtraArgs, true, S)) { 8100 AddToScope = ExtraArgs.AddToScope; 8101 return Result; 8102 } 8103 } 8104 8105 } else if (!D.isFunctionDefinition() && 8106 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 8107 !isFriend && !isFunctionTemplateSpecialization && 8108 !isExplicitSpecialization) { 8109 // An out-of-line member function declaration must also be a 8110 // definition (C++ [class.mfct]p2). 8111 // Note that this is not the case for explicit specializations of 8112 // function templates or member functions of class templates, per 8113 // C++ [temp.expl.spec]p2. We also allow these declarations as an 8114 // extension for compatibility with old SWIG code which likes to 8115 // generate them. 8116 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 8117 << D.getCXXScopeSpec().getRange(); 8118 } 8119 } 8120 8121 ProcessPragmaWeak(S, NewFD); 8122 checkAttributesAfterMerging(*this, *NewFD); 8123 8124 AddKnownFunctionAttributes(NewFD); 8125 8126 if (NewFD->hasAttr<OverloadableAttr>() && 8127 !NewFD->getType()->getAs<FunctionProtoType>()) { 8128 Diag(NewFD->getLocation(), 8129 diag::err_attribute_overloadable_no_prototype) 8130 << NewFD; 8131 8132 // Turn this into a variadic function with no parameters. 8133 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 8134 FunctionProtoType::ExtProtoInfo EPI( 8135 Context.getDefaultCallingConvention(true, false)); 8136 EPI.Variadic = true; 8137 EPI.ExtInfo = FT->getExtInfo(); 8138 8139 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 8140 NewFD->setType(R); 8141 } 8142 8143 // If there's a #pragma GCC visibility in scope, and this isn't a class 8144 // member, set the visibility of this function. 8145 if (!DC->isRecord() && NewFD->isExternallyVisible()) 8146 AddPushedVisibilityAttribute(NewFD); 8147 8148 // If there's a #pragma clang arc_cf_code_audited in scope, consider 8149 // marking the function. 8150 AddCFAuditedAttribute(NewFD); 8151 8152 // If this is a function definition, check if we have to apply optnone due to 8153 // a pragma. 8154 if(D.isFunctionDefinition()) 8155 AddRangeBasedOptnone(NewFD); 8156 8157 // If this is the first declaration of an extern C variable, update 8158 // the map of such variables. 8159 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 8160 isIncompleteDeclExternC(*this, NewFD)) 8161 RegisterLocallyScopedExternCDecl(NewFD, S); 8162 8163 // Set this FunctionDecl's range up to the right paren. 8164 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 8165 8166 if (D.isRedeclaration() && !Previous.empty()) { 8167 checkDLLAttributeRedeclaration( 8168 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 8169 isExplicitSpecialization || isFunctionTemplateSpecialization); 8170 } 8171 8172 if (getLangOpts().CPlusPlus) { 8173 if (FunctionTemplate) { 8174 if (NewFD->isInvalidDecl()) 8175 FunctionTemplate->setInvalidDecl(); 8176 return FunctionTemplate; 8177 } 8178 } 8179 8180 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 8181 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 8182 if ((getLangOpts().OpenCLVersion >= 120) 8183 && (SC == SC_Static)) { 8184 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 8185 D.setInvalidType(); 8186 } 8187 8188 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 8189 if (!NewFD->getReturnType()->isVoidType()) { 8190 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 8191 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 8192 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 8193 : FixItHint()); 8194 D.setInvalidType(); 8195 } 8196 8197 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 8198 for (auto Param : NewFD->params()) 8199 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 8200 } 8201 8202 MarkUnusedFileScopedDecl(NewFD); 8203 8204 if (getLangOpts().CUDA) 8205 if (IdentifierInfo *II = NewFD->getIdentifier()) 8206 if (!NewFD->isInvalidDecl() && 8207 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 8208 if (II->isStr("cudaConfigureCall")) { 8209 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 8210 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 8211 8212 Context.setcudaConfigureCallDecl(NewFD); 8213 } 8214 } 8215 8216 // Here we have an function template explicit specialization at class scope. 8217 // The actually specialization will be postponed to template instatiation 8218 // time via the ClassScopeFunctionSpecializationDecl node. 8219 if (isDependentClassScopeExplicitSpecialization) { 8220 ClassScopeFunctionSpecializationDecl *NewSpec = 8221 ClassScopeFunctionSpecializationDecl::Create( 8222 Context, CurContext, SourceLocation(), 8223 cast<CXXMethodDecl>(NewFD), 8224 HasExplicitTemplateArgs, TemplateArgs); 8225 CurContext->addDecl(NewSpec); 8226 AddToScope = false; 8227 } 8228 8229 return NewFD; 8230 } 8231 8232 /// \brief Perform semantic checking of a new function declaration. 8233 /// 8234 /// Performs semantic analysis of the new function declaration 8235 /// NewFD. This routine performs all semantic checking that does not 8236 /// require the actual declarator involved in the declaration, and is 8237 /// used both for the declaration of functions as they are parsed 8238 /// (called via ActOnDeclarator) and for the declaration of functions 8239 /// that have been instantiated via C++ template instantiation (called 8240 /// via InstantiateDecl). 8241 /// 8242 /// \param IsExplicitSpecialization whether this new function declaration is 8243 /// an explicit specialization of the previous declaration. 8244 /// 8245 /// This sets NewFD->isInvalidDecl() to true if there was an error. 8246 /// 8247 /// \returns true if the function declaration is a redeclaration. 8248 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 8249 LookupResult &Previous, 8250 bool IsExplicitSpecialization) { 8251 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 8252 "Variably modified return types are not handled here"); 8253 8254 // Determine whether the type of this function should be merged with 8255 // a previous visible declaration. This never happens for functions in C++, 8256 // and always happens in C if the previous declaration was visible. 8257 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 8258 !Previous.isShadowed(); 8259 8260 bool Redeclaration = false; 8261 NamedDecl *OldDecl = nullptr; 8262 8263 // Merge or overload the declaration with an existing declaration of 8264 // the same name, if appropriate. 8265 if (!Previous.empty()) { 8266 // Determine whether NewFD is an overload of PrevDecl or 8267 // a declaration that requires merging. If it's an overload, 8268 // there's no more work to do here; we'll just add the new 8269 // function to the scope. 8270 if (!AllowOverloadingOfFunction(Previous, Context)) { 8271 NamedDecl *Candidate = Previous.getRepresentativeDecl(); 8272 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 8273 Redeclaration = true; 8274 OldDecl = Candidate; 8275 } 8276 } else { 8277 switch (CheckOverload(S, NewFD, Previous, OldDecl, 8278 /*NewIsUsingDecl*/ false)) { 8279 case Ovl_Match: 8280 Redeclaration = true; 8281 break; 8282 8283 case Ovl_NonFunction: 8284 Redeclaration = true; 8285 break; 8286 8287 case Ovl_Overload: 8288 Redeclaration = false; 8289 break; 8290 } 8291 8292 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8293 // If a function name is overloadable in C, then every function 8294 // with that name must be marked "overloadable". 8295 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8296 << Redeclaration << NewFD; 8297 NamedDecl *OverloadedDecl = nullptr; 8298 if (Redeclaration) 8299 OverloadedDecl = OldDecl; 8300 else if (!Previous.empty()) 8301 OverloadedDecl = Previous.getRepresentativeDecl(); 8302 if (OverloadedDecl) 8303 Diag(OverloadedDecl->getLocation(), 8304 diag::note_attribute_overloadable_prev_overload); 8305 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8306 } 8307 } 8308 } 8309 8310 // Check for a previous extern "C" declaration with this name. 8311 if (!Redeclaration && 8312 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 8313 if (!Previous.empty()) { 8314 // This is an extern "C" declaration with the same name as a previous 8315 // declaration, and thus redeclares that entity... 8316 Redeclaration = true; 8317 OldDecl = Previous.getFoundDecl(); 8318 MergeTypeWithPrevious = false; 8319 8320 // ... except in the presence of __attribute__((overloadable)). 8321 if (OldDecl->hasAttr<OverloadableAttr>()) { 8322 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 8323 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 8324 << Redeclaration << NewFD; 8325 Diag(Previous.getFoundDecl()->getLocation(), 8326 diag::note_attribute_overloadable_prev_overload); 8327 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 8328 } 8329 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 8330 Redeclaration = false; 8331 OldDecl = nullptr; 8332 } 8333 } 8334 } 8335 } 8336 8337 // C++11 [dcl.constexpr]p8: 8338 // A constexpr specifier for a non-static member function that is not 8339 // a constructor declares that member function to be const. 8340 // 8341 // This needs to be delayed until we know whether this is an out-of-line 8342 // definition of a static member function. 8343 // 8344 // This rule is not present in C++1y, so we produce a backwards 8345 // compatibility warning whenever it happens in C++11. 8346 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 8347 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 8348 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 8349 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 8350 CXXMethodDecl *OldMD = nullptr; 8351 if (OldDecl) 8352 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 8353 if (!OldMD || !OldMD->isStatic()) { 8354 const FunctionProtoType *FPT = 8355 MD->getType()->castAs<FunctionProtoType>(); 8356 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8357 EPI.TypeQuals |= Qualifiers::Const; 8358 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8359 FPT->getParamTypes(), EPI)); 8360 8361 // Warn that we did this, if we're not performing template instantiation. 8362 // In that case, we'll have warned already when the template was defined. 8363 if (ActiveTemplateInstantiations.empty()) { 8364 SourceLocation AddConstLoc; 8365 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8366 .IgnoreParens().getAs<FunctionTypeLoc>()) 8367 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8368 8369 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8370 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8371 } 8372 } 8373 } 8374 8375 if (Redeclaration) { 8376 // NewFD and OldDecl represent declarations that need to be 8377 // merged. 8378 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8379 NewFD->setInvalidDecl(); 8380 return Redeclaration; 8381 } 8382 8383 Previous.clear(); 8384 Previous.addDecl(OldDecl); 8385 8386 if (FunctionTemplateDecl *OldTemplateDecl 8387 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8388 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8389 FunctionTemplateDecl *NewTemplateDecl 8390 = NewFD->getDescribedFunctionTemplate(); 8391 assert(NewTemplateDecl && "Template/non-template mismatch"); 8392 if (CXXMethodDecl *Method 8393 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8394 Method->setAccess(OldTemplateDecl->getAccess()); 8395 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8396 } 8397 8398 // If this is an explicit specialization of a member that is a function 8399 // template, mark it as a member specialization. 8400 if (IsExplicitSpecialization && 8401 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8402 NewTemplateDecl->setMemberSpecialization(); 8403 assert(OldTemplateDecl->isMemberSpecialization()); 8404 } 8405 8406 } else { 8407 // This needs to happen first so that 'inline' propagates. 8408 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8409 8410 if (isa<CXXMethodDecl>(NewFD)) 8411 NewFD->setAccess(OldDecl->getAccess()); 8412 } 8413 } 8414 8415 // Semantic checking for this function declaration (in isolation). 8416 8417 if (getLangOpts().CPlusPlus) { 8418 // C++-specific checks. 8419 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8420 CheckConstructor(Constructor); 8421 } else if (CXXDestructorDecl *Destructor = 8422 dyn_cast<CXXDestructorDecl>(NewFD)) { 8423 CXXRecordDecl *Record = Destructor->getParent(); 8424 QualType ClassType = Context.getTypeDeclType(Record); 8425 8426 // FIXME: Shouldn't we be able to perform this check even when the class 8427 // type is dependent? Both gcc and edg can handle that. 8428 if (!ClassType->isDependentType()) { 8429 DeclarationName Name 8430 = Context.DeclarationNames.getCXXDestructorName( 8431 Context.getCanonicalType(ClassType)); 8432 if (NewFD->getDeclName() != Name) { 8433 Diag(NewFD->getLocation(), diag::err_destructor_name); 8434 NewFD->setInvalidDecl(); 8435 return Redeclaration; 8436 } 8437 } 8438 } else if (CXXConversionDecl *Conversion 8439 = dyn_cast<CXXConversionDecl>(NewFD)) { 8440 ActOnConversionDeclarator(Conversion); 8441 } 8442 8443 // Find any virtual functions that this function overrides. 8444 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8445 if (!Method->isFunctionTemplateSpecialization() && 8446 !Method->getDescribedFunctionTemplate() && 8447 Method->isCanonicalDecl()) { 8448 if (AddOverriddenMethods(Method->getParent(), Method)) { 8449 // If the function was marked as "static", we have a problem. 8450 if (NewFD->getStorageClass() == SC_Static) { 8451 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8452 } 8453 } 8454 } 8455 8456 if (Method->isStatic()) 8457 checkThisInStaticMemberFunctionType(Method); 8458 } 8459 8460 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8461 if (NewFD->isOverloadedOperator() && 8462 CheckOverloadedOperatorDeclaration(NewFD)) { 8463 NewFD->setInvalidDecl(); 8464 return Redeclaration; 8465 } 8466 8467 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8468 if (NewFD->getLiteralIdentifier() && 8469 CheckLiteralOperatorDeclaration(NewFD)) { 8470 NewFD->setInvalidDecl(); 8471 return Redeclaration; 8472 } 8473 8474 // In C++, check default arguments now that we have merged decls. Unless 8475 // the lexical context is the class, because in this case this is done 8476 // during delayed parsing anyway. 8477 if (!CurContext->isRecord()) 8478 CheckCXXDefaultArguments(NewFD); 8479 8480 // If this function declares a builtin function, check the type of this 8481 // declaration against the expected type for the builtin. 8482 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8483 ASTContext::GetBuiltinTypeError Error; 8484 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8485 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8486 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8487 // The type of this function differs from the type of the builtin, 8488 // so forget about the builtin entirely. 8489 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents); 8490 } 8491 } 8492 8493 // If this function is declared as being extern "C", then check to see if 8494 // the function returns a UDT (class, struct, or union type) that is not C 8495 // compatible, and if it does, warn the user. 8496 // But, issue any diagnostic on the first declaration only. 8497 if (Previous.empty() && NewFD->isExternC()) { 8498 QualType R = NewFD->getReturnType(); 8499 if (R->isIncompleteType() && !R->isVoidType()) 8500 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8501 << NewFD << R; 8502 else if (!R.isPODType(Context) && !R->isVoidType() && 8503 !R->isObjCObjectPointerType()) 8504 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8505 } 8506 } 8507 return Redeclaration; 8508 } 8509 8510 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8511 // C++11 [basic.start.main]p3: 8512 // A program that [...] declares main to be inline, static or 8513 // constexpr is ill-formed. 8514 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8515 // appear in a declaration of main. 8516 // static main is not an error under C99, but we should warn about it. 8517 // We accept _Noreturn main as an extension. 8518 if (FD->getStorageClass() == SC_Static) 8519 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8520 ? diag::err_static_main : diag::warn_static_main) 8521 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8522 if (FD->isInlineSpecified()) 8523 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8524 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8525 if (DS.isNoreturnSpecified()) { 8526 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8527 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8528 Diag(NoreturnLoc, diag::ext_noreturn_main); 8529 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8530 << FixItHint::CreateRemoval(NoreturnRange); 8531 } 8532 if (FD->isConstexpr()) { 8533 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8534 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8535 FD->setConstexpr(false); 8536 } 8537 8538 if (getLangOpts().OpenCL) { 8539 Diag(FD->getLocation(), diag::err_opencl_no_main) 8540 << FD->hasAttr<OpenCLKernelAttr>(); 8541 FD->setInvalidDecl(); 8542 return; 8543 } 8544 8545 QualType T = FD->getType(); 8546 assert(T->isFunctionType() && "function decl is not of function type"); 8547 const FunctionType* FT = T->castAs<FunctionType>(); 8548 8549 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8550 // In C with GNU extensions we allow main() to have non-integer return 8551 // type, but we should warn about the extension, and we disable the 8552 // implicit-return-zero rule. 8553 8554 // GCC in C mode accepts qualified 'int'. 8555 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8556 FD->setHasImplicitReturnZero(true); 8557 else { 8558 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8559 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8560 if (RTRange.isValid()) 8561 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8562 << FixItHint::CreateReplacement(RTRange, "int"); 8563 } 8564 } else { 8565 // In C and C++, main magically returns 0 if you fall off the end; 8566 // set the flag which tells us that. 8567 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8568 8569 // All the standards say that main() should return 'int'. 8570 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8571 FD->setHasImplicitReturnZero(true); 8572 else { 8573 // Otherwise, this is just a flat-out error. 8574 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8575 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8576 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8577 : FixItHint()); 8578 FD->setInvalidDecl(true); 8579 } 8580 } 8581 8582 // Treat protoless main() as nullary. 8583 if (isa<FunctionNoProtoType>(FT)) return; 8584 8585 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8586 unsigned nparams = FTP->getNumParams(); 8587 assert(FD->getNumParams() == nparams); 8588 8589 bool HasExtraParameters = (nparams > 3); 8590 8591 if (FTP->isVariadic()) { 8592 Diag(FD->getLocation(), diag::ext_variadic_main); 8593 // FIXME: if we had information about the location of the ellipsis, we 8594 // could add a FixIt hint to remove it as a parameter. 8595 } 8596 8597 // Darwin passes an undocumented fourth argument of type char**. If 8598 // other platforms start sprouting these, the logic below will start 8599 // getting shifty. 8600 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8601 HasExtraParameters = false; 8602 8603 if (HasExtraParameters) { 8604 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8605 FD->setInvalidDecl(true); 8606 nparams = 3; 8607 } 8608 8609 // FIXME: a lot of the following diagnostics would be improved 8610 // if we had some location information about types. 8611 8612 QualType CharPP = 8613 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8614 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8615 8616 for (unsigned i = 0; i < nparams; ++i) { 8617 QualType AT = FTP->getParamType(i); 8618 8619 bool mismatch = true; 8620 8621 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8622 mismatch = false; 8623 else if (Expected[i] == CharPP) { 8624 // As an extension, the following forms are okay: 8625 // char const ** 8626 // char const * const * 8627 // char * const * 8628 8629 QualifierCollector qs; 8630 const PointerType* PT; 8631 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8632 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8633 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8634 Context.CharTy)) { 8635 qs.removeConst(); 8636 mismatch = !qs.empty(); 8637 } 8638 } 8639 8640 if (mismatch) { 8641 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8642 // TODO: suggest replacing given type with expected type 8643 FD->setInvalidDecl(true); 8644 } 8645 } 8646 8647 if (nparams == 1 && !FD->isInvalidDecl()) { 8648 Diag(FD->getLocation(), diag::warn_main_one_arg); 8649 } 8650 8651 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8652 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8653 FD->setInvalidDecl(); 8654 } 8655 } 8656 8657 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8658 QualType T = FD->getType(); 8659 assert(T->isFunctionType() && "function decl is not of function type"); 8660 const FunctionType *FT = T->castAs<FunctionType>(); 8661 8662 // Set an implicit return of 'zero' if the function can return some integral, 8663 // enumeration, pointer or nullptr type. 8664 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8665 FT->getReturnType()->isAnyPointerType() || 8666 FT->getReturnType()->isNullPtrType()) 8667 // DllMain is exempt because a return value of zero means it failed. 8668 if (FD->getName() != "DllMain") 8669 FD->setHasImplicitReturnZero(true); 8670 8671 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8672 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8673 FD->setInvalidDecl(); 8674 } 8675 } 8676 8677 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8678 // FIXME: Need strict checking. In C89, we need to check for 8679 // any assignment, increment, decrement, function-calls, or 8680 // commas outside of a sizeof. In C99, it's the same list, 8681 // except that the aforementioned are allowed in unevaluated 8682 // expressions. Everything else falls under the 8683 // "may accept other forms of constant expressions" exception. 8684 // (We never end up here for C++, so the constant expression 8685 // rules there don't matter.) 8686 const Expr *Culprit; 8687 if (Init->isConstantInitializer(Context, false, &Culprit)) 8688 return false; 8689 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8690 << Culprit->getSourceRange(); 8691 return true; 8692 } 8693 8694 namespace { 8695 // Visits an initialization expression to see if OrigDecl is evaluated in 8696 // its own initialization and throws a warning if it does. 8697 class SelfReferenceChecker 8698 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8699 Sema &S; 8700 Decl *OrigDecl; 8701 bool isRecordType; 8702 bool isPODType; 8703 bool isReferenceType; 8704 8705 bool isInitList; 8706 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8707 public: 8708 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8709 8710 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8711 S(S), OrigDecl(OrigDecl) { 8712 isPODType = false; 8713 isRecordType = false; 8714 isReferenceType = false; 8715 isInitList = false; 8716 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8717 isPODType = VD->getType().isPODType(S.Context); 8718 isRecordType = VD->getType()->isRecordType(); 8719 isReferenceType = VD->getType()->isReferenceType(); 8720 } 8721 } 8722 8723 // For most expressions, just call the visitor. For initializer lists, 8724 // track the index of the field being initialized since fields are 8725 // initialized in order allowing use of previously initialized fields. 8726 void CheckExpr(Expr *E) { 8727 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8728 if (!InitList) { 8729 Visit(E); 8730 return; 8731 } 8732 8733 // Track and increment the index here. 8734 isInitList = true; 8735 InitFieldIndex.push_back(0); 8736 for (auto Child : InitList->children()) { 8737 CheckExpr(cast<Expr>(Child)); 8738 ++InitFieldIndex.back(); 8739 } 8740 InitFieldIndex.pop_back(); 8741 } 8742 8743 // Returns true if MemberExpr is checked and no futher checking is needed. 8744 // Returns false if additional checking is required. 8745 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8746 llvm::SmallVector<FieldDecl*, 4> Fields; 8747 Expr *Base = E; 8748 bool ReferenceField = false; 8749 8750 // Get the field memebers used. 8751 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8752 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8753 if (!FD) 8754 return false; 8755 Fields.push_back(FD); 8756 if (FD->getType()->isReferenceType()) 8757 ReferenceField = true; 8758 Base = ME->getBase()->IgnoreParenImpCasts(); 8759 } 8760 8761 // Keep checking only if the base Decl is the same. 8762 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8763 if (!DRE || DRE->getDecl() != OrigDecl) 8764 return false; 8765 8766 // A reference field can be bound to an unininitialized field. 8767 if (CheckReference && !ReferenceField) 8768 return true; 8769 8770 // Convert FieldDecls to their index number. 8771 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8772 for (const FieldDecl *I : llvm::reverse(Fields)) 8773 UsedFieldIndex.push_back(I->getFieldIndex()); 8774 8775 // See if a warning is needed by checking the first difference in index 8776 // numbers. If field being used has index less than the field being 8777 // initialized, then the use is safe. 8778 for (auto UsedIter = UsedFieldIndex.begin(), 8779 UsedEnd = UsedFieldIndex.end(), 8780 OrigIter = InitFieldIndex.begin(), 8781 OrigEnd = InitFieldIndex.end(); 8782 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8783 if (*UsedIter < *OrigIter) 8784 return true; 8785 if (*UsedIter > *OrigIter) 8786 break; 8787 } 8788 8789 // TODO: Add a different warning which will print the field names. 8790 HandleDeclRefExpr(DRE); 8791 return true; 8792 } 8793 8794 // For most expressions, the cast is directly above the DeclRefExpr. 8795 // For conditional operators, the cast can be outside the conditional 8796 // operator if both expressions are DeclRefExpr's. 8797 void HandleValue(Expr *E) { 8798 E = E->IgnoreParens(); 8799 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8800 HandleDeclRefExpr(DRE); 8801 return; 8802 } 8803 8804 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8805 Visit(CO->getCond()); 8806 HandleValue(CO->getTrueExpr()); 8807 HandleValue(CO->getFalseExpr()); 8808 return; 8809 } 8810 8811 if (BinaryConditionalOperator *BCO = 8812 dyn_cast<BinaryConditionalOperator>(E)) { 8813 Visit(BCO->getCond()); 8814 HandleValue(BCO->getFalseExpr()); 8815 return; 8816 } 8817 8818 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8819 HandleValue(OVE->getSourceExpr()); 8820 return; 8821 } 8822 8823 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8824 if (BO->getOpcode() == BO_Comma) { 8825 Visit(BO->getLHS()); 8826 HandleValue(BO->getRHS()); 8827 return; 8828 } 8829 } 8830 8831 if (isa<MemberExpr>(E)) { 8832 if (isInitList) { 8833 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8834 false /*CheckReference*/)) 8835 return; 8836 } 8837 8838 Expr *Base = E->IgnoreParenImpCasts(); 8839 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8840 // Check for static member variables and don't warn on them. 8841 if (!isa<FieldDecl>(ME->getMemberDecl())) 8842 return; 8843 Base = ME->getBase()->IgnoreParenImpCasts(); 8844 } 8845 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8846 HandleDeclRefExpr(DRE); 8847 return; 8848 } 8849 8850 Visit(E); 8851 } 8852 8853 // Reference types not handled in HandleValue are handled here since all 8854 // uses of references are bad, not just r-value uses. 8855 void VisitDeclRefExpr(DeclRefExpr *E) { 8856 if (isReferenceType) 8857 HandleDeclRefExpr(E); 8858 } 8859 8860 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8861 if (E->getCastKind() == CK_LValueToRValue) { 8862 HandleValue(E->getSubExpr()); 8863 return; 8864 } 8865 8866 Inherited::VisitImplicitCastExpr(E); 8867 } 8868 8869 void VisitMemberExpr(MemberExpr *E) { 8870 if (isInitList) { 8871 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 8872 return; 8873 } 8874 8875 // Don't warn on arrays since they can be treated as pointers. 8876 if (E->getType()->canDecayToPointerType()) return; 8877 8878 // Warn when a non-static method call is followed by non-static member 8879 // field accesses, which is followed by a DeclRefExpr. 8880 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8881 bool Warn = (MD && !MD->isStatic()); 8882 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8883 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8884 if (!isa<FieldDecl>(ME->getMemberDecl())) 8885 Warn = false; 8886 Base = ME->getBase()->IgnoreParenImpCasts(); 8887 } 8888 8889 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8890 if (Warn) 8891 HandleDeclRefExpr(DRE); 8892 return; 8893 } 8894 8895 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8896 // Visit that expression. 8897 Visit(Base); 8898 } 8899 8900 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8901 Expr *Callee = E->getCallee(); 8902 8903 if (isa<UnresolvedLookupExpr>(Callee)) 8904 return Inherited::VisitCXXOperatorCallExpr(E); 8905 8906 Visit(Callee); 8907 for (auto Arg: E->arguments()) 8908 HandleValue(Arg->IgnoreParenImpCasts()); 8909 } 8910 8911 void VisitUnaryOperator(UnaryOperator *E) { 8912 // For POD record types, addresses of its own members are well-defined. 8913 if (E->getOpcode() == UO_AddrOf && isRecordType && 8914 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8915 if (!isPODType) 8916 HandleValue(E->getSubExpr()); 8917 return; 8918 } 8919 8920 if (E->isIncrementDecrementOp()) { 8921 HandleValue(E->getSubExpr()); 8922 return; 8923 } 8924 8925 Inherited::VisitUnaryOperator(E); 8926 } 8927 8928 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8929 8930 void VisitCXXConstructExpr(CXXConstructExpr *E) { 8931 if (E->getConstructor()->isCopyConstructor()) { 8932 Expr *ArgExpr = E->getArg(0); 8933 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 8934 if (ILE->getNumInits() == 1) 8935 ArgExpr = ILE->getInit(0); 8936 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8937 if (ICE->getCastKind() == CK_NoOp) 8938 ArgExpr = ICE->getSubExpr(); 8939 HandleValue(ArgExpr); 8940 return; 8941 } 8942 Inherited::VisitCXXConstructExpr(E); 8943 } 8944 8945 void VisitCallExpr(CallExpr *E) { 8946 // Treat std::move as a use. 8947 if (E->getNumArgs() == 1) { 8948 if (FunctionDecl *FD = E->getDirectCallee()) { 8949 if (FD->isInStdNamespace() && FD->getIdentifier() && 8950 FD->getIdentifier()->isStr("move")) { 8951 HandleValue(E->getArg(0)); 8952 return; 8953 } 8954 } 8955 } 8956 8957 Inherited::VisitCallExpr(E); 8958 } 8959 8960 void VisitBinaryOperator(BinaryOperator *E) { 8961 if (E->isCompoundAssignmentOp()) { 8962 HandleValue(E->getLHS()); 8963 Visit(E->getRHS()); 8964 return; 8965 } 8966 8967 Inherited::VisitBinaryOperator(E); 8968 } 8969 8970 // A custom visitor for BinaryConditionalOperator is needed because the 8971 // regular visitor would check the condition and true expression separately 8972 // but both point to the same place giving duplicate diagnostics. 8973 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 8974 Visit(E->getCond()); 8975 Visit(E->getFalseExpr()); 8976 } 8977 8978 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8979 Decl* ReferenceDecl = DRE->getDecl(); 8980 if (OrigDecl != ReferenceDecl) return; 8981 unsigned diag; 8982 if (isReferenceType) { 8983 diag = diag::warn_uninit_self_reference_in_reference_init; 8984 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8985 diag = diag::warn_static_self_reference_in_init; 8986 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 8987 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 8988 DRE->getDecl()->getType()->isRecordType()) { 8989 diag = diag::warn_uninit_self_reference_in_init; 8990 } else { 8991 // Local variables will be handled by the CFG analysis. 8992 return; 8993 } 8994 8995 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8996 S.PDiag(diag) 8997 << DRE->getNameInfo().getName() 8998 << OrigDecl->getLocation() 8999 << DRE->getSourceRange()); 9000 } 9001 }; 9002 9003 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 9004 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 9005 bool DirectInit) { 9006 // Parameters arguments are occassionially constructed with itself, 9007 // for instance, in recursive functions. Skip them. 9008 if (isa<ParmVarDecl>(OrigDecl)) 9009 return; 9010 9011 E = E->IgnoreParens(); 9012 9013 // Skip checking T a = a where T is not a record or reference type. 9014 // Doing so is a way to silence uninitialized warnings. 9015 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 9016 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 9017 if (ICE->getCastKind() == CK_LValueToRValue) 9018 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 9019 if (DRE->getDecl() == OrigDecl) 9020 return; 9021 9022 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 9023 } 9024 } 9025 9026 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl, 9027 DeclarationName Name, QualType Type, 9028 TypeSourceInfo *TSI, 9029 SourceRange Range, bool DirectInit, 9030 Expr *Init) { 9031 bool IsInitCapture = !VDecl; 9032 assert((!VDecl || !VDecl->isInitCapture()) && 9033 "init captures are expected to be deduced prior to initialization"); 9034 9035 ArrayRef<Expr *> DeduceInits = Init; 9036 if (DirectInit) { 9037 if (auto *PL = dyn_cast<ParenListExpr>(Init)) 9038 DeduceInits = PL->exprs(); 9039 else if (auto *IL = dyn_cast<InitListExpr>(Init)) 9040 DeduceInits = IL->inits(); 9041 } 9042 9043 // Deduction only works if we have exactly one source expression. 9044 if (DeduceInits.empty()) { 9045 // It isn't possible to write this directly, but it is possible to 9046 // end up in this situation with "auto x(some_pack...);" 9047 Diag(Init->getLocStart(), IsInitCapture 9048 ? diag::err_init_capture_no_expression 9049 : diag::err_auto_var_init_no_expression) 9050 << Name << Type << Range; 9051 return QualType(); 9052 } 9053 9054 if (DeduceInits.size() > 1) { 9055 Diag(DeduceInits[1]->getLocStart(), 9056 IsInitCapture ? diag::err_init_capture_multiple_expressions 9057 : diag::err_auto_var_init_multiple_expressions) 9058 << Name << Type << Range; 9059 return QualType(); 9060 } 9061 9062 Expr *DeduceInit = DeduceInits[0]; 9063 if (DirectInit && isa<InitListExpr>(DeduceInit)) { 9064 Diag(Init->getLocStart(), IsInitCapture 9065 ? diag::err_init_capture_paren_braces 9066 : diag::err_auto_var_init_paren_braces) 9067 << isa<InitListExpr>(Init) << Name << Type << Range; 9068 return QualType(); 9069 } 9070 9071 // Expressions default to 'id' when we're in a debugger. 9072 bool DefaultedAnyToId = false; 9073 if (getLangOpts().DebuggerCastResultToId && 9074 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) { 9075 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9076 if (Result.isInvalid()) { 9077 return QualType(); 9078 } 9079 Init = Result.get(); 9080 DefaultedAnyToId = true; 9081 } 9082 9083 QualType DeducedType; 9084 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) { 9085 if (!IsInitCapture) 9086 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 9087 else if (isa<InitListExpr>(Init)) 9088 Diag(Range.getBegin(), 9089 diag::err_init_capture_deduction_failure_from_init_list) 9090 << Name 9091 << (DeduceInit->getType().isNull() ? TSI->getType() 9092 : DeduceInit->getType()) 9093 << DeduceInit->getSourceRange(); 9094 else 9095 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure) 9096 << Name << TSI->getType() 9097 << (DeduceInit->getType().isNull() ? TSI->getType() 9098 : DeduceInit->getType()) 9099 << DeduceInit->getSourceRange(); 9100 } 9101 9102 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 9103 // 'id' instead of a specific object type prevents most of our usual 9104 // checks. 9105 // We only want to warn outside of template instantiations, though: 9106 // inside a template, the 'id' could have come from a parameter. 9107 if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId && 9108 !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) { 9109 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc(); 9110 Diag(Loc, diag::warn_auto_var_is_id) << Name << Range; 9111 } 9112 9113 return DeducedType; 9114 } 9115 9116 /// AddInitializerToDecl - Adds the initializer Init to the 9117 /// declaration dcl. If DirectInit is true, this is C++ direct 9118 /// initialization rather than copy initialization. 9119 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 9120 bool DirectInit, bool TypeMayContainAuto) { 9121 // If there is no declaration, there was an error parsing it. Just ignore 9122 // the initializer. 9123 if (!RealDecl || RealDecl->isInvalidDecl()) { 9124 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl)); 9125 return; 9126 } 9127 9128 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 9129 // Pure-specifiers are handled in ActOnPureSpecifier. 9130 Diag(Method->getLocation(), diag::err_member_function_initialization) 9131 << Method->getDeclName() << Init->getSourceRange(); 9132 Method->setInvalidDecl(); 9133 return; 9134 } 9135 9136 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 9137 if (!VDecl) { 9138 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 9139 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 9140 RealDecl->setInvalidDecl(); 9141 return; 9142 } 9143 9144 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 9145 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 9146 // Attempt typo correction early so that the type of the init expression can 9147 // be deduced based on the chosen correction if the original init contains a 9148 // TypoExpr. 9149 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl); 9150 if (!Res.isUsable()) { 9151 RealDecl->setInvalidDecl(); 9152 return; 9153 } 9154 Init = Res.get(); 9155 9156 QualType DeducedType = deduceVarTypeFromInitializer( 9157 VDecl, VDecl->getDeclName(), VDecl->getType(), 9158 VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init); 9159 if (DeducedType.isNull()) { 9160 RealDecl->setInvalidDecl(); 9161 return; 9162 } 9163 9164 VDecl->setType(DeducedType); 9165 assert(VDecl->isLinkageValid()); 9166 9167 // In ARC, infer lifetime. 9168 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 9169 VDecl->setInvalidDecl(); 9170 9171 // If this is a redeclaration, check that the type we just deduced matches 9172 // the previously declared type. 9173 if (VarDecl *Old = VDecl->getPreviousDecl()) { 9174 // We never need to merge the type, because we cannot form an incomplete 9175 // array of auto, nor deduce such a type. 9176 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false); 9177 } 9178 9179 // Check the deduced type is valid for a variable declaration. 9180 CheckVariableDeclarationType(VDecl); 9181 if (VDecl->isInvalidDecl()) 9182 return; 9183 } 9184 9185 // dllimport cannot be used on variable definitions. 9186 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 9187 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 9188 VDecl->setInvalidDecl(); 9189 return; 9190 } 9191 9192 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 9193 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 9194 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 9195 VDecl->setInvalidDecl(); 9196 return; 9197 } 9198 9199 if (!VDecl->getType()->isDependentType()) { 9200 // A definition must end up with a complete type, which means it must be 9201 // complete with the restriction that an array type might be completed by 9202 // the initializer; note that later code assumes this restriction. 9203 QualType BaseDeclType = VDecl->getType(); 9204 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 9205 BaseDeclType = Array->getElementType(); 9206 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 9207 diag::err_typecheck_decl_incomplete_type)) { 9208 RealDecl->setInvalidDecl(); 9209 return; 9210 } 9211 9212 // The variable can not have an abstract class type. 9213 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 9214 diag::err_abstract_type_in_decl, 9215 AbstractVariableType)) 9216 VDecl->setInvalidDecl(); 9217 } 9218 9219 VarDecl *Def; 9220 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 9221 NamedDecl *Hidden = nullptr; 9222 if (!hasVisibleDefinition(Def, &Hidden) && 9223 (VDecl->getFormalLinkage() == InternalLinkage || 9224 VDecl->getDescribedVarTemplate() || 9225 VDecl->getNumTemplateParameterLists() || 9226 VDecl->getDeclContext()->isDependentContext())) { 9227 // The previous definition is hidden, and multiple definitions are 9228 // permitted (in separate TUs). Form another definition of it. 9229 } else { 9230 Diag(VDecl->getLocation(), diag::err_redefinition) 9231 << VDecl->getDeclName(); 9232 Diag(Def->getLocation(), diag::note_previous_definition); 9233 VDecl->setInvalidDecl(); 9234 return; 9235 } 9236 } 9237 9238 if (getLangOpts().CPlusPlus) { 9239 // C++ [class.static.data]p4 9240 // If a static data member is of const integral or const 9241 // enumeration type, its declaration in the class definition can 9242 // specify a constant-initializer which shall be an integral 9243 // constant expression (5.19). In that case, the member can appear 9244 // in integral constant expressions. The member shall still be 9245 // defined in a namespace scope if it is used in the program and the 9246 // namespace scope definition shall not contain an initializer. 9247 // 9248 // We already performed a redefinition check above, but for static 9249 // data members we also need to check whether there was an in-class 9250 // declaration with an initializer. 9251 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) { 9252 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 9253 << VDecl->getDeclName(); 9254 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(), 9255 diag::note_previous_initializer) 9256 << 0; 9257 return; 9258 } 9259 9260 if (VDecl->hasLocalStorage()) 9261 getCurFunction()->setHasBranchProtectedScope(); 9262 9263 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 9264 VDecl->setInvalidDecl(); 9265 return; 9266 } 9267 } 9268 9269 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 9270 // a kernel function cannot be initialized." 9271 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) { 9272 Diag(VDecl->getLocation(), diag::err_local_cant_init); 9273 VDecl->setInvalidDecl(); 9274 return; 9275 } 9276 9277 // Get the decls type and save a reference for later, since 9278 // CheckInitializerTypes may change it. 9279 QualType DclT = VDecl->getType(), SavT = DclT; 9280 9281 // Expressions default to 'id' when we're in a debugger 9282 // and we are assigning it to a variable of Objective-C pointer type. 9283 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 9284 Init->getType() == Context.UnknownAnyTy) { 9285 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 9286 if (Result.isInvalid()) { 9287 VDecl->setInvalidDecl(); 9288 return; 9289 } 9290 Init = Result.get(); 9291 } 9292 9293 // Perform the initialization. 9294 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 9295 if (!VDecl->isInvalidDecl()) { 9296 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 9297 InitializationKind Kind = 9298 DirectInit 9299 ? CXXDirectInit 9300 ? InitializationKind::CreateDirect(VDecl->getLocation(), 9301 Init->getLocStart(), 9302 Init->getLocEnd()) 9303 : InitializationKind::CreateDirectList(VDecl->getLocation()) 9304 : InitializationKind::CreateCopy(VDecl->getLocation(), 9305 Init->getLocStart()); 9306 9307 MultiExprArg Args = Init; 9308 if (CXXDirectInit) 9309 Args = MultiExprArg(CXXDirectInit->getExprs(), 9310 CXXDirectInit->getNumExprs()); 9311 9312 // Try to correct any TypoExprs in the initialization arguments. 9313 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 9314 ExprResult Res = CorrectDelayedTyposInExpr( 9315 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) { 9316 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 9317 return Init.Failed() ? ExprError() : E; 9318 }); 9319 if (Res.isInvalid()) { 9320 VDecl->setInvalidDecl(); 9321 } else if (Res.get() != Args[Idx]) { 9322 Args[Idx] = Res.get(); 9323 } 9324 } 9325 if (VDecl->isInvalidDecl()) 9326 return; 9327 9328 InitializationSequence InitSeq(*this, Entity, Kind, Args); 9329 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 9330 if (Result.isInvalid()) { 9331 VDecl->setInvalidDecl(); 9332 return; 9333 } 9334 9335 Init = Result.getAs<Expr>(); 9336 } 9337 9338 // Check for self-references within variable initializers. 9339 // Variables declared within a function/method body (except for references) 9340 // are handled by a dataflow analysis. 9341 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 9342 VDecl->getType()->isReferenceType()) { 9343 CheckSelfReference(*this, RealDecl, Init, DirectInit); 9344 } 9345 9346 // If the type changed, it means we had an incomplete type that was 9347 // completed by the initializer. For example: 9348 // int ary[] = { 1, 3, 5 }; 9349 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 9350 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 9351 VDecl->setType(DclT); 9352 9353 if (!VDecl->isInvalidDecl()) { 9354 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 9355 9356 if (VDecl->hasAttr<BlocksAttr>()) 9357 checkRetainCycles(VDecl, Init); 9358 9359 // It is safe to assign a weak reference into a strong variable. 9360 // Although this code can still have problems: 9361 // id x = self.weakProp; 9362 // id y = self.weakProp; 9363 // we do not warn to warn spuriously when 'x' and 'y' are on separate 9364 // paths through the function. This should be revisited if 9365 // -Wrepeated-use-of-weak is made flow-sensitive. 9366 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 9367 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 9368 Init->getLocStart())) 9369 getCurFunction()->markSafeWeakUse(Init); 9370 } 9371 9372 // The initialization is usually a full-expression. 9373 // 9374 // FIXME: If this is a braced initialization of an aggregate, it is not 9375 // an expression, and each individual field initializer is a separate 9376 // full-expression. For instance, in: 9377 // 9378 // struct Temp { ~Temp(); }; 9379 // struct S { S(Temp); }; 9380 // struct T { S a, b; } t = { Temp(), Temp() } 9381 // 9382 // we should destroy the first Temp before constructing the second. 9383 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9384 false, 9385 VDecl->isConstexpr()); 9386 if (Result.isInvalid()) { 9387 VDecl->setInvalidDecl(); 9388 return; 9389 } 9390 Init = Result.get(); 9391 9392 // Attach the initializer to the decl. 9393 VDecl->setInit(Init); 9394 9395 if (VDecl->isLocalVarDecl()) { 9396 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9397 // static storage duration shall be constant expressions or string literals. 9398 // C++ does not have this restriction. 9399 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9400 const Expr *Culprit; 9401 if (VDecl->getStorageClass() == SC_Static) 9402 CheckForConstantInitializer(Init, DclT); 9403 // C89 is stricter than C99 for non-static aggregate types. 9404 // C89 6.5.7p3: All the expressions [...] in an initializer list 9405 // for an object that has aggregate or union type shall be 9406 // constant expressions. 9407 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9408 isa<InitListExpr>(Init) && 9409 !Init->isConstantInitializer(Context, false, &Culprit)) 9410 Diag(Culprit->getExprLoc(), 9411 diag::ext_aggregate_init_not_constant) 9412 << Culprit->getSourceRange(); 9413 } 9414 } else if (VDecl->isStaticDataMember() && 9415 VDecl->getLexicalDeclContext()->isRecord()) { 9416 // This is an in-class initialization for a static data member, e.g., 9417 // 9418 // struct S { 9419 // static const int value = 17; 9420 // }; 9421 9422 // C++ [class.mem]p4: 9423 // A member-declarator can contain a constant-initializer only 9424 // if it declares a static member (9.4) of const integral or 9425 // const enumeration type, see 9.4.2. 9426 // 9427 // C++11 [class.static.data]p3: 9428 // If a non-volatile const static data member is of integral or 9429 // enumeration type, its declaration in the class definition can 9430 // specify a brace-or-equal-initializer in which every initalizer-clause 9431 // that is an assignment-expression is a constant expression. A static 9432 // data member of literal type can be declared in the class definition 9433 // with the constexpr specifier; if so, its declaration shall specify a 9434 // brace-or-equal-initializer in which every initializer-clause that is 9435 // an assignment-expression is a constant expression. 9436 9437 // Do nothing on dependent types. 9438 if (DclT->isDependentType()) { 9439 9440 // Allow any 'static constexpr' members, whether or not they are of literal 9441 // type. We separately check that every constexpr variable is of literal 9442 // type. 9443 } else if (VDecl->isConstexpr()) { 9444 9445 // Require constness. 9446 } else if (!DclT.isConstQualified()) { 9447 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9448 << Init->getSourceRange(); 9449 VDecl->setInvalidDecl(); 9450 9451 // We allow integer constant expressions in all cases. 9452 } else if (DclT->isIntegralOrEnumerationType()) { 9453 // Check whether the expression is a constant expression. 9454 SourceLocation Loc; 9455 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9456 // In C++11, a non-constexpr const static data member with an 9457 // in-class initializer cannot be volatile. 9458 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9459 else if (Init->isValueDependent()) 9460 ; // Nothing to check. 9461 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9462 ; // Ok, it's an ICE! 9463 else if (Init->isEvaluatable(Context)) { 9464 // If we can constant fold the initializer through heroics, accept it, 9465 // but report this as a use of an extension for -pedantic. 9466 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9467 << Init->getSourceRange(); 9468 } else { 9469 // Otherwise, this is some crazy unknown case. Report the issue at the 9470 // location provided by the isIntegerConstantExpr failed check. 9471 Diag(Loc, diag::err_in_class_initializer_non_constant) 9472 << Init->getSourceRange(); 9473 VDecl->setInvalidDecl(); 9474 } 9475 9476 // We allow foldable floating-point constants as an extension. 9477 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9478 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9479 // it anyway and provide a fixit to add the 'constexpr'. 9480 if (getLangOpts().CPlusPlus11) { 9481 Diag(VDecl->getLocation(), 9482 diag::ext_in_class_initializer_float_type_cxx11) 9483 << DclT << Init->getSourceRange(); 9484 Diag(VDecl->getLocStart(), 9485 diag::note_in_class_initializer_float_type_cxx11) 9486 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9487 } else { 9488 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9489 << DclT << Init->getSourceRange(); 9490 9491 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9492 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9493 << Init->getSourceRange(); 9494 VDecl->setInvalidDecl(); 9495 } 9496 } 9497 9498 // Suggest adding 'constexpr' in C++11 for literal types. 9499 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9500 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9501 << DclT << Init->getSourceRange() 9502 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9503 VDecl->setConstexpr(true); 9504 9505 } else { 9506 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9507 << DclT << Init->getSourceRange(); 9508 VDecl->setInvalidDecl(); 9509 } 9510 } else if (VDecl->isFileVarDecl()) { 9511 if (VDecl->getStorageClass() == SC_Extern && 9512 (!getLangOpts().CPlusPlus || 9513 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 9514 VDecl->isExternC())) && 9515 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9516 Diag(VDecl->getLocation(), diag::warn_extern_init); 9517 9518 // C99 6.7.8p4. All file scoped initializers need to be constant. 9519 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9520 CheckForConstantInitializer(Init, DclT); 9521 } 9522 9523 // We will represent direct-initialization similarly to copy-initialization: 9524 // int x(1); -as-> int x = 1; 9525 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9526 // 9527 // Clients that want to distinguish between the two forms, can check for 9528 // direct initializer using VarDecl::getInitStyle(). 9529 // A major benefit is that clients that don't particularly care about which 9530 // exactly form was it (like the CodeGen) can handle both cases without 9531 // special case code. 9532 9533 // C++ 8.5p11: 9534 // The form of initialization (using parentheses or '=') is generally 9535 // insignificant, but does matter when the entity being initialized has a 9536 // class type. 9537 if (CXXDirectInit) { 9538 assert(DirectInit && "Call-style initializer must be direct init."); 9539 VDecl->setInitStyle(VarDecl::CallInit); 9540 } else if (DirectInit) { 9541 // This must be list-initialization. No other way is direct-initialization. 9542 VDecl->setInitStyle(VarDecl::ListInit); 9543 } 9544 9545 CheckCompleteVariableDeclaration(VDecl); 9546 } 9547 9548 /// ActOnInitializerError - Given that there was an error parsing an 9549 /// initializer for the given declaration, try to return to some form 9550 /// of sanity. 9551 void Sema::ActOnInitializerError(Decl *D) { 9552 // Our main concern here is re-establishing invariants like "a 9553 // variable's type is either dependent or complete". 9554 if (!D || D->isInvalidDecl()) return; 9555 9556 VarDecl *VD = dyn_cast<VarDecl>(D); 9557 if (!VD) return; 9558 9559 // Auto types are meaningless if we can't make sense of the initializer. 9560 if (ParsingInitForAutoVars.count(D)) { 9561 D->setInvalidDecl(); 9562 return; 9563 } 9564 9565 QualType Ty = VD->getType(); 9566 if (Ty->isDependentType()) return; 9567 9568 // Require a complete type. 9569 if (RequireCompleteType(VD->getLocation(), 9570 Context.getBaseElementType(Ty), 9571 diag::err_typecheck_decl_incomplete_type)) { 9572 VD->setInvalidDecl(); 9573 return; 9574 } 9575 9576 // Require a non-abstract type. 9577 if (RequireNonAbstractType(VD->getLocation(), Ty, 9578 diag::err_abstract_type_in_decl, 9579 AbstractVariableType)) { 9580 VD->setInvalidDecl(); 9581 return; 9582 } 9583 9584 // Don't bother complaining about constructors or destructors, 9585 // though. 9586 } 9587 9588 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9589 bool TypeMayContainAuto) { 9590 // If there is no declaration, there was an error parsing it. Just ignore it. 9591 if (!RealDecl) 9592 return; 9593 9594 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9595 QualType Type = Var->getType(); 9596 9597 // C++11 [dcl.spec.auto]p3 9598 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9599 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9600 << Var->getDeclName() << Type; 9601 Var->setInvalidDecl(); 9602 return; 9603 } 9604 9605 // C++11 [class.static.data]p3: A static data member can be declared with 9606 // the constexpr specifier; if so, its declaration shall specify 9607 // a brace-or-equal-initializer. 9608 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9609 // the definition of a variable [...] or the declaration of a static data 9610 // member. 9611 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9612 if (Var->isStaticDataMember()) 9613 Diag(Var->getLocation(), 9614 diag::err_constexpr_static_mem_var_requires_init) 9615 << Var->getDeclName(); 9616 else 9617 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9618 Var->setInvalidDecl(); 9619 return; 9620 } 9621 9622 // C++ Concepts TS [dcl.spec.concept]p1: [...] A variable template 9623 // definition having the concept specifier is called a variable concept. A 9624 // concept definition refers to [...] a variable concept and its initializer. 9625 if (Var->isConcept()) { 9626 Diag(Var->getLocation(), diag::err_var_concept_not_initialized); 9627 Var->setInvalidDecl(); 9628 return; 9629 } 9630 9631 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9632 // be initialized. 9633 if (!Var->isInvalidDecl() && 9634 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9635 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9636 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9637 Var->setInvalidDecl(); 9638 return; 9639 } 9640 9641 switch (Var->isThisDeclarationADefinition()) { 9642 case VarDecl::Definition: 9643 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9644 break; 9645 9646 // We have an out-of-line definition of a static data member 9647 // that has an in-class initializer, so we type-check this like 9648 // a declaration. 9649 // 9650 // Fall through 9651 9652 case VarDecl::DeclarationOnly: 9653 // It's only a declaration. 9654 9655 // Block scope. C99 6.7p7: If an identifier for an object is 9656 // declared with no linkage (C99 6.2.2p6), the type for the 9657 // object shall be complete. 9658 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9659 !Var->hasLinkage() && !Var->isInvalidDecl() && 9660 RequireCompleteType(Var->getLocation(), Type, 9661 diag::err_typecheck_decl_incomplete_type)) 9662 Var->setInvalidDecl(); 9663 9664 // Make sure that the type is not abstract. 9665 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9666 RequireNonAbstractType(Var->getLocation(), Type, 9667 diag::err_abstract_type_in_decl, 9668 AbstractVariableType)) 9669 Var->setInvalidDecl(); 9670 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9671 Var->getStorageClass() == SC_PrivateExtern) { 9672 Diag(Var->getLocation(), diag::warn_private_extern); 9673 Diag(Var->getLocation(), diag::note_private_extern); 9674 } 9675 9676 return; 9677 9678 case VarDecl::TentativeDefinition: 9679 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9680 // object that has file scope without an initializer, and without a 9681 // storage-class specifier or with the storage-class specifier "static", 9682 // constitutes a tentative definition. Note: A tentative definition with 9683 // external linkage is valid (C99 6.2.2p5). 9684 if (!Var->isInvalidDecl()) { 9685 if (const IncompleteArrayType *ArrayT 9686 = Context.getAsIncompleteArrayType(Type)) { 9687 if (RequireCompleteType(Var->getLocation(), 9688 ArrayT->getElementType(), 9689 diag::err_illegal_decl_array_incomplete_type)) 9690 Var->setInvalidDecl(); 9691 } else if (Var->getStorageClass() == SC_Static) { 9692 // C99 6.9.2p3: If the declaration of an identifier for an object is 9693 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9694 // declared type shall not be an incomplete type. 9695 // NOTE: code such as the following 9696 // static struct s; 9697 // struct s { int a; }; 9698 // is accepted by gcc. Hence here we issue a warning instead of 9699 // an error and we do not invalidate the static declaration. 9700 // NOTE: to avoid multiple warnings, only check the first declaration. 9701 if (Var->isFirstDecl()) 9702 RequireCompleteType(Var->getLocation(), Type, 9703 diag::ext_typecheck_decl_incomplete_type); 9704 } 9705 } 9706 9707 // Record the tentative definition; we're done. 9708 if (!Var->isInvalidDecl()) 9709 TentativeDefinitions.push_back(Var); 9710 return; 9711 } 9712 9713 // Provide a specific diagnostic for uninitialized variable 9714 // definitions with incomplete array type. 9715 if (Type->isIncompleteArrayType()) { 9716 Diag(Var->getLocation(), 9717 diag::err_typecheck_incomplete_array_needs_initializer); 9718 Var->setInvalidDecl(); 9719 return; 9720 } 9721 9722 // Provide a specific diagnostic for uninitialized variable 9723 // definitions with reference type. 9724 if (Type->isReferenceType()) { 9725 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9726 << Var->getDeclName() 9727 << SourceRange(Var->getLocation(), Var->getLocation()); 9728 Var->setInvalidDecl(); 9729 return; 9730 } 9731 9732 // Do not attempt to type-check the default initializer for a 9733 // variable with dependent type. 9734 if (Type->isDependentType()) 9735 return; 9736 9737 if (Var->isInvalidDecl()) 9738 return; 9739 9740 if (!Var->hasAttr<AliasAttr>()) { 9741 if (RequireCompleteType(Var->getLocation(), 9742 Context.getBaseElementType(Type), 9743 diag::err_typecheck_decl_incomplete_type)) { 9744 Var->setInvalidDecl(); 9745 return; 9746 } 9747 } else { 9748 return; 9749 } 9750 9751 // The variable can not have an abstract class type. 9752 if (RequireNonAbstractType(Var->getLocation(), Type, 9753 diag::err_abstract_type_in_decl, 9754 AbstractVariableType)) { 9755 Var->setInvalidDecl(); 9756 return; 9757 } 9758 9759 // Check for jumps past the implicit initializer. C++0x 9760 // clarifies that this applies to a "variable with automatic 9761 // storage duration", not a "local variable". 9762 // C++11 [stmt.dcl]p3 9763 // A program that jumps from a point where a variable with automatic 9764 // storage duration is not in scope to a point where it is in scope is 9765 // ill-formed unless the variable has scalar type, class type with a 9766 // trivial default constructor and a trivial destructor, a cv-qualified 9767 // version of one of these types, or an array of one of the preceding 9768 // types and is declared without an initializer. 9769 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9770 if (const RecordType *Record 9771 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9772 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9773 // Mark the function for further checking even if the looser rules of 9774 // C++11 do not require such checks, so that we can diagnose 9775 // incompatibilities with C++98. 9776 if (!CXXRecord->isPOD()) 9777 getCurFunction()->setHasBranchProtectedScope(); 9778 } 9779 } 9780 9781 // C++03 [dcl.init]p9: 9782 // If no initializer is specified for an object, and the 9783 // object is of (possibly cv-qualified) non-POD class type (or 9784 // array thereof), the object shall be default-initialized; if 9785 // the object is of const-qualified type, the underlying class 9786 // type shall have a user-declared default 9787 // constructor. Otherwise, if no initializer is specified for 9788 // a non- static object, the object and its subobjects, if 9789 // any, have an indeterminate initial value); if the object 9790 // or any of its subobjects are of const-qualified type, the 9791 // program is ill-formed. 9792 // C++0x [dcl.init]p11: 9793 // If no initializer is specified for an object, the object is 9794 // default-initialized; [...]. 9795 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9796 InitializationKind Kind 9797 = InitializationKind::CreateDefault(Var->getLocation()); 9798 9799 InitializationSequence InitSeq(*this, Entity, Kind, None); 9800 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9801 if (Init.isInvalid()) 9802 Var->setInvalidDecl(); 9803 else if (Init.get()) { 9804 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9805 // This is important for template substitution. 9806 Var->setInitStyle(VarDecl::CallInit); 9807 } 9808 9809 CheckCompleteVariableDeclaration(Var); 9810 } 9811 } 9812 9813 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9814 VarDecl *VD = dyn_cast<VarDecl>(D); 9815 if (!VD) { 9816 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9817 D->setInvalidDecl(); 9818 return; 9819 } 9820 9821 VD->setCXXForRangeDecl(true); 9822 9823 // for-range-declaration cannot be given a storage class specifier. 9824 int Error = -1; 9825 switch (VD->getStorageClass()) { 9826 case SC_None: 9827 break; 9828 case SC_Extern: 9829 Error = 0; 9830 break; 9831 case SC_Static: 9832 Error = 1; 9833 break; 9834 case SC_PrivateExtern: 9835 Error = 2; 9836 break; 9837 case SC_Auto: 9838 Error = 3; 9839 break; 9840 case SC_Register: 9841 Error = 4; 9842 break; 9843 } 9844 if (Error != -1) { 9845 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9846 << VD->getDeclName() << Error; 9847 D->setInvalidDecl(); 9848 } 9849 } 9850 9851 StmtResult 9852 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9853 IdentifierInfo *Ident, 9854 ParsedAttributes &Attrs, 9855 SourceLocation AttrEnd) { 9856 // C++1y [stmt.iter]p1: 9857 // A range-based for statement of the form 9858 // for ( for-range-identifier : for-range-initializer ) statement 9859 // is equivalent to 9860 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9861 DeclSpec DS(Attrs.getPool().getFactory()); 9862 9863 const char *PrevSpec; 9864 unsigned DiagID; 9865 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 9866 getPrintingPolicy()); 9867 9868 Declarator D(DS, Declarator::ForContext); 9869 D.SetIdentifier(Ident, IdentLoc); 9870 D.takeAttributes(Attrs, AttrEnd); 9871 9872 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 9873 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 9874 EmptyAttrs, IdentLoc); 9875 Decl *Var = ActOnDeclarator(S, D); 9876 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 9877 FinalizeDeclaration(Var); 9878 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 9879 AttrEnd.isValid() ? AttrEnd : IdentLoc); 9880 } 9881 9882 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 9883 if (var->isInvalidDecl()) return; 9884 9885 // In Objective-C, don't allow jumps past the implicit initialization of a 9886 // local retaining variable. 9887 if (getLangOpts().ObjC1 && 9888 var->hasLocalStorage()) { 9889 switch (var->getType().getObjCLifetime()) { 9890 case Qualifiers::OCL_None: 9891 case Qualifiers::OCL_ExplicitNone: 9892 case Qualifiers::OCL_Autoreleasing: 9893 break; 9894 9895 case Qualifiers::OCL_Weak: 9896 case Qualifiers::OCL_Strong: 9897 getCurFunction()->setHasBranchProtectedScope(); 9898 break; 9899 } 9900 } 9901 9902 // Warn about externally-visible variables being defined without a 9903 // prior declaration. We only want to do this for global 9904 // declarations, but we also specifically need to avoid doing it for 9905 // class members because the linkage of an anonymous class can 9906 // change if it's later given a typedef name. 9907 if (var->isThisDeclarationADefinition() && 9908 var->getDeclContext()->getRedeclContext()->isFileContext() && 9909 var->isExternallyVisible() && var->hasLinkage() && 9910 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9911 var->getLocation())) { 9912 // Find a previous declaration that's not a definition. 9913 VarDecl *prev = var->getPreviousDecl(); 9914 while (prev && prev->isThisDeclarationADefinition()) 9915 prev = prev->getPreviousDecl(); 9916 9917 if (!prev) 9918 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9919 } 9920 9921 if (var->getTLSKind() == VarDecl::TLS_Static) { 9922 const Expr *Culprit; 9923 if (var->getType().isDestructedType()) { 9924 // GNU C++98 edits for __thread, [basic.start.term]p3: 9925 // The type of an object with thread storage duration shall not 9926 // have a non-trivial destructor. 9927 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9928 if (getLangOpts().CPlusPlus11) 9929 Diag(var->getLocation(), diag::note_use_thread_local); 9930 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9931 !var->getInit()->isConstantInitializer( 9932 Context, var->getType()->isReferenceType(), &Culprit)) { 9933 // GNU C++98 edits for __thread, [basic.start.init]p4: 9934 // An object of thread storage duration shall not require dynamic 9935 // initialization. 9936 // FIXME: Need strict checking here. 9937 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9938 << Culprit->getSourceRange(); 9939 if (getLangOpts().CPlusPlus11) 9940 Diag(var->getLocation(), diag::note_use_thread_local); 9941 } 9942 9943 } 9944 9945 // Apply section attributes and pragmas to global variables. 9946 bool GlobalStorage = var->hasGlobalStorage(); 9947 if (GlobalStorage && var->isThisDeclarationADefinition() && 9948 ActiveTemplateInstantiations.empty()) { 9949 PragmaStack<StringLiteral *> *Stack = nullptr; 9950 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 9951 if (var->getType().isConstQualified()) 9952 Stack = &ConstSegStack; 9953 else if (!var->getInit()) { 9954 Stack = &BSSSegStack; 9955 SectionFlags |= ASTContext::PSF_Write; 9956 } else { 9957 Stack = &DataSegStack; 9958 SectionFlags |= ASTContext::PSF_Write; 9959 } 9960 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 9961 var->addAttr(SectionAttr::CreateImplicit( 9962 Context, SectionAttr::Declspec_allocate, 9963 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 9964 } 9965 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9966 if (UnifySection(SA->getName(), SectionFlags, var)) 9967 var->dropAttr<SectionAttr>(); 9968 9969 // Apply the init_seg attribute if this has an initializer. If the 9970 // initializer turns out to not be dynamic, we'll end up ignoring this 9971 // attribute. 9972 if (CurInitSeg && var->getInit()) 9973 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 9974 CurInitSegLoc)); 9975 } 9976 9977 // All the following checks are C++ only. 9978 if (!getLangOpts().CPlusPlus) return; 9979 9980 QualType type = var->getType(); 9981 if (type->isDependentType()) return; 9982 9983 // __block variables might require us to capture a copy-initializer. 9984 if (var->hasAttr<BlocksAttr>()) { 9985 // It's currently invalid to ever have a __block variable with an 9986 // array type; should we diagnose that here? 9987 9988 // Regardless, we don't want to ignore array nesting when 9989 // constructing this copy. 9990 if (type->isStructureOrClassType()) { 9991 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9992 SourceLocation poi = var->getLocation(); 9993 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9994 ExprResult result 9995 = PerformMoveOrCopyInitialization( 9996 InitializedEntity::InitializeBlock(poi, type, false), 9997 var, var->getType(), varRef, /*AllowNRVO=*/true); 9998 if (!result.isInvalid()) { 9999 result = MaybeCreateExprWithCleanups(result); 10000 Expr *init = result.getAs<Expr>(); 10001 Context.setBlockVarCopyInits(var, init); 10002 } 10003 } 10004 } 10005 10006 Expr *Init = var->getInit(); 10007 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 10008 QualType baseType = Context.getBaseElementType(type); 10009 10010 if (!var->getDeclContext()->isDependentContext() && 10011 Init && !Init->isValueDependent()) { 10012 if (IsGlobal && !var->isConstexpr() && 10013 !getDiagnostics().isIgnored(diag::warn_global_constructor, 10014 var->getLocation())) { 10015 // Warn about globals which don't have a constant initializer. Don't 10016 // warn about globals with a non-trivial destructor because we already 10017 // warned about them. 10018 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 10019 if (!(RD && !RD->hasTrivialDestructor()) && 10020 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 10021 Diag(var->getLocation(), diag::warn_global_constructor) 10022 << Init->getSourceRange(); 10023 } 10024 10025 if (var->isConstexpr()) { 10026 SmallVector<PartialDiagnosticAt, 8> Notes; 10027 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 10028 SourceLocation DiagLoc = var->getLocation(); 10029 // If the note doesn't add any useful information other than a source 10030 // location, fold it into the primary diagnostic. 10031 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 10032 diag::note_invalid_subexpr_in_const_expr) { 10033 DiagLoc = Notes[0].first; 10034 Notes.clear(); 10035 } 10036 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 10037 << var << Init->getSourceRange(); 10038 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 10039 Diag(Notes[I].first, Notes[I].second); 10040 } 10041 } else if (var->isUsableInConstantExpressions(Context)) { 10042 // Check whether the initializer of a const variable of integral or 10043 // enumeration type is an ICE now, since we can't tell whether it was 10044 // initialized by a constant expression if we check later. 10045 var->checkInitIsICE(); 10046 } 10047 } 10048 10049 // Require the destructor. 10050 if (const RecordType *recordType = baseType->getAs<RecordType>()) 10051 FinalizeVarWithDestructor(var, recordType); 10052 } 10053 10054 /// \brief Determines if a variable's alignment is dependent. 10055 static bool hasDependentAlignment(VarDecl *VD) { 10056 if (VD->getType()->isDependentType()) 10057 return true; 10058 for (auto *I : VD->specific_attrs<AlignedAttr>()) 10059 if (I->isAlignmentDependent()) 10060 return true; 10061 return false; 10062 } 10063 10064 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 10065 /// any semantic actions necessary after any initializer has been attached. 10066 void 10067 Sema::FinalizeDeclaration(Decl *ThisDecl) { 10068 // Note that we are no longer parsing the initializer for this declaration. 10069 ParsingInitForAutoVars.erase(ThisDecl); 10070 10071 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 10072 if (!VD) 10073 return; 10074 10075 checkAttributesAfterMerging(*this, *VD); 10076 10077 // Perform TLS alignment check here after attributes attached to the variable 10078 // which may affect the alignment have been processed. Only perform the check 10079 // if the target has a maximum TLS alignment (zero means no constraints). 10080 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) { 10081 // Protect the check so that it's not performed on dependent types and 10082 // dependent alignments (we can't determine the alignment in that case). 10083 if (VD->getTLSKind() && !hasDependentAlignment(VD)) { 10084 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign); 10085 if (Context.getDeclAlign(VD) > MaxAlignChars) { 10086 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 10087 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD 10088 << (unsigned)MaxAlignChars.getQuantity(); 10089 } 10090 } 10091 } 10092 10093 // Static locals inherit dll attributes from their function. 10094 if (VD->isStaticLocal()) { 10095 if (FunctionDecl *FD = 10096 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 10097 if (Attr *A = getDLLAttr(FD)) { 10098 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 10099 NewAttr->setInherited(true); 10100 VD->addAttr(NewAttr); 10101 } 10102 } 10103 } 10104 10105 // Grab the dllimport or dllexport attribute off of the VarDecl. 10106 const InheritableAttr *DLLAttr = getDLLAttr(VD); 10107 10108 // Imported static data members cannot be defined out-of-line. 10109 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 10110 if (VD->isStaticDataMember() && VD->isOutOfLine() && 10111 VD->isThisDeclarationADefinition()) { 10112 // We allow definitions of dllimport class template static data members 10113 // with a warning. 10114 CXXRecordDecl *Context = 10115 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 10116 bool IsClassTemplateMember = 10117 isa<ClassTemplatePartialSpecializationDecl>(Context) || 10118 Context->getDescribedClassTemplate(); 10119 10120 Diag(VD->getLocation(), 10121 IsClassTemplateMember 10122 ? diag::warn_attribute_dllimport_static_field_definition 10123 : diag::err_attribute_dllimport_static_field_definition); 10124 Diag(IA->getLocation(), diag::note_attribute); 10125 if (!IsClassTemplateMember) 10126 VD->setInvalidDecl(); 10127 } 10128 } 10129 10130 // dllimport/dllexport variables cannot be thread local, their TLS index 10131 // isn't exported with the variable. 10132 if (DLLAttr && VD->getTLSKind()) { 10133 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod()); 10134 if (F && getDLLAttr(F)) { 10135 assert(VD->isStaticLocal()); 10136 // But if this is a static local in a dlimport/dllexport function, the 10137 // function will never be inlined, which means the var would never be 10138 // imported, so having it marked import/export is safe. 10139 } else { 10140 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 10141 << DLLAttr; 10142 VD->setInvalidDecl(); 10143 } 10144 } 10145 10146 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 10147 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 10148 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 10149 VD->dropAttr<UsedAttr>(); 10150 } 10151 } 10152 10153 const DeclContext *DC = VD->getDeclContext(); 10154 // If there's a #pragma GCC visibility in scope, and this isn't a class 10155 // member, set the visibility of this variable. 10156 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 10157 AddPushedVisibilityAttribute(VD); 10158 10159 // FIXME: Warn on unused templates. 10160 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 10161 !isa<VarTemplatePartialSpecializationDecl>(VD)) 10162 MarkUnusedFileScopedDecl(VD); 10163 10164 // Now we have parsed the initializer and can update the table of magic 10165 // tag values. 10166 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 10167 !VD->getType()->isIntegralOrEnumerationType()) 10168 return; 10169 10170 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 10171 const Expr *MagicValueExpr = VD->getInit(); 10172 if (!MagicValueExpr) { 10173 continue; 10174 } 10175 llvm::APSInt MagicValueInt; 10176 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 10177 Diag(I->getRange().getBegin(), 10178 diag::err_type_tag_for_datatype_not_ice) 10179 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10180 continue; 10181 } 10182 if (MagicValueInt.getActiveBits() > 64) { 10183 Diag(I->getRange().getBegin(), 10184 diag::err_type_tag_for_datatype_too_large) 10185 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 10186 continue; 10187 } 10188 uint64_t MagicValue = MagicValueInt.getZExtValue(); 10189 RegisterTypeTagForDatatype(I->getArgumentKind(), 10190 MagicValue, 10191 I->getMatchingCType(), 10192 I->getLayoutCompatible(), 10193 I->getMustBeNull()); 10194 } 10195 } 10196 10197 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 10198 ArrayRef<Decl *> Group) { 10199 SmallVector<Decl*, 8> Decls; 10200 10201 if (DS.isTypeSpecOwned()) 10202 Decls.push_back(DS.getRepAsDecl()); 10203 10204 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 10205 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10206 if (Decl *D = Group[i]) { 10207 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 10208 if (!FirstDeclaratorInGroup) 10209 FirstDeclaratorInGroup = DD; 10210 Decls.push_back(D); 10211 } 10212 10213 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 10214 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 10215 handleTagNumbering(Tag, S); 10216 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() && 10217 getLangOpts().CPlusPlus) 10218 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup); 10219 } 10220 } 10221 10222 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 10223 } 10224 10225 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 10226 /// group, performing any necessary semantic checking. 10227 Sema::DeclGroupPtrTy 10228 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 10229 bool TypeMayContainAuto) { 10230 // C++0x [dcl.spec.auto]p7: 10231 // If the type deduced for the template parameter U is not the same in each 10232 // deduction, the program is ill-formed. 10233 // FIXME: When initializer-list support is added, a distinction is needed 10234 // between the deduced type U and the deduced type which 'auto' stands for. 10235 // auto a = 0, b = { 1, 2, 3 }; 10236 // is legal because the deduced type U is 'int' in both cases. 10237 if (TypeMayContainAuto && Group.size() > 1) { 10238 QualType Deduced; 10239 CanQualType DeducedCanon; 10240 VarDecl *DeducedDecl = nullptr; 10241 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 10242 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 10243 AutoType *AT = D->getType()->getContainedAutoType(); 10244 // Don't reissue diagnostics when instantiating a template. 10245 if (AT && D->isInvalidDecl()) 10246 break; 10247 QualType U = AT ? AT->getDeducedType() : QualType(); 10248 if (!U.isNull()) { 10249 CanQualType UCanon = Context.getCanonicalType(U); 10250 if (Deduced.isNull()) { 10251 Deduced = U; 10252 DeducedCanon = UCanon; 10253 DeducedDecl = D; 10254 } else if (DeducedCanon != UCanon) { 10255 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 10256 diag::err_auto_different_deductions) 10257 << (unsigned)AT->getKeyword() 10258 << Deduced << DeducedDecl->getDeclName() 10259 << U << D->getDeclName() 10260 << DeducedDecl->getInit()->getSourceRange() 10261 << D->getInit()->getSourceRange(); 10262 D->setInvalidDecl(); 10263 break; 10264 } 10265 } 10266 } 10267 } 10268 } 10269 10270 ActOnDocumentableDecls(Group); 10271 10272 return DeclGroupPtrTy::make( 10273 DeclGroupRef::Create(Context, Group.data(), Group.size())); 10274 } 10275 10276 void Sema::ActOnDocumentableDecl(Decl *D) { 10277 ActOnDocumentableDecls(D); 10278 } 10279 10280 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 10281 // Don't parse the comment if Doxygen diagnostics are ignored. 10282 if (Group.empty() || !Group[0]) 10283 return; 10284 10285 if (Diags.isIgnored(diag::warn_doc_param_not_found, 10286 Group[0]->getLocation()) && 10287 Diags.isIgnored(diag::warn_unknown_comment_command_name, 10288 Group[0]->getLocation())) 10289 return; 10290 10291 if (Group.size() >= 2) { 10292 // This is a decl group. Normally it will contain only declarations 10293 // produced from declarator list. But in case we have any definitions or 10294 // additional declaration references: 10295 // 'typedef struct S {} S;' 10296 // 'typedef struct S *S;' 10297 // 'struct S *pS;' 10298 // FinalizeDeclaratorGroup adds these as separate declarations. 10299 Decl *MaybeTagDecl = Group[0]; 10300 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 10301 Group = Group.slice(1); 10302 } 10303 } 10304 10305 // See if there are any new comments that are not attached to a decl. 10306 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 10307 if (!Comments.empty() && 10308 !Comments.back()->isAttached()) { 10309 // There is at least one comment that not attached to a decl. 10310 // Maybe it should be attached to one of these decls? 10311 // 10312 // Note that this way we pick up not only comments that precede the 10313 // declaration, but also comments that *follow* the declaration -- thanks to 10314 // the lookahead in the lexer: we've consumed the semicolon and looked 10315 // ahead through comments. 10316 for (unsigned i = 0, e = Group.size(); i != e; ++i) 10317 Context.getCommentForDecl(Group[i], &PP); 10318 } 10319 } 10320 10321 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 10322 /// to introduce parameters into function prototype scope. 10323 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 10324 const DeclSpec &DS = D.getDeclSpec(); 10325 10326 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 10327 10328 // C++03 [dcl.stc]p2 also permits 'auto'. 10329 StorageClass SC = SC_None; 10330 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 10331 SC = SC_Register; 10332 } else if (getLangOpts().CPlusPlus && 10333 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 10334 SC = SC_Auto; 10335 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 10336 Diag(DS.getStorageClassSpecLoc(), 10337 diag::err_invalid_storage_class_in_func_decl); 10338 D.getMutableDeclSpec().ClearStorageClassSpecs(); 10339 } 10340 10341 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 10342 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 10343 << DeclSpec::getSpecifierName(TSCS); 10344 if (DS.isConstexprSpecified()) 10345 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 10346 << 0; 10347 if (DS.isConceptSpecified()) 10348 Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind); 10349 10350 DiagnoseFunctionSpecifiers(DS); 10351 10352 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 10353 QualType parmDeclType = TInfo->getType(); 10354 10355 if (getLangOpts().CPlusPlus) { 10356 // Check that there are no default arguments inside the type of this 10357 // parameter. 10358 CheckExtraCXXDefaultArguments(D); 10359 10360 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 10361 if (D.getCXXScopeSpec().isSet()) { 10362 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 10363 << D.getCXXScopeSpec().getRange(); 10364 D.getCXXScopeSpec().clear(); 10365 } 10366 } 10367 10368 // Ensure we have a valid name 10369 IdentifierInfo *II = nullptr; 10370 if (D.hasName()) { 10371 II = D.getIdentifier(); 10372 if (!II) { 10373 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 10374 << GetNameForDeclarator(D).getName(); 10375 D.setInvalidType(true); 10376 } 10377 } 10378 10379 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 10380 if (II) { 10381 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 10382 ForRedeclaration); 10383 LookupName(R, S); 10384 if (R.isSingleResult()) { 10385 NamedDecl *PrevDecl = R.getFoundDecl(); 10386 if (PrevDecl->isTemplateParameter()) { 10387 // Maybe we will complain about the shadowed template parameter. 10388 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 10389 // Just pretend that we didn't see the previous declaration. 10390 PrevDecl = nullptr; 10391 } else if (S->isDeclScope(PrevDecl)) { 10392 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 10393 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 10394 10395 // Recover by removing the name 10396 II = nullptr; 10397 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 10398 D.setInvalidType(true); 10399 } 10400 } 10401 } 10402 10403 // Temporarily put parameter variables in the translation unit, not 10404 // the enclosing context. This prevents them from accidentally 10405 // looking like class members in C++. 10406 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 10407 D.getLocStart(), 10408 D.getIdentifierLoc(), II, 10409 parmDeclType, TInfo, 10410 SC); 10411 10412 if (D.isInvalidType()) 10413 New->setInvalidDecl(); 10414 10415 assert(S->isFunctionPrototypeScope()); 10416 assert(S->getFunctionPrototypeDepth() >= 1); 10417 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 10418 S->getNextFunctionPrototypeIndex()); 10419 10420 // Add the parameter declaration into this scope. 10421 S->AddDecl(New); 10422 if (II) 10423 IdResolver.AddDecl(New); 10424 10425 ProcessDeclAttributes(S, New, D); 10426 10427 if (D.getDeclSpec().isModulePrivateSpecified()) 10428 Diag(New->getLocation(), diag::err_module_private_local) 10429 << 1 << New->getDeclName() 10430 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10431 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10432 10433 if (New->hasAttr<BlocksAttr>()) { 10434 Diag(New->getLocation(), diag::err_block_on_nonlocal); 10435 } 10436 return New; 10437 } 10438 10439 /// \brief Synthesizes a variable for a parameter arising from a 10440 /// typedef. 10441 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 10442 SourceLocation Loc, 10443 QualType T) { 10444 /* FIXME: setting StartLoc == Loc. 10445 Would it be worth to modify callers so as to provide proper source 10446 location for the unnamed parameters, embedding the parameter's type? */ 10447 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 10448 T, Context.getTrivialTypeSourceInfo(T, Loc), 10449 SC_None, nullptr); 10450 Param->setImplicit(); 10451 return Param; 10452 } 10453 10454 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 10455 ParmVarDecl * const *ParamEnd) { 10456 // Don't diagnose unused-parameter errors in template instantiations; we 10457 // will already have done so in the template itself. 10458 if (!ActiveTemplateInstantiations.empty()) 10459 return; 10460 10461 for (; Param != ParamEnd; ++Param) { 10462 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 10463 !(*Param)->hasAttr<UnusedAttr>()) { 10464 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 10465 << (*Param)->getDeclName(); 10466 } 10467 } 10468 } 10469 10470 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 10471 ParmVarDecl * const *ParamEnd, 10472 QualType ReturnTy, 10473 NamedDecl *D) { 10474 if (LangOpts.NumLargeByValueCopy == 0) // No check. 10475 return; 10476 10477 // Warn if the return value is pass-by-value and larger than the specified 10478 // threshold. 10479 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 10480 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 10481 if (Size > LangOpts.NumLargeByValueCopy) 10482 Diag(D->getLocation(), diag::warn_return_value_size) 10483 << D->getDeclName() << Size; 10484 } 10485 10486 // Warn if any parameter is pass-by-value and larger than the specified 10487 // threshold. 10488 for (; Param != ParamEnd; ++Param) { 10489 QualType T = (*Param)->getType(); 10490 if (T->isDependentType() || !T.isPODType(Context)) 10491 continue; 10492 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 10493 if (Size > LangOpts.NumLargeByValueCopy) 10494 Diag((*Param)->getLocation(), diag::warn_parameter_size) 10495 << (*Param)->getDeclName() << Size; 10496 } 10497 } 10498 10499 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 10500 SourceLocation NameLoc, IdentifierInfo *Name, 10501 QualType T, TypeSourceInfo *TSInfo, 10502 StorageClass SC) { 10503 // In ARC, infer a lifetime qualifier for appropriate parameter types. 10504 if (getLangOpts().ObjCAutoRefCount && 10505 T.getObjCLifetime() == Qualifiers::OCL_None && 10506 T->isObjCLifetimeType()) { 10507 10508 Qualifiers::ObjCLifetime lifetime; 10509 10510 // Special cases for arrays: 10511 // - if it's const, use __unsafe_unretained 10512 // - otherwise, it's an error 10513 if (T->isArrayType()) { 10514 if (!T.isConstQualified()) { 10515 DelayedDiagnostics.add( 10516 sema::DelayedDiagnostic::makeForbiddenType( 10517 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 10518 } 10519 lifetime = Qualifiers::OCL_ExplicitNone; 10520 } else { 10521 lifetime = T->getObjCARCImplicitLifetime(); 10522 } 10523 T = Context.getLifetimeQualifiedType(T, lifetime); 10524 } 10525 10526 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 10527 Context.getAdjustedParameterType(T), 10528 TSInfo, SC, nullptr); 10529 10530 // Parameters can not be abstract class types. 10531 // For record types, this is done by the AbstractClassUsageDiagnoser once 10532 // the class has been completely parsed. 10533 if (!CurContext->isRecord() && 10534 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 10535 AbstractParamType)) 10536 New->setInvalidDecl(); 10537 10538 // Parameter declarators cannot be interface types. All ObjC objects are 10539 // passed by reference. 10540 if (T->isObjCObjectType()) { 10541 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 10542 Diag(NameLoc, 10543 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 10544 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 10545 T = Context.getObjCObjectPointerType(T); 10546 New->setType(T); 10547 } 10548 10549 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 10550 // duration shall not be qualified by an address-space qualifier." 10551 // Since all parameters have automatic store duration, they can not have 10552 // an address space. 10553 if (T.getAddressSpace() != 0) { 10554 // OpenCL allows function arguments declared to be an array of a type 10555 // to be qualified with an address space. 10556 if (!(getLangOpts().OpenCL && T->isArrayType())) { 10557 Diag(NameLoc, diag::err_arg_with_address_space); 10558 New->setInvalidDecl(); 10559 } 10560 } 10561 10562 return New; 10563 } 10564 10565 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 10566 SourceLocation LocAfterDecls) { 10567 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10568 10569 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 10570 // for a K&R function. 10571 if (!FTI.hasPrototype) { 10572 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10573 --i; 10574 if (FTI.Params[i].Param == nullptr) { 10575 SmallString<256> Code; 10576 llvm::raw_svector_ostream(Code) 10577 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10578 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10579 << FTI.Params[i].Ident 10580 << FixItHint::CreateInsertion(LocAfterDecls, Code); 10581 10582 // Implicitly declare the argument as type 'int' for lack of a better 10583 // type. 10584 AttributeFactory attrs; 10585 DeclSpec DS(attrs); 10586 const char* PrevSpec; // unused 10587 unsigned DiagID; // unused 10588 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10589 DiagID, Context.getPrintingPolicy()); 10590 // Use the identifier location for the type source range. 10591 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10592 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10593 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10594 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10595 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10596 } 10597 } 10598 } 10599 } 10600 10601 Decl * 10602 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D, 10603 MultiTemplateParamsArg TemplateParameterLists, 10604 SkipBodyInfo *SkipBody) { 10605 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10606 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10607 Scope *ParentScope = FnBodyScope->getParent(); 10608 10609 D.setFunctionDefinitionKind(FDK_Definition); 10610 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists); 10611 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody); 10612 } 10613 10614 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10615 Consumer.HandleInlineMethodDefinition(D); 10616 } 10617 10618 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10619 const FunctionDecl*& PossibleZeroParamPrototype) { 10620 // Don't warn about invalid declarations. 10621 if (FD->isInvalidDecl()) 10622 return false; 10623 10624 // Or declarations that aren't global. 10625 if (!FD->isGlobal()) 10626 return false; 10627 10628 // Don't warn about C++ member functions. 10629 if (isa<CXXMethodDecl>(FD)) 10630 return false; 10631 10632 // Don't warn about 'main'. 10633 if (FD->isMain()) 10634 return false; 10635 10636 // Don't warn about inline functions. 10637 if (FD->isInlined()) 10638 return false; 10639 10640 // Don't warn about function templates. 10641 if (FD->getDescribedFunctionTemplate()) 10642 return false; 10643 10644 // Don't warn about function template specializations. 10645 if (FD->isFunctionTemplateSpecialization()) 10646 return false; 10647 10648 // Don't warn for OpenCL kernels. 10649 if (FD->hasAttr<OpenCLKernelAttr>()) 10650 return false; 10651 10652 // Don't warn on explicitly deleted functions. 10653 if (FD->isDeleted()) 10654 return false; 10655 10656 bool MissingPrototype = true; 10657 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10658 Prev; Prev = Prev->getPreviousDecl()) { 10659 // Ignore any declarations that occur in function or method 10660 // scope, because they aren't visible from the header. 10661 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10662 continue; 10663 10664 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10665 if (FD->getNumParams() == 0) 10666 PossibleZeroParamPrototype = Prev; 10667 break; 10668 } 10669 10670 return MissingPrototype; 10671 } 10672 10673 void 10674 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10675 const FunctionDecl *EffectiveDefinition, 10676 SkipBodyInfo *SkipBody) { 10677 // Don't complain if we're in GNU89 mode and the previous definition 10678 // was an extern inline function. 10679 const FunctionDecl *Definition = EffectiveDefinition; 10680 if (!Definition) 10681 if (!FD->isDefined(Definition)) 10682 return; 10683 10684 if (canRedefineFunction(Definition, getLangOpts())) 10685 return; 10686 10687 // If we don't have a visible definition of the function, and it's inline or 10688 // a template, skip the new definition. 10689 if (SkipBody && !hasVisibleDefinition(Definition) && 10690 (Definition->getFormalLinkage() == InternalLinkage || 10691 Definition->isInlined() || 10692 Definition->getDescribedFunctionTemplate() || 10693 Definition->getNumTemplateParameterLists())) { 10694 SkipBody->ShouldSkip = true; 10695 if (auto *TD = Definition->getDescribedFunctionTemplate()) 10696 makeMergedDefinitionVisible(TD, FD->getLocation()); 10697 else 10698 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition), 10699 FD->getLocation()); 10700 return; 10701 } 10702 10703 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10704 Definition->getStorageClass() == SC_Extern) 10705 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10706 << FD->getDeclName() << getLangOpts().CPlusPlus; 10707 else 10708 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10709 10710 Diag(Definition->getLocation(), diag::note_previous_definition); 10711 FD->setInvalidDecl(); 10712 } 10713 10714 10715 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10716 Sema &S) { 10717 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10718 10719 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10720 LSI->CallOperator = CallOperator; 10721 LSI->Lambda = LambdaClass; 10722 LSI->ReturnType = CallOperator->getReturnType(); 10723 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10724 10725 if (LCD == LCD_None) 10726 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10727 else if (LCD == LCD_ByCopy) 10728 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10729 else if (LCD == LCD_ByRef) 10730 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10731 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10732 10733 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10734 LSI->Mutable = !CallOperator->isConst(); 10735 10736 // Add the captures to the LSI so they can be noted as already 10737 // captured within tryCaptureVar. 10738 auto I = LambdaClass->field_begin(); 10739 for (const auto &C : LambdaClass->captures()) { 10740 if (C.capturesVariable()) { 10741 VarDecl *VD = C.getCapturedVar(); 10742 if (VD->isInitCapture()) 10743 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10744 QualType CaptureType = VD->getType(); 10745 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10746 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10747 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 10748 /*EllipsisLoc*/C.isPackExpansion() 10749 ? C.getEllipsisLoc() : SourceLocation(), 10750 CaptureType, /*Expr*/ nullptr); 10751 10752 } else if (C.capturesThis()) { 10753 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10754 S.getCurrentThisType(), /*Expr*/ nullptr); 10755 } else { 10756 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10757 } 10758 ++I; 10759 } 10760 } 10761 10762 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D, 10763 SkipBodyInfo *SkipBody) { 10764 // Clear the last template instantiation error context. 10765 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10766 10767 if (!D) 10768 return D; 10769 FunctionDecl *FD = nullptr; 10770 10771 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10772 FD = FunTmpl->getTemplatedDecl(); 10773 else 10774 FD = cast<FunctionDecl>(D); 10775 10776 // See if this is a redefinition. 10777 if (!FD->isLateTemplateParsed()) { 10778 CheckForFunctionRedefinition(FD, nullptr, SkipBody); 10779 10780 // If we're skipping the body, we're done. Don't enter the scope. 10781 if (SkipBody && SkipBody->ShouldSkip) 10782 return D; 10783 } 10784 10785 // If we are instantiating a generic lambda call operator, push 10786 // a LambdaScopeInfo onto the function stack. But use the information 10787 // that's already been calculated (ActOnLambdaExpr) to prime the current 10788 // LambdaScopeInfo. 10789 // When the template operator is being specialized, the LambdaScopeInfo, 10790 // has to be properly restored so that tryCaptureVariable doesn't try 10791 // and capture any new variables. In addition when calculating potential 10792 // captures during transformation of nested lambdas, it is necessary to 10793 // have the LSI properly restored. 10794 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10795 assert(ActiveTemplateInstantiations.size() && 10796 "There should be an active template instantiation on the stack " 10797 "when instantiating a generic lambda!"); 10798 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10799 } 10800 else 10801 // Enter a new function scope 10802 PushFunctionScope(); 10803 10804 // Builtin functions cannot be defined. 10805 if (unsigned BuiltinID = FD->getBuiltinID()) { 10806 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10807 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10808 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10809 FD->setInvalidDecl(); 10810 } 10811 } 10812 10813 // The return type of a function definition must be complete 10814 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10815 QualType ResultType = FD->getReturnType(); 10816 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10817 !FD->isInvalidDecl() && 10818 RequireCompleteType(FD->getLocation(), ResultType, 10819 diag::err_func_def_incomplete_result)) 10820 FD->setInvalidDecl(); 10821 10822 if (FnBodyScope) 10823 PushDeclContext(FnBodyScope, FD); 10824 10825 // Check the validity of our function parameters 10826 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10827 /*CheckParameterNames=*/true); 10828 10829 // Introduce our parameters into the function scope 10830 for (auto Param : FD->params()) { 10831 Param->setOwningFunction(FD); 10832 10833 // If this has an identifier, add it to the scope stack. 10834 if (Param->getIdentifier() && FnBodyScope) { 10835 CheckShadow(FnBodyScope, Param); 10836 10837 PushOnScopeChains(Param, FnBodyScope); 10838 } 10839 } 10840 10841 // If we had any tags defined in the function prototype, 10842 // introduce them into the function scope. 10843 if (FnBodyScope) { 10844 for (ArrayRef<NamedDecl *>::iterator 10845 I = FD->getDeclsInPrototypeScope().begin(), 10846 E = FD->getDeclsInPrototypeScope().end(); 10847 I != E; ++I) { 10848 NamedDecl *D = *I; 10849 10850 // Some of these decls (like enums) may have been pinned to the 10851 // translation unit for lack of a real context earlier. If so, remove 10852 // from the translation unit and reattach to the current context. 10853 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 10854 // Is the decl actually in the context? 10855 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 10856 if (DI == D) { 10857 Context.getTranslationUnitDecl()->removeDecl(D); 10858 break; 10859 } 10860 } 10861 // Either way, reassign the lexical decl context to our FunctionDecl. 10862 D->setLexicalDeclContext(CurContext); 10863 } 10864 10865 // If the decl has a non-null name, make accessible in the current scope. 10866 if (!D->getName().empty()) 10867 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 10868 10869 // Similarly, dive into enums and fish their constants out, making them 10870 // accessible in this scope. 10871 if (auto *ED = dyn_cast<EnumDecl>(D)) { 10872 for (auto *EI : ED->enumerators()) 10873 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 10874 } 10875 } 10876 } 10877 10878 // Ensure that the function's exception specification is instantiated. 10879 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 10880 ResolveExceptionSpec(D->getLocation(), FPT); 10881 10882 // dllimport cannot be applied to non-inline function definitions. 10883 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 10884 !FD->isTemplateInstantiation()) { 10885 assert(!FD->hasAttr<DLLExportAttr>()); 10886 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 10887 FD->setInvalidDecl(); 10888 return D; 10889 } 10890 // We want to attach documentation to original Decl (which might be 10891 // a function template). 10892 ActOnDocumentableDecl(D); 10893 if (getCurLexicalContext()->isObjCContainer() && 10894 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 10895 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 10896 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 10897 10898 return D; 10899 } 10900 10901 /// \brief Given the set of return statements within a function body, 10902 /// compute the variables that are subject to the named return value 10903 /// optimization. 10904 /// 10905 /// Each of the variables that is subject to the named return value 10906 /// optimization will be marked as NRVO variables in the AST, and any 10907 /// return statement that has a marked NRVO variable as its NRVO candidate can 10908 /// use the named return value optimization. 10909 /// 10910 /// This function applies a very simplistic algorithm for NRVO: if every return 10911 /// statement in the scope of a variable has the same NRVO candidate, that 10912 /// candidate is an NRVO variable. 10913 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 10914 ReturnStmt **Returns = Scope->Returns.data(); 10915 10916 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 10917 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 10918 if (!NRVOCandidate->isNRVOVariable()) 10919 Returns[I]->setNRVOCandidate(nullptr); 10920 } 10921 } 10922 } 10923 10924 bool Sema::canDelayFunctionBody(const Declarator &D) { 10925 // We can't delay parsing the body of a constexpr function template (yet). 10926 if (D.getDeclSpec().isConstexprSpecified()) 10927 return false; 10928 10929 // We can't delay parsing the body of a function template with a deduced 10930 // return type (yet). 10931 if (D.getDeclSpec().containsPlaceholderType()) { 10932 // If the placeholder introduces a non-deduced trailing return type, 10933 // we can still delay parsing it. 10934 if (D.getNumTypeObjects()) { 10935 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 10936 if (Outer.Kind == DeclaratorChunk::Function && 10937 Outer.Fun.hasTrailingReturnType()) { 10938 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 10939 return Ty.isNull() || !Ty->isUndeducedType(); 10940 } 10941 } 10942 return false; 10943 } 10944 10945 return true; 10946 } 10947 10948 bool Sema::canSkipFunctionBody(Decl *D) { 10949 // We cannot skip the body of a function (or function template) which is 10950 // constexpr, since we may need to evaluate its body in order to parse the 10951 // rest of the file. 10952 // We cannot skip the body of a function with an undeduced return type, 10953 // because any callers of that function need to know the type. 10954 if (const FunctionDecl *FD = D->getAsFunction()) 10955 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 10956 return false; 10957 return Consumer.shouldSkipFunctionBody(D); 10958 } 10959 10960 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 10961 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 10962 FD->setHasSkippedBody(); 10963 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10964 MD->setHasSkippedBody(); 10965 return ActOnFinishFunctionBody(Decl, nullptr); 10966 } 10967 10968 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10969 return ActOnFinishFunctionBody(D, BodyArg, false); 10970 } 10971 10972 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10973 bool IsInstantiation) { 10974 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10975 10976 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10977 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10978 10979 if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty()) 10980 CheckCompletedCoroutineBody(FD, Body); 10981 10982 if (FD) { 10983 FD->setBody(Body); 10984 10985 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body && 10986 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10987 // If the function has a deduced result type but contains no 'return' 10988 // statements, the result type as written must be exactly 'auto', and 10989 // the deduced result type is 'void'. 10990 if (!FD->getReturnType()->getAs<AutoType>()) { 10991 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10992 << FD->getReturnType(); 10993 FD->setInvalidDecl(); 10994 } else { 10995 // Substitute 'void' for the 'auto' in the type. 10996 TypeLoc ResultType = getReturnTypeLoc(FD); 10997 Context.adjustDeducedFunctionResultType( 10998 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10999 } 11000 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) { 11001 auto *LSI = getCurLambda(); 11002 if (LSI->HasImplicitReturnType) { 11003 deduceClosureReturnType(*LSI); 11004 11005 // C++11 [expr.prim.lambda]p4: 11006 // [...] if there are no return statements in the compound-statement 11007 // [the deduced type is] the type void 11008 QualType RetType = 11009 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType; 11010 11011 // Update the return type to the deduced type. 11012 const FunctionProtoType *Proto = 11013 FD->getType()->getAs<FunctionProtoType>(); 11014 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(), 11015 Proto->getExtProtoInfo())); 11016 } 11017 } 11018 11019 // The only way to be included in UndefinedButUsed is if there is an 11020 // ODR use before the definition. Avoid the expensive map lookup if this 11021 // is the first declaration. 11022 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 11023 if (!FD->isExternallyVisible()) 11024 UndefinedButUsed.erase(FD); 11025 else if (FD->isInlined() && 11026 !LangOpts.GNUInline && 11027 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 11028 UndefinedButUsed.erase(FD); 11029 } 11030 11031 // If the function implicitly returns zero (like 'main') or is naked, 11032 // don't complain about missing return statements. 11033 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 11034 WP.disableCheckFallThrough(); 11035 11036 // MSVC permits the use of pure specifier (=0) on function definition, 11037 // defined at class scope, warn about this non-standard construct. 11038 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 11039 Diag(FD->getLocation(), diag::ext_pure_function_definition); 11040 11041 if (!FD->isInvalidDecl()) { 11042 // Don't diagnose unused parameters of defaulted or deleted functions. 11043 if (!FD->isDeleted() && !FD->isDefaulted()) 11044 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 11045 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 11046 FD->getReturnType(), FD); 11047 11048 // If this is a structor, we need a vtable. 11049 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 11050 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 11051 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 11052 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 11053 11054 // Try to apply the named return value optimization. We have to check 11055 // if we can do this here because lambdas keep return statements around 11056 // to deduce an implicit return type. 11057 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 11058 !FD->isDependentContext()) 11059 computeNRVO(Body, getCurFunction()); 11060 } 11061 11062 // GNU warning -Wmissing-prototypes: 11063 // Warn if a global function is defined without a previous 11064 // prototype declaration. This warning is issued even if the 11065 // definition itself provides a prototype. The aim is to detect 11066 // global functions that fail to be declared in header files. 11067 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 11068 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 11069 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 11070 11071 if (PossibleZeroParamPrototype) { 11072 // We found a declaration that is not a prototype, 11073 // but that could be a zero-parameter prototype 11074 if (TypeSourceInfo *TI = 11075 PossibleZeroParamPrototype->getTypeSourceInfo()) { 11076 TypeLoc TL = TI->getTypeLoc(); 11077 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 11078 Diag(PossibleZeroParamPrototype->getLocation(), 11079 diag::note_declaration_not_a_prototype) 11080 << PossibleZeroParamPrototype 11081 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 11082 } 11083 } 11084 } 11085 11086 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 11087 const CXXMethodDecl *KeyFunction; 11088 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 11089 MD->isVirtual() && 11090 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 11091 MD == KeyFunction->getCanonicalDecl()) { 11092 // Update the key-function state if necessary for this ABI. 11093 if (FD->isInlined() && 11094 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 11095 Context.setNonKeyFunction(MD); 11096 11097 // If the newly-chosen key function is already defined, then we 11098 // need to mark the vtable as used retroactively. 11099 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 11100 const FunctionDecl *Definition; 11101 if (KeyFunction && KeyFunction->isDefined(Definition)) 11102 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 11103 } else { 11104 // We just defined they key function; mark the vtable as used. 11105 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 11106 } 11107 } 11108 } 11109 11110 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 11111 "Function parsing confused"); 11112 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 11113 assert(MD == getCurMethodDecl() && "Method parsing confused"); 11114 MD->setBody(Body); 11115 if (!MD->isInvalidDecl()) { 11116 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 11117 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 11118 MD->getReturnType(), MD); 11119 11120 if (Body) 11121 computeNRVO(Body, getCurFunction()); 11122 } 11123 if (getCurFunction()->ObjCShouldCallSuper) { 11124 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 11125 << MD->getSelector().getAsString(); 11126 getCurFunction()->ObjCShouldCallSuper = false; 11127 } 11128 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 11129 const ObjCMethodDecl *InitMethod = nullptr; 11130 bool isDesignated = 11131 MD->isDesignatedInitializerForTheInterface(&InitMethod); 11132 assert(isDesignated && InitMethod); 11133 (void)isDesignated; 11134 11135 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 11136 auto IFace = MD->getClassInterface(); 11137 if (!IFace) 11138 return false; 11139 auto SuperD = IFace->getSuperClass(); 11140 if (!SuperD) 11141 return false; 11142 return SuperD->getIdentifier() == 11143 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 11144 }; 11145 // Don't issue this warning for unavailable inits or direct subclasses 11146 // of NSObject. 11147 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 11148 Diag(MD->getLocation(), 11149 diag::warn_objc_designated_init_missing_super_call); 11150 Diag(InitMethod->getLocation(), 11151 diag::note_objc_designated_init_marked_here); 11152 } 11153 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 11154 } 11155 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 11156 // Don't issue this warning for unavaialable inits. 11157 if (!MD->isUnavailable()) 11158 Diag(MD->getLocation(), 11159 diag::warn_objc_secondary_init_missing_init_call); 11160 getCurFunction()->ObjCWarnForNoInitDelegation = false; 11161 } 11162 } else { 11163 return nullptr; 11164 } 11165 11166 assert(!getCurFunction()->ObjCShouldCallSuper && 11167 "This should only be set for ObjC methods, which should have been " 11168 "handled in the block above."); 11169 11170 // Verify and clean out per-function state. 11171 if (Body && (!FD || !FD->isDefaulted())) { 11172 // C++ constructors that have function-try-blocks can't have return 11173 // statements in the handlers of that block. (C++ [except.handle]p14) 11174 // Verify this. 11175 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 11176 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 11177 11178 // Verify that gotos and switch cases don't jump into scopes illegally. 11179 if (getCurFunction()->NeedsScopeChecking() && 11180 !PP.isCodeCompletionEnabled()) 11181 DiagnoseInvalidJumps(Body); 11182 11183 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 11184 if (!Destructor->getParent()->isDependentType()) 11185 CheckDestructor(Destructor); 11186 11187 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 11188 Destructor->getParent()); 11189 } 11190 11191 // If any errors have occurred, clear out any temporaries that may have 11192 // been leftover. This ensures that these temporaries won't be picked up for 11193 // deletion in some later function. 11194 if (getDiagnostics().hasErrorOccurred() || 11195 getDiagnostics().getSuppressAllDiagnostics()) { 11196 DiscardCleanupsInEvaluationContext(); 11197 } 11198 if (!getDiagnostics().hasUncompilableErrorOccurred() && 11199 !isa<FunctionTemplateDecl>(dcl)) { 11200 // Since the body is valid, issue any analysis-based warnings that are 11201 // enabled. 11202 ActivePolicy = &WP; 11203 } 11204 11205 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 11206 (!CheckConstexprFunctionDecl(FD) || 11207 !CheckConstexprFunctionBody(FD, Body))) 11208 FD->setInvalidDecl(); 11209 11210 if (FD && FD->hasAttr<NakedAttr>()) { 11211 for (const Stmt *S : Body->children()) { 11212 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 11213 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 11214 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 11215 FD->setInvalidDecl(); 11216 break; 11217 } 11218 } 11219 } 11220 11221 assert(ExprCleanupObjects.size() == 11222 ExprEvalContexts.back().NumCleanupObjects && 11223 "Leftover temporaries in function"); 11224 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 11225 assert(MaybeODRUseExprs.empty() && 11226 "Leftover expressions for odr-use checking"); 11227 } 11228 11229 if (!IsInstantiation) 11230 PopDeclContext(); 11231 11232 PopFunctionScopeInfo(ActivePolicy, dcl); 11233 // If any errors have occurred, clear out any temporaries that may have 11234 // been leftover. This ensures that these temporaries won't be picked up for 11235 // deletion in some later function. 11236 if (getDiagnostics().hasErrorOccurred()) { 11237 DiscardCleanupsInEvaluationContext(); 11238 } 11239 11240 return dcl; 11241 } 11242 11243 11244 /// When we finish delayed parsing of an attribute, we must attach it to the 11245 /// relevant Decl. 11246 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 11247 ParsedAttributes &Attrs) { 11248 // Always attach attributes to the underlying decl. 11249 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 11250 D = TD->getTemplatedDecl(); 11251 ProcessDeclAttributeList(S, D, Attrs.getList()); 11252 11253 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 11254 if (Method->isStatic()) 11255 checkThisInStaticMemberFunctionAttributes(Method); 11256 } 11257 11258 11259 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 11260 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 11261 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 11262 IdentifierInfo &II, Scope *S) { 11263 // Before we produce a declaration for an implicitly defined 11264 // function, see whether there was a locally-scoped declaration of 11265 // this name as a function or variable. If so, use that 11266 // (non-visible) declaration, and complain about it. 11267 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 11268 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 11269 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 11270 return ExternCPrev; 11271 } 11272 11273 // Extension in C99. Legal in C90, but warn about it. 11274 unsigned diag_id; 11275 if (II.getName().startswith("__builtin_")) 11276 diag_id = diag::warn_builtin_unknown; 11277 else if (getLangOpts().C99) 11278 diag_id = diag::ext_implicit_function_decl; 11279 else 11280 diag_id = diag::warn_implicit_function_decl; 11281 Diag(Loc, diag_id) << &II; 11282 11283 // Because typo correction is expensive, only do it if the implicit 11284 // function declaration is going to be treated as an error. 11285 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 11286 TypoCorrection Corrected; 11287 if (S && 11288 (Corrected = CorrectTypo( 11289 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 11290 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 11291 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 11292 /*ErrorRecovery*/false); 11293 } 11294 11295 // Set a Declarator for the implicit definition: int foo(); 11296 const char *Dummy; 11297 AttributeFactory attrFactory; 11298 DeclSpec DS(attrFactory); 11299 unsigned DiagID; 11300 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 11301 Context.getPrintingPolicy()); 11302 (void)Error; // Silence warning. 11303 assert(!Error && "Error setting up implicit decl!"); 11304 SourceLocation NoLoc; 11305 Declarator D(DS, Declarator::BlockContext); 11306 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 11307 /*IsAmbiguous=*/false, 11308 /*LParenLoc=*/NoLoc, 11309 /*Params=*/nullptr, 11310 /*NumParams=*/0, 11311 /*EllipsisLoc=*/NoLoc, 11312 /*RParenLoc=*/NoLoc, 11313 /*TypeQuals=*/0, 11314 /*RefQualifierIsLvalueRef=*/true, 11315 /*RefQualifierLoc=*/NoLoc, 11316 /*ConstQualifierLoc=*/NoLoc, 11317 /*VolatileQualifierLoc=*/NoLoc, 11318 /*RestrictQualifierLoc=*/NoLoc, 11319 /*MutableLoc=*/NoLoc, 11320 EST_None, 11321 /*ESpecRange=*/SourceRange(), 11322 /*Exceptions=*/nullptr, 11323 /*ExceptionRanges=*/nullptr, 11324 /*NumExceptions=*/0, 11325 /*NoexceptExpr=*/nullptr, 11326 /*ExceptionSpecTokens=*/nullptr, 11327 Loc, Loc, D), 11328 DS.getAttributes(), 11329 SourceLocation()); 11330 D.SetIdentifier(&II, Loc); 11331 11332 // Insert this function into translation-unit scope. 11333 11334 DeclContext *PrevDC = CurContext; 11335 CurContext = Context.getTranslationUnitDecl(); 11336 11337 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 11338 FD->setImplicit(); 11339 11340 CurContext = PrevDC; 11341 11342 AddKnownFunctionAttributes(FD); 11343 11344 return FD; 11345 } 11346 11347 /// \brief Adds any function attributes that we know a priori based on 11348 /// the declaration of this function. 11349 /// 11350 /// These attributes can apply both to implicitly-declared builtins 11351 /// (like __builtin___printf_chk) or to library-declared functions 11352 /// like NSLog or printf. 11353 /// 11354 /// We need to check for duplicate attributes both here and where user-written 11355 /// attributes are applied to declarations. 11356 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 11357 if (FD->isInvalidDecl()) 11358 return; 11359 11360 // If this is a built-in function, map its builtin attributes to 11361 // actual attributes. 11362 if (unsigned BuiltinID = FD->getBuiltinID()) { 11363 // Handle printf-formatting attributes. 11364 unsigned FormatIdx; 11365 bool HasVAListArg; 11366 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 11367 if (!FD->hasAttr<FormatAttr>()) { 11368 const char *fmt = "printf"; 11369 unsigned int NumParams = FD->getNumParams(); 11370 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 11371 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 11372 fmt = "NSString"; 11373 FD->addAttr(FormatAttr::CreateImplicit(Context, 11374 &Context.Idents.get(fmt), 11375 FormatIdx+1, 11376 HasVAListArg ? 0 : FormatIdx+2, 11377 FD->getLocation())); 11378 } 11379 } 11380 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 11381 HasVAListArg)) { 11382 if (!FD->hasAttr<FormatAttr>()) 11383 FD->addAttr(FormatAttr::CreateImplicit(Context, 11384 &Context.Idents.get("scanf"), 11385 FormatIdx+1, 11386 HasVAListArg ? 0 : FormatIdx+2, 11387 FD->getLocation())); 11388 } 11389 11390 // Mark const if we don't care about errno and that is the only 11391 // thing preventing the function from being const. This allows 11392 // IRgen to use LLVM intrinsics for such functions. 11393 if (!getLangOpts().MathErrno && 11394 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 11395 if (!FD->hasAttr<ConstAttr>()) 11396 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11397 } 11398 11399 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 11400 !FD->hasAttr<ReturnsTwiceAttr>()) 11401 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 11402 FD->getLocation())); 11403 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 11404 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 11405 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 11406 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 11407 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads && 11408 Context.BuiltinInfo.isTSBuiltin(BuiltinID) && 11409 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) { 11410 // Assign appropriate attribute depending on CUDA compilation 11411 // mode and the target builtin belongs to. E.g. during host 11412 // compilation, aux builtins are __device__, the rest are __host__. 11413 if (getLangOpts().CUDAIsDevice != 11414 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 11415 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation())); 11416 else 11417 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation())); 11418 } 11419 } 11420 11421 IdentifierInfo *Name = FD->getIdentifier(); 11422 if (!Name) 11423 return; 11424 if ((!getLangOpts().CPlusPlus && 11425 FD->getDeclContext()->isTranslationUnit()) || 11426 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 11427 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 11428 LinkageSpecDecl::lang_c)) { 11429 // Okay: this could be a libc/libm/Objective-C function we know 11430 // about. 11431 } else 11432 return; 11433 11434 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 11435 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 11436 // target-specific builtins, perhaps? 11437 if (!FD->hasAttr<FormatAttr>()) 11438 FD->addAttr(FormatAttr::CreateImplicit(Context, 11439 &Context.Idents.get("printf"), 2, 11440 Name->isStr("vasprintf") ? 0 : 3, 11441 FD->getLocation())); 11442 } 11443 11444 if (Name->isStr("__CFStringMakeConstantString")) { 11445 // We already have a __builtin___CFStringMakeConstantString, 11446 // but builds that use -fno-constant-cfstrings don't go through that. 11447 if (!FD->hasAttr<FormatArgAttr>()) 11448 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 11449 FD->getLocation())); 11450 } 11451 } 11452 11453 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 11454 TypeSourceInfo *TInfo) { 11455 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 11456 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 11457 11458 if (!TInfo) { 11459 assert(D.isInvalidType() && "no declarator info for valid type"); 11460 TInfo = Context.getTrivialTypeSourceInfo(T); 11461 } 11462 11463 // Scope manipulation handled by caller. 11464 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 11465 D.getLocStart(), 11466 D.getIdentifierLoc(), 11467 D.getIdentifier(), 11468 TInfo); 11469 11470 // Bail out immediately if we have an invalid declaration. 11471 if (D.isInvalidType()) { 11472 NewTD->setInvalidDecl(); 11473 return NewTD; 11474 } 11475 11476 if (D.getDeclSpec().isModulePrivateSpecified()) { 11477 if (CurContext->isFunctionOrMethod()) 11478 Diag(NewTD->getLocation(), diag::err_module_private_local) 11479 << 2 << NewTD->getDeclName() 11480 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 11481 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 11482 else 11483 NewTD->setModulePrivate(); 11484 } 11485 11486 // C++ [dcl.typedef]p8: 11487 // If the typedef declaration defines an unnamed class (or 11488 // enum), the first typedef-name declared by the declaration 11489 // to be that class type (or enum type) is used to denote the 11490 // class type (or enum type) for linkage purposes only. 11491 // We need to check whether the type was declared in the declaration. 11492 switch (D.getDeclSpec().getTypeSpecType()) { 11493 case TST_enum: 11494 case TST_struct: 11495 case TST_interface: 11496 case TST_union: 11497 case TST_class: { 11498 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 11499 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 11500 break; 11501 } 11502 11503 default: 11504 break; 11505 } 11506 11507 return NewTD; 11508 } 11509 11510 11511 /// \brief Check that this is a valid underlying type for an enum declaration. 11512 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 11513 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 11514 QualType T = TI->getType(); 11515 11516 if (T->isDependentType()) 11517 return false; 11518 11519 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 11520 if (BT->isInteger()) 11521 return false; 11522 11523 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 11524 return true; 11525 } 11526 11527 /// Check whether this is a valid redeclaration of a previous enumeration. 11528 /// \return true if the redeclaration was invalid. 11529 bool Sema::CheckEnumRedeclaration( 11530 SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, 11531 bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) { 11532 bool IsFixed = !EnumUnderlyingTy.isNull(); 11533 11534 if (IsScoped != Prev->isScoped()) { 11535 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 11536 << Prev->isScoped(); 11537 Diag(Prev->getLocation(), diag::note_previous_declaration); 11538 return true; 11539 } 11540 11541 if (IsFixed && Prev->isFixed()) { 11542 if (!EnumUnderlyingTy->isDependentType() && 11543 !Prev->getIntegerType()->isDependentType() && 11544 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 11545 Prev->getIntegerType())) { 11546 // TODO: Highlight the underlying type of the redeclaration. 11547 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 11548 << EnumUnderlyingTy << Prev->getIntegerType(); 11549 Diag(Prev->getLocation(), diag::note_previous_declaration) 11550 << Prev->getIntegerTypeRange(); 11551 return true; 11552 } 11553 } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) { 11554 ; 11555 } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) { 11556 ; 11557 } else if (IsFixed != Prev->isFixed()) { 11558 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 11559 << Prev->isFixed(); 11560 Diag(Prev->getLocation(), diag::note_previous_declaration); 11561 return true; 11562 } 11563 11564 return false; 11565 } 11566 11567 /// \brief Get diagnostic %select index for tag kind for 11568 /// redeclaration diagnostic message. 11569 /// WARNING: Indexes apply to particular diagnostics only! 11570 /// 11571 /// \returns diagnostic %select index. 11572 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 11573 switch (Tag) { 11574 case TTK_Struct: return 0; 11575 case TTK_Interface: return 1; 11576 case TTK_Class: return 2; 11577 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 11578 } 11579 } 11580 11581 /// \brief Determine if tag kind is a class-key compatible with 11582 /// class for redeclaration (class, struct, or __interface). 11583 /// 11584 /// \returns true iff the tag kind is compatible. 11585 static bool isClassCompatTagKind(TagTypeKind Tag) 11586 { 11587 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 11588 } 11589 11590 /// \brief Determine whether a tag with a given kind is acceptable 11591 /// as a redeclaration of the given tag declaration. 11592 /// 11593 /// \returns true if the new tag kind is acceptable, false otherwise. 11594 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 11595 TagTypeKind NewTag, bool isDefinition, 11596 SourceLocation NewTagLoc, 11597 const IdentifierInfo *Name) { 11598 // C++ [dcl.type.elab]p3: 11599 // The class-key or enum keyword present in the 11600 // elaborated-type-specifier shall agree in kind with the 11601 // declaration to which the name in the elaborated-type-specifier 11602 // refers. This rule also applies to the form of 11603 // elaborated-type-specifier that declares a class-name or 11604 // friend class since it can be construed as referring to the 11605 // definition of the class. Thus, in any 11606 // elaborated-type-specifier, the enum keyword shall be used to 11607 // refer to an enumeration (7.2), the union class-key shall be 11608 // used to refer to a union (clause 9), and either the class or 11609 // struct class-key shall be used to refer to a class (clause 9) 11610 // declared using the class or struct class-key. 11611 TagTypeKind OldTag = Previous->getTagKind(); 11612 if (!isDefinition || !isClassCompatTagKind(NewTag)) 11613 if (OldTag == NewTag) 11614 return true; 11615 11616 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 11617 // Warn about the struct/class tag mismatch. 11618 bool isTemplate = false; 11619 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 11620 isTemplate = Record->getDescribedClassTemplate(); 11621 11622 if (!ActiveTemplateInstantiations.empty()) { 11623 // In a template instantiation, do not offer fix-its for tag mismatches 11624 // since they usually mess up the template instead of fixing the problem. 11625 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11626 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 11627 << getRedeclDiagFromTagKind(OldTag); 11628 return true; 11629 } 11630 11631 if (isDefinition) { 11632 // On definitions, check previous tags and issue a fix-it for each 11633 // one that doesn't match the current tag. 11634 if (Previous->getDefinition()) { 11635 // Don't suggest fix-its for redefinitions. 11636 return true; 11637 } 11638 11639 bool previousMismatch = false; 11640 for (auto I : Previous->redecls()) { 11641 if (I->getTagKind() != NewTag) { 11642 if (!previousMismatch) { 11643 previousMismatch = true; 11644 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11645 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 11646 << getRedeclDiagFromTagKind(I->getTagKind()); 11647 } 11648 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11649 << getRedeclDiagFromTagKind(NewTag) 11650 << FixItHint::CreateReplacement(I->getInnerLocStart(), 11651 TypeWithKeyword::getTagTypeKindName(NewTag)); 11652 } 11653 } 11654 return true; 11655 } 11656 11657 // Check for a previous definition. If current tag and definition 11658 // are same type, do nothing. If no definition, but disagree with 11659 // with previous tag type, give a warning, but no fix-it. 11660 const TagDecl *Redecl = Previous->getDefinition() ? 11661 Previous->getDefinition() : Previous; 11662 if (Redecl->getTagKind() == NewTag) { 11663 return true; 11664 } 11665 11666 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11667 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name 11668 << getRedeclDiagFromTagKind(OldTag); 11669 Diag(Redecl->getLocation(), diag::note_previous_use); 11670 11671 // If there is a previous definition, suggest a fix-it. 11672 if (Previous->getDefinition()) { 11673 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11674 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11675 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11676 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11677 } 11678 11679 return true; 11680 } 11681 return false; 11682 } 11683 11684 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11685 /// from an outer enclosing namespace or file scope inside a friend declaration. 11686 /// This should provide the commented out code in the following snippet: 11687 /// namespace N { 11688 /// struct X; 11689 /// namespace M { 11690 /// struct Y { friend struct /*N::*/ X; }; 11691 /// } 11692 /// } 11693 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11694 SourceLocation NameLoc) { 11695 // While the decl is in a namespace, do repeated lookup of that name and see 11696 // if we get the same namespace back. If we do not, continue until 11697 // translation unit scope, at which point we have a fully qualified NNS. 11698 SmallVector<IdentifierInfo *, 4> Namespaces; 11699 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11700 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11701 // This tag should be declared in a namespace, which can only be enclosed by 11702 // other namespaces. Bail if there's an anonymous namespace in the chain. 11703 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11704 if (!Namespace || Namespace->isAnonymousNamespace()) 11705 return FixItHint(); 11706 IdentifierInfo *II = Namespace->getIdentifier(); 11707 Namespaces.push_back(II); 11708 NamedDecl *Lookup = SemaRef.LookupSingleName( 11709 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11710 if (Lookup == Namespace) 11711 break; 11712 } 11713 11714 // Once we have all the namespaces, reverse them to go outermost first, and 11715 // build an NNS. 11716 SmallString<64> Insertion; 11717 llvm::raw_svector_ostream OS(Insertion); 11718 if (DC->isTranslationUnit()) 11719 OS << "::"; 11720 std::reverse(Namespaces.begin(), Namespaces.end()); 11721 for (auto *II : Namespaces) 11722 OS << II->getName() << "::"; 11723 return FixItHint::CreateInsertion(NameLoc, Insertion); 11724 } 11725 11726 /// \brief Determine whether a tag originally declared in context \p OldDC can 11727 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup 11728 /// found a declaration in \p OldDC as a previous decl, perhaps through a 11729 /// using-declaration). 11730 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, 11731 DeclContext *NewDC) { 11732 OldDC = OldDC->getRedeclContext(); 11733 NewDC = NewDC->getRedeclContext(); 11734 11735 if (OldDC->Equals(NewDC)) 11736 return true; 11737 11738 // In MSVC mode, we allow a redeclaration if the contexts are related (either 11739 // encloses the other). 11740 if (S.getLangOpts().MSVCCompat && 11741 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC))) 11742 return true; 11743 11744 return false; 11745 } 11746 11747 /// \brief This is invoked when we see 'struct foo' or 'struct {'. In the 11748 /// former case, Name will be non-null. In the later case, Name will be null. 11749 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11750 /// reference/declaration/definition of a tag. 11751 /// 11752 /// \param IsTypeSpecifier \c true if this is a type-specifier (or 11753 /// trailing-type-specifier) other than one in an alias-declaration. 11754 /// 11755 /// \param SkipBody If non-null, will be set to indicate if the caller should 11756 /// skip the definition of this tag and treat it as if it were a declaration. 11757 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11758 SourceLocation KWLoc, CXXScopeSpec &SS, 11759 IdentifierInfo *Name, SourceLocation NameLoc, 11760 AttributeList *Attr, AccessSpecifier AS, 11761 SourceLocation ModulePrivateLoc, 11762 MultiTemplateParamsArg TemplateParameterLists, 11763 bool &OwnedDecl, bool &IsDependent, 11764 SourceLocation ScopedEnumKWLoc, 11765 bool ScopedEnumUsesClassTag, 11766 TypeResult UnderlyingType, 11767 bool IsTypeSpecifier, SkipBodyInfo *SkipBody) { 11768 // If this is not a definition, it must have a name. 11769 IdentifierInfo *OrigName = Name; 11770 assert((Name != nullptr || TUK == TUK_Definition) && 11771 "Nameless record must be a definition!"); 11772 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11773 11774 OwnedDecl = false; 11775 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11776 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11777 11778 // FIXME: Check explicit specializations more carefully. 11779 bool isExplicitSpecialization = false; 11780 bool Invalid = false; 11781 11782 // We only need to do this matching if we have template parameters 11783 // or a scope specifier, which also conveniently avoids this work 11784 // for non-C++ cases. 11785 if (TemplateParameterLists.size() > 0 || 11786 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11787 if (TemplateParameterList *TemplateParams = 11788 MatchTemplateParametersToScopeSpecifier( 11789 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11790 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11791 if (Kind == TTK_Enum) { 11792 Diag(KWLoc, diag::err_enum_template); 11793 return nullptr; 11794 } 11795 11796 if (TemplateParams->size() > 0) { 11797 // This is a declaration or definition of a class template (which may 11798 // be a member of another template). 11799 11800 if (Invalid) 11801 return nullptr; 11802 11803 OwnedDecl = false; 11804 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11805 SS, Name, NameLoc, Attr, 11806 TemplateParams, AS, 11807 ModulePrivateLoc, 11808 /*FriendLoc*/SourceLocation(), 11809 TemplateParameterLists.size()-1, 11810 TemplateParameterLists.data(), 11811 SkipBody); 11812 return Result.get(); 11813 } else { 11814 // The "template<>" header is extraneous. 11815 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11816 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11817 isExplicitSpecialization = true; 11818 } 11819 } 11820 } 11821 11822 // Figure out the underlying type if this a enum declaration. We need to do 11823 // this early, because it's needed to detect if this is an incompatible 11824 // redeclaration. 11825 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 11826 bool EnumUnderlyingIsImplicit = false; 11827 11828 if (Kind == TTK_Enum) { 11829 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 11830 // No underlying type explicitly specified, or we failed to parse the 11831 // type, default to int. 11832 EnumUnderlying = Context.IntTy.getTypePtr(); 11833 else if (UnderlyingType.get()) { 11834 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 11835 // integral type; any cv-qualification is ignored. 11836 TypeSourceInfo *TI = nullptr; 11837 GetTypeFromParser(UnderlyingType.get(), &TI); 11838 EnumUnderlying = TI; 11839 11840 if (CheckEnumUnderlyingType(TI)) 11841 // Recover by falling back to int. 11842 EnumUnderlying = Context.IntTy.getTypePtr(); 11843 11844 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 11845 UPPC_FixedUnderlyingType)) 11846 EnumUnderlying = Context.IntTy.getTypePtr(); 11847 11848 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 11849 if (getLangOpts().MSVCCompat || TUK == TUK_Definition) { 11850 // Microsoft enums are always of int type. 11851 EnumUnderlying = Context.IntTy.getTypePtr(); 11852 EnumUnderlyingIsImplicit = true; 11853 } 11854 } 11855 } 11856 11857 DeclContext *SearchDC = CurContext; 11858 DeclContext *DC = CurContext; 11859 bool isStdBadAlloc = false; 11860 11861 RedeclarationKind Redecl = ForRedeclaration; 11862 if (TUK == TUK_Friend || TUK == TUK_Reference) 11863 Redecl = NotForRedeclaration; 11864 11865 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 11866 if (Name && SS.isNotEmpty()) { 11867 // We have a nested-name tag ('struct foo::bar'). 11868 11869 // Check for invalid 'foo::'. 11870 if (SS.isInvalid()) { 11871 Name = nullptr; 11872 goto CreateNewDecl; 11873 } 11874 11875 // If this is a friend or a reference to a class in a dependent 11876 // context, don't try to make a decl for it. 11877 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11878 DC = computeDeclContext(SS, false); 11879 if (!DC) { 11880 IsDependent = true; 11881 return nullptr; 11882 } 11883 } else { 11884 DC = computeDeclContext(SS, true); 11885 if (!DC) { 11886 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 11887 << SS.getRange(); 11888 return nullptr; 11889 } 11890 } 11891 11892 if (RequireCompleteDeclContext(SS, DC)) 11893 return nullptr; 11894 11895 SearchDC = DC; 11896 // Look-up name inside 'foo::'. 11897 LookupQualifiedName(Previous, DC); 11898 11899 if (Previous.isAmbiguous()) 11900 return nullptr; 11901 11902 if (Previous.empty()) { 11903 // Name lookup did not find anything. However, if the 11904 // nested-name-specifier refers to the current instantiation, 11905 // and that current instantiation has any dependent base 11906 // classes, we might find something at instantiation time: treat 11907 // this as a dependent elaborated-type-specifier. 11908 // But this only makes any sense for reference-like lookups. 11909 if (Previous.wasNotFoundInCurrentInstantiation() && 11910 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11911 IsDependent = true; 11912 return nullptr; 11913 } 11914 11915 // A tag 'foo::bar' must already exist. 11916 Diag(NameLoc, diag::err_not_tag_in_scope) 11917 << Kind << Name << DC << SS.getRange(); 11918 Name = nullptr; 11919 Invalid = true; 11920 goto CreateNewDecl; 11921 } 11922 } else if (Name) { 11923 // C++14 [class.mem]p14: 11924 // If T is the name of a class, then each of the following shall have a 11925 // name different from T: 11926 // -- every member of class T that is itself a type 11927 if (TUK != TUK_Reference && TUK != TUK_Friend && 11928 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc))) 11929 return nullptr; 11930 11931 // If this is a named struct, check to see if there was a previous forward 11932 // declaration or definition. 11933 // FIXME: We're looking into outer scopes here, even when we 11934 // shouldn't be. Doing so can result in ambiguities that we 11935 // shouldn't be diagnosing. 11936 LookupName(Previous, S); 11937 11938 // When declaring or defining a tag, ignore ambiguities introduced 11939 // by types using'ed into this scope. 11940 if (Previous.isAmbiguous() && 11941 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 11942 LookupResult::Filter F = Previous.makeFilter(); 11943 while (F.hasNext()) { 11944 NamedDecl *ND = F.next(); 11945 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 11946 F.erase(); 11947 } 11948 F.done(); 11949 } 11950 11951 // C++11 [namespace.memdef]p3: 11952 // If the name in a friend declaration is neither qualified nor 11953 // a template-id and the declaration is a function or an 11954 // elaborated-type-specifier, the lookup to determine whether 11955 // the entity has been previously declared shall not consider 11956 // any scopes outside the innermost enclosing namespace. 11957 // 11958 // MSVC doesn't implement the above rule for types, so a friend tag 11959 // declaration may be a redeclaration of a type declared in an enclosing 11960 // scope. They do implement this rule for friend functions. 11961 // 11962 // Does it matter that this should be by scope instead of by 11963 // semantic context? 11964 if (!Previous.empty() && TUK == TUK_Friend) { 11965 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 11966 LookupResult::Filter F = Previous.makeFilter(); 11967 bool FriendSawTagOutsideEnclosingNamespace = false; 11968 while (F.hasNext()) { 11969 NamedDecl *ND = F.next(); 11970 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11971 if (DC->isFileContext() && 11972 !EnclosingNS->Encloses(ND->getDeclContext())) { 11973 if (getLangOpts().MSVCCompat) 11974 FriendSawTagOutsideEnclosingNamespace = true; 11975 else 11976 F.erase(); 11977 } 11978 } 11979 F.done(); 11980 11981 // Diagnose this MSVC extension in the easy case where lookup would have 11982 // unambiguously found something outside the enclosing namespace. 11983 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 11984 NamedDecl *ND = Previous.getFoundDecl(); 11985 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 11986 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 11987 } 11988 } 11989 11990 // Note: there used to be some attempt at recovery here. 11991 if (Previous.isAmbiguous()) 11992 return nullptr; 11993 11994 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 11995 // FIXME: This makes sure that we ignore the contexts associated 11996 // with C structs, unions, and enums when looking for a matching 11997 // tag declaration or definition. See the similar lookup tweak 11998 // in Sema::LookupName; is there a better way to deal with this? 11999 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 12000 SearchDC = SearchDC->getParent(); 12001 } 12002 } 12003 12004 if (Previous.isSingleResult() && 12005 Previous.getFoundDecl()->isTemplateParameter()) { 12006 // Maybe we will complain about the shadowed template parameter. 12007 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 12008 // Just pretend that we didn't see the previous declaration. 12009 Previous.clear(); 12010 } 12011 12012 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 12013 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 12014 // This is a declaration of or a reference to "std::bad_alloc". 12015 isStdBadAlloc = true; 12016 12017 if (Previous.empty() && StdBadAlloc) { 12018 // std::bad_alloc has been implicitly declared (but made invisible to 12019 // name lookup). Fill in this implicit declaration as the previous 12020 // declaration, so that the declarations get chained appropriately. 12021 Previous.addDecl(getStdBadAlloc()); 12022 } 12023 } 12024 12025 // If we didn't find a previous declaration, and this is a reference 12026 // (or friend reference), move to the correct scope. In C++, we 12027 // also need to do a redeclaration lookup there, just in case 12028 // there's a shadow friend decl. 12029 if (Name && Previous.empty() && 12030 (TUK == TUK_Reference || TUK == TUK_Friend)) { 12031 if (Invalid) goto CreateNewDecl; 12032 assert(SS.isEmpty()); 12033 12034 if (TUK == TUK_Reference) { 12035 // C++ [basic.scope.pdecl]p5: 12036 // -- for an elaborated-type-specifier of the form 12037 // 12038 // class-key identifier 12039 // 12040 // if the elaborated-type-specifier is used in the 12041 // decl-specifier-seq or parameter-declaration-clause of a 12042 // function defined in namespace scope, the identifier is 12043 // declared as a class-name in the namespace that contains 12044 // the declaration; otherwise, except as a friend 12045 // declaration, the identifier is declared in the smallest 12046 // non-class, non-function-prototype scope that contains the 12047 // declaration. 12048 // 12049 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 12050 // C structs and unions. 12051 // 12052 // It is an error in C++ to declare (rather than define) an enum 12053 // type, including via an elaborated type specifier. We'll 12054 // diagnose that later; for now, declare the enum in the same 12055 // scope as we would have picked for any other tag type. 12056 // 12057 // GNU C also supports this behavior as part of its incomplete 12058 // enum types extension, while GNU C++ does not. 12059 // 12060 // Find the context where we'll be declaring the tag. 12061 // FIXME: We would like to maintain the current DeclContext as the 12062 // lexical context, 12063 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 12064 SearchDC = SearchDC->getParent(); 12065 12066 // Find the scope where we'll be declaring the tag. 12067 while (S->isClassScope() || 12068 (getLangOpts().CPlusPlus && 12069 S->isFunctionPrototypeScope()) || 12070 ((S->getFlags() & Scope::DeclScope) == 0) || 12071 (S->getEntity() && S->getEntity()->isTransparentContext())) 12072 S = S->getParent(); 12073 } else { 12074 assert(TUK == TUK_Friend); 12075 // C++ [namespace.memdef]p3: 12076 // If a friend declaration in a non-local class first declares a 12077 // class or function, the friend class or function is a member of 12078 // the innermost enclosing namespace. 12079 SearchDC = SearchDC->getEnclosingNamespaceContext(); 12080 } 12081 12082 // In C++, we need to do a redeclaration lookup to properly 12083 // diagnose some problems. 12084 if (getLangOpts().CPlusPlus) { 12085 Previous.setRedeclarationKind(ForRedeclaration); 12086 LookupQualifiedName(Previous, SearchDC); 12087 } 12088 } 12089 12090 // If we have a known previous declaration to use, then use it. 12091 if (Previous.empty() && SkipBody && SkipBody->Previous) 12092 Previous.addDecl(SkipBody->Previous); 12093 12094 if (!Previous.empty()) { 12095 NamedDecl *PrevDecl = Previous.getFoundDecl(); 12096 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl(); 12097 12098 // It's okay to have a tag decl in the same scope as a typedef 12099 // which hides a tag decl in the same scope. Finding this 12100 // insanity with a redeclaration lookup can only actually happen 12101 // in C++. 12102 // 12103 // This is also okay for elaborated-type-specifiers, which is 12104 // technically forbidden by the current standard but which is 12105 // okay according to the likely resolution of an open issue; 12106 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 12107 if (getLangOpts().CPlusPlus) { 12108 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12109 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 12110 TagDecl *Tag = TT->getDecl(); 12111 if (Tag->getDeclName() == Name && 12112 Tag->getDeclContext()->getRedeclContext() 12113 ->Equals(TD->getDeclContext()->getRedeclContext())) { 12114 PrevDecl = Tag; 12115 Previous.clear(); 12116 Previous.addDecl(Tag); 12117 Previous.resolveKind(); 12118 } 12119 } 12120 } 12121 } 12122 12123 // If this is a redeclaration of a using shadow declaration, it must 12124 // declare a tag in the same context. In MSVC mode, we allow a 12125 // redefinition if either context is within the other. 12126 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) { 12127 auto *OldTag = dyn_cast<TagDecl>(PrevDecl); 12128 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend && 12129 isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) && 12130 !(OldTag && isAcceptableTagRedeclContext( 12131 *this, OldTag->getDeclContext(), SearchDC))) { 12132 Diag(KWLoc, diag::err_using_decl_conflict_reverse); 12133 Diag(Shadow->getTargetDecl()->getLocation(), 12134 diag::note_using_decl_target); 12135 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) 12136 << 0; 12137 // Recover by ignoring the old declaration. 12138 Previous.clear(); 12139 goto CreateNewDecl; 12140 } 12141 } 12142 12143 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 12144 // If this is a use of a previous tag, or if the tag is already declared 12145 // in the same scope (so that the definition/declaration completes or 12146 // rementions the tag), reuse the decl. 12147 if (TUK == TUK_Reference || TUK == TUK_Friend || 12148 isDeclInScope(DirectPrevDecl, SearchDC, S, 12149 SS.isNotEmpty() || isExplicitSpecialization)) { 12150 // Make sure that this wasn't declared as an enum and now used as a 12151 // struct or something similar. 12152 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 12153 TUK == TUK_Definition, KWLoc, 12154 Name)) { 12155 bool SafeToContinue 12156 = (PrevTagDecl->getTagKind() != TTK_Enum && 12157 Kind != TTK_Enum); 12158 if (SafeToContinue) 12159 Diag(KWLoc, diag::err_use_with_wrong_tag) 12160 << Name 12161 << FixItHint::CreateReplacement(SourceRange(KWLoc), 12162 PrevTagDecl->getKindName()); 12163 else 12164 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 12165 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 12166 12167 if (SafeToContinue) 12168 Kind = PrevTagDecl->getTagKind(); 12169 else { 12170 // Recover by making this an anonymous redefinition. 12171 Name = nullptr; 12172 Previous.clear(); 12173 Invalid = true; 12174 } 12175 } 12176 12177 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 12178 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 12179 12180 // If this is an elaborated-type-specifier for a scoped enumeration, 12181 // the 'class' keyword is not necessary and not permitted. 12182 if (TUK == TUK_Reference || TUK == TUK_Friend) { 12183 if (ScopedEnum) 12184 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 12185 << PrevEnum->isScoped() 12186 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 12187 return PrevTagDecl; 12188 } 12189 12190 QualType EnumUnderlyingTy; 12191 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12192 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 12193 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 12194 EnumUnderlyingTy = QualType(T, 0); 12195 12196 // All conflicts with previous declarations are recovered by 12197 // returning the previous declaration, unless this is a definition, 12198 // in which case we want the caller to bail out. 12199 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 12200 ScopedEnum, EnumUnderlyingTy, 12201 EnumUnderlyingIsImplicit, PrevEnum)) 12202 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 12203 } 12204 12205 // C++11 [class.mem]p1: 12206 // A member shall not be declared twice in the member-specification, 12207 // except that a nested class or member class template can be declared 12208 // and then later defined. 12209 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 12210 S->isDeclScope(PrevDecl)) { 12211 Diag(NameLoc, diag::ext_member_redeclared); 12212 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 12213 } 12214 12215 if (!Invalid) { 12216 // If this is a use, just return the declaration we found, unless 12217 // we have attributes. 12218 12219 // FIXME: In the future, return a variant or some other clue 12220 // for the consumer of this Decl to know it doesn't own it. 12221 // For our current ASTs this shouldn't be a problem, but will 12222 // need to be changed with DeclGroups. 12223 if (!Attr && 12224 ((TUK == TUK_Reference && 12225 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 12226 || TUK == TUK_Friend)) 12227 return PrevTagDecl; 12228 12229 // Diagnose attempts to redefine a tag. 12230 if (TUK == TUK_Definition) { 12231 if (NamedDecl *Def = PrevTagDecl->getDefinition()) { 12232 // If we're defining a specialization and the previous definition 12233 // is from an implicit instantiation, don't emit an error 12234 // here; we'll catch this in the general case below. 12235 bool IsExplicitSpecializationAfterInstantiation = false; 12236 if (isExplicitSpecialization) { 12237 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 12238 IsExplicitSpecializationAfterInstantiation = 12239 RD->getTemplateSpecializationKind() != 12240 TSK_ExplicitSpecialization; 12241 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 12242 IsExplicitSpecializationAfterInstantiation = 12243 ED->getTemplateSpecializationKind() != 12244 TSK_ExplicitSpecialization; 12245 } 12246 12247 NamedDecl *Hidden = nullptr; 12248 if (SkipBody && getLangOpts().CPlusPlus && 12249 !hasVisibleDefinition(Def, &Hidden)) { 12250 // There is a definition of this tag, but it is not visible. We 12251 // explicitly make use of C++'s one definition rule here, and 12252 // assume that this definition is identical to the hidden one 12253 // we already have. Make the existing definition visible and 12254 // use it in place of this one. 12255 SkipBody->ShouldSkip = true; 12256 makeMergedDefinitionVisible(Hidden, KWLoc); 12257 return Def; 12258 } else if (!IsExplicitSpecializationAfterInstantiation) { 12259 // A redeclaration in function prototype scope in C isn't 12260 // visible elsewhere, so merely issue a warning. 12261 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 12262 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 12263 else 12264 Diag(NameLoc, diag::err_redefinition) << Name; 12265 Diag(Def->getLocation(), diag::note_previous_definition); 12266 // If this is a redefinition, recover by making this 12267 // struct be anonymous, which will make any later 12268 // references get the previous definition. 12269 Name = nullptr; 12270 Previous.clear(); 12271 Invalid = true; 12272 } 12273 } else { 12274 // If the type is currently being defined, complain 12275 // about a nested redefinition. 12276 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 12277 if (TD->isBeingDefined()) { 12278 Diag(NameLoc, diag::err_nested_redefinition) << Name; 12279 Diag(PrevTagDecl->getLocation(), 12280 diag::note_previous_definition); 12281 Name = nullptr; 12282 Previous.clear(); 12283 Invalid = true; 12284 } 12285 } 12286 12287 // Okay, this is definition of a previously declared or referenced 12288 // tag. We're going to create a new Decl for it. 12289 } 12290 12291 // Okay, we're going to make a redeclaration. If this is some kind 12292 // of reference, make sure we build the redeclaration in the same DC 12293 // as the original, and ignore the current access specifier. 12294 if (TUK == TUK_Friend || TUK == TUK_Reference) { 12295 SearchDC = PrevTagDecl->getDeclContext(); 12296 AS = AS_none; 12297 } 12298 } 12299 // If we get here we have (another) forward declaration or we 12300 // have a definition. Just create a new decl. 12301 12302 } else { 12303 // If we get here, this is a definition of a new tag type in a nested 12304 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 12305 // new decl/type. We set PrevDecl to NULL so that the entities 12306 // have distinct types. 12307 Previous.clear(); 12308 } 12309 // If we get here, we're going to create a new Decl. If PrevDecl 12310 // is non-NULL, it's a definition of the tag declared by 12311 // PrevDecl. If it's NULL, we have a new definition. 12312 12313 12314 // Otherwise, PrevDecl is not a tag, but was found with tag 12315 // lookup. This is only actually possible in C++, where a few 12316 // things like templates still live in the tag namespace. 12317 } else { 12318 // Use a better diagnostic if an elaborated-type-specifier 12319 // found the wrong kind of type on the first 12320 // (non-redeclaration) lookup. 12321 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 12322 !Previous.isForRedeclaration()) { 12323 unsigned Kind = 0; 12324 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 12325 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 12326 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 12327 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 12328 Diag(PrevDecl->getLocation(), diag::note_declared_at); 12329 Invalid = true; 12330 12331 // Otherwise, only diagnose if the declaration is in scope. 12332 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S, 12333 SS.isNotEmpty() || isExplicitSpecialization)) { 12334 // do nothing 12335 12336 // Diagnose implicit declarations introduced by elaborated types. 12337 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 12338 unsigned Kind = 0; 12339 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 12340 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 12341 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 12342 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 12343 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 12344 Invalid = true; 12345 12346 // Otherwise it's a declaration. Call out a particularly common 12347 // case here. 12348 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 12349 unsigned Kind = 0; 12350 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 12351 Diag(NameLoc, diag::err_tag_definition_of_typedef) 12352 << Name << Kind << TND->getUnderlyingType(); 12353 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 12354 Invalid = true; 12355 12356 // Otherwise, diagnose. 12357 } else { 12358 // The tag name clashes with something else in the target scope, 12359 // issue an error and recover by making this tag be anonymous. 12360 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 12361 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 12362 Name = nullptr; 12363 Invalid = true; 12364 } 12365 12366 // The existing declaration isn't relevant to us; we're in a 12367 // new scope, so clear out the previous declaration. 12368 Previous.clear(); 12369 } 12370 } 12371 12372 CreateNewDecl: 12373 12374 TagDecl *PrevDecl = nullptr; 12375 if (Previous.isSingleResult()) 12376 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 12377 12378 // If there is an identifier, use the location of the identifier as the 12379 // location of the decl, otherwise use the location of the struct/union 12380 // keyword. 12381 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 12382 12383 // Otherwise, create a new declaration. If there is a previous 12384 // declaration of the same entity, the two will be linked via 12385 // PrevDecl. 12386 TagDecl *New; 12387 12388 bool IsForwardReference = false; 12389 if (Kind == TTK_Enum) { 12390 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 12391 // enum X { A, B, C } D; D should chain to X. 12392 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 12393 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 12394 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 12395 // If this is an undefined enum, warn. 12396 if (TUK != TUK_Definition && !Invalid) { 12397 TagDecl *Def; 12398 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 12399 cast<EnumDecl>(New)->isFixed()) { 12400 // C++0x: 7.2p2: opaque-enum-declaration. 12401 // Conflicts are diagnosed above. Do nothing. 12402 } 12403 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 12404 Diag(Loc, diag::ext_forward_ref_enum_def) 12405 << New; 12406 Diag(Def->getLocation(), diag::note_previous_definition); 12407 } else { 12408 unsigned DiagID = diag::ext_forward_ref_enum; 12409 if (getLangOpts().MSVCCompat) 12410 DiagID = diag::ext_ms_forward_ref_enum; 12411 else if (getLangOpts().CPlusPlus) 12412 DiagID = diag::err_forward_ref_enum; 12413 Diag(Loc, DiagID); 12414 12415 // If this is a forward-declared reference to an enumeration, make a 12416 // note of it; we won't actually be introducing the declaration into 12417 // the declaration context. 12418 if (TUK == TUK_Reference) 12419 IsForwardReference = true; 12420 } 12421 } 12422 12423 if (EnumUnderlying) { 12424 EnumDecl *ED = cast<EnumDecl>(New); 12425 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 12426 ED->setIntegerTypeSourceInfo(TI); 12427 else 12428 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 12429 ED->setPromotionType(ED->getIntegerType()); 12430 } 12431 12432 } else { 12433 // struct/union/class 12434 12435 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 12436 // struct X { int A; } D; D should chain to X. 12437 if (getLangOpts().CPlusPlus) { 12438 // FIXME: Look for a way to use RecordDecl for simple structs. 12439 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12440 cast_or_null<CXXRecordDecl>(PrevDecl)); 12441 12442 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 12443 StdBadAlloc = cast<CXXRecordDecl>(New); 12444 } else 12445 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 12446 cast_or_null<RecordDecl>(PrevDecl)); 12447 } 12448 12449 // C++11 [dcl.type]p3: 12450 // A type-specifier-seq shall not define a class or enumeration [...]. 12451 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 12452 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 12453 << Context.getTagDeclType(New); 12454 Invalid = true; 12455 } 12456 12457 // Maybe add qualifier info. 12458 if (SS.isNotEmpty()) { 12459 if (SS.isSet()) { 12460 // If this is either a declaration or a definition, check the 12461 // nested-name-specifier against the current context. We don't do this 12462 // for explicit specializations, because they have similar checking 12463 // (with more specific diagnostics) in the call to 12464 // CheckMemberSpecialization, below. 12465 if (!isExplicitSpecialization && 12466 (TUK == TUK_Definition || TUK == TUK_Declaration) && 12467 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 12468 Invalid = true; 12469 12470 New->setQualifierInfo(SS.getWithLocInContext(Context)); 12471 if (TemplateParameterLists.size() > 0) { 12472 New->setTemplateParameterListsInfo(Context, TemplateParameterLists); 12473 } 12474 } 12475 else 12476 Invalid = true; 12477 } 12478 12479 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 12480 // Add alignment attributes if necessary; these attributes are checked when 12481 // the ASTContext lays out the structure. 12482 // 12483 // It is important for implementing the correct semantics that this 12484 // happen here (in act on tag decl). The #pragma pack stack is 12485 // maintained as a result of parser callbacks which can occur at 12486 // many points during the parsing of a struct declaration (because 12487 // the #pragma tokens are effectively skipped over during the 12488 // parsing of the struct). 12489 if (TUK == TUK_Definition) { 12490 AddAlignmentAttributesForRecord(RD); 12491 AddMsStructLayoutForRecord(RD); 12492 } 12493 } 12494 12495 if (ModulePrivateLoc.isValid()) { 12496 if (isExplicitSpecialization) 12497 Diag(New->getLocation(), diag::err_module_private_specialization) 12498 << 2 12499 << FixItHint::CreateRemoval(ModulePrivateLoc); 12500 // __module_private__ does not apply to local classes. However, we only 12501 // diagnose this as an error when the declaration specifiers are 12502 // freestanding. Here, we just ignore the __module_private__. 12503 else if (!SearchDC->isFunctionOrMethod()) 12504 New->setModulePrivate(); 12505 } 12506 12507 // If this is a specialization of a member class (of a class template), 12508 // check the specialization. 12509 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 12510 Invalid = true; 12511 12512 // If we're declaring or defining a tag in function prototype scope in C, 12513 // note that this type can only be used within the function and add it to 12514 // the list of decls to inject into the function definition scope. 12515 if ((Name || Kind == TTK_Enum) && 12516 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 12517 if (getLangOpts().CPlusPlus) { 12518 // C++ [dcl.fct]p6: 12519 // Types shall not be defined in return or parameter types. 12520 if (TUK == TUK_Definition && !IsTypeSpecifier) { 12521 Diag(Loc, diag::err_type_defined_in_param_type) 12522 << Name; 12523 Invalid = true; 12524 } 12525 } else { 12526 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 12527 } 12528 DeclsInPrototypeScope.push_back(New); 12529 } 12530 12531 if (Invalid) 12532 New->setInvalidDecl(); 12533 12534 if (Attr) 12535 ProcessDeclAttributeList(S, New, Attr); 12536 12537 // Set the lexical context. If the tag has a C++ scope specifier, the 12538 // lexical context will be different from the semantic context. 12539 New->setLexicalDeclContext(CurContext); 12540 12541 // Mark this as a friend decl if applicable. 12542 // In Microsoft mode, a friend declaration also acts as a forward 12543 // declaration so we always pass true to setObjectOfFriendDecl to make 12544 // the tag name visible. 12545 if (TUK == TUK_Friend) 12546 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 12547 12548 // Set the access specifier. 12549 if (!Invalid && SearchDC->isRecord()) 12550 SetMemberAccessSpecifier(New, PrevDecl, AS); 12551 12552 if (TUK == TUK_Definition) 12553 New->startDefinition(); 12554 12555 // If this has an identifier, add it to the scope stack. 12556 if (TUK == TUK_Friend) { 12557 // We might be replacing an existing declaration in the lookup tables; 12558 // if so, borrow its access specifier. 12559 if (PrevDecl) 12560 New->setAccess(PrevDecl->getAccess()); 12561 12562 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 12563 DC->makeDeclVisibleInContext(New); 12564 if (Name) // can be null along some error paths 12565 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12566 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 12567 } else if (Name) { 12568 S = getNonFieldDeclScope(S); 12569 PushOnScopeChains(New, S, !IsForwardReference); 12570 if (IsForwardReference) 12571 SearchDC->makeDeclVisibleInContext(New); 12572 12573 } else { 12574 CurContext->addDecl(New); 12575 } 12576 12577 // If this is the C FILE type, notify the AST context. 12578 if (IdentifierInfo *II = New->getIdentifier()) 12579 if (!New->isInvalidDecl() && 12580 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 12581 II->isStr("FILE")) 12582 Context.setFILEDecl(New); 12583 12584 if (PrevDecl) 12585 mergeDeclAttributes(New, PrevDecl); 12586 12587 // If there's a #pragma GCC visibility in scope, set the visibility of this 12588 // record. 12589 AddPushedVisibilityAttribute(New); 12590 12591 OwnedDecl = true; 12592 // In C++, don't return an invalid declaration. We can't recover well from 12593 // the cases where we make the type anonymous. 12594 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 12595 } 12596 12597 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 12598 AdjustDeclIfTemplate(TagD); 12599 TagDecl *Tag = cast<TagDecl>(TagD); 12600 12601 // Enter the tag context. 12602 PushDeclContext(S, Tag); 12603 12604 ActOnDocumentableDecl(TagD); 12605 12606 // If there's a #pragma GCC visibility in scope, set the visibility of this 12607 // record. 12608 AddPushedVisibilityAttribute(Tag); 12609 } 12610 12611 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 12612 assert(isa<ObjCContainerDecl>(IDecl) && 12613 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 12614 DeclContext *OCD = cast<DeclContext>(IDecl); 12615 assert(getContainingDC(OCD) == CurContext && 12616 "The next DeclContext should be lexically contained in the current one."); 12617 CurContext = OCD; 12618 return IDecl; 12619 } 12620 12621 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 12622 SourceLocation FinalLoc, 12623 bool IsFinalSpelledSealed, 12624 SourceLocation LBraceLoc) { 12625 AdjustDeclIfTemplate(TagD); 12626 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 12627 12628 FieldCollector->StartClass(); 12629 12630 if (!Record->getIdentifier()) 12631 return; 12632 12633 if (FinalLoc.isValid()) 12634 Record->addAttr(new (Context) 12635 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 12636 12637 // C++ [class]p2: 12638 // [...] The class-name is also inserted into the scope of the 12639 // class itself; this is known as the injected-class-name. For 12640 // purposes of access checking, the injected-class-name is treated 12641 // as if it were a public member name. 12642 CXXRecordDecl *InjectedClassName 12643 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 12644 Record->getLocStart(), Record->getLocation(), 12645 Record->getIdentifier(), 12646 /*PrevDecl=*/nullptr, 12647 /*DelayTypeCreation=*/true); 12648 Context.getTypeDeclType(InjectedClassName, Record); 12649 InjectedClassName->setImplicit(); 12650 InjectedClassName->setAccess(AS_public); 12651 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 12652 InjectedClassName->setDescribedClassTemplate(Template); 12653 PushOnScopeChains(InjectedClassName, S); 12654 assert(InjectedClassName->isInjectedClassName() && 12655 "Broken injected-class-name"); 12656 } 12657 12658 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 12659 SourceLocation RBraceLoc) { 12660 AdjustDeclIfTemplate(TagD); 12661 TagDecl *Tag = cast<TagDecl>(TagD); 12662 Tag->setRBraceLoc(RBraceLoc); 12663 12664 // Make sure we "complete" the definition even it is invalid. 12665 if (Tag->isBeingDefined()) { 12666 assert(Tag->isInvalidDecl() && "We should already have completed it"); 12667 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12668 RD->completeDefinition(); 12669 } 12670 12671 if (isa<CXXRecordDecl>(Tag)) 12672 FieldCollector->FinishClass(); 12673 12674 // Exit this scope of this tag's definition. 12675 PopDeclContext(); 12676 12677 if (getCurLexicalContext()->isObjCContainer() && 12678 Tag->getDeclContext()->isFileContext()) 12679 Tag->setTopLevelDeclInObjCContainer(); 12680 12681 // Notify the consumer that we've defined a tag. 12682 if (!Tag->isInvalidDecl()) 12683 Consumer.HandleTagDeclDefinition(Tag); 12684 } 12685 12686 void Sema::ActOnObjCContainerFinishDefinition() { 12687 // Exit this scope of this interface definition. 12688 PopDeclContext(); 12689 } 12690 12691 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 12692 assert(DC == CurContext && "Mismatch of container contexts"); 12693 OriginalLexicalContext = DC; 12694 ActOnObjCContainerFinishDefinition(); 12695 } 12696 12697 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 12698 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 12699 OriginalLexicalContext = nullptr; 12700 } 12701 12702 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 12703 AdjustDeclIfTemplate(TagD); 12704 TagDecl *Tag = cast<TagDecl>(TagD); 12705 Tag->setInvalidDecl(); 12706 12707 // Make sure we "complete" the definition even it is invalid. 12708 if (Tag->isBeingDefined()) { 12709 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12710 RD->completeDefinition(); 12711 } 12712 12713 // We're undoing ActOnTagStartDefinition here, not 12714 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 12715 // the FieldCollector. 12716 12717 PopDeclContext(); 12718 } 12719 12720 // Note that FieldName may be null for anonymous bitfields. 12721 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 12722 IdentifierInfo *FieldName, 12723 QualType FieldTy, bool IsMsStruct, 12724 Expr *BitWidth, bool *ZeroWidth) { 12725 // Default to true; that shouldn't confuse checks for emptiness 12726 if (ZeroWidth) 12727 *ZeroWidth = true; 12728 12729 // C99 6.7.2.1p4 - verify the field type. 12730 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 12731 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 12732 // Handle incomplete types with specific error. 12733 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12734 return ExprError(); 12735 if (FieldName) 12736 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12737 << FieldName << FieldTy << BitWidth->getSourceRange(); 12738 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12739 << FieldTy << BitWidth->getSourceRange(); 12740 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12741 UPPC_BitFieldWidth)) 12742 return ExprError(); 12743 12744 // If the bit-width is type- or value-dependent, don't try to check 12745 // it now. 12746 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12747 return BitWidth; 12748 12749 llvm::APSInt Value; 12750 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12751 if (ICE.isInvalid()) 12752 return ICE; 12753 BitWidth = ICE.get(); 12754 12755 if (Value != 0 && ZeroWidth) 12756 *ZeroWidth = false; 12757 12758 // Zero-width bitfield is ok for anonymous field. 12759 if (Value == 0 && FieldName) 12760 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12761 12762 if (Value.isSigned() && Value.isNegative()) { 12763 if (FieldName) 12764 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12765 << FieldName << Value.toString(10); 12766 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12767 << Value.toString(10); 12768 } 12769 12770 if (!FieldTy->isDependentType()) { 12771 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy); 12772 uint64_t TypeWidth = Context.getIntWidth(FieldTy); 12773 bool BitfieldIsOverwide = Value.ugt(TypeWidth); 12774 12775 // Over-wide bitfields are an error in C or when using the MSVC bitfield 12776 // ABI. 12777 bool CStdConstraintViolation = 12778 BitfieldIsOverwide && !getLangOpts().CPlusPlus; 12779 bool MSBitfieldViolation = 12780 Value.ugt(TypeStorageSize) && 12781 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft()); 12782 if (CStdConstraintViolation || MSBitfieldViolation) { 12783 unsigned DiagWidth = 12784 CStdConstraintViolation ? TypeWidth : TypeStorageSize; 12785 if (FieldName) 12786 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width) 12787 << FieldName << (unsigned)Value.getZExtValue() 12788 << !CStdConstraintViolation << DiagWidth; 12789 12790 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width) 12791 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation 12792 << DiagWidth; 12793 } 12794 12795 // Warn on types where the user might conceivably expect to get all 12796 // specified bits as value bits: that's all integral types other than 12797 // 'bool'. 12798 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) { 12799 if (FieldName) 12800 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width) 12801 << FieldName << (unsigned)Value.getZExtValue() 12802 << (unsigned)TypeWidth; 12803 else 12804 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width) 12805 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth; 12806 } 12807 } 12808 12809 return BitWidth; 12810 } 12811 12812 /// ActOnField - Each field of a C struct/union is passed into this in order 12813 /// to create a FieldDecl object for it. 12814 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 12815 Declarator &D, Expr *BitfieldWidth) { 12816 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 12817 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 12818 /*InitStyle=*/ICIS_NoInit, AS_public); 12819 return Res; 12820 } 12821 12822 /// HandleField - Analyze a field of a C struct or a C++ data member. 12823 /// 12824 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 12825 SourceLocation DeclStart, 12826 Declarator &D, Expr *BitWidth, 12827 InClassInitStyle InitStyle, 12828 AccessSpecifier AS) { 12829 IdentifierInfo *II = D.getIdentifier(); 12830 SourceLocation Loc = DeclStart; 12831 if (II) Loc = D.getIdentifierLoc(); 12832 12833 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12834 QualType T = TInfo->getType(); 12835 if (getLangOpts().CPlusPlus) { 12836 CheckExtraCXXDefaultArguments(D); 12837 12838 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12839 UPPC_DataMemberType)) { 12840 D.setInvalidType(); 12841 T = Context.IntTy; 12842 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12843 } 12844 } 12845 12846 // TR 18037 does not allow fields to be declared with address spaces. 12847 if (T.getQualifiers().hasAddressSpace()) { 12848 Diag(Loc, diag::err_field_with_address_space); 12849 D.setInvalidType(); 12850 } 12851 12852 // OpenCL 1.2 spec, s6.9 r: 12853 // The event type cannot be used to declare a structure or union field. 12854 if (LangOpts.OpenCL && T->isEventT()) { 12855 Diag(Loc, diag::err_event_t_struct_field); 12856 D.setInvalidType(); 12857 } 12858 12859 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12860 12861 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12862 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12863 diag::err_invalid_thread) 12864 << DeclSpec::getSpecifierName(TSCS); 12865 12866 // Check to see if this name was declared as a member previously 12867 NamedDecl *PrevDecl = nullptr; 12868 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12869 LookupName(Previous, S); 12870 switch (Previous.getResultKind()) { 12871 case LookupResult::Found: 12872 case LookupResult::FoundUnresolvedValue: 12873 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12874 break; 12875 12876 case LookupResult::FoundOverloaded: 12877 PrevDecl = Previous.getRepresentativeDecl(); 12878 break; 12879 12880 case LookupResult::NotFound: 12881 case LookupResult::NotFoundInCurrentInstantiation: 12882 case LookupResult::Ambiguous: 12883 break; 12884 } 12885 Previous.suppressDiagnostics(); 12886 12887 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12888 // Maybe we will complain about the shadowed template parameter. 12889 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12890 // Just pretend that we didn't see the previous declaration. 12891 PrevDecl = nullptr; 12892 } 12893 12894 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12895 PrevDecl = nullptr; 12896 12897 bool Mutable 12898 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 12899 SourceLocation TSSL = D.getLocStart(); 12900 FieldDecl *NewFD 12901 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 12902 TSSL, AS, PrevDecl, &D); 12903 12904 if (NewFD->isInvalidDecl()) 12905 Record->setInvalidDecl(); 12906 12907 if (D.getDeclSpec().isModulePrivateSpecified()) 12908 NewFD->setModulePrivate(); 12909 12910 if (NewFD->isInvalidDecl() && PrevDecl) { 12911 // Don't introduce NewFD into scope; there's already something 12912 // with the same name in the same scope. 12913 } else if (II) { 12914 PushOnScopeChains(NewFD, S); 12915 } else 12916 Record->addDecl(NewFD); 12917 12918 return NewFD; 12919 } 12920 12921 /// \brief Build a new FieldDecl and check its well-formedness. 12922 /// 12923 /// This routine builds a new FieldDecl given the fields name, type, 12924 /// record, etc. \p PrevDecl should refer to any previous declaration 12925 /// with the same name and in the same scope as the field to be 12926 /// created. 12927 /// 12928 /// \returns a new FieldDecl. 12929 /// 12930 /// \todo The Declarator argument is a hack. It will be removed once 12931 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 12932 TypeSourceInfo *TInfo, 12933 RecordDecl *Record, SourceLocation Loc, 12934 bool Mutable, Expr *BitWidth, 12935 InClassInitStyle InitStyle, 12936 SourceLocation TSSL, 12937 AccessSpecifier AS, NamedDecl *PrevDecl, 12938 Declarator *D) { 12939 IdentifierInfo *II = Name.getAsIdentifierInfo(); 12940 bool InvalidDecl = false; 12941 if (D) InvalidDecl = D->isInvalidType(); 12942 12943 // If we receive a broken type, recover by assuming 'int' and 12944 // marking this declaration as invalid. 12945 if (T.isNull()) { 12946 InvalidDecl = true; 12947 T = Context.IntTy; 12948 } 12949 12950 QualType EltTy = Context.getBaseElementType(T); 12951 if (!EltTy->isDependentType()) { 12952 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 12953 // Fields of incomplete type force their record to be invalid. 12954 Record->setInvalidDecl(); 12955 InvalidDecl = true; 12956 } else { 12957 NamedDecl *Def; 12958 EltTy->isIncompleteType(&Def); 12959 if (Def && Def->isInvalidDecl()) { 12960 Record->setInvalidDecl(); 12961 InvalidDecl = true; 12962 } 12963 } 12964 } 12965 12966 // OpenCL v1.2 s6.9.c: bitfields are not supported. 12967 if (BitWidth && getLangOpts().OpenCL) { 12968 Diag(Loc, diag::err_opencl_bitfields); 12969 InvalidDecl = true; 12970 } 12971 12972 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12973 // than a variably modified type. 12974 if (!InvalidDecl && T->isVariablyModifiedType()) { 12975 bool SizeIsNegative; 12976 llvm::APSInt Oversized; 12977 12978 TypeSourceInfo *FixedTInfo = 12979 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 12980 SizeIsNegative, 12981 Oversized); 12982 if (FixedTInfo) { 12983 Diag(Loc, diag::warn_illegal_constant_array_size); 12984 TInfo = FixedTInfo; 12985 T = FixedTInfo->getType(); 12986 } else { 12987 if (SizeIsNegative) 12988 Diag(Loc, diag::err_typecheck_negative_array_size); 12989 else if (Oversized.getBoolValue()) 12990 Diag(Loc, diag::err_array_too_large) 12991 << Oversized.toString(10); 12992 else 12993 Diag(Loc, diag::err_typecheck_field_variable_size); 12994 InvalidDecl = true; 12995 } 12996 } 12997 12998 // Fields can not have abstract class types 12999 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 13000 diag::err_abstract_type_in_decl, 13001 AbstractFieldType)) 13002 InvalidDecl = true; 13003 13004 bool ZeroWidth = false; 13005 if (InvalidDecl) 13006 BitWidth = nullptr; 13007 // If this is declared as a bit-field, check the bit-field. 13008 if (BitWidth) { 13009 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 13010 &ZeroWidth).get(); 13011 if (!BitWidth) { 13012 InvalidDecl = true; 13013 BitWidth = nullptr; 13014 ZeroWidth = false; 13015 } 13016 } 13017 13018 // Check that 'mutable' is consistent with the type of the declaration. 13019 if (!InvalidDecl && Mutable) { 13020 unsigned DiagID = 0; 13021 if (T->isReferenceType()) 13022 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 13023 : diag::err_mutable_reference; 13024 else if (T.isConstQualified()) 13025 DiagID = diag::err_mutable_const; 13026 13027 if (DiagID) { 13028 SourceLocation ErrLoc = Loc; 13029 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 13030 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 13031 Diag(ErrLoc, DiagID); 13032 if (DiagID != diag::ext_mutable_reference) { 13033 Mutable = false; 13034 InvalidDecl = true; 13035 } 13036 } 13037 } 13038 13039 // C++11 [class.union]p8 (DR1460): 13040 // At most one variant member of a union may have a 13041 // brace-or-equal-initializer. 13042 if (InitStyle != ICIS_NoInit) 13043 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 13044 13045 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 13046 BitWidth, Mutable, InitStyle); 13047 if (InvalidDecl) 13048 NewFD->setInvalidDecl(); 13049 13050 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 13051 Diag(Loc, diag::err_duplicate_member) << II; 13052 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13053 NewFD->setInvalidDecl(); 13054 } 13055 13056 if (!InvalidDecl && getLangOpts().CPlusPlus) { 13057 if (Record->isUnion()) { 13058 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13059 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13060 if (RDecl->getDefinition()) { 13061 // C++ [class.union]p1: An object of a class with a non-trivial 13062 // constructor, a non-trivial copy constructor, a non-trivial 13063 // destructor, or a non-trivial copy assignment operator 13064 // cannot be a member of a union, nor can an array of such 13065 // objects. 13066 if (CheckNontrivialField(NewFD)) 13067 NewFD->setInvalidDecl(); 13068 } 13069 } 13070 13071 // C++ [class.union]p1: If a union contains a member of reference type, 13072 // the program is ill-formed, except when compiling with MSVC extensions 13073 // enabled. 13074 if (EltTy->isReferenceType()) { 13075 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 13076 diag::ext_union_member_of_reference_type : 13077 diag::err_union_member_of_reference_type) 13078 << NewFD->getDeclName() << EltTy; 13079 if (!getLangOpts().MicrosoftExt) 13080 NewFD->setInvalidDecl(); 13081 } 13082 } 13083 } 13084 13085 // FIXME: We need to pass in the attributes given an AST 13086 // representation, not a parser representation. 13087 if (D) { 13088 // FIXME: The current scope is almost... but not entirely... correct here. 13089 ProcessDeclAttributes(getCurScope(), NewFD, *D); 13090 13091 if (NewFD->hasAttrs()) 13092 CheckAlignasUnderalignment(NewFD); 13093 } 13094 13095 // In auto-retain/release, infer strong retension for fields of 13096 // retainable type. 13097 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 13098 NewFD->setInvalidDecl(); 13099 13100 if (T.isObjCGCWeak()) 13101 Diag(Loc, diag::warn_attribute_weak_on_field); 13102 13103 NewFD->setAccess(AS); 13104 return NewFD; 13105 } 13106 13107 bool Sema::CheckNontrivialField(FieldDecl *FD) { 13108 assert(FD); 13109 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 13110 13111 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 13112 return false; 13113 13114 QualType EltTy = Context.getBaseElementType(FD->getType()); 13115 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 13116 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 13117 if (RDecl->getDefinition()) { 13118 // We check for copy constructors before constructors 13119 // because otherwise we'll never get complaints about 13120 // copy constructors. 13121 13122 CXXSpecialMember member = CXXInvalid; 13123 // We're required to check for any non-trivial constructors. Since the 13124 // implicit default constructor is suppressed if there are any 13125 // user-declared constructors, we just need to check that there is a 13126 // trivial default constructor and a trivial copy constructor. (We don't 13127 // worry about move constructors here, since this is a C++98 check.) 13128 if (RDecl->hasNonTrivialCopyConstructor()) 13129 member = CXXCopyConstructor; 13130 else if (!RDecl->hasTrivialDefaultConstructor()) 13131 member = CXXDefaultConstructor; 13132 else if (RDecl->hasNonTrivialCopyAssignment()) 13133 member = CXXCopyAssignment; 13134 else if (RDecl->hasNonTrivialDestructor()) 13135 member = CXXDestructor; 13136 13137 if (member != CXXInvalid) { 13138 if (!getLangOpts().CPlusPlus11 && 13139 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 13140 // Objective-C++ ARC: it is an error to have a non-trivial field of 13141 // a union. However, system headers in Objective-C programs 13142 // occasionally have Objective-C lifetime objects within unions, 13143 // and rather than cause the program to fail, we make those 13144 // members unavailable. 13145 SourceLocation Loc = FD->getLocation(); 13146 if (getSourceManager().isInSystemHeader(Loc)) { 13147 if (!FD->hasAttr<UnavailableAttr>()) 13148 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13149 UnavailableAttr::IR_ARCFieldWithOwnership, Loc)); 13150 return false; 13151 } 13152 } 13153 13154 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 13155 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 13156 diag::err_illegal_union_or_anon_struct_member) 13157 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 13158 DiagnoseNontrivial(RDecl, member); 13159 return !getLangOpts().CPlusPlus11; 13160 } 13161 } 13162 } 13163 13164 return false; 13165 } 13166 13167 /// TranslateIvarVisibility - Translate visibility from a token ID to an 13168 /// AST enum value. 13169 static ObjCIvarDecl::AccessControl 13170 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 13171 switch (ivarVisibility) { 13172 default: llvm_unreachable("Unknown visitibility kind"); 13173 case tok::objc_private: return ObjCIvarDecl::Private; 13174 case tok::objc_public: return ObjCIvarDecl::Public; 13175 case tok::objc_protected: return ObjCIvarDecl::Protected; 13176 case tok::objc_package: return ObjCIvarDecl::Package; 13177 } 13178 } 13179 13180 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 13181 /// in order to create an IvarDecl object for it. 13182 Decl *Sema::ActOnIvar(Scope *S, 13183 SourceLocation DeclStart, 13184 Declarator &D, Expr *BitfieldWidth, 13185 tok::ObjCKeywordKind Visibility) { 13186 13187 IdentifierInfo *II = D.getIdentifier(); 13188 Expr *BitWidth = (Expr*)BitfieldWidth; 13189 SourceLocation Loc = DeclStart; 13190 if (II) Loc = D.getIdentifierLoc(); 13191 13192 // FIXME: Unnamed fields can be handled in various different ways, for 13193 // example, unnamed unions inject all members into the struct namespace! 13194 13195 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13196 QualType T = TInfo->getType(); 13197 13198 if (BitWidth) { 13199 // 6.7.2.1p3, 6.7.2.1p4 13200 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 13201 if (!BitWidth) 13202 D.setInvalidType(); 13203 } else { 13204 // Not a bitfield. 13205 13206 // validate II. 13207 13208 } 13209 if (T->isReferenceType()) { 13210 Diag(Loc, diag::err_ivar_reference_type); 13211 D.setInvalidType(); 13212 } 13213 // C99 6.7.2.1p8: A member of a structure or union may have any type other 13214 // than a variably modified type. 13215 else if (T->isVariablyModifiedType()) { 13216 Diag(Loc, diag::err_typecheck_ivar_variable_size); 13217 D.setInvalidType(); 13218 } 13219 13220 // Get the visibility (access control) for this ivar. 13221 ObjCIvarDecl::AccessControl ac = 13222 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 13223 : ObjCIvarDecl::None; 13224 // Must set ivar's DeclContext to its enclosing interface. 13225 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 13226 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 13227 return nullptr; 13228 ObjCContainerDecl *EnclosingContext; 13229 if (ObjCImplementationDecl *IMPDecl = 13230 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13231 if (LangOpts.ObjCRuntime.isFragile()) { 13232 // Case of ivar declared in an implementation. Context is that of its class. 13233 EnclosingContext = IMPDecl->getClassInterface(); 13234 assert(EnclosingContext && "Implementation has no class interface!"); 13235 } 13236 else 13237 EnclosingContext = EnclosingDecl; 13238 } else { 13239 if (ObjCCategoryDecl *CDecl = 13240 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13241 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 13242 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 13243 return nullptr; 13244 } 13245 } 13246 EnclosingContext = EnclosingDecl; 13247 } 13248 13249 // Construct the decl. 13250 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 13251 DeclStart, Loc, II, T, 13252 TInfo, ac, (Expr *)BitfieldWidth); 13253 13254 if (II) { 13255 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 13256 ForRedeclaration); 13257 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 13258 && !isa<TagDecl>(PrevDecl)) { 13259 Diag(Loc, diag::err_duplicate_member) << II; 13260 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 13261 NewID->setInvalidDecl(); 13262 } 13263 } 13264 13265 // Process attributes attached to the ivar. 13266 ProcessDeclAttributes(S, NewID, D); 13267 13268 if (D.isInvalidType()) 13269 NewID->setInvalidDecl(); 13270 13271 // In ARC, infer 'retaining' for ivars of retainable type. 13272 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 13273 NewID->setInvalidDecl(); 13274 13275 if (D.getDeclSpec().isModulePrivateSpecified()) 13276 NewID->setModulePrivate(); 13277 13278 if (II) { 13279 // FIXME: When interfaces are DeclContexts, we'll need to add 13280 // these to the interface. 13281 S->AddDecl(NewID); 13282 IdResolver.AddDecl(NewID); 13283 } 13284 13285 if (LangOpts.ObjCRuntime.isNonFragile() && 13286 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 13287 Diag(Loc, diag::warn_ivars_in_interface); 13288 13289 return NewID; 13290 } 13291 13292 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 13293 /// class and class extensions. For every class \@interface and class 13294 /// extension \@interface, if the last ivar is a bitfield of any type, 13295 /// then add an implicit `char :0` ivar to the end of that interface. 13296 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 13297 SmallVectorImpl<Decl *> &AllIvarDecls) { 13298 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 13299 return; 13300 13301 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 13302 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 13303 13304 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 13305 return; 13306 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 13307 if (!ID) { 13308 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 13309 if (!CD->IsClassExtension()) 13310 return; 13311 } 13312 // No need to add this to end of @implementation. 13313 else 13314 return; 13315 } 13316 // All conditions are met. Add a new bitfield to the tail end of ivars. 13317 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 13318 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 13319 13320 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 13321 DeclLoc, DeclLoc, nullptr, 13322 Context.CharTy, 13323 Context.getTrivialTypeSourceInfo(Context.CharTy, 13324 DeclLoc), 13325 ObjCIvarDecl::Private, BW, 13326 true); 13327 AllIvarDecls.push_back(Ivar); 13328 } 13329 13330 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 13331 ArrayRef<Decl *> Fields, SourceLocation LBrac, 13332 SourceLocation RBrac, AttributeList *Attr) { 13333 assert(EnclosingDecl && "missing record or interface decl"); 13334 13335 // If this is an Objective-C @implementation or category and we have 13336 // new fields here we should reset the layout of the interface since 13337 // it will now change. 13338 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 13339 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 13340 switch (DC->getKind()) { 13341 default: break; 13342 case Decl::ObjCCategory: 13343 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 13344 break; 13345 case Decl::ObjCImplementation: 13346 Context. 13347 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 13348 break; 13349 } 13350 } 13351 13352 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 13353 13354 // Start counting up the number of named members; make sure to include 13355 // members of anonymous structs and unions in the total. 13356 unsigned NumNamedMembers = 0; 13357 if (Record) { 13358 for (const auto *I : Record->decls()) { 13359 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 13360 if (IFD->getDeclName()) 13361 ++NumNamedMembers; 13362 } 13363 } 13364 13365 // Verify that all the fields are okay. 13366 SmallVector<FieldDecl*, 32> RecFields; 13367 13368 bool ARCErrReported = false; 13369 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 13370 i != end; ++i) { 13371 FieldDecl *FD = cast<FieldDecl>(*i); 13372 13373 // Get the type for the field. 13374 const Type *FDTy = FD->getType().getTypePtr(); 13375 13376 if (!FD->isAnonymousStructOrUnion()) { 13377 // Remember all fields written by the user. 13378 RecFields.push_back(FD); 13379 } 13380 13381 // If the field is already invalid for some reason, don't emit more 13382 // diagnostics about it. 13383 if (FD->isInvalidDecl()) { 13384 EnclosingDecl->setInvalidDecl(); 13385 continue; 13386 } 13387 13388 // C99 6.7.2.1p2: 13389 // A structure or union shall not contain a member with 13390 // incomplete or function type (hence, a structure shall not 13391 // contain an instance of itself, but may contain a pointer to 13392 // an instance of itself), except that the last member of a 13393 // structure with more than one named member may have incomplete 13394 // array type; such a structure (and any union containing, 13395 // possibly recursively, a member that is such a structure) 13396 // shall not be a member of a structure or an element of an 13397 // array. 13398 if (FDTy->isFunctionType()) { 13399 // Field declared as a function. 13400 Diag(FD->getLocation(), diag::err_field_declared_as_function) 13401 << FD->getDeclName(); 13402 FD->setInvalidDecl(); 13403 EnclosingDecl->setInvalidDecl(); 13404 continue; 13405 } else if (FDTy->isIncompleteArrayType() && Record && 13406 ((i + 1 == Fields.end() && !Record->isUnion()) || 13407 ((getLangOpts().MicrosoftExt || 13408 getLangOpts().CPlusPlus) && 13409 (i + 1 == Fields.end() || Record->isUnion())))) { 13410 // Flexible array member. 13411 // Microsoft and g++ is more permissive regarding flexible array. 13412 // It will accept flexible array in union and also 13413 // as the sole element of a struct/class. 13414 unsigned DiagID = 0; 13415 if (Record->isUnion()) 13416 DiagID = getLangOpts().MicrosoftExt 13417 ? diag::ext_flexible_array_union_ms 13418 : getLangOpts().CPlusPlus 13419 ? diag::ext_flexible_array_union_gnu 13420 : diag::err_flexible_array_union; 13421 else if (Fields.size() == 1) 13422 DiagID = getLangOpts().MicrosoftExt 13423 ? diag::ext_flexible_array_empty_aggregate_ms 13424 : getLangOpts().CPlusPlus 13425 ? diag::ext_flexible_array_empty_aggregate_gnu 13426 : NumNamedMembers < 1 13427 ? diag::err_flexible_array_empty_aggregate 13428 : 0; 13429 13430 if (DiagID) 13431 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 13432 << Record->getTagKind(); 13433 // While the layout of types that contain virtual bases is not specified 13434 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 13435 // virtual bases after the derived members. This would make a flexible 13436 // array member declared at the end of an object not adjacent to the end 13437 // of the type. 13438 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 13439 if (RD->getNumVBases() != 0) 13440 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 13441 << FD->getDeclName() << Record->getTagKind(); 13442 if (!getLangOpts().C99) 13443 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 13444 << FD->getDeclName() << Record->getTagKind(); 13445 13446 // If the element type has a non-trivial destructor, we would not 13447 // implicitly destroy the elements, so disallow it for now. 13448 // 13449 // FIXME: GCC allows this. We should probably either implicitly delete 13450 // the destructor of the containing class, or just allow this. 13451 QualType BaseElem = Context.getBaseElementType(FD->getType()); 13452 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 13453 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 13454 << FD->getDeclName() << FD->getType(); 13455 FD->setInvalidDecl(); 13456 EnclosingDecl->setInvalidDecl(); 13457 continue; 13458 } 13459 // Okay, we have a legal flexible array member at the end of the struct. 13460 Record->setHasFlexibleArrayMember(true); 13461 } else if (!FDTy->isDependentType() && 13462 RequireCompleteType(FD->getLocation(), FD->getType(), 13463 diag::err_field_incomplete)) { 13464 // Incomplete type 13465 FD->setInvalidDecl(); 13466 EnclosingDecl->setInvalidDecl(); 13467 continue; 13468 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 13469 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 13470 // A type which contains a flexible array member is considered to be a 13471 // flexible array member. 13472 Record->setHasFlexibleArrayMember(true); 13473 if (!Record->isUnion()) { 13474 // If this is a struct/class and this is not the last element, reject 13475 // it. Note that GCC supports variable sized arrays in the middle of 13476 // structures. 13477 if (i + 1 != Fields.end()) 13478 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 13479 << FD->getDeclName() << FD->getType(); 13480 else { 13481 // We support flexible arrays at the end of structs in 13482 // other structs as an extension. 13483 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 13484 << FD->getDeclName(); 13485 } 13486 } 13487 } 13488 if (isa<ObjCContainerDecl>(EnclosingDecl) && 13489 RequireNonAbstractType(FD->getLocation(), FD->getType(), 13490 diag::err_abstract_type_in_decl, 13491 AbstractIvarType)) { 13492 // Ivars can not have abstract class types 13493 FD->setInvalidDecl(); 13494 } 13495 if (Record && FDTTy->getDecl()->hasObjectMember()) 13496 Record->setHasObjectMember(true); 13497 if (Record && FDTTy->getDecl()->hasVolatileMember()) 13498 Record->setHasVolatileMember(true); 13499 } else if (FDTy->isObjCObjectType()) { 13500 /// A field cannot be an Objective-c object 13501 Diag(FD->getLocation(), diag::err_statically_allocated_object) 13502 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 13503 QualType T = Context.getObjCObjectPointerType(FD->getType()); 13504 FD->setType(T); 13505 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 13506 (!getLangOpts().CPlusPlus || Record->isUnion())) { 13507 // It's an error in ARC if a field has lifetime. 13508 // We don't want to report this in a system header, though, 13509 // so we just make the field unavailable. 13510 // FIXME: that's really not sufficient; we need to make the type 13511 // itself invalid to, say, initialize or copy. 13512 QualType T = FD->getType(); 13513 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 13514 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 13515 SourceLocation loc = FD->getLocation(); 13516 if (getSourceManager().isInSystemHeader(loc)) { 13517 if (!FD->hasAttr<UnavailableAttr>()) { 13518 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "", 13519 UnavailableAttr::IR_ARCFieldWithOwnership, loc)); 13520 } 13521 } else { 13522 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 13523 << T->isBlockPointerType() << Record->getTagKind(); 13524 } 13525 ARCErrReported = true; 13526 } 13527 } else if (getLangOpts().ObjC1 && 13528 getLangOpts().getGC() != LangOptions::NonGC && 13529 Record && !Record->hasObjectMember()) { 13530 if (FD->getType()->isObjCObjectPointerType() || 13531 FD->getType().isObjCGCStrong()) 13532 Record->setHasObjectMember(true); 13533 else if (Context.getAsArrayType(FD->getType())) { 13534 QualType BaseType = Context.getBaseElementType(FD->getType()); 13535 if (BaseType->isRecordType() && 13536 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 13537 Record->setHasObjectMember(true); 13538 else if (BaseType->isObjCObjectPointerType() || 13539 BaseType.isObjCGCStrong()) 13540 Record->setHasObjectMember(true); 13541 } 13542 } 13543 if (Record && FD->getType().isVolatileQualified()) 13544 Record->setHasVolatileMember(true); 13545 // Keep track of the number of named members. 13546 if (FD->getIdentifier()) 13547 ++NumNamedMembers; 13548 } 13549 13550 // Okay, we successfully defined 'Record'. 13551 if (Record) { 13552 bool Completed = false; 13553 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 13554 if (!CXXRecord->isInvalidDecl()) { 13555 // Set access bits correctly on the directly-declared conversions. 13556 for (CXXRecordDecl::conversion_iterator 13557 I = CXXRecord->conversion_begin(), 13558 E = CXXRecord->conversion_end(); I != E; ++I) 13559 I.setAccess((*I)->getAccess()); 13560 13561 if (!CXXRecord->isDependentType()) { 13562 if (CXXRecord->hasUserDeclaredDestructor()) { 13563 // Adjust user-defined destructor exception spec. 13564 if (getLangOpts().CPlusPlus11) 13565 AdjustDestructorExceptionSpec(CXXRecord, 13566 CXXRecord->getDestructor()); 13567 } 13568 13569 // Add any implicitly-declared members to this class. 13570 AddImplicitlyDeclaredMembersToClass(CXXRecord); 13571 13572 // If we have virtual base classes, we may end up finding multiple 13573 // final overriders for a given virtual function. Check for this 13574 // problem now. 13575 if (CXXRecord->getNumVBases()) { 13576 CXXFinalOverriderMap FinalOverriders; 13577 CXXRecord->getFinalOverriders(FinalOverriders); 13578 13579 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 13580 MEnd = FinalOverriders.end(); 13581 M != MEnd; ++M) { 13582 for (OverridingMethods::iterator SO = M->second.begin(), 13583 SOEnd = M->second.end(); 13584 SO != SOEnd; ++SO) { 13585 assert(SO->second.size() > 0 && 13586 "Virtual function without overridding functions?"); 13587 if (SO->second.size() == 1) 13588 continue; 13589 13590 // C++ [class.virtual]p2: 13591 // In a derived class, if a virtual member function of a base 13592 // class subobject has more than one final overrider the 13593 // program is ill-formed. 13594 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 13595 << (const NamedDecl *)M->first << Record; 13596 Diag(M->first->getLocation(), 13597 diag::note_overridden_virtual_function); 13598 for (OverridingMethods::overriding_iterator 13599 OM = SO->second.begin(), 13600 OMEnd = SO->second.end(); 13601 OM != OMEnd; ++OM) 13602 Diag(OM->Method->getLocation(), diag::note_final_overrider) 13603 << (const NamedDecl *)M->first << OM->Method->getParent(); 13604 13605 Record->setInvalidDecl(); 13606 } 13607 } 13608 CXXRecord->completeDefinition(&FinalOverriders); 13609 Completed = true; 13610 } 13611 } 13612 } 13613 } 13614 13615 if (!Completed) 13616 Record->completeDefinition(); 13617 13618 if (Record->hasAttrs()) { 13619 CheckAlignasUnderalignment(Record); 13620 13621 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 13622 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 13623 IA->getRange(), IA->getBestCase(), 13624 IA->getSemanticSpelling()); 13625 } 13626 13627 // Check if the structure/union declaration is a type that can have zero 13628 // size in C. For C this is a language extension, for C++ it may cause 13629 // compatibility problems. 13630 bool CheckForZeroSize; 13631 if (!getLangOpts().CPlusPlus) { 13632 CheckForZeroSize = true; 13633 } else { 13634 // For C++ filter out types that cannot be referenced in C code. 13635 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 13636 CheckForZeroSize = 13637 CXXRecord->getLexicalDeclContext()->isExternCContext() && 13638 !CXXRecord->isDependentType() && 13639 CXXRecord->isCLike(); 13640 } 13641 if (CheckForZeroSize) { 13642 bool ZeroSize = true; 13643 bool IsEmpty = true; 13644 unsigned NonBitFields = 0; 13645 for (RecordDecl::field_iterator I = Record->field_begin(), 13646 E = Record->field_end(); 13647 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 13648 IsEmpty = false; 13649 if (I->isUnnamedBitfield()) { 13650 if (I->getBitWidthValue(Context) > 0) 13651 ZeroSize = false; 13652 } else { 13653 ++NonBitFields; 13654 QualType FieldType = I->getType(); 13655 if (FieldType->isIncompleteType() || 13656 !Context.getTypeSizeInChars(FieldType).isZero()) 13657 ZeroSize = false; 13658 } 13659 } 13660 13661 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 13662 // allowed in C++, but warn if its declaration is inside 13663 // extern "C" block. 13664 if (ZeroSize) { 13665 Diag(RecLoc, getLangOpts().CPlusPlus ? 13666 diag::warn_zero_size_struct_union_in_extern_c : 13667 diag::warn_zero_size_struct_union_compat) 13668 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 13669 } 13670 13671 // Structs without named members are extension in C (C99 6.7.2.1p7), 13672 // but are accepted by GCC. 13673 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 13674 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 13675 diag::ext_no_named_members_in_struct_union) 13676 << Record->isUnion(); 13677 } 13678 } 13679 } else { 13680 ObjCIvarDecl **ClsFields = 13681 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 13682 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 13683 ID->setEndOfDefinitionLoc(RBrac); 13684 // Add ivar's to class's DeclContext. 13685 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13686 ClsFields[i]->setLexicalDeclContext(ID); 13687 ID->addDecl(ClsFields[i]); 13688 } 13689 // Must enforce the rule that ivars in the base classes may not be 13690 // duplicates. 13691 if (ID->getSuperClass()) 13692 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 13693 } else if (ObjCImplementationDecl *IMPDecl = 13694 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13695 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 13696 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 13697 // Ivar declared in @implementation never belongs to the implementation. 13698 // Only it is in implementation's lexical context. 13699 ClsFields[I]->setLexicalDeclContext(IMPDecl); 13700 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 13701 IMPDecl->setIvarLBraceLoc(LBrac); 13702 IMPDecl->setIvarRBraceLoc(RBrac); 13703 } else if (ObjCCategoryDecl *CDecl = 13704 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13705 // case of ivars in class extension; all other cases have been 13706 // reported as errors elsewhere. 13707 // FIXME. Class extension does not have a LocEnd field. 13708 // CDecl->setLocEnd(RBrac); 13709 // Add ivar's to class extension's DeclContext. 13710 // Diagnose redeclaration of private ivars. 13711 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 13712 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13713 if (IDecl) { 13714 if (const ObjCIvarDecl *ClsIvar = 13715 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 13716 Diag(ClsFields[i]->getLocation(), 13717 diag::err_duplicate_ivar_declaration); 13718 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 13719 continue; 13720 } 13721 for (const auto *Ext : IDecl->known_extensions()) { 13722 if (const ObjCIvarDecl *ClsExtIvar 13723 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 13724 Diag(ClsFields[i]->getLocation(), 13725 diag::err_duplicate_ivar_declaration); 13726 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 13727 continue; 13728 } 13729 } 13730 } 13731 ClsFields[i]->setLexicalDeclContext(CDecl); 13732 CDecl->addDecl(ClsFields[i]); 13733 } 13734 CDecl->setIvarLBraceLoc(LBrac); 13735 CDecl->setIvarRBraceLoc(RBrac); 13736 } 13737 } 13738 13739 if (Attr) 13740 ProcessDeclAttributeList(S, Record, Attr); 13741 } 13742 13743 /// \brief Determine whether the given integral value is representable within 13744 /// the given type T. 13745 static bool isRepresentableIntegerValue(ASTContext &Context, 13746 llvm::APSInt &Value, 13747 QualType T) { 13748 assert(T->isIntegralType(Context) && "Integral type required!"); 13749 unsigned BitWidth = Context.getIntWidth(T); 13750 13751 if (Value.isUnsigned() || Value.isNonNegative()) { 13752 if (T->isSignedIntegerOrEnumerationType()) 13753 --BitWidth; 13754 return Value.getActiveBits() <= BitWidth; 13755 } 13756 return Value.getMinSignedBits() <= BitWidth; 13757 } 13758 13759 // \brief Given an integral type, return the next larger integral type 13760 // (or a NULL type of no such type exists). 13761 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13762 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13763 // enum checking below. 13764 assert(T->isIntegralType(Context) && "Integral type required!"); 13765 const unsigned NumTypes = 4; 13766 QualType SignedIntegralTypes[NumTypes] = { 13767 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13768 }; 13769 QualType UnsignedIntegralTypes[NumTypes] = { 13770 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13771 Context.UnsignedLongLongTy 13772 }; 13773 13774 unsigned BitWidth = Context.getTypeSize(T); 13775 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13776 : UnsignedIntegralTypes; 13777 for (unsigned I = 0; I != NumTypes; ++I) 13778 if (Context.getTypeSize(Types[I]) > BitWidth) 13779 return Types[I]; 13780 13781 return QualType(); 13782 } 13783 13784 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13785 EnumConstantDecl *LastEnumConst, 13786 SourceLocation IdLoc, 13787 IdentifierInfo *Id, 13788 Expr *Val) { 13789 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13790 llvm::APSInt EnumVal(IntWidth); 13791 QualType EltTy; 13792 13793 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13794 Val = nullptr; 13795 13796 if (Val) 13797 Val = DefaultLvalueConversion(Val).get(); 13798 13799 if (Val) { 13800 if (Enum->isDependentType() || Val->isTypeDependent()) 13801 EltTy = Context.DependentTy; 13802 else { 13803 SourceLocation ExpLoc; 13804 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 13805 !getLangOpts().MSVCCompat) { 13806 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 13807 // constant-expression in the enumerator-definition shall be a converted 13808 // constant expression of the underlying type. 13809 EltTy = Enum->getIntegerType(); 13810 ExprResult Converted = 13811 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 13812 CCEK_Enumerator); 13813 if (Converted.isInvalid()) 13814 Val = nullptr; 13815 else 13816 Val = Converted.get(); 13817 } else if (!Val->isValueDependent() && 13818 !(Val = VerifyIntegerConstantExpression(Val, 13819 &EnumVal).get())) { 13820 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 13821 } else { 13822 if (Enum->isFixed()) { 13823 EltTy = Enum->getIntegerType(); 13824 13825 // In Obj-C and Microsoft mode, require the enumeration value to be 13826 // representable in the underlying type of the enumeration. In C++11, 13827 // we perform a non-narrowing conversion as part of converted constant 13828 // expression checking. 13829 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13830 if (getLangOpts().MSVCCompat) { 13831 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 13832 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13833 } else 13834 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 13835 } else 13836 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13837 } else if (getLangOpts().CPlusPlus) { 13838 // C++11 [dcl.enum]p5: 13839 // If the underlying type is not fixed, the type of each enumerator 13840 // is the type of its initializing value: 13841 // - If an initializer is specified for an enumerator, the 13842 // initializing value has the same type as the expression. 13843 EltTy = Val->getType(); 13844 } else { 13845 // C99 6.7.2.2p2: 13846 // The expression that defines the value of an enumeration constant 13847 // shall be an integer constant expression that has a value 13848 // representable as an int. 13849 13850 // Complain if the value is not representable in an int. 13851 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 13852 Diag(IdLoc, diag::ext_enum_value_not_int) 13853 << EnumVal.toString(10) << Val->getSourceRange() 13854 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 13855 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 13856 // Force the type of the expression to 'int'. 13857 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 13858 } 13859 EltTy = Val->getType(); 13860 } 13861 } 13862 } 13863 } 13864 13865 if (!Val) { 13866 if (Enum->isDependentType()) 13867 EltTy = Context.DependentTy; 13868 else if (!LastEnumConst) { 13869 // C++0x [dcl.enum]p5: 13870 // If the underlying type is not fixed, the type of each enumerator 13871 // is the type of its initializing value: 13872 // - If no initializer is specified for the first enumerator, the 13873 // initializing value has an unspecified integral type. 13874 // 13875 // GCC uses 'int' for its unspecified integral type, as does 13876 // C99 6.7.2.2p3. 13877 if (Enum->isFixed()) { 13878 EltTy = Enum->getIntegerType(); 13879 } 13880 else { 13881 EltTy = Context.IntTy; 13882 } 13883 } else { 13884 // Assign the last value + 1. 13885 EnumVal = LastEnumConst->getInitVal(); 13886 ++EnumVal; 13887 EltTy = LastEnumConst->getType(); 13888 13889 // Check for overflow on increment. 13890 if (EnumVal < LastEnumConst->getInitVal()) { 13891 // C++0x [dcl.enum]p5: 13892 // If the underlying type is not fixed, the type of each enumerator 13893 // is the type of its initializing value: 13894 // 13895 // - Otherwise the type of the initializing value is the same as 13896 // the type of the initializing value of the preceding enumerator 13897 // unless the incremented value is not representable in that type, 13898 // in which case the type is an unspecified integral type 13899 // sufficient to contain the incremented value. If no such type 13900 // exists, the program is ill-formed. 13901 QualType T = getNextLargerIntegralType(Context, EltTy); 13902 if (T.isNull() || Enum->isFixed()) { 13903 // There is no integral type larger enough to represent this 13904 // value. Complain, then allow the value to wrap around. 13905 EnumVal = LastEnumConst->getInitVal(); 13906 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 13907 ++EnumVal; 13908 if (Enum->isFixed()) 13909 // When the underlying type is fixed, this is ill-formed. 13910 Diag(IdLoc, diag::err_enumerator_wrapped) 13911 << EnumVal.toString(10) 13912 << EltTy; 13913 else 13914 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 13915 << EnumVal.toString(10); 13916 } else { 13917 EltTy = T; 13918 } 13919 13920 // Retrieve the last enumerator's value, extent that type to the 13921 // type that is supposed to be large enough to represent the incremented 13922 // value, then increment. 13923 EnumVal = LastEnumConst->getInitVal(); 13924 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13925 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 13926 ++EnumVal; 13927 13928 // If we're not in C++, diagnose the overflow of enumerator values, 13929 // which in C99 means that the enumerator value is not representable in 13930 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 13931 // permits enumerator values that are representable in some larger 13932 // integral type. 13933 if (!getLangOpts().CPlusPlus && !T.isNull()) 13934 Diag(IdLoc, diag::warn_enum_value_overflow); 13935 } else if (!getLangOpts().CPlusPlus && 13936 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13937 // Enforce C99 6.7.2.2p2 even when we compute the next value. 13938 Diag(IdLoc, diag::ext_enum_value_not_int) 13939 << EnumVal.toString(10) << 1; 13940 } 13941 } 13942 } 13943 13944 if (!EltTy->isDependentType()) { 13945 // Make the enumerator value match the signedness and size of the 13946 // enumerator's type. 13947 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 13948 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13949 } 13950 13951 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 13952 Val, EnumVal); 13953 } 13954 13955 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, 13956 SourceLocation IILoc) { 13957 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) || 13958 !getLangOpts().CPlusPlus) 13959 return SkipBodyInfo(); 13960 13961 // We have an anonymous enum definition. Look up the first enumerator to 13962 // determine if we should merge the definition with an existing one and 13963 // skip the body. 13964 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName, 13965 ForRedeclaration); 13966 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl); 13967 if (!PrevECD) 13968 return SkipBodyInfo(); 13969 13970 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext()); 13971 NamedDecl *Hidden; 13972 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) { 13973 SkipBodyInfo Skip; 13974 Skip.Previous = Hidden; 13975 return Skip; 13976 } 13977 13978 return SkipBodyInfo(); 13979 } 13980 13981 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 13982 SourceLocation IdLoc, IdentifierInfo *Id, 13983 AttributeList *Attr, 13984 SourceLocation EqualLoc, Expr *Val) { 13985 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 13986 EnumConstantDecl *LastEnumConst = 13987 cast_or_null<EnumConstantDecl>(lastEnumConst); 13988 13989 // The scope passed in may not be a decl scope. Zip up the scope tree until 13990 // we find one that is. 13991 S = getNonFieldDeclScope(S); 13992 13993 // Verify that there isn't already something declared with this name in this 13994 // scope. 13995 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 13996 ForRedeclaration); 13997 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13998 // Maybe we will complain about the shadowed template parameter. 13999 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 14000 // Just pretend that we didn't see the previous declaration. 14001 PrevDecl = nullptr; 14002 } 14003 14004 if (PrevDecl) { 14005 // When in C++, we may get a TagDecl with the same name; in this case the 14006 // enum constant will 'hide' the tag. 14007 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 14008 "Received TagDecl when not in C++!"); 14009 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 14010 if (isa<EnumConstantDecl>(PrevDecl)) 14011 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 14012 else 14013 Diag(IdLoc, diag::err_redefinition) << Id; 14014 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 14015 return nullptr; 14016 } 14017 } 14018 14019 // C++ [class.mem]p15: 14020 // If T is the name of a class, then each of the following shall have a name 14021 // different from T: 14022 // - every enumerator of every member of class T that is an unscoped 14023 // enumerated type 14024 if (!TheEnumDecl->isScoped()) 14025 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(), 14026 DeclarationNameInfo(Id, IdLoc)); 14027 14028 EnumConstantDecl *New = 14029 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 14030 14031 if (New) { 14032 // Process attributes. 14033 if (Attr) ProcessDeclAttributeList(S, New, Attr); 14034 14035 // Register this decl in the current scope stack. 14036 New->setAccess(TheEnumDecl->getAccess()); 14037 PushOnScopeChains(New, S); 14038 } 14039 14040 ActOnDocumentableDecl(New); 14041 14042 return New; 14043 } 14044 14045 // Returns true when the enum initial expression does not trigger the 14046 // duplicate enum warning. A few common cases are exempted as follows: 14047 // Element2 = Element1 14048 // Element2 = Element1 + 1 14049 // Element2 = Element1 - 1 14050 // Where Element2 and Element1 are from the same enum. 14051 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 14052 Expr *InitExpr = ECD->getInitExpr(); 14053 if (!InitExpr) 14054 return true; 14055 InitExpr = InitExpr->IgnoreImpCasts(); 14056 14057 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 14058 if (!BO->isAdditiveOp()) 14059 return true; 14060 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 14061 if (!IL) 14062 return true; 14063 if (IL->getValue() != 1) 14064 return true; 14065 14066 InitExpr = BO->getLHS(); 14067 } 14068 14069 // This checks if the elements are from the same enum. 14070 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 14071 if (!DRE) 14072 return true; 14073 14074 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 14075 if (!EnumConstant) 14076 return true; 14077 14078 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 14079 Enum) 14080 return true; 14081 14082 return false; 14083 } 14084 14085 namespace { 14086 struct DupKey { 14087 int64_t val; 14088 bool isTombstoneOrEmptyKey; 14089 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 14090 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 14091 }; 14092 14093 static DupKey GetDupKey(const llvm::APSInt& Val) { 14094 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 14095 false); 14096 } 14097 14098 struct DenseMapInfoDupKey { 14099 static DupKey getEmptyKey() { return DupKey(0, true); } 14100 static DupKey getTombstoneKey() { return DupKey(1, true); } 14101 static unsigned getHashValue(const DupKey Key) { 14102 return (unsigned)(Key.val * 37); 14103 } 14104 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 14105 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 14106 LHS.val == RHS.val; 14107 } 14108 }; 14109 } // end anonymous namespace 14110 14111 // Emits a warning when an element is implicitly set a value that 14112 // a previous element has already been set to. 14113 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 14114 EnumDecl *Enum, 14115 QualType EnumType) { 14116 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 14117 return; 14118 // Avoid anonymous enums 14119 if (!Enum->getIdentifier()) 14120 return; 14121 14122 // Only check for small enums. 14123 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 14124 return; 14125 14126 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 14127 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 14128 14129 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 14130 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 14131 ValueToVectorMap; 14132 14133 DuplicatesVector DupVector; 14134 ValueToVectorMap EnumMap; 14135 14136 // Populate the EnumMap with all values represented by enum constants without 14137 // an initialier. 14138 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14139 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 14140 14141 // Null EnumConstantDecl means a previous diagnostic has been emitted for 14142 // this constant. Skip this enum since it may be ill-formed. 14143 if (!ECD) { 14144 return; 14145 } 14146 14147 if (ECD->getInitExpr()) 14148 continue; 14149 14150 DupKey Key = GetDupKey(ECD->getInitVal()); 14151 DeclOrVector &Entry = EnumMap[Key]; 14152 14153 // First time encountering this value. 14154 if (Entry.isNull()) 14155 Entry = ECD; 14156 } 14157 14158 // Create vectors for any values that has duplicates. 14159 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14160 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 14161 if (!ValidDuplicateEnum(ECD, Enum)) 14162 continue; 14163 14164 DupKey Key = GetDupKey(ECD->getInitVal()); 14165 14166 DeclOrVector& Entry = EnumMap[Key]; 14167 if (Entry.isNull()) 14168 continue; 14169 14170 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 14171 // Ensure constants are different. 14172 if (D == ECD) 14173 continue; 14174 14175 // Create new vector and push values onto it. 14176 ECDVector *Vec = new ECDVector(); 14177 Vec->push_back(D); 14178 Vec->push_back(ECD); 14179 14180 // Update entry to point to the duplicates vector. 14181 Entry = Vec; 14182 14183 // Store the vector somewhere we can consult later for quick emission of 14184 // diagnostics. 14185 DupVector.push_back(Vec); 14186 continue; 14187 } 14188 14189 ECDVector *Vec = Entry.get<ECDVector*>(); 14190 // Make sure constants are not added more than once. 14191 if (*Vec->begin() == ECD) 14192 continue; 14193 14194 Vec->push_back(ECD); 14195 } 14196 14197 // Emit diagnostics. 14198 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 14199 DupVectorEnd = DupVector.end(); 14200 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 14201 ECDVector *Vec = *DupVectorIter; 14202 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 14203 14204 // Emit warning for one enum constant. 14205 ECDVector::iterator I = Vec->begin(); 14206 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 14207 << (*I)->getName() << (*I)->getInitVal().toString(10) 14208 << (*I)->getSourceRange(); 14209 ++I; 14210 14211 // Emit one note for each of the remaining enum constants with 14212 // the same value. 14213 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 14214 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 14215 << (*I)->getName() << (*I)->getInitVal().toString(10) 14216 << (*I)->getSourceRange(); 14217 delete Vec; 14218 } 14219 } 14220 14221 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 14222 bool AllowMask) const { 14223 assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum"); 14224 assert(ED->isCompleteDefinition() && "expected enum definition"); 14225 14226 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt())); 14227 llvm::APInt &FlagBits = R.first->second; 14228 14229 if (R.second) { 14230 for (auto *E : ED->enumerators()) { 14231 const auto &EVal = E->getInitVal(); 14232 // Only single-bit enumerators introduce new flag values. 14233 if (EVal.isPowerOf2()) 14234 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal; 14235 } 14236 } 14237 14238 // A value is in a flag enum if either its bits are a subset of the enum's 14239 // flag bits (the first condition) or we are allowing masks and the same is 14240 // true of its complement (the second condition). When masks are allowed, we 14241 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 14242 // 14243 // While it's true that any value could be used as a mask, the assumption is 14244 // that a mask will have all of the insignificant bits set. Anything else is 14245 // likely a logic error. 14246 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth()); 14247 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val)); 14248 } 14249 14250 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 14251 SourceLocation RBraceLoc, Decl *EnumDeclX, 14252 ArrayRef<Decl *> Elements, 14253 Scope *S, AttributeList *Attr) { 14254 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 14255 QualType EnumType = Context.getTypeDeclType(Enum); 14256 14257 if (Attr) 14258 ProcessDeclAttributeList(S, Enum, Attr); 14259 14260 if (Enum->isDependentType()) { 14261 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14262 EnumConstantDecl *ECD = 14263 cast_or_null<EnumConstantDecl>(Elements[i]); 14264 if (!ECD) continue; 14265 14266 ECD->setType(EnumType); 14267 } 14268 14269 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 14270 return; 14271 } 14272 14273 // TODO: If the result value doesn't fit in an int, it must be a long or long 14274 // long value. ISO C does not support this, but GCC does as an extension, 14275 // emit a warning. 14276 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 14277 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 14278 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 14279 14280 // Verify that all the values are okay, compute the size of the values, and 14281 // reverse the list. 14282 unsigned NumNegativeBits = 0; 14283 unsigned NumPositiveBits = 0; 14284 14285 // Keep track of whether all elements have type int. 14286 bool AllElementsInt = true; 14287 14288 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 14289 EnumConstantDecl *ECD = 14290 cast_or_null<EnumConstantDecl>(Elements[i]); 14291 if (!ECD) continue; // Already issued a diagnostic. 14292 14293 const llvm::APSInt &InitVal = ECD->getInitVal(); 14294 14295 // Keep track of the size of positive and negative values. 14296 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 14297 NumPositiveBits = std::max(NumPositiveBits, 14298 (unsigned)InitVal.getActiveBits()); 14299 else 14300 NumNegativeBits = std::max(NumNegativeBits, 14301 (unsigned)InitVal.getMinSignedBits()); 14302 14303 // Keep track of whether every enum element has type int (very commmon). 14304 if (AllElementsInt) 14305 AllElementsInt = ECD->getType() == Context.IntTy; 14306 } 14307 14308 // Figure out the type that should be used for this enum. 14309 QualType BestType; 14310 unsigned BestWidth; 14311 14312 // C++0x N3000 [conv.prom]p3: 14313 // An rvalue of an unscoped enumeration type whose underlying 14314 // type is not fixed can be converted to an rvalue of the first 14315 // of the following types that can represent all the values of 14316 // the enumeration: int, unsigned int, long int, unsigned long 14317 // int, long long int, or unsigned long long int. 14318 // C99 6.4.4.3p2: 14319 // An identifier declared as an enumeration constant has type int. 14320 // The C99 rule is modified by a gcc extension 14321 QualType BestPromotionType; 14322 14323 bool Packed = Enum->hasAttr<PackedAttr>(); 14324 // -fshort-enums is the equivalent to specifying the packed attribute on all 14325 // enum definitions. 14326 if (LangOpts.ShortEnums) 14327 Packed = true; 14328 14329 if (Enum->isFixed()) { 14330 BestType = Enum->getIntegerType(); 14331 if (BestType->isPromotableIntegerType()) 14332 BestPromotionType = Context.getPromotedIntegerType(BestType); 14333 else 14334 BestPromotionType = BestType; 14335 14336 BestWidth = Context.getIntWidth(BestType); 14337 } 14338 else if (NumNegativeBits) { 14339 // If there is a negative value, figure out the smallest integer type (of 14340 // int/long/longlong) that fits. 14341 // If it's packed, check also if it fits a char or a short. 14342 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 14343 BestType = Context.SignedCharTy; 14344 BestWidth = CharWidth; 14345 } else if (Packed && NumNegativeBits <= ShortWidth && 14346 NumPositiveBits < ShortWidth) { 14347 BestType = Context.ShortTy; 14348 BestWidth = ShortWidth; 14349 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 14350 BestType = Context.IntTy; 14351 BestWidth = IntWidth; 14352 } else { 14353 BestWidth = Context.getTargetInfo().getLongWidth(); 14354 14355 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 14356 BestType = Context.LongTy; 14357 } else { 14358 BestWidth = Context.getTargetInfo().getLongLongWidth(); 14359 14360 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 14361 Diag(Enum->getLocation(), diag::ext_enum_too_large); 14362 BestType = Context.LongLongTy; 14363 } 14364 } 14365 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 14366 } else { 14367 // If there is no negative value, figure out the smallest type that fits 14368 // all of the enumerator values. 14369 // If it's packed, check also if it fits a char or a short. 14370 if (Packed && NumPositiveBits <= CharWidth) { 14371 BestType = Context.UnsignedCharTy; 14372 BestPromotionType = Context.IntTy; 14373 BestWidth = CharWidth; 14374 } else if (Packed && NumPositiveBits <= ShortWidth) { 14375 BestType = Context.UnsignedShortTy; 14376 BestPromotionType = Context.IntTy; 14377 BestWidth = ShortWidth; 14378 } else if (NumPositiveBits <= IntWidth) { 14379 BestType = Context.UnsignedIntTy; 14380 BestWidth = IntWidth; 14381 BestPromotionType 14382 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14383 ? Context.UnsignedIntTy : Context.IntTy; 14384 } else if (NumPositiveBits <= 14385 (BestWidth = Context.getTargetInfo().getLongWidth())) { 14386 BestType = Context.UnsignedLongTy; 14387 BestPromotionType 14388 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14389 ? Context.UnsignedLongTy : Context.LongTy; 14390 } else { 14391 BestWidth = Context.getTargetInfo().getLongLongWidth(); 14392 assert(NumPositiveBits <= BestWidth && 14393 "How could an initializer get larger than ULL?"); 14394 BestType = Context.UnsignedLongLongTy; 14395 BestPromotionType 14396 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 14397 ? Context.UnsignedLongLongTy : Context.LongLongTy; 14398 } 14399 } 14400 14401 // Loop over all of the enumerator constants, changing their types to match 14402 // the type of the enum if needed. 14403 for (auto *D : Elements) { 14404 auto *ECD = cast_or_null<EnumConstantDecl>(D); 14405 if (!ECD) continue; // Already issued a diagnostic. 14406 14407 // Standard C says the enumerators have int type, but we allow, as an 14408 // extension, the enumerators to be larger than int size. If each 14409 // enumerator value fits in an int, type it as an int, otherwise type it the 14410 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 14411 // that X has type 'int', not 'unsigned'. 14412 14413 // Determine whether the value fits into an int. 14414 llvm::APSInt InitVal = ECD->getInitVal(); 14415 14416 // If it fits into an integer type, force it. Otherwise force it to match 14417 // the enum decl type. 14418 QualType NewTy; 14419 unsigned NewWidth; 14420 bool NewSign; 14421 if (!getLangOpts().CPlusPlus && 14422 !Enum->isFixed() && 14423 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 14424 NewTy = Context.IntTy; 14425 NewWidth = IntWidth; 14426 NewSign = true; 14427 } else if (ECD->getType() == BestType) { 14428 // Already the right type! 14429 if (getLangOpts().CPlusPlus) 14430 // C++ [dcl.enum]p4: Following the closing brace of an 14431 // enum-specifier, each enumerator has the type of its 14432 // enumeration. 14433 ECD->setType(EnumType); 14434 continue; 14435 } else { 14436 NewTy = BestType; 14437 NewWidth = BestWidth; 14438 NewSign = BestType->isSignedIntegerOrEnumerationType(); 14439 } 14440 14441 // Adjust the APSInt value. 14442 InitVal = InitVal.extOrTrunc(NewWidth); 14443 InitVal.setIsSigned(NewSign); 14444 ECD->setInitVal(InitVal); 14445 14446 // Adjust the Expr initializer and type. 14447 if (ECD->getInitExpr() && 14448 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 14449 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 14450 CK_IntegralCast, 14451 ECD->getInitExpr(), 14452 /*base paths*/ nullptr, 14453 VK_RValue)); 14454 if (getLangOpts().CPlusPlus) 14455 // C++ [dcl.enum]p4: Following the closing brace of an 14456 // enum-specifier, each enumerator has the type of its 14457 // enumeration. 14458 ECD->setType(EnumType); 14459 else 14460 ECD->setType(NewTy); 14461 } 14462 14463 Enum->completeDefinition(BestType, BestPromotionType, 14464 NumPositiveBits, NumNegativeBits); 14465 14466 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 14467 14468 if (Enum->hasAttr<FlagEnumAttr>()) { 14469 for (Decl *D : Elements) { 14470 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 14471 if (!ECD) continue; // Already issued a diagnostic. 14472 14473 llvm::APSInt InitVal = ECD->getInitVal(); 14474 if (InitVal != 0 && !InitVal.isPowerOf2() && 14475 !IsValueInFlagEnum(Enum, InitVal, true)) 14476 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 14477 << ECD << Enum; 14478 } 14479 } 14480 14481 // Now that the enum type is defined, ensure it's not been underaligned. 14482 if (Enum->hasAttrs()) 14483 CheckAlignasUnderalignment(Enum); 14484 } 14485 14486 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 14487 SourceLocation StartLoc, 14488 SourceLocation EndLoc) { 14489 StringLiteral *AsmString = cast<StringLiteral>(expr); 14490 14491 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 14492 AsmString, StartLoc, 14493 EndLoc); 14494 CurContext->addDecl(New); 14495 return New; 14496 } 14497 14498 static void checkModuleImportContext(Sema &S, Module *M, 14499 SourceLocation ImportLoc, 14500 DeclContext *DC) { 14501 SourceLocation ExternCLoc; 14502 14503 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 14504 switch (LSD->getLanguage()) { 14505 case LinkageSpecDecl::lang_c: 14506 if (ExternCLoc.isInvalid()) 14507 ExternCLoc = LSD->getLocStart(); 14508 break; 14509 case LinkageSpecDecl::lang_cxx: 14510 break; 14511 } 14512 DC = LSD->getParent(); 14513 } 14514 14515 while (isa<LinkageSpecDecl>(DC)) 14516 DC = DC->getParent(); 14517 14518 if (!isa<TranslationUnitDecl>(DC)) { 14519 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level_fatal) 14520 << M->getFullModuleName() << DC; 14521 S.Diag(cast<Decl>(DC)->getLocStart(), 14522 diag::note_module_import_not_at_top_level) << DC; 14523 } else if (!M->IsExternC && ExternCLoc.isValid()) { 14524 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 14525 << M->getFullModuleName(); 14526 S.Diag(ExternCLoc, diag::note_module_import_in_extern_c); 14527 } 14528 } 14529 14530 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) { 14531 return checkModuleImportContext(*this, M, ImportLoc, CurContext); 14532 } 14533 14534 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 14535 SourceLocation ImportLoc, 14536 ModuleIdPath Path) { 14537 Module *Mod = 14538 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 14539 /*IsIncludeDirective=*/false); 14540 if (!Mod) 14541 return true; 14542 14543 VisibleModules.setVisible(Mod, ImportLoc); 14544 14545 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 14546 14547 // FIXME: we should support importing a submodule within a different submodule 14548 // of the same top-level module. Until we do, make it an error rather than 14549 // silently ignoring the import. 14550 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 14551 Diag(ImportLoc, diag::err_module_self_import) 14552 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 14553 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule) 14554 Diag(ImportLoc, diag::err_module_import_in_implementation) 14555 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule; 14556 14557 SmallVector<SourceLocation, 2> IdentifierLocs; 14558 Module *ModCheck = Mod; 14559 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 14560 // If we've run out of module parents, just drop the remaining identifiers. 14561 // We need the length to be consistent. 14562 if (!ModCheck) 14563 break; 14564 ModCheck = ModCheck->Parent; 14565 14566 IdentifierLocs.push_back(Path[I].second); 14567 } 14568 14569 ImportDecl *Import = ImportDecl::Create(Context, 14570 Context.getTranslationUnitDecl(), 14571 AtLoc.isValid()? AtLoc : ImportLoc, 14572 Mod, IdentifierLocs); 14573 Context.getTranslationUnitDecl()->addDecl(Import); 14574 return Import; 14575 } 14576 14577 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 14578 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14579 14580 // Determine whether we're in the #include buffer for a module. The #includes 14581 // in that buffer do not qualify as module imports; they're just an 14582 // implementation detail of us building the module. 14583 // 14584 // FIXME: Should we even get ActOnModuleInclude calls for those? 14585 bool IsInModuleIncludes = 14586 TUKind == TU_Module && 14587 getSourceManager().isWrittenInMainFile(DirectiveLoc); 14588 14589 // If this module import was due to an inclusion directive, create an 14590 // implicit import declaration to capture it in the AST. 14591 if (!IsInModuleIncludes) { 14592 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14593 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14594 DirectiveLoc, Mod, 14595 DirectiveLoc); 14596 TU->addDecl(ImportD); 14597 Consumer.HandleImplicitImportDecl(ImportD); 14598 } 14599 14600 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 14601 VisibleModules.setVisible(Mod, DirectiveLoc); 14602 } 14603 14604 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 14605 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14606 14607 if (getLangOpts().ModulesLocalVisibility) 14608 VisibleModulesStack.push_back(std::move(VisibleModules)); 14609 VisibleModules.setVisible(Mod, DirectiveLoc); 14610 } 14611 14612 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) { 14613 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14614 14615 if (getLangOpts().ModulesLocalVisibility) { 14616 VisibleModules = std::move(VisibleModulesStack.back()); 14617 VisibleModulesStack.pop_back(); 14618 VisibleModules.setVisible(Mod, DirectiveLoc); 14619 } 14620 } 14621 14622 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 14623 Module *Mod) { 14624 // Bail if we're not allowed to implicitly import a module here. 14625 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 14626 return; 14627 14628 // Create the implicit import declaration. 14629 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14630 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14631 Loc, Mod, Loc); 14632 TU->addDecl(ImportD); 14633 Consumer.HandleImplicitImportDecl(ImportD); 14634 14635 // Make the module visible. 14636 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 14637 VisibleModules.setVisible(Mod, Loc); 14638 } 14639 14640 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 14641 IdentifierInfo* AliasName, 14642 SourceLocation PragmaLoc, 14643 SourceLocation NameLoc, 14644 SourceLocation AliasNameLoc) { 14645 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 14646 LookupOrdinaryName); 14647 AsmLabelAttr *Attr = 14648 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc); 14649 14650 // If a declaration that: 14651 // 1) declares a function or a variable 14652 // 2) has external linkage 14653 // already exists, add a label attribute to it. 14654 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 14655 if (isDeclExternC(PrevDecl)) 14656 PrevDecl->addAttr(Attr); 14657 else 14658 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied) 14659 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl; 14660 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers. 14661 } else 14662 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr)); 14663 } 14664 14665 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 14666 SourceLocation PragmaLoc, 14667 SourceLocation NameLoc) { 14668 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 14669 14670 if (PrevDecl) { 14671 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 14672 } else { 14673 (void)WeakUndeclaredIdentifiers.insert( 14674 std::pair<IdentifierInfo*,WeakInfo> 14675 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 14676 } 14677 } 14678 14679 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 14680 IdentifierInfo* AliasName, 14681 SourceLocation PragmaLoc, 14682 SourceLocation NameLoc, 14683 SourceLocation AliasNameLoc) { 14684 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 14685 LookupOrdinaryName); 14686 WeakInfo W = WeakInfo(Name, NameLoc); 14687 14688 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) { 14689 if (!PrevDecl->hasAttr<AliasAttr>()) 14690 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 14691 DeclApplyPragmaWeak(TUScope, ND, W); 14692 } else { 14693 (void)WeakUndeclaredIdentifiers.insert( 14694 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 14695 } 14696 } 14697 14698 Decl *Sema::getObjCDeclContext() const { 14699 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 14700 } 14701 14702 AvailabilityResult Sema::getCurContextAvailability() const { 14703 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 14704 if (!D) 14705 return AR_Available; 14706 14707 // If we are within an Objective-C method, we should consult 14708 // both the availability of the method as well as the 14709 // enclosing class. If the class is (say) deprecated, 14710 // the entire method is considered deprecated from the 14711 // purpose of checking if the current context is deprecated. 14712 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 14713 AvailabilityResult R = MD->getAvailability(); 14714 if (R != AR_Available) 14715 return R; 14716 D = MD->getClassInterface(); 14717 } 14718 // If we are within an Objective-c @implementation, it 14719 // gets the same availability context as the @interface. 14720 else if (const ObjCImplementationDecl *ID = 14721 dyn_cast<ObjCImplementationDecl>(D)) { 14722 D = ID->getClassInterface(); 14723 } 14724 // Recover from user error. 14725 return D ? D->getAvailability() : AR_Available; 14726 } 14727