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 return true; 115 116 case tok::annot_typename: 117 case tok::kw_char16_t: 118 case tok::kw_char32_t: 119 case tok::kw_typeof: 120 case tok::annot_decltype: 121 case tok::kw_decltype: 122 return getLangOpts().CPlusPlus; 123 124 default: 125 break; 126 } 127 128 return false; 129 } 130 131 namespace { 132 enum class UnqualifiedTypeNameLookupResult { 133 NotFound, 134 FoundNonType, 135 FoundType 136 }; 137 } // namespace 138 139 /// \brief Tries to perform unqualified lookup of the type decls in bases for 140 /// dependent class. 141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a 142 /// type decl, \a FoundType if only type decls are found. 143 static UnqualifiedTypeNameLookupResult 144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, 145 SourceLocation NameLoc, 146 const CXXRecordDecl *RD) { 147 if (!RD->hasDefinition()) 148 return UnqualifiedTypeNameLookupResult::NotFound; 149 // Look for type decls in base classes. 150 UnqualifiedTypeNameLookupResult FoundTypeDecl = 151 UnqualifiedTypeNameLookupResult::NotFound; 152 for (const auto &Base : RD->bases()) { 153 const CXXRecordDecl *BaseRD = nullptr; 154 if (auto *BaseTT = Base.getType()->getAs<TagType>()) 155 BaseRD = BaseTT->getAsCXXRecordDecl(); 156 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) { 157 // Look for type decls in dependent base classes that have known primary 158 // templates. 159 if (!TST || !TST->isDependentType()) 160 continue; 161 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 162 if (!TD) 163 continue; 164 auto *BasePrimaryTemplate = 165 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl()); 166 if (!BasePrimaryTemplate) 167 continue; 168 BaseRD = BasePrimaryTemplate; 169 } 170 if (BaseRD) { 171 for (NamedDecl *ND : BaseRD->lookup(&II)) { 172 if (!isa<TypeDecl>(ND)) 173 return UnqualifiedTypeNameLookupResult::FoundNonType; 174 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 175 } 176 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) { 177 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) { 178 case UnqualifiedTypeNameLookupResult::FoundNonType: 179 return UnqualifiedTypeNameLookupResult::FoundNonType; 180 case UnqualifiedTypeNameLookupResult::FoundType: 181 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType; 182 break; 183 case UnqualifiedTypeNameLookupResult::NotFound: 184 break; 185 } 186 } 187 } 188 } 189 190 return FoundTypeDecl; 191 } 192 193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 194 const IdentifierInfo &II, 195 SourceLocation NameLoc) { 196 // Lookup in the parent class template context, if any. 197 const CXXRecordDecl *RD = nullptr; 198 UnqualifiedTypeNameLookupResult FoundTypeDecl = 199 UnqualifiedTypeNameLookupResult::NotFound; 200 for (DeclContext *DC = S.CurContext; 201 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound; 202 DC = DC->getParent()) { 203 // Look for type decls in dependent base classes that have known primary 204 // templates. 205 RD = dyn_cast<CXXRecordDecl>(DC); 206 if (RD && RD->getDescribedClassTemplate()) 207 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD); 208 } 209 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType) 210 return ParsedType(); 211 212 // We found some types in dependent base classes. Recover as if the user 213 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 214 // lookup during template instantiation. 215 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 216 217 ASTContext &Context = S.Context; 218 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 219 cast<Type>(Context.getRecordType(RD))); 220 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 221 222 CXXScopeSpec SS; 223 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 224 225 TypeLocBuilder Builder; 226 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 227 DepTL.setNameLoc(NameLoc); 228 DepTL.setElaboratedKeywordLoc(SourceLocation()); 229 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 230 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 231 } 232 233 /// \brief If the identifier refers to a type name within this scope, 234 /// return the declaration of that type. 235 /// 236 /// This routine performs ordinary name lookup of the identifier II 237 /// within the given scope, with optional C++ scope specifier SS, to 238 /// determine whether the name refers to a type. If so, returns an 239 /// opaque pointer (actually a QualType) corresponding to that 240 /// type. Otherwise, returns NULL. 241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 242 Scope *S, CXXScopeSpec *SS, 243 bool isClassName, bool HasTrailingDot, 244 ParsedType ObjectTypePtr, 245 bool IsCtorOrDtorName, 246 bool WantNontrivialTypeSourceInfo, 247 IdentifierInfo **CorrectedII) { 248 // Determine where we will perform name lookup. 249 DeclContext *LookupCtx = nullptr; 250 if (ObjectTypePtr) { 251 QualType ObjectType = ObjectTypePtr.get(); 252 if (ObjectType->isRecordType()) 253 LookupCtx = computeDeclContext(ObjectType); 254 } else if (SS && SS->isNotEmpty()) { 255 LookupCtx = computeDeclContext(*SS, false); 256 257 if (!LookupCtx) { 258 if (isDependentScopeSpecifier(*SS)) { 259 // C++ [temp.res]p3: 260 // A qualified-id that refers to a type and in which the 261 // nested-name-specifier depends on a template-parameter (14.6.2) 262 // shall be prefixed by the keyword typename to indicate that the 263 // qualified-id denotes a type, forming an 264 // elaborated-type-specifier (7.1.5.3). 265 // 266 // We therefore do not perform any name lookup if the result would 267 // refer to a member of an unknown specialization. 268 if (!isClassName && !IsCtorOrDtorName) 269 return ParsedType(); 270 271 // We know from the grammar that this name refers to a type, 272 // so build a dependent node to describe the type. 273 if (WantNontrivialTypeSourceInfo) 274 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 275 276 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 277 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 278 II, NameLoc); 279 return ParsedType::make(T); 280 } 281 282 return ParsedType(); 283 } 284 285 if (!LookupCtx->isDependentContext() && 286 RequireCompleteDeclContext(*SS, LookupCtx)) 287 return ParsedType(); 288 } 289 290 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 291 // lookup for class-names. 292 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 293 LookupOrdinaryName; 294 LookupResult Result(*this, &II, NameLoc, Kind); 295 if (LookupCtx) { 296 // Perform "qualified" name lookup into the declaration context we 297 // computed, which is either the type of the base of a member access 298 // expression or the declaration context associated with a prior 299 // nested-name-specifier. 300 LookupQualifiedName(Result, LookupCtx); 301 302 if (ObjectTypePtr && Result.empty()) { 303 // C++ [basic.lookup.classref]p3: 304 // If the unqualified-id is ~type-name, the type-name is looked up 305 // in the context of the entire postfix-expression. If the type T of 306 // the object expression is of a class type C, the type-name is also 307 // looked up in the scope of class C. At least one of the lookups shall 308 // find a name that refers to (possibly cv-qualified) T. 309 LookupName(Result, S); 310 } 311 } else { 312 // Perform unqualified name lookup. 313 LookupName(Result, S); 314 315 // For unqualified lookup in a class template in MSVC mode, look into 316 // dependent base classes where the primary class template is known. 317 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 318 if (ParsedType TypeInBase = 319 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 320 return TypeInBase; 321 } 322 } 323 324 NamedDecl *IIDecl = nullptr; 325 switch (Result.getResultKind()) { 326 case LookupResult::NotFound: 327 case LookupResult::NotFoundInCurrentInstantiation: 328 if (CorrectedII) { 329 TypoCorrection Correction = CorrectTypo( 330 Result.getLookupNameInfo(), Kind, S, SS, 331 llvm::make_unique<TypeNameValidatorCCC>(true, isClassName), 332 CTK_ErrorRecovery); 333 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 334 TemplateTy Template; 335 bool MemberOfUnknownSpecialization; 336 UnqualifiedId TemplateName; 337 TemplateName.setIdentifier(NewII, NameLoc); 338 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 339 CXXScopeSpec NewSS, *NewSSPtr = SS; 340 if (SS && NNS) { 341 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 342 NewSSPtr = &NewSS; 343 } 344 if (Correction && (NNS || NewII != &II) && 345 // Ignore a correction to a template type as the to-be-corrected 346 // identifier is not a template (typo correction for template names 347 // is handled elsewhere). 348 !(getLangOpts().CPlusPlus && NewSSPtr && 349 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 350 false, Template, MemberOfUnknownSpecialization))) { 351 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 352 isClassName, HasTrailingDot, ObjectTypePtr, 353 IsCtorOrDtorName, 354 WantNontrivialTypeSourceInfo); 355 if (Ty) { 356 diagnoseTypo(Correction, 357 PDiag(diag::err_unknown_type_or_class_name_suggest) 358 << Result.getLookupName() << isClassName); 359 if (SS && NNS) 360 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 361 *CorrectedII = NewII; 362 return Ty; 363 } 364 } 365 } 366 // If typo correction failed or was not performed, fall through 367 case LookupResult::FoundOverloaded: 368 case LookupResult::FoundUnresolvedValue: 369 Result.suppressDiagnostics(); 370 return ParsedType(); 371 372 case LookupResult::Ambiguous: 373 // Recover from type-hiding ambiguities by hiding the type. We'll 374 // do the lookup again when looking for an object, and we can 375 // diagnose the error then. If we don't do this, then the error 376 // about hiding the type will be immediately followed by an error 377 // that only makes sense if the identifier was treated like a type. 378 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 379 Result.suppressDiagnostics(); 380 return ParsedType(); 381 } 382 383 // Look to see if we have a type anywhere in the list of results. 384 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 385 Res != ResEnd; ++Res) { 386 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 387 if (!IIDecl || 388 (*Res)->getLocation().getRawEncoding() < 389 IIDecl->getLocation().getRawEncoding()) 390 IIDecl = *Res; 391 } 392 } 393 394 if (!IIDecl) { 395 // None of the entities we found is a type, so there is no way 396 // to even assume that the result is a type. In this case, don't 397 // complain about the ambiguity. The parser will either try to 398 // perform this lookup again (e.g., as an object name), which 399 // will produce the ambiguity, or will complain that it expected 400 // a type name. 401 Result.suppressDiagnostics(); 402 return ParsedType(); 403 } 404 405 // We found a type within the ambiguous lookup; diagnose the 406 // ambiguity and then return that type. This might be the right 407 // answer, or it might not be, but it suppresses any attempt to 408 // perform the name lookup again. 409 break; 410 411 case LookupResult::Found: 412 IIDecl = Result.getFoundDecl(); 413 break; 414 } 415 416 assert(IIDecl && "Didn't find decl"); 417 418 QualType T; 419 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 420 DiagnoseUseOfDecl(IIDecl, NameLoc); 421 422 T = Context.getTypeDeclType(TD); 423 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 424 425 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 426 // constructor or destructor name (in such a case, the scope specifier 427 // will be attached to the enclosing Expr or Decl node). 428 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 429 if (WantNontrivialTypeSourceInfo) { 430 // Construct a type with type-source information. 431 TypeLocBuilder Builder; 432 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 433 434 T = getElaboratedType(ETK_None, *SS, T); 435 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 436 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 437 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 438 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 439 } else { 440 T = getElaboratedType(ETK_None, *SS, T); 441 } 442 } 443 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 444 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 445 if (!HasTrailingDot) 446 T = Context.getObjCInterfaceType(IDecl); 447 } 448 449 if (T.isNull()) { 450 // If it's not plausibly a type, suppress diagnostics. 451 Result.suppressDiagnostics(); 452 return ParsedType(); 453 } 454 return ParsedType::make(T); 455 } 456 457 // Builds a fake NNS for the given decl context. 458 static NestedNameSpecifier * 459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 460 for (;; DC = DC->getLookupParent()) { 461 DC = DC->getPrimaryContext(); 462 auto *ND = dyn_cast<NamespaceDecl>(DC); 463 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 464 return NestedNameSpecifier::Create(Context, nullptr, ND); 465 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 466 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 467 RD->getTypeForDecl()); 468 else if (isa<TranslationUnitDecl>(DC)) 469 return NestedNameSpecifier::GlobalSpecifier(Context); 470 } 471 llvm_unreachable("something isn't in TU scope?"); 472 } 473 474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 475 SourceLocation NameLoc) { 476 // Accepting an undeclared identifier as a default argument for a template 477 // type parameter is a Microsoft extension. 478 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 479 480 // Build a fake DependentNameType that will perform lookup into CurContext at 481 // instantiation time. The name specifier isn't dependent, so template 482 // instantiation won't transform it. It will retry the lookup, however. 483 NestedNameSpecifier *NNS = 484 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 485 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 486 487 // Build type location information. We synthesized the qualifier, so we have 488 // to build a fake NestedNameSpecifierLoc. 489 NestedNameSpecifierLocBuilder NNSLocBuilder; 490 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 491 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 492 493 TypeLocBuilder Builder; 494 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 495 DepTL.setNameLoc(NameLoc); 496 DepTL.setElaboratedKeywordLoc(SourceLocation()); 497 DepTL.setQualifierLoc(QualifierLoc); 498 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 499 } 500 501 /// isTagName() - This method is called *for error recovery purposes only* 502 /// to determine if the specified name is a valid tag name ("struct foo"). If 503 /// so, this returns the TST for the tag corresponding to it (TST_enum, 504 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 505 /// cases in C where the user forgot to specify the tag. 506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 507 // Do a tag name lookup in this scope. 508 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 509 LookupName(R, S, false); 510 R.suppressDiagnostics(); 511 if (R.getResultKind() == LookupResult::Found) 512 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 513 switch (TD->getTagKind()) { 514 case TTK_Struct: return DeclSpec::TST_struct; 515 case TTK_Interface: return DeclSpec::TST_interface; 516 case TTK_Union: return DeclSpec::TST_union; 517 case TTK_Class: return DeclSpec::TST_class; 518 case TTK_Enum: return DeclSpec::TST_enum; 519 } 520 } 521 522 return DeclSpec::TST_unspecified; 523 } 524 525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 527 /// then downgrade the missing typename error to a warning. 528 /// This is needed for MSVC compatibility; Example: 529 /// @code 530 /// template<class T> class A { 531 /// public: 532 /// typedef int TYPE; 533 /// }; 534 /// template<class T> class B : public A<T> { 535 /// public: 536 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 537 /// }; 538 /// @endcode 539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 540 if (CurContext->isRecord()) { 541 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 542 return true; 543 544 const Type *Ty = SS->getScopeRep()->getAsType(); 545 546 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 547 for (const auto &Base : RD->bases()) 548 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 549 return true; 550 return S->isFunctionPrototypeScope(); 551 } 552 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 553 } 554 555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 556 SourceLocation IILoc, 557 Scope *S, 558 CXXScopeSpec *SS, 559 ParsedType &SuggestedType, 560 bool AllowClassTemplates) { 561 // We don't have anything to suggest (yet). 562 SuggestedType = ParsedType(); 563 564 // There may have been a typo in the name of the type. Look up typo 565 // results, in case we have something that we can suggest. 566 if (TypoCorrection Corrected = 567 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS, 568 llvm::make_unique<TypeNameValidatorCCC>( 569 false, false, AllowClassTemplates), 570 CTK_ErrorRecovery)) { 571 if (Corrected.isKeyword()) { 572 // We corrected to a keyword. 573 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 574 II = Corrected.getCorrectionAsIdentifierInfo(); 575 } else { 576 // We found a similarly-named type or interface; suggest that. 577 if (!SS || !SS->isSet()) { 578 diagnoseTypo(Corrected, 579 PDiag(diag::err_unknown_typename_suggest) << II); 580 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 581 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 582 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 583 II->getName().equals(CorrectedStr); 584 diagnoseTypo(Corrected, 585 PDiag(diag::err_unknown_nested_typename_suggest) 586 << II << DC << DroppedSpecifier << SS->getRange()); 587 } else { 588 llvm_unreachable("could not have corrected a typo here"); 589 } 590 591 CXXScopeSpec tmpSS; 592 if (Corrected.getCorrectionSpecifier()) 593 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 594 SourceRange(IILoc)); 595 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 596 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 597 false, ParsedType(), 598 /*IsCtorOrDtorName=*/false, 599 /*NonTrivialTypeSourceInfo=*/true); 600 } 601 return; 602 } 603 604 if (getLangOpts().CPlusPlus) { 605 // See if II is a class template that the user forgot to pass arguments to. 606 UnqualifiedId Name; 607 Name.setIdentifier(II, IILoc); 608 CXXScopeSpec EmptySS; 609 TemplateTy TemplateResult; 610 bool MemberOfUnknownSpecialization; 611 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 612 Name, ParsedType(), true, TemplateResult, 613 MemberOfUnknownSpecialization) == TNK_Type_template) { 614 TemplateName TplName = TemplateResult.get(); 615 Diag(IILoc, diag::err_template_missing_args) << TplName; 616 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 617 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 618 << TplDecl->getTemplateParameters()->getSourceRange(); 619 } 620 return; 621 } 622 } 623 624 // FIXME: Should we move the logic that tries to recover from a missing tag 625 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 626 627 if (!SS || (!SS->isSet() && !SS->isInvalid())) 628 Diag(IILoc, diag::err_unknown_typename) << II; 629 else if (DeclContext *DC = computeDeclContext(*SS, false)) 630 Diag(IILoc, diag::err_typename_nested_not_found) 631 << II << DC << SS->getRange(); 632 else if (isDependentScopeSpecifier(*SS)) { 633 unsigned DiagID = diag::err_typename_missing; 634 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 635 DiagID = diag::ext_typename_missing; 636 637 Diag(SS->getRange().getBegin(), DiagID) 638 << SS->getScopeRep() << II->getName() 639 << SourceRange(SS->getRange().getBegin(), IILoc) 640 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 641 SuggestedType = ActOnTypenameType(S, SourceLocation(), 642 *SS, *II, IILoc).get(); 643 } else { 644 assert(SS && SS->isInvalid() && 645 "Invalid scope specifier has already been diagnosed"); 646 } 647 } 648 649 /// \brief Determine whether the given result set contains either a type name 650 /// or 651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 652 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 653 NextToken.is(tok::less); 654 655 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 656 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 657 return true; 658 659 if (CheckTemplate && isa<TemplateDecl>(*I)) 660 return true; 661 } 662 663 return false; 664 } 665 666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 667 Scope *S, CXXScopeSpec &SS, 668 IdentifierInfo *&Name, 669 SourceLocation NameLoc) { 670 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 671 SemaRef.LookupParsedName(R, S, &SS); 672 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 673 StringRef FixItTagName; 674 switch (Tag->getTagKind()) { 675 case TTK_Class: 676 FixItTagName = "class "; 677 break; 678 679 case TTK_Enum: 680 FixItTagName = "enum "; 681 break; 682 683 case TTK_Struct: 684 FixItTagName = "struct "; 685 break; 686 687 case TTK_Interface: 688 FixItTagName = "__interface "; 689 break; 690 691 case TTK_Union: 692 FixItTagName = "union "; 693 break; 694 } 695 696 StringRef TagName = FixItTagName.drop_back(); 697 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 698 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 699 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 700 701 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 702 I != IEnd; ++I) 703 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 704 << Name << TagName; 705 706 // Replace lookup results with just the tag decl. 707 Result.clear(Sema::LookupTagName); 708 SemaRef.LookupParsedName(Result, S, &SS); 709 return true; 710 } 711 712 return false; 713 } 714 715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 717 QualType T, SourceLocation NameLoc) { 718 ASTContext &Context = S.Context; 719 720 TypeLocBuilder Builder; 721 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 722 723 T = S.getElaboratedType(ETK_None, SS, T); 724 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 725 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 726 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 727 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 728 } 729 730 Sema::NameClassification 731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, 732 SourceLocation NameLoc, const Token &NextToken, 733 bool IsAddressOfOperand, 734 std::unique_ptr<CorrectionCandidateCallback> CCC) { 735 DeclarationNameInfo NameInfo(Name, NameLoc); 736 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 737 738 if (NextToken.is(tok::coloncolon)) { 739 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 740 QualType(), false, SS, nullptr, false); 741 } 742 743 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 744 LookupParsedName(Result, S, &SS, !CurMethod); 745 746 // For unqualified lookup in a class template in MSVC mode, look into 747 // dependent base classes where the primary class template is known. 748 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 749 if (ParsedType TypeInBase = 750 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 751 return TypeInBase; 752 } 753 754 // Perform lookup for Objective-C instance variables (including automatically 755 // synthesized instance variables), if we're in an Objective-C method. 756 // FIXME: This lookup really, really needs to be folded in to the normal 757 // unqualified lookup mechanism. 758 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 759 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 760 if (E.get() || E.isInvalid()) 761 return E; 762 } 763 764 bool SecondTry = false; 765 bool IsFilteredTemplateName = false; 766 767 Corrected: 768 switch (Result.getResultKind()) { 769 case LookupResult::NotFound: 770 // If an unqualified-id is followed by a '(', then we have a function 771 // call. 772 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 773 // In C++, this is an ADL-only call. 774 // FIXME: Reference? 775 if (getLangOpts().CPlusPlus) 776 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 777 778 // C90 6.3.2.2: 779 // If the expression that precedes the parenthesized argument list in a 780 // function call consists solely of an identifier, and if no 781 // declaration is visible for this identifier, the identifier is 782 // implicitly declared exactly as if, in the innermost block containing 783 // the function call, the declaration 784 // 785 // extern int identifier (); 786 // 787 // appeared. 788 // 789 // We also allow this in C99 as an extension. 790 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 791 Result.addDecl(D); 792 Result.resolveKind(); 793 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 794 } 795 } 796 797 // In C, we first see whether there is a tag type by the same name, in 798 // which case it's likely that the user just forget to write "enum", 799 // "struct", or "union". 800 if (!getLangOpts().CPlusPlus && !SecondTry && 801 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 802 break; 803 } 804 805 // Perform typo correction to determine if there is another name that is 806 // close to this name. 807 if (!SecondTry && CCC) { 808 SecondTry = true; 809 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 810 Result.getLookupKind(), S, 811 &SS, std::move(CCC), 812 CTK_ErrorRecovery)) { 813 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 814 unsigned QualifiedDiag = diag::err_no_member_suggest; 815 816 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 817 NamedDecl *UnderlyingFirstDecl 818 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr; 819 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 820 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 821 UnqualifiedDiag = diag::err_no_template_suggest; 822 QualifiedDiag = diag::err_no_member_template_suggest; 823 } else if (UnderlyingFirstDecl && 824 (isa<TypeDecl>(UnderlyingFirstDecl) || 825 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 826 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 827 UnqualifiedDiag = diag::err_unknown_typename_suggest; 828 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 829 } 830 831 if (SS.isEmpty()) { 832 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 833 } else {// FIXME: is this even reachable? Test it. 834 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 835 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 836 Name->getName().equals(CorrectedStr); 837 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 838 << Name << computeDeclContext(SS, false) 839 << DroppedSpecifier << SS.getRange()); 840 } 841 842 // Update the name, so that the caller has the new name. 843 Name = Corrected.getCorrectionAsIdentifierInfo(); 844 845 // Typo correction corrected to a keyword. 846 if (Corrected.isKeyword()) 847 return Name; 848 849 // Also update the LookupResult... 850 // FIXME: This should probably go away at some point 851 Result.clear(); 852 Result.setLookupName(Corrected.getCorrection()); 853 if (FirstDecl) 854 Result.addDecl(FirstDecl); 855 856 // If we found an Objective-C instance variable, let 857 // LookupInObjCMethod build the appropriate expression to 858 // reference the ivar. 859 // FIXME: This is a gross hack. 860 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 861 Result.clear(); 862 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 863 return E; 864 } 865 866 goto Corrected; 867 } 868 } 869 870 // We failed to correct; just fall through and let the parser deal with it. 871 Result.suppressDiagnostics(); 872 return NameClassification::Unknown(); 873 874 case LookupResult::NotFoundInCurrentInstantiation: { 875 // We performed name lookup into the current instantiation, and there were 876 // dependent bases, so we treat this result the same way as any other 877 // dependent nested-name-specifier. 878 879 // C++ [temp.res]p2: 880 // A name used in a template declaration or definition and that is 881 // dependent on a template-parameter is assumed not to name a type 882 // unless the applicable name lookup finds a type name or the name is 883 // qualified by the keyword typename. 884 // 885 // FIXME: If the next token is '<', we might want to ask the parser to 886 // perform some heroics to see if we actually have a 887 // template-argument-list, which would indicate a missing 'template' 888 // keyword here. 889 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 890 NameInfo, IsAddressOfOperand, 891 /*TemplateArgs=*/nullptr); 892 } 893 894 case LookupResult::Found: 895 case LookupResult::FoundOverloaded: 896 case LookupResult::FoundUnresolvedValue: 897 break; 898 899 case LookupResult::Ambiguous: 900 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 901 hasAnyAcceptableTemplateNames(Result)) { 902 // C++ [temp.local]p3: 903 // A lookup that finds an injected-class-name (10.2) can result in an 904 // ambiguity in certain cases (for example, if it is found in more than 905 // one base class). If all of the injected-class-names that are found 906 // refer to specializations of the same class template, and if the name 907 // is followed by a template-argument-list, the reference refers to the 908 // class template itself and not a specialization thereof, and is not 909 // ambiguous. 910 // 911 // This filtering can make an ambiguous result into an unambiguous one, 912 // so try again after filtering out template names. 913 FilterAcceptableTemplateNames(Result); 914 if (!Result.isAmbiguous()) { 915 IsFilteredTemplateName = true; 916 break; 917 } 918 } 919 920 // Diagnose the ambiguity and return an error. 921 return NameClassification::Error(); 922 } 923 924 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 925 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 926 // C++ [temp.names]p3: 927 // After name lookup (3.4) finds that a name is a template-name or that 928 // an operator-function-id or a literal- operator-id refers to a set of 929 // overloaded functions any member of which is a function template if 930 // this is followed by a <, the < is always taken as the delimiter of a 931 // template-argument-list and never as the less-than operator. 932 if (!IsFilteredTemplateName) 933 FilterAcceptableTemplateNames(Result); 934 935 if (!Result.empty()) { 936 bool IsFunctionTemplate; 937 bool IsVarTemplate; 938 TemplateName Template; 939 if (Result.end() - Result.begin() > 1) { 940 IsFunctionTemplate = true; 941 Template = Context.getOverloadedTemplateName(Result.begin(), 942 Result.end()); 943 } else { 944 TemplateDecl *TD 945 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 946 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 947 IsVarTemplate = isa<VarTemplateDecl>(TD); 948 949 if (SS.isSet() && !SS.isInvalid()) 950 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 951 /*TemplateKeyword=*/false, 952 TD); 953 else 954 Template = TemplateName(TD); 955 } 956 957 if (IsFunctionTemplate) { 958 // Function templates always go through overload resolution, at which 959 // point we'll perform the various checks (e.g., accessibility) we need 960 // to based on which function we selected. 961 Result.suppressDiagnostics(); 962 963 return NameClassification::FunctionTemplate(Template); 964 } 965 966 return IsVarTemplate ? NameClassification::VarTemplate(Template) 967 : NameClassification::TypeTemplate(Template); 968 } 969 } 970 971 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 972 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 973 DiagnoseUseOfDecl(Type, NameLoc); 974 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 975 QualType T = Context.getTypeDeclType(Type); 976 if (SS.isNotEmpty()) 977 return buildNestedType(*this, SS, T, NameLoc); 978 return ParsedType::make(T); 979 } 980 981 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 982 if (!Class) { 983 // FIXME: It's unfortunate that we don't have a Type node for handling this. 984 if (ObjCCompatibleAliasDecl *Alias = 985 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 986 Class = Alias->getClassInterface(); 987 } 988 989 if (Class) { 990 DiagnoseUseOfDecl(Class, NameLoc); 991 992 if (NextToken.is(tok::period)) { 993 // Interface. <something> is parsed as a property reference expression. 994 // Just return "unknown" as a fall-through for now. 995 Result.suppressDiagnostics(); 996 return NameClassification::Unknown(); 997 } 998 999 QualType T = Context.getObjCInterfaceType(Class); 1000 return ParsedType::make(T); 1001 } 1002 1003 // We can have a type template here if we're classifying a template argument. 1004 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 1005 return NameClassification::TypeTemplate( 1006 TemplateName(cast<TemplateDecl>(FirstDecl))); 1007 1008 // Check for a tag type hidden by a non-type decl in a few cases where it 1009 // seems likely a type is wanted instead of the non-type that was found. 1010 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 1011 if ((NextToken.is(tok::identifier) || 1012 (NextIsOp && 1013 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 1014 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 1015 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 1016 DiagnoseUseOfDecl(Type, NameLoc); 1017 QualType T = Context.getTypeDeclType(Type); 1018 if (SS.isNotEmpty()) 1019 return buildNestedType(*this, SS, T, NameLoc); 1020 return ParsedType::make(T); 1021 } 1022 1023 if (FirstDecl->isCXXClassMember()) 1024 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 1025 nullptr); 1026 1027 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 1028 return BuildDeclarationNameExpr(SS, Result, ADL); 1029 } 1030 1031 // Determines the context to return to after temporarily entering a 1032 // context. This depends in an unnecessarily complicated way on the 1033 // exact ordering of callbacks from the parser. 1034 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1035 1036 // Functions defined inline within classes aren't parsed until we've 1037 // finished parsing the top-level class, so the top-level class is 1038 // the context we'll need to return to. 1039 // A Lambda call operator whose parent is a class must not be treated 1040 // as an inline member function. A Lambda can be used legally 1041 // either as an in-class member initializer or a default argument. These 1042 // are parsed once the class has been marked complete and so the containing 1043 // context would be the nested class (when the lambda is defined in one); 1044 // If the class is not complete, then the lambda is being used in an 1045 // ill-formed fashion (such as to specify the width of a bit-field, or 1046 // in an array-bound) - in which case we still want to return the 1047 // lexically containing DC (which could be a nested class). 1048 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1049 DC = DC->getLexicalParent(); 1050 1051 // A function not defined within a class will always return to its 1052 // lexical context. 1053 if (!isa<CXXRecordDecl>(DC)) 1054 return DC; 1055 1056 // A C++ inline method/friend is parsed *after* the topmost class 1057 // it was declared in is fully parsed ("complete"); the topmost 1058 // class is the context we need to return to. 1059 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1060 DC = RD; 1061 1062 // Return the declaration context of the topmost class the inline method is 1063 // declared in. 1064 return DC; 1065 } 1066 1067 return DC->getLexicalParent(); 1068 } 1069 1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1071 assert(getContainingDC(DC) == CurContext && 1072 "The next DeclContext should be lexically contained in the current one."); 1073 CurContext = DC; 1074 S->setEntity(DC); 1075 } 1076 1077 void Sema::PopDeclContext() { 1078 assert(CurContext && "DeclContext imbalance!"); 1079 1080 CurContext = getContainingDC(CurContext); 1081 assert(CurContext && "Popped translation unit!"); 1082 } 1083 1084 /// EnterDeclaratorContext - Used when we must lookup names in the context 1085 /// of a declarator's nested name specifier. 1086 /// 1087 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1088 // C++0x [basic.lookup.unqual]p13: 1089 // A name used in the definition of a static data member of class 1090 // X (after the qualified-id of the static member) is looked up as 1091 // if the name was used in a member function of X. 1092 // C++0x [basic.lookup.unqual]p14: 1093 // If a variable member of a namespace is defined outside of the 1094 // scope of its namespace then any name used in the definition of 1095 // the variable member (after the declarator-id) is looked up as 1096 // if the definition of the variable member occurred in its 1097 // namespace. 1098 // Both of these imply that we should push a scope whose context 1099 // is the semantic context of the declaration. We can't use 1100 // PushDeclContext here because that context is not necessarily 1101 // lexically contained in the current context. Fortunately, 1102 // the containing scope should have the appropriate information. 1103 1104 assert(!S->getEntity() && "scope already has entity"); 1105 1106 #ifndef NDEBUG 1107 Scope *Ancestor = S->getParent(); 1108 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1109 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1110 #endif 1111 1112 CurContext = DC; 1113 S->setEntity(DC); 1114 } 1115 1116 void Sema::ExitDeclaratorContext(Scope *S) { 1117 assert(S->getEntity() == CurContext && "Context imbalance!"); 1118 1119 // Switch back to the lexical context. The safety of this is 1120 // enforced by an assert in EnterDeclaratorContext. 1121 Scope *Ancestor = S->getParent(); 1122 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1123 CurContext = Ancestor->getEntity(); 1124 1125 // We don't need to do anything with the scope, which is going to 1126 // disappear. 1127 } 1128 1129 1130 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1131 // We assume that the caller has already called 1132 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1133 FunctionDecl *FD = D->getAsFunction(); 1134 if (!FD) 1135 return; 1136 1137 // Same implementation as PushDeclContext, but enters the context 1138 // from the lexical parent, rather than the top-level class. 1139 assert(CurContext == FD->getLexicalParent() && 1140 "The next DeclContext should be lexically contained in the current one."); 1141 CurContext = FD; 1142 S->setEntity(CurContext); 1143 1144 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1145 ParmVarDecl *Param = FD->getParamDecl(P); 1146 // If the parameter has an identifier, then add it to the scope 1147 if (Param->getIdentifier()) { 1148 S->AddDecl(Param); 1149 IdResolver.AddDecl(Param); 1150 } 1151 } 1152 } 1153 1154 1155 void Sema::ActOnExitFunctionContext() { 1156 // Same implementation as PopDeclContext, but returns to the lexical parent, 1157 // rather than the top-level class. 1158 assert(CurContext && "DeclContext imbalance!"); 1159 CurContext = CurContext->getLexicalParent(); 1160 assert(CurContext && "Popped translation unit!"); 1161 } 1162 1163 1164 /// \brief Determine whether we allow overloading of the function 1165 /// PrevDecl with another declaration. 1166 /// 1167 /// This routine determines whether overloading is possible, not 1168 /// whether some new function is actually an overload. It will return 1169 /// true in C++ (where we can always provide overloads) or, as an 1170 /// extension, in C when the previous function is already an 1171 /// overloaded function declaration or has the "overloadable" 1172 /// attribute. 1173 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1174 ASTContext &Context) { 1175 if (Context.getLangOpts().CPlusPlus) 1176 return true; 1177 1178 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1179 return true; 1180 1181 return (Previous.getResultKind() == LookupResult::Found 1182 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1183 } 1184 1185 /// Add this decl to the scope shadowed decl chains. 1186 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1187 // Move up the scope chain until we find the nearest enclosing 1188 // non-transparent context. The declaration will be introduced into this 1189 // scope. 1190 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1191 S = S->getParent(); 1192 1193 // Add scoped declarations into their context, so that they can be 1194 // found later. Declarations without a context won't be inserted 1195 // into any context. 1196 if (AddToContext) 1197 CurContext->addDecl(D); 1198 1199 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1200 // are function-local declarations. 1201 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1202 !D->getDeclContext()->getRedeclContext()->Equals( 1203 D->getLexicalDeclContext()->getRedeclContext()) && 1204 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1205 return; 1206 1207 // Template instantiations should also not be pushed into scope. 1208 if (isa<FunctionDecl>(D) && 1209 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1210 return; 1211 1212 // If this replaces anything in the current scope, 1213 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1214 IEnd = IdResolver.end(); 1215 for (; I != IEnd; ++I) { 1216 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1217 S->RemoveDecl(*I); 1218 IdResolver.RemoveDecl(*I); 1219 1220 // Should only need to replace one decl. 1221 break; 1222 } 1223 } 1224 1225 S->AddDecl(D); 1226 1227 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1228 // Implicitly-generated labels may end up getting generated in an order that 1229 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1230 // the label at the appropriate place in the identifier chain. 1231 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1232 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1233 if (IDC == CurContext) { 1234 if (!S->isDeclScope(*I)) 1235 continue; 1236 } else if (IDC->Encloses(CurContext)) 1237 break; 1238 } 1239 1240 IdResolver.InsertDeclAfter(I, D); 1241 } else { 1242 IdResolver.AddDecl(D); 1243 } 1244 } 1245 1246 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1247 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1248 TUScope->AddDecl(D); 1249 } 1250 1251 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1252 bool AllowInlineNamespace) { 1253 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1254 } 1255 1256 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1257 DeclContext *TargetDC = DC->getPrimaryContext(); 1258 do { 1259 if (DeclContext *ScopeDC = S->getEntity()) 1260 if (ScopeDC->getPrimaryContext() == TargetDC) 1261 return S; 1262 } while ((S = S->getParent())); 1263 1264 return nullptr; 1265 } 1266 1267 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1268 DeclContext*, 1269 ASTContext&); 1270 1271 /// Filters out lookup results that don't fall within the given scope 1272 /// as determined by isDeclInScope. 1273 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1274 bool ConsiderLinkage, 1275 bool AllowInlineNamespace) { 1276 LookupResult::Filter F = R.makeFilter(); 1277 while (F.hasNext()) { 1278 NamedDecl *D = F.next(); 1279 1280 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1281 continue; 1282 1283 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1284 continue; 1285 1286 F.erase(); 1287 } 1288 1289 F.done(); 1290 } 1291 1292 static bool isUsingDecl(NamedDecl *D) { 1293 return isa<UsingShadowDecl>(D) || 1294 isa<UnresolvedUsingTypenameDecl>(D) || 1295 isa<UnresolvedUsingValueDecl>(D); 1296 } 1297 1298 /// Removes using shadow declarations from the lookup results. 1299 static void RemoveUsingDecls(LookupResult &R) { 1300 LookupResult::Filter F = R.makeFilter(); 1301 while (F.hasNext()) 1302 if (isUsingDecl(F.next())) 1303 F.erase(); 1304 1305 F.done(); 1306 } 1307 1308 /// \brief Check for this common pattern: 1309 /// @code 1310 /// class S { 1311 /// S(const S&); // DO NOT IMPLEMENT 1312 /// void operator=(const S&); // DO NOT IMPLEMENT 1313 /// }; 1314 /// @endcode 1315 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1316 // FIXME: Should check for private access too but access is set after we get 1317 // the decl here. 1318 if (D->doesThisDeclarationHaveABody()) 1319 return false; 1320 1321 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1322 return CD->isCopyConstructor(); 1323 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1324 return Method->isCopyAssignmentOperator(); 1325 return false; 1326 } 1327 1328 // We need this to handle 1329 // 1330 // typedef struct { 1331 // void *foo() { return 0; } 1332 // } A; 1333 // 1334 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1335 // for example. If 'A', foo will have external linkage. If we have '*A', 1336 // foo will have no linkage. Since we can't know until we get to the end 1337 // of the typedef, this function finds out if D might have non-external linkage. 1338 // Callers should verify at the end of the TU if it D has external linkage or 1339 // not. 1340 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1341 const DeclContext *DC = D->getDeclContext(); 1342 while (!DC->isTranslationUnit()) { 1343 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1344 if (!RD->hasNameForLinkage()) 1345 return true; 1346 } 1347 DC = DC->getParent(); 1348 } 1349 1350 return !D->isExternallyVisible(); 1351 } 1352 1353 // FIXME: This needs to be refactored; some other isInMainFile users want 1354 // these semantics. 1355 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1356 if (S.TUKind != TU_Complete) 1357 return false; 1358 return S.SourceMgr.isInMainFile(Loc); 1359 } 1360 1361 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1362 assert(D); 1363 1364 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1365 return false; 1366 1367 // Ignore all entities declared within templates, and out-of-line definitions 1368 // of members of class templates. 1369 if (D->getDeclContext()->isDependentContext() || 1370 D->getLexicalDeclContext()->isDependentContext()) 1371 return false; 1372 1373 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1374 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1375 return false; 1376 1377 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1378 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1379 return false; 1380 } else { 1381 // 'static inline' functions are defined in headers; don't warn. 1382 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1383 return false; 1384 } 1385 1386 if (FD->doesThisDeclarationHaveABody() && 1387 Context.DeclMustBeEmitted(FD)) 1388 return false; 1389 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1390 // Constants and utility variables are defined in headers with internal 1391 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1392 // like "inline".) 1393 if (!isMainFileLoc(*this, VD->getLocation())) 1394 return false; 1395 1396 if (Context.DeclMustBeEmitted(VD)) 1397 return false; 1398 1399 if (VD->isStaticDataMember() && 1400 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1401 return false; 1402 } else { 1403 return false; 1404 } 1405 1406 // Only warn for unused decls internal to the translation unit. 1407 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1408 // for inline functions defined in the main source file, for instance. 1409 return mightHaveNonExternalLinkage(D); 1410 } 1411 1412 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1413 if (!D) 1414 return; 1415 1416 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1417 const FunctionDecl *First = FD->getFirstDecl(); 1418 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1419 return; // First should already be in the vector. 1420 } 1421 1422 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1423 const VarDecl *First = VD->getFirstDecl(); 1424 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1425 return; // First should already be in the vector. 1426 } 1427 1428 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1429 UnusedFileScopedDecls.push_back(D); 1430 } 1431 1432 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1433 if (D->isInvalidDecl()) 1434 return false; 1435 1436 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1437 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1438 return false; 1439 1440 if (isa<LabelDecl>(D)) 1441 return true; 1442 1443 // Except for labels, we only care about unused decls that are local to 1444 // functions. 1445 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1446 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1447 // For dependent types, the diagnostic is deferred. 1448 WithinFunction = 1449 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1450 if (!WithinFunction) 1451 return false; 1452 1453 if (isa<TypedefNameDecl>(D)) 1454 return true; 1455 1456 // White-list anything that isn't a local variable. 1457 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1458 return false; 1459 1460 // Types of valid local variables should be complete, so this should succeed. 1461 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1462 1463 // White-list anything with an __attribute__((unused)) type. 1464 QualType Ty = VD->getType(); 1465 1466 // Only look at the outermost level of typedef. 1467 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1468 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1469 return false; 1470 } 1471 1472 // If we failed to complete the type for some reason, or if the type is 1473 // dependent, don't diagnose the variable. 1474 if (Ty->isIncompleteType() || Ty->isDependentType()) 1475 return false; 1476 1477 if (const TagType *TT = Ty->getAs<TagType>()) { 1478 const TagDecl *Tag = TT->getDecl(); 1479 if (Tag->hasAttr<UnusedAttr>()) 1480 return false; 1481 1482 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1483 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1484 return false; 1485 1486 if (const Expr *Init = VD->getInit()) { 1487 if (const ExprWithCleanups *Cleanups = 1488 dyn_cast<ExprWithCleanups>(Init)) 1489 Init = Cleanups->getSubExpr(); 1490 const CXXConstructExpr *Construct = 1491 dyn_cast<CXXConstructExpr>(Init); 1492 if (Construct && !Construct->isElidable()) { 1493 CXXConstructorDecl *CD = Construct->getConstructor(); 1494 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1495 return false; 1496 } 1497 } 1498 } 1499 } 1500 1501 // TODO: __attribute__((unused)) templates? 1502 } 1503 1504 return true; 1505 } 1506 1507 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1508 FixItHint &Hint) { 1509 if (isa<LabelDecl>(D)) { 1510 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1511 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1512 if (AfterColon.isInvalid()) 1513 return; 1514 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1515 getCharRange(D->getLocStart(), AfterColon)); 1516 } 1517 return; 1518 } 1519 1520 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1521 if (D->getTypeForDecl()->isDependentType()) 1522 return; 1523 1524 for (auto *TmpD : D->decls()) { 1525 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1526 DiagnoseUnusedDecl(T); 1527 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1528 DiagnoseUnusedNestedTypedefs(R); 1529 } 1530 } 1531 1532 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1533 /// unless they are marked attr(unused). 1534 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1535 if (!ShouldDiagnoseUnusedDecl(D)) 1536 return; 1537 1538 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1539 // typedefs can be referenced later on, so the diagnostics are emitted 1540 // at end-of-translation-unit. 1541 UnusedLocalTypedefNameCandidates.insert(TD); 1542 return; 1543 } 1544 1545 FixItHint Hint; 1546 GenerateFixForUnusedDecl(D, Context, Hint); 1547 1548 unsigned DiagID; 1549 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1550 DiagID = diag::warn_unused_exception_param; 1551 else if (isa<LabelDecl>(D)) 1552 DiagID = diag::warn_unused_label; 1553 else 1554 DiagID = diag::warn_unused_variable; 1555 1556 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1557 } 1558 1559 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1560 // Verify that we have no forward references left. If so, there was a goto 1561 // or address of a label taken, but no definition of it. Label fwd 1562 // definitions are indicated with a null substmt which is also not a resolved 1563 // MS inline assembly label name. 1564 bool Diagnose = false; 1565 if (L->isMSAsmLabel()) 1566 Diagnose = !L->isResolvedMSAsmLabel(); 1567 else 1568 Diagnose = L->getStmt() == nullptr; 1569 if (Diagnose) 1570 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1571 } 1572 1573 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1574 S->mergeNRVOIntoParent(); 1575 1576 if (S->decl_empty()) return; 1577 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1578 "Scope shouldn't contain decls!"); 1579 1580 for (auto *TmpD : S->decls()) { 1581 assert(TmpD && "This decl didn't get pushed??"); 1582 1583 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1584 NamedDecl *D = cast<NamedDecl>(TmpD); 1585 1586 if (!D->getDeclName()) continue; 1587 1588 // Diagnose unused variables in this scope. 1589 if (!S->hasUnrecoverableErrorOccurred()) { 1590 DiagnoseUnusedDecl(D); 1591 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1592 DiagnoseUnusedNestedTypedefs(RD); 1593 } 1594 1595 // If this was a forward reference to a label, verify it was defined. 1596 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1597 CheckPoppedLabel(LD, *this); 1598 1599 // Remove this name from our lexical scope. 1600 IdResolver.RemoveDecl(D); 1601 } 1602 } 1603 1604 /// \brief Look for an Objective-C class in the translation unit. 1605 /// 1606 /// \param Id The name of the Objective-C class we're looking for. If 1607 /// typo-correction fixes this name, the Id will be updated 1608 /// to the fixed name. 1609 /// 1610 /// \param IdLoc The location of the name in the translation unit. 1611 /// 1612 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1613 /// if there is no class with the given name. 1614 /// 1615 /// \returns The declaration of the named Objective-C class, or NULL if the 1616 /// class could not be found. 1617 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1618 SourceLocation IdLoc, 1619 bool DoTypoCorrection) { 1620 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1621 // creation from this context. 1622 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1623 1624 if (!IDecl && DoTypoCorrection) { 1625 // Perform typo correction at the given location, but only if we 1626 // find an Objective-C class name. 1627 if (TypoCorrection C = CorrectTypo( 1628 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr, 1629 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(), 1630 CTK_ErrorRecovery)) { 1631 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1632 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1633 Id = IDecl->getIdentifier(); 1634 } 1635 } 1636 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1637 // This routine must always return a class definition, if any. 1638 if (Def && Def->getDefinition()) 1639 Def = Def->getDefinition(); 1640 return Def; 1641 } 1642 1643 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1644 /// from S, where a non-field would be declared. This routine copes 1645 /// with the difference between C and C++ scoping rules in structs and 1646 /// unions. For example, the following code is well-formed in C but 1647 /// ill-formed in C++: 1648 /// @code 1649 /// struct S6 { 1650 /// enum { BAR } e; 1651 /// }; 1652 /// 1653 /// void test_S6() { 1654 /// struct S6 a; 1655 /// a.e = BAR; 1656 /// } 1657 /// @endcode 1658 /// For the declaration of BAR, this routine will return a different 1659 /// scope. The scope S will be the scope of the unnamed enumeration 1660 /// within S6. In C++, this routine will return the scope associated 1661 /// with S6, because the enumeration's scope is a transparent 1662 /// context but structures can contain non-field names. In C, this 1663 /// routine will return the translation unit scope, since the 1664 /// enumeration's scope is a transparent context and structures cannot 1665 /// contain non-field names. 1666 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1667 while (((S->getFlags() & Scope::DeclScope) == 0) || 1668 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1669 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1670 S = S->getParent(); 1671 return S; 1672 } 1673 1674 /// \brief Looks up the declaration of "struct objc_super" and 1675 /// saves it for later use in building builtin declaration of 1676 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1677 /// pre-existing declaration exists no action takes place. 1678 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1679 IdentifierInfo *II) { 1680 if (!II->isStr("objc_msgSendSuper")) 1681 return; 1682 ASTContext &Context = ThisSema.Context; 1683 1684 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1685 SourceLocation(), Sema::LookupTagName); 1686 ThisSema.LookupName(Result, S); 1687 if (Result.getResultKind() == LookupResult::Found) 1688 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1689 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1690 } 1691 1692 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1693 switch (Error) { 1694 case ASTContext::GE_None: 1695 return ""; 1696 case ASTContext::GE_Missing_stdio: 1697 return "stdio.h"; 1698 case ASTContext::GE_Missing_setjmp: 1699 return "setjmp.h"; 1700 case ASTContext::GE_Missing_ucontext: 1701 return "ucontext.h"; 1702 } 1703 llvm_unreachable("unhandled error kind"); 1704 } 1705 1706 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1707 /// file scope. lazily create a decl for it. ForRedeclaration is true 1708 /// if we're creating this built-in in anticipation of redeclaring the 1709 /// built-in. 1710 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1711 Scope *S, bool ForRedeclaration, 1712 SourceLocation Loc) { 1713 LookupPredefedObjCSuperType(*this, S, II); 1714 1715 ASTContext::GetBuiltinTypeError Error; 1716 QualType R = Context.GetBuiltinType(ID, Error); 1717 if (Error) { 1718 if (ForRedeclaration) 1719 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1720 << getHeaderName(Error) 1721 << Context.BuiltinInfo.GetName(ID); 1722 return nullptr; 1723 } 1724 1725 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1726 Diag(Loc, diag::ext_implicit_lib_function_decl) 1727 << Context.BuiltinInfo.GetName(ID) 1728 << R; 1729 if (Context.BuiltinInfo.getHeaderName(ID) && 1730 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1731 Diag(Loc, diag::note_include_header_or_declare) 1732 << Context.BuiltinInfo.getHeaderName(ID) 1733 << Context.BuiltinInfo.GetName(ID); 1734 } 1735 1736 DeclContext *Parent = Context.getTranslationUnitDecl(); 1737 if (getLangOpts().CPlusPlus) { 1738 LinkageSpecDecl *CLinkageDecl = 1739 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1740 LinkageSpecDecl::lang_c, false); 1741 CLinkageDecl->setImplicit(); 1742 Parent->addDecl(CLinkageDecl); 1743 Parent = CLinkageDecl; 1744 } 1745 1746 FunctionDecl *New = FunctionDecl::Create(Context, 1747 Parent, 1748 Loc, Loc, II, R, /*TInfo=*/nullptr, 1749 SC_Extern, 1750 false, 1751 /*hasPrototype=*/true); 1752 New->setImplicit(); 1753 1754 // Create Decl objects for each parameter, adding them to the 1755 // FunctionDecl. 1756 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1757 SmallVector<ParmVarDecl*, 16> Params; 1758 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1759 ParmVarDecl *parm = 1760 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1761 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1762 SC_None, nullptr); 1763 parm->setScopeInfo(0, i); 1764 Params.push_back(parm); 1765 } 1766 New->setParams(Params); 1767 } 1768 1769 AddKnownFunctionAttributes(New); 1770 RegisterLocallyScopedExternCDecl(New, S); 1771 1772 // TUScope is the translation-unit scope to insert this function into. 1773 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1774 // relate Scopes to DeclContexts, and probably eliminate CurContext 1775 // entirely, but we're not there yet. 1776 DeclContext *SavedContext = CurContext; 1777 CurContext = Parent; 1778 PushOnScopeChains(New, TUScope); 1779 CurContext = SavedContext; 1780 return New; 1781 } 1782 1783 /// \brief Filter out any previous declarations that the given declaration 1784 /// should not consider because they are not permitted to conflict, e.g., 1785 /// because they come from hidden sub-modules and do not refer to the same 1786 /// entity. 1787 static void filterNonConflictingPreviousDecls(ASTContext &context, 1788 NamedDecl *decl, 1789 LookupResult &previous){ 1790 // This is only interesting when modules are enabled. 1791 if (!context.getLangOpts().Modules) 1792 return; 1793 1794 // Empty sets are uninteresting. 1795 if (previous.empty()) 1796 return; 1797 1798 LookupResult::Filter filter = previous.makeFilter(); 1799 while (filter.hasNext()) { 1800 NamedDecl *old = filter.next(); 1801 1802 // Non-hidden declarations are never ignored. 1803 if (!old->isHidden()) 1804 continue; 1805 1806 if (!old->isExternallyVisible()) 1807 filter.erase(); 1808 } 1809 1810 filter.done(); 1811 } 1812 1813 /// Typedef declarations don't have linkage, but they still denote the same 1814 /// entity if their types are the same. 1815 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1816 /// isSameEntity. 1817 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context, 1818 TypedefNameDecl *Decl, 1819 LookupResult &Previous) { 1820 // This is only interesting when modules are enabled. 1821 if (!Context.getLangOpts().Modules) 1822 return; 1823 1824 // Empty sets are uninteresting. 1825 if (Previous.empty()) 1826 return; 1827 1828 LookupResult::Filter Filter = Previous.makeFilter(); 1829 while (Filter.hasNext()) { 1830 NamedDecl *Old = Filter.next(); 1831 1832 // Non-hidden declarations are never ignored. 1833 if (!Old->isHidden()) 1834 continue; 1835 1836 // Declarations of the same entity are not ignored, even if they have 1837 // different linkages. 1838 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) 1839 if (Context.hasSameType(OldTD->getUnderlyingType(), 1840 Decl->getUnderlyingType())) 1841 continue; 1842 1843 if (!Old->isExternallyVisible()) 1844 Filter.erase(); 1845 } 1846 1847 Filter.done(); 1848 } 1849 1850 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1851 QualType OldType; 1852 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1853 OldType = OldTypedef->getUnderlyingType(); 1854 else 1855 OldType = Context.getTypeDeclType(Old); 1856 QualType NewType = New->getUnderlyingType(); 1857 1858 if (NewType->isVariablyModifiedType()) { 1859 // Must not redefine a typedef with a variably-modified type. 1860 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1861 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1862 << Kind << NewType; 1863 if (Old->getLocation().isValid()) 1864 Diag(Old->getLocation(), diag::note_previous_definition); 1865 New->setInvalidDecl(); 1866 return true; 1867 } 1868 1869 if (OldType != NewType && 1870 !OldType->isDependentType() && 1871 !NewType->isDependentType() && 1872 !Context.hasSameType(OldType, NewType)) { 1873 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1874 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1875 << Kind << NewType << OldType; 1876 if (Old->getLocation().isValid()) 1877 Diag(Old->getLocation(), diag::note_previous_definition); 1878 New->setInvalidDecl(); 1879 return true; 1880 } 1881 return false; 1882 } 1883 1884 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1885 /// same name and scope as a previous declaration 'Old'. Figure out 1886 /// how to resolve this situation, merging decls or emitting 1887 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1888 /// 1889 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1890 // If the new decl is known invalid already, don't bother doing any 1891 // merging checks. 1892 if (New->isInvalidDecl()) return; 1893 1894 // Allow multiple definitions for ObjC built-in typedefs. 1895 // FIXME: Verify the underlying types are equivalent! 1896 if (getLangOpts().ObjC1) { 1897 const IdentifierInfo *TypeID = New->getIdentifier(); 1898 switch (TypeID->getLength()) { 1899 default: break; 1900 case 2: 1901 { 1902 if (!TypeID->isStr("id")) 1903 break; 1904 QualType T = New->getUnderlyingType(); 1905 if (!T->isPointerType()) 1906 break; 1907 if (!T->isVoidPointerType()) { 1908 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1909 if (!PT->isStructureType()) 1910 break; 1911 } 1912 Context.setObjCIdRedefinitionType(T); 1913 // Install the built-in type for 'id', ignoring the current definition. 1914 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1915 return; 1916 } 1917 case 5: 1918 if (!TypeID->isStr("Class")) 1919 break; 1920 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1921 // Install the built-in type for 'Class', ignoring the current definition. 1922 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1923 return; 1924 case 3: 1925 if (!TypeID->isStr("SEL")) 1926 break; 1927 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1928 // Install the built-in type for 'SEL', ignoring the current definition. 1929 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1930 return; 1931 } 1932 // Fall through - the typedef name was not a builtin type. 1933 } 1934 1935 // Verify the old decl was also a type. 1936 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1937 if (!Old) { 1938 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1939 << New->getDeclName(); 1940 1941 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1942 if (OldD->getLocation().isValid()) 1943 Diag(OldD->getLocation(), diag::note_previous_definition); 1944 1945 return New->setInvalidDecl(); 1946 } 1947 1948 // If the old declaration is invalid, just give up here. 1949 if (Old->isInvalidDecl()) 1950 return New->setInvalidDecl(); 1951 1952 // If the typedef types are not identical, reject them in all languages and 1953 // with any extensions enabled. 1954 if (isIncompatibleTypedef(Old, New)) 1955 return; 1956 1957 // The types match. Link up the redeclaration chain and merge attributes if 1958 // the old declaration was a typedef. 1959 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1960 New->setPreviousDecl(Typedef); 1961 mergeDeclAttributes(New, Old); 1962 } 1963 1964 if (getLangOpts().MicrosoftExt) 1965 return; 1966 1967 if (getLangOpts().CPlusPlus) { 1968 // C++ [dcl.typedef]p2: 1969 // In a given non-class scope, a typedef specifier can be used to 1970 // redefine the name of any type declared in that scope to refer 1971 // to the type to which it already refers. 1972 if (!isa<CXXRecordDecl>(CurContext)) 1973 return; 1974 1975 // C++0x [dcl.typedef]p4: 1976 // In a given class scope, a typedef specifier can be used to redefine 1977 // any class-name declared in that scope that is not also a typedef-name 1978 // to refer to the type to which it already refers. 1979 // 1980 // This wording came in via DR424, which was a correction to the 1981 // wording in DR56, which accidentally banned code like: 1982 // 1983 // struct S { 1984 // typedef struct A { } A; 1985 // }; 1986 // 1987 // in the C++03 standard. We implement the C++0x semantics, which 1988 // allow the above but disallow 1989 // 1990 // struct S { 1991 // typedef int I; 1992 // typedef int I; 1993 // }; 1994 // 1995 // since that was the intent of DR56. 1996 if (!isa<TypedefNameDecl>(Old)) 1997 return; 1998 1999 Diag(New->getLocation(), diag::err_redefinition) 2000 << New->getDeclName(); 2001 Diag(Old->getLocation(), diag::note_previous_definition); 2002 return New->setInvalidDecl(); 2003 } 2004 2005 // Modules always permit redefinition of typedefs, as does C11. 2006 if (getLangOpts().Modules || getLangOpts().C11) 2007 return; 2008 2009 // If we have a redefinition of a typedef in C, emit a warning. This warning 2010 // is normally mapped to an error, but can be controlled with 2011 // -Wtypedef-redefinition. If either the original or the redefinition is 2012 // in a system header, don't emit this for compatibility with GCC. 2013 if (getDiagnostics().getSuppressSystemWarnings() && 2014 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 2015 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 2016 return; 2017 2018 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 2019 << New->getDeclName(); 2020 Diag(Old->getLocation(), diag::note_previous_definition); 2021 return; 2022 } 2023 2024 /// DeclhasAttr - returns true if decl Declaration already has the target 2025 /// attribute. 2026 static bool DeclHasAttr(const Decl *D, const Attr *A) { 2027 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 2028 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 2029 for (const auto *i : D->attrs()) 2030 if (i->getKind() == A->getKind()) { 2031 if (Ann) { 2032 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 2033 return true; 2034 continue; 2035 } 2036 // FIXME: Don't hardcode this check 2037 if (OA && isa<OwnershipAttr>(i)) 2038 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2039 return true; 2040 } 2041 2042 return false; 2043 } 2044 2045 static bool isAttributeTargetADefinition(Decl *D) { 2046 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2047 return VD->isThisDeclarationADefinition(); 2048 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2049 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2050 return true; 2051 } 2052 2053 /// Merge alignment attributes from \p Old to \p New, taking into account the 2054 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2055 /// 2056 /// \return \c true if any attributes were added to \p New. 2057 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2058 // Look for alignas attributes on Old, and pick out whichever attribute 2059 // specifies the strictest alignment requirement. 2060 AlignedAttr *OldAlignasAttr = nullptr; 2061 AlignedAttr *OldStrictestAlignAttr = nullptr; 2062 unsigned OldAlign = 0; 2063 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2064 // FIXME: We have no way of representing inherited dependent alignments 2065 // in a case like: 2066 // template<int A, int B> struct alignas(A) X; 2067 // template<int A, int B> struct alignas(B) X {}; 2068 // For now, we just ignore any alignas attributes which are not on the 2069 // definition in such a case. 2070 if (I->isAlignmentDependent()) 2071 return false; 2072 2073 if (I->isAlignas()) 2074 OldAlignasAttr = I; 2075 2076 unsigned Align = I->getAlignment(S.Context); 2077 if (Align > OldAlign) { 2078 OldAlign = Align; 2079 OldStrictestAlignAttr = I; 2080 } 2081 } 2082 2083 // Look for alignas attributes on New. 2084 AlignedAttr *NewAlignasAttr = nullptr; 2085 unsigned NewAlign = 0; 2086 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2087 if (I->isAlignmentDependent()) 2088 return false; 2089 2090 if (I->isAlignas()) 2091 NewAlignasAttr = I; 2092 2093 unsigned Align = I->getAlignment(S.Context); 2094 if (Align > NewAlign) 2095 NewAlign = Align; 2096 } 2097 2098 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2099 // Both declarations have 'alignas' attributes. We require them to match. 2100 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2101 // fall short. (If two declarations both have alignas, they must both match 2102 // every definition, and so must match each other if there is a definition.) 2103 2104 // If either declaration only contains 'alignas(0)' specifiers, then it 2105 // specifies the natural alignment for the type. 2106 if (OldAlign == 0 || NewAlign == 0) { 2107 QualType Ty; 2108 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2109 Ty = VD->getType(); 2110 else 2111 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2112 2113 if (OldAlign == 0) 2114 OldAlign = S.Context.getTypeAlign(Ty); 2115 if (NewAlign == 0) 2116 NewAlign = S.Context.getTypeAlign(Ty); 2117 } 2118 2119 if (OldAlign != NewAlign) { 2120 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2121 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2122 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2123 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2124 } 2125 } 2126 2127 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2128 // C++11 [dcl.align]p6: 2129 // if any declaration of an entity has an alignment-specifier, 2130 // every defining declaration of that entity shall specify an 2131 // equivalent alignment. 2132 // C11 6.7.5/7: 2133 // If the definition of an object does not have an alignment 2134 // specifier, any other declaration of that object shall also 2135 // have no alignment specifier. 2136 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2137 << OldAlignasAttr; 2138 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2139 << OldAlignasAttr; 2140 } 2141 2142 bool AnyAdded = false; 2143 2144 // Ensure we have an attribute representing the strictest alignment. 2145 if (OldAlign > NewAlign) { 2146 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2147 Clone->setInherited(true); 2148 New->addAttr(Clone); 2149 AnyAdded = true; 2150 } 2151 2152 // Ensure we have an alignas attribute if the old declaration had one. 2153 if (OldAlignasAttr && !NewAlignasAttr && 2154 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2155 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2156 Clone->setInherited(true); 2157 New->addAttr(Clone); 2158 AnyAdded = true; 2159 } 2160 2161 return AnyAdded; 2162 } 2163 2164 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2165 const InheritableAttr *Attr, bool Override) { 2166 InheritableAttr *NewAttr = nullptr; 2167 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2168 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2169 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2170 AA->getIntroduced(), AA->getDeprecated(), 2171 AA->getObsoleted(), AA->getUnavailable(), 2172 AA->getMessage(), Override, 2173 AttrSpellingListIndex); 2174 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2175 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2176 AttrSpellingListIndex); 2177 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2178 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2179 AttrSpellingListIndex); 2180 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2181 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2182 AttrSpellingListIndex); 2183 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2184 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2185 AttrSpellingListIndex); 2186 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2187 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2188 FA->getFormatIdx(), FA->getFirstArg(), 2189 AttrSpellingListIndex); 2190 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2191 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2192 AttrSpellingListIndex); 2193 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2194 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2195 AttrSpellingListIndex, 2196 IA->getSemanticSpelling()); 2197 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr)) 2198 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(), 2199 &S.Context.Idents.get(AA->getSpelling()), 2200 AttrSpellingListIndex); 2201 else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr)) 2202 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex); 2203 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr)) 2204 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex); 2205 else if (isa<AlignedAttr>(Attr)) 2206 // AlignedAttrs are handled separately, because we need to handle all 2207 // such attributes on a declaration at the same time. 2208 NewAttr = nullptr; 2209 else if (isa<DeprecatedAttr>(Attr) && Override) 2210 NewAttr = nullptr; 2211 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2212 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2213 2214 if (NewAttr) { 2215 NewAttr->setInherited(true); 2216 D->addAttr(NewAttr); 2217 return true; 2218 } 2219 2220 return false; 2221 } 2222 2223 static const Decl *getDefinition(const Decl *D) { 2224 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2225 return TD->getDefinition(); 2226 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2227 const VarDecl *Def = VD->getDefinition(); 2228 if (Def) 2229 return Def; 2230 return VD->getActingDefinition(); 2231 } 2232 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2233 const FunctionDecl* Def; 2234 if (FD->isDefined(Def)) 2235 return Def; 2236 } 2237 return nullptr; 2238 } 2239 2240 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2241 for (const auto *Attribute : D->attrs()) 2242 if (Attribute->getKind() == Kind) 2243 return true; 2244 return false; 2245 } 2246 2247 /// checkNewAttributesAfterDef - If we already have a definition, check that 2248 /// there are no new attributes in this declaration. 2249 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2250 if (!New->hasAttrs()) 2251 return; 2252 2253 const Decl *Def = getDefinition(Old); 2254 if (!Def || Def == New) 2255 return; 2256 2257 AttrVec &NewAttributes = New->getAttrs(); 2258 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2259 const Attr *NewAttribute = NewAttributes[I]; 2260 2261 if (isa<AliasAttr>(NewAttribute)) { 2262 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2263 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2264 else { 2265 VarDecl *VD = cast<VarDecl>(New); 2266 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2267 VarDecl::TentativeDefinition 2268 ? diag::err_alias_after_tentative 2269 : diag::err_redefinition; 2270 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2271 S.Diag(Def->getLocation(), diag::note_previous_definition); 2272 VD->setInvalidDecl(); 2273 } 2274 ++I; 2275 continue; 2276 } 2277 2278 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2279 // Tentative definitions are only interesting for the alias check above. 2280 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2281 ++I; 2282 continue; 2283 } 2284 } 2285 2286 if (hasAttribute(Def, NewAttribute->getKind())) { 2287 ++I; 2288 continue; // regular attr merging will take care of validating this. 2289 } 2290 2291 if (isa<C11NoReturnAttr>(NewAttribute)) { 2292 // C's _Noreturn is allowed to be added to a function after it is defined. 2293 ++I; 2294 continue; 2295 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2296 if (AA->isAlignas()) { 2297 // C++11 [dcl.align]p6: 2298 // if any declaration of an entity has an alignment-specifier, 2299 // every defining declaration of that entity shall specify an 2300 // equivalent alignment. 2301 // C11 6.7.5/7: 2302 // If the definition of an object does not have an alignment 2303 // specifier, any other declaration of that object shall also 2304 // have no alignment specifier. 2305 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2306 << AA; 2307 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2308 << AA; 2309 NewAttributes.erase(NewAttributes.begin() + I); 2310 --E; 2311 continue; 2312 } 2313 } 2314 2315 S.Diag(NewAttribute->getLocation(), 2316 diag::warn_attribute_precede_definition); 2317 S.Diag(Def->getLocation(), diag::note_previous_definition); 2318 NewAttributes.erase(NewAttributes.begin() + I); 2319 --E; 2320 } 2321 } 2322 2323 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2324 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2325 AvailabilityMergeKind AMK) { 2326 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2327 UsedAttr *NewAttr = OldAttr->clone(Context); 2328 NewAttr->setInherited(true); 2329 New->addAttr(NewAttr); 2330 } 2331 2332 if (!Old->hasAttrs() && !New->hasAttrs()) 2333 return; 2334 2335 // attributes declared post-definition are currently ignored 2336 checkNewAttributesAfterDef(*this, New, Old); 2337 2338 if (!Old->hasAttrs()) 2339 return; 2340 2341 bool foundAny = New->hasAttrs(); 2342 2343 // Ensure that any moving of objects within the allocated map is done before 2344 // we process them. 2345 if (!foundAny) New->setAttrs(AttrVec()); 2346 2347 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2348 bool Override = false; 2349 // Ignore deprecated/unavailable/availability attributes if requested. 2350 if (isa<DeprecatedAttr>(I) || 2351 isa<UnavailableAttr>(I) || 2352 isa<AvailabilityAttr>(I)) { 2353 switch (AMK) { 2354 case AMK_None: 2355 continue; 2356 2357 case AMK_Redeclaration: 2358 break; 2359 2360 case AMK_Override: 2361 Override = true; 2362 break; 2363 } 2364 } 2365 2366 // Already handled. 2367 if (isa<UsedAttr>(I)) 2368 continue; 2369 2370 if (mergeDeclAttribute(*this, New, I, Override)) 2371 foundAny = true; 2372 } 2373 2374 if (mergeAlignedAttrs(*this, New, Old)) 2375 foundAny = true; 2376 2377 if (!foundAny) New->dropAttrs(); 2378 } 2379 2380 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2381 /// to the new one. 2382 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2383 const ParmVarDecl *oldDecl, 2384 Sema &S) { 2385 // C++11 [dcl.attr.depend]p2: 2386 // The first declaration of a function shall specify the 2387 // carries_dependency attribute for its declarator-id if any declaration 2388 // of the function specifies the carries_dependency attribute. 2389 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2390 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2391 S.Diag(CDA->getLocation(), 2392 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2393 // Find the first declaration of the parameter. 2394 // FIXME: Should we build redeclaration chains for function parameters? 2395 const FunctionDecl *FirstFD = 2396 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2397 const ParmVarDecl *FirstVD = 2398 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2399 S.Diag(FirstVD->getLocation(), 2400 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2401 } 2402 2403 if (!oldDecl->hasAttrs()) 2404 return; 2405 2406 bool foundAny = newDecl->hasAttrs(); 2407 2408 // Ensure that any moving of objects within the allocated map is 2409 // done before we process them. 2410 if (!foundAny) newDecl->setAttrs(AttrVec()); 2411 2412 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2413 if (!DeclHasAttr(newDecl, I)) { 2414 InheritableAttr *newAttr = 2415 cast<InheritableParamAttr>(I->clone(S.Context)); 2416 newAttr->setInherited(true); 2417 newDecl->addAttr(newAttr); 2418 foundAny = true; 2419 } 2420 } 2421 2422 if (!foundAny) newDecl->dropAttrs(); 2423 } 2424 2425 namespace { 2426 2427 /// Used in MergeFunctionDecl to keep track of function parameters in 2428 /// C. 2429 struct GNUCompatibleParamWarning { 2430 ParmVarDecl *OldParm; 2431 ParmVarDecl *NewParm; 2432 QualType PromotedType; 2433 }; 2434 2435 } 2436 2437 /// getSpecialMember - get the special member enum for a method. 2438 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2439 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2440 if (Ctor->isDefaultConstructor()) 2441 return Sema::CXXDefaultConstructor; 2442 2443 if (Ctor->isCopyConstructor()) 2444 return Sema::CXXCopyConstructor; 2445 2446 if (Ctor->isMoveConstructor()) 2447 return Sema::CXXMoveConstructor; 2448 } else if (isa<CXXDestructorDecl>(MD)) { 2449 return Sema::CXXDestructor; 2450 } else if (MD->isCopyAssignmentOperator()) { 2451 return Sema::CXXCopyAssignment; 2452 } else if (MD->isMoveAssignmentOperator()) { 2453 return Sema::CXXMoveAssignment; 2454 } 2455 2456 return Sema::CXXInvalid; 2457 } 2458 2459 // Determine whether the previous declaration was a definition, implicit 2460 // declaration, or a declaration. 2461 template <typename T> 2462 static std::pair<diag::kind, SourceLocation> 2463 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2464 diag::kind PrevDiag; 2465 SourceLocation OldLocation = Old->getLocation(); 2466 if (Old->isThisDeclarationADefinition()) 2467 PrevDiag = diag::note_previous_definition; 2468 else if (Old->isImplicit()) { 2469 PrevDiag = diag::note_previous_implicit_declaration; 2470 if (OldLocation.isInvalid()) 2471 OldLocation = New->getLocation(); 2472 } else 2473 PrevDiag = diag::note_previous_declaration; 2474 return std::make_pair(PrevDiag, OldLocation); 2475 } 2476 2477 /// canRedefineFunction - checks if a function can be redefined. Currently, 2478 /// only extern inline functions can be redefined, and even then only in 2479 /// GNU89 mode. 2480 static bool canRedefineFunction(const FunctionDecl *FD, 2481 const LangOptions& LangOpts) { 2482 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2483 !LangOpts.CPlusPlus && 2484 FD->isInlineSpecified() && 2485 FD->getStorageClass() == SC_Extern); 2486 } 2487 2488 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2489 const AttributedType *AT = T->getAs<AttributedType>(); 2490 while (AT && !AT->isCallingConv()) 2491 AT = AT->getModifiedType()->getAs<AttributedType>(); 2492 return AT; 2493 } 2494 2495 template <typename T> 2496 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2497 const DeclContext *DC = Old->getDeclContext(); 2498 if (DC->isRecord()) 2499 return false; 2500 2501 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2502 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2503 return true; 2504 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2505 return true; 2506 return false; 2507 } 2508 2509 /// MergeFunctionDecl - We just parsed a function 'New' from 2510 /// declarator D which has the same name and scope as a previous 2511 /// declaration 'Old'. Figure out how to resolve this situation, 2512 /// merging decls or emitting diagnostics as appropriate. 2513 /// 2514 /// In C++, New and Old must be declarations that are not 2515 /// overloaded. Use IsOverload to determine whether New and Old are 2516 /// overloaded, and to select the Old declaration that New should be 2517 /// merged with. 2518 /// 2519 /// Returns true if there was an error, false otherwise. 2520 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2521 Scope *S, bool MergeTypeWithOld) { 2522 // Verify the old decl was also a function. 2523 FunctionDecl *Old = OldD->getAsFunction(); 2524 if (!Old) { 2525 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2526 if (New->getFriendObjectKind()) { 2527 Diag(New->getLocation(), diag::err_using_decl_friend); 2528 Diag(Shadow->getTargetDecl()->getLocation(), 2529 diag::note_using_decl_target); 2530 Diag(Shadow->getUsingDecl()->getLocation(), 2531 diag::note_using_decl) << 0; 2532 return true; 2533 } 2534 2535 // C++11 [namespace.udecl]p14: 2536 // If a function declaration in namespace scope or block scope has the 2537 // same name and the same parameter-type-list as a function introduced 2538 // by a using-declaration, and the declarations do not declare the same 2539 // function, the program is ill-formed. 2540 2541 // Check whether the two declarations might declare the same function. 2542 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2543 if (Old && 2544 !Old->getDeclContext()->getRedeclContext()->Equals( 2545 New->getDeclContext()->getRedeclContext()) && 2546 !(Old->isExternC() && New->isExternC())) 2547 Old = nullptr; 2548 2549 if (!Old) { 2550 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2551 Diag(Shadow->getTargetDecl()->getLocation(), 2552 diag::note_using_decl_target); 2553 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2554 return true; 2555 } 2556 OldD = Old; 2557 } else { 2558 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2559 << New->getDeclName(); 2560 Diag(OldD->getLocation(), diag::note_previous_definition); 2561 return true; 2562 } 2563 } 2564 2565 // If the old declaration is invalid, just give up here. 2566 if (Old->isInvalidDecl()) 2567 return true; 2568 2569 diag::kind PrevDiag; 2570 SourceLocation OldLocation; 2571 std::tie(PrevDiag, OldLocation) = 2572 getNoteDiagForInvalidRedeclaration(Old, New); 2573 2574 // Don't complain about this if we're in GNU89 mode and the old function 2575 // is an extern inline function. 2576 // Don't complain about specializations. They are not supposed to have 2577 // storage classes. 2578 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2579 New->getStorageClass() == SC_Static && 2580 Old->hasExternalFormalLinkage() && 2581 !New->getTemplateSpecializationInfo() && 2582 !canRedefineFunction(Old, getLangOpts())) { 2583 if (getLangOpts().MicrosoftExt) { 2584 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2585 Diag(OldLocation, PrevDiag); 2586 } else { 2587 Diag(New->getLocation(), diag::err_static_non_static) << New; 2588 Diag(OldLocation, PrevDiag); 2589 return true; 2590 } 2591 } 2592 2593 2594 // If a function is first declared with a calling convention, but is later 2595 // declared or defined without one, all following decls assume the calling 2596 // convention of the first. 2597 // 2598 // It's OK if a function is first declared without a calling convention, 2599 // but is later declared or defined with the default calling convention. 2600 // 2601 // To test if either decl has an explicit calling convention, we look for 2602 // AttributedType sugar nodes on the type as written. If they are missing or 2603 // were canonicalized away, we assume the calling convention was implicit. 2604 // 2605 // Note also that we DO NOT return at this point, because we still have 2606 // other tests to run. 2607 QualType OldQType = Context.getCanonicalType(Old->getType()); 2608 QualType NewQType = Context.getCanonicalType(New->getType()); 2609 const FunctionType *OldType = cast<FunctionType>(OldQType); 2610 const FunctionType *NewType = cast<FunctionType>(NewQType); 2611 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2612 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2613 bool RequiresAdjustment = false; 2614 2615 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2616 FunctionDecl *First = Old->getFirstDecl(); 2617 const FunctionType *FT = 2618 First->getType().getCanonicalType()->castAs<FunctionType>(); 2619 FunctionType::ExtInfo FI = FT->getExtInfo(); 2620 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2621 if (!NewCCExplicit) { 2622 // Inherit the CC from the previous declaration if it was specified 2623 // there but not here. 2624 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2625 RequiresAdjustment = true; 2626 } else { 2627 // Calling conventions aren't compatible, so complain. 2628 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2629 Diag(New->getLocation(), diag::err_cconv_change) 2630 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2631 << !FirstCCExplicit 2632 << (!FirstCCExplicit ? "" : 2633 FunctionType::getNameForCallConv(FI.getCC())); 2634 2635 // Put the note on the first decl, since it is the one that matters. 2636 Diag(First->getLocation(), diag::note_previous_declaration); 2637 return true; 2638 } 2639 } 2640 2641 // FIXME: diagnose the other way around? 2642 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2643 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2644 RequiresAdjustment = true; 2645 } 2646 2647 // Merge regparm attribute. 2648 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2649 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2650 if (NewTypeInfo.getHasRegParm()) { 2651 Diag(New->getLocation(), diag::err_regparm_mismatch) 2652 << NewType->getRegParmType() 2653 << OldType->getRegParmType(); 2654 Diag(OldLocation, diag::note_previous_declaration); 2655 return true; 2656 } 2657 2658 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2659 RequiresAdjustment = true; 2660 } 2661 2662 // Merge ns_returns_retained attribute. 2663 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2664 if (NewTypeInfo.getProducesResult()) { 2665 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2666 Diag(OldLocation, diag::note_previous_declaration); 2667 return true; 2668 } 2669 2670 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2671 RequiresAdjustment = true; 2672 } 2673 2674 if (RequiresAdjustment) { 2675 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2676 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2677 New->setType(QualType(AdjustedType, 0)); 2678 NewQType = Context.getCanonicalType(New->getType()); 2679 NewType = cast<FunctionType>(NewQType); 2680 } 2681 2682 // If this redeclaration makes the function inline, we may need to add it to 2683 // UndefinedButUsed. 2684 if (!Old->isInlined() && New->isInlined() && 2685 !New->hasAttr<GNUInlineAttr>() && 2686 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2687 Old->isUsed(false) && 2688 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2689 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2690 SourceLocation())); 2691 2692 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2693 // about it. 2694 if (New->hasAttr<GNUInlineAttr>() && 2695 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2696 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2697 } 2698 2699 if (getLangOpts().CPlusPlus) { 2700 // (C++98 13.1p2): 2701 // Certain function declarations cannot be overloaded: 2702 // -- Function declarations that differ only in the return type 2703 // cannot be overloaded. 2704 2705 // Go back to the type source info to compare the declared return types, 2706 // per C++1y [dcl.type.auto]p13: 2707 // Redeclarations or specializations of a function or function template 2708 // with a declared return type that uses a placeholder type shall also 2709 // use that placeholder, not a deduced type. 2710 QualType OldDeclaredReturnType = 2711 (Old->getTypeSourceInfo() 2712 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2713 : OldType)->getReturnType(); 2714 QualType NewDeclaredReturnType = 2715 (New->getTypeSourceInfo() 2716 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2717 : NewType)->getReturnType(); 2718 QualType ResQT; 2719 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2720 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2721 New->isLocalExternDecl())) { 2722 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2723 OldDeclaredReturnType->isObjCObjectPointerType()) 2724 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2725 if (ResQT.isNull()) { 2726 if (New->isCXXClassMember() && New->isOutOfLine()) 2727 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2728 << New << New->getReturnTypeSourceRange(); 2729 else 2730 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2731 << New->getReturnTypeSourceRange(); 2732 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2733 << Old->getReturnTypeSourceRange(); 2734 return true; 2735 } 2736 else 2737 NewQType = ResQT; 2738 } 2739 2740 QualType OldReturnType = OldType->getReturnType(); 2741 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2742 if (OldReturnType != NewReturnType) { 2743 // If this function has a deduced return type and has already been 2744 // defined, copy the deduced value from the old declaration. 2745 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2746 if (OldAT && OldAT->isDeduced()) { 2747 New->setType( 2748 SubstAutoType(New->getType(), 2749 OldAT->isDependentType() ? Context.DependentTy 2750 : OldAT->getDeducedType())); 2751 NewQType = Context.getCanonicalType( 2752 SubstAutoType(NewQType, 2753 OldAT->isDependentType() ? Context.DependentTy 2754 : OldAT->getDeducedType())); 2755 } 2756 } 2757 2758 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2759 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2760 if (OldMethod && NewMethod) { 2761 // Preserve triviality. 2762 NewMethod->setTrivial(OldMethod->isTrivial()); 2763 2764 // MSVC allows explicit template specialization at class scope: 2765 // 2 CXXMethodDecls referring to the same function will be injected. 2766 // We don't want a redeclaration error. 2767 bool IsClassScopeExplicitSpecialization = 2768 OldMethod->isFunctionTemplateSpecialization() && 2769 NewMethod->isFunctionTemplateSpecialization(); 2770 bool isFriend = NewMethod->getFriendObjectKind(); 2771 2772 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2773 !IsClassScopeExplicitSpecialization) { 2774 // -- Member function declarations with the same name and the 2775 // same parameter types cannot be overloaded if any of them 2776 // is a static member function declaration. 2777 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2778 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2779 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2780 return true; 2781 } 2782 2783 // C++ [class.mem]p1: 2784 // [...] A member shall not be declared twice in the 2785 // member-specification, except that a nested class or member 2786 // class template can be declared and then later defined. 2787 if (ActiveTemplateInstantiations.empty()) { 2788 unsigned NewDiag; 2789 if (isa<CXXConstructorDecl>(OldMethod)) 2790 NewDiag = diag::err_constructor_redeclared; 2791 else if (isa<CXXDestructorDecl>(NewMethod)) 2792 NewDiag = diag::err_destructor_redeclared; 2793 else if (isa<CXXConversionDecl>(NewMethod)) 2794 NewDiag = diag::err_conv_function_redeclared; 2795 else 2796 NewDiag = diag::err_member_redeclared; 2797 2798 Diag(New->getLocation(), NewDiag); 2799 } else { 2800 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2801 << New << New->getType(); 2802 } 2803 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2804 return true; 2805 2806 // Complain if this is an explicit declaration of a special 2807 // member that was initially declared implicitly. 2808 // 2809 // As an exception, it's okay to befriend such methods in order 2810 // to permit the implicit constructor/destructor/operator calls. 2811 } else if (OldMethod->isImplicit()) { 2812 if (isFriend) { 2813 NewMethod->setImplicit(); 2814 } else { 2815 Diag(NewMethod->getLocation(), 2816 diag::err_definition_of_implicitly_declared_member) 2817 << New << getSpecialMember(OldMethod); 2818 return true; 2819 } 2820 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2821 Diag(NewMethod->getLocation(), 2822 diag::err_definition_of_explicitly_defaulted_member) 2823 << getSpecialMember(OldMethod); 2824 return true; 2825 } 2826 } 2827 2828 // C++11 [dcl.attr.noreturn]p1: 2829 // The first declaration of a function shall specify the noreturn 2830 // attribute if any declaration of that function specifies the noreturn 2831 // attribute. 2832 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2833 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2834 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2835 Diag(Old->getFirstDecl()->getLocation(), 2836 diag::note_noreturn_missing_first_decl); 2837 } 2838 2839 // C++11 [dcl.attr.depend]p2: 2840 // The first declaration of a function shall specify the 2841 // carries_dependency attribute for its declarator-id if any declaration 2842 // of the function specifies the carries_dependency attribute. 2843 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2844 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2845 Diag(CDA->getLocation(), 2846 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2847 Diag(Old->getFirstDecl()->getLocation(), 2848 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2849 } 2850 2851 // (C++98 8.3.5p3): 2852 // All declarations for a function shall agree exactly in both the 2853 // return type and the parameter-type-list. 2854 // We also want to respect all the extended bits except noreturn. 2855 2856 // noreturn should now match unless the old type info didn't have it. 2857 QualType OldQTypeForComparison = OldQType; 2858 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2859 assert(OldQType == QualType(OldType, 0)); 2860 const FunctionType *OldTypeForComparison 2861 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2862 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2863 assert(OldQTypeForComparison.isCanonical()); 2864 } 2865 2866 if (haveIncompatibleLanguageLinkages(Old, New)) { 2867 // As a special case, retain the language linkage from previous 2868 // declarations of a friend function as an extension. 2869 // 2870 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2871 // and is useful because there's otherwise no way to specify language 2872 // linkage within class scope. 2873 // 2874 // Check cautiously as the friend object kind isn't yet complete. 2875 if (New->getFriendObjectKind() != Decl::FOK_None) { 2876 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2877 Diag(OldLocation, PrevDiag); 2878 } else { 2879 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2880 Diag(OldLocation, PrevDiag); 2881 return true; 2882 } 2883 } 2884 2885 if (OldQTypeForComparison == NewQType) 2886 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2887 2888 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2889 New->isLocalExternDecl()) { 2890 // It's OK if we couldn't merge types for a local function declaraton 2891 // if either the old or new type is dependent. We'll merge the types 2892 // when we instantiate the function. 2893 return false; 2894 } 2895 2896 // Fall through for conflicting redeclarations and redefinitions. 2897 } 2898 2899 // C: Function types need to be compatible, not identical. This handles 2900 // duplicate function decls like "void f(int); void f(enum X);" properly. 2901 if (!getLangOpts().CPlusPlus && 2902 Context.typesAreCompatible(OldQType, NewQType)) { 2903 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2904 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2905 const FunctionProtoType *OldProto = nullptr; 2906 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2907 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2908 // The old declaration provided a function prototype, but the 2909 // new declaration does not. Merge in the prototype. 2910 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2911 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2912 NewQType = 2913 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2914 OldProto->getExtProtoInfo()); 2915 New->setType(NewQType); 2916 New->setHasInheritedPrototype(); 2917 2918 // Synthesize parameters with the same types. 2919 SmallVector<ParmVarDecl*, 16> Params; 2920 for (const auto &ParamType : OldProto->param_types()) { 2921 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2922 SourceLocation(), nullptr, 2923 ParamType, /*TInfo=*/nullptr, 2924 SC_None, nullptr); 2925 Param->setScopeInfo(0, Params.size()); 2926 Param->setImplicit(); 2927 Params.push_back(Param); 2928 } 2929 2930 New->setParams(Params); 2931 } 2932 2933 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2934 } 2935 2936 // GNU C permits a K&R definition to follow a prototype declaration 2937 // if the declared types of the parameters in the K&R definition 2938 // match the types in the prototype declaration, even when the 2939 // promoted types of the parameters from the K&R definition differ 2940 // from the types in the prototype. GCC then keeps the types from 2941 // the prototype. 2942 // 2943 // If a variadic prototype is followed by a non-variadic K&R definition, 2944 // the K&R definition becomes variadic. This is sort of an edge case, but 2945 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2946 // C99 6.9.1p8. 2947 if (!getLangOpts().CPlusPlus && 2948 Old->hasPrototype() && !New->hasPrototype() && 2949 New->getType()->getAs<FunctionProtoType>() && 2950 Old->getNumParams() == New->getNumParams()) { 2951 SmallVector<QualType, 16> ArgTypes; 2952 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2953 const FunctionProtoType *OldProto 2954 = Old->getType()->getAs<FunctionProtoType>(); 2955 const FunctionProtoType *NewProto 2956 = New->getType()->getAs<FunctionProtoType>(); 2957 2958 // Determine whether this is the GNU C extension. 2959 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2960 NewProto->getReturnType()); 2961 bool LooseCompatible = !MergedReturn.isNull(); 2962 for (unsigned Idx = 0, End = Old->getNumParams(); 2963 LooseCompatible && Idx != End; ++Idx) { 2964 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2965 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2966 if (Context.typesAreCompatible(OldParm->getType(), 2967 NewProto->getParamType(Idx))) { 2968 ArgTypes.push_back(NewParm->getType()); 2969 } else if (Context.typesAreCompatible(OldParm->getType(), 2970 NewParm->getType(), 2971 /*CompareUnqualified=*/true)) { 2972 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2973 NewProto->getParamType(Idx) }; 2974 Warnings.push_back(Warn); 2975 ArgTypes.push_back(NewParm->getType()); 2976 } else 2977 LooseCompatible = false; 2978 } 2979 2980 if (LooseCompatible) { 2981 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2982 Diag(Warnings[Warn].NewParm->getLocation(), 2983 diag::ext_param_promoted_not_compatible_with_prototype) 2984 << Warnings[Warn].PromotedType 2985 << Warnings[Warn].OldParm->getType(); 2986 if (Warnings[Warn].OldParm->getLocation().isValid()) 2987 Diag(Warnings[Warn].OldParm->getLocation(), 2988 diag::note_previous_declaration); 2989 } 2990 2991 if (MergeTypeWithOld) 2992 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2993 OldProto->getExtProtoInfo())); 2994 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2995 } 2996 2997 // Fall through to diagnose conflicting types. 2998 } 2999 3000 // A function that has already been declared has been redeclared or 3001 // defined with a different type; show an appropriate diagnostic. 3002 3003 // If the previous declaration was an implicitly-generated builtin 3004 // declaration, then at the very least we should use a specialized note. 3005 unsigned BuiltinID; 3006 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 3007 // If it's actually a library-defined builtin function like 'malloc' 3008 // or 'printf', just warn about the incompatible redeclaration. 3009 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 3010 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 3011 Diag(OldLocation, diag::note_previous_builtin_declaration) 3012 << Old << Old->getType(); 3013 3014 // If this is a global redeclaration, just forget hereafter 3015 // about the "builtin-ness" of the function. 3016 // 3017 // Doing this for local extern declarations is problematic. If 3018 // the builtin declaration remains visible, a second invalid 3019 // local declaration will produce a hard error; if it doesn't 3020 // remain visible, a single bogus local redeclaration (which is 3021 // actually only a warning) could break all the downstream code. 3022 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 3023 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 3024 3025 return false; 3026 } 3027 3028 PrevDiag = diag::note_previous_builtin_declaration; 3029 } 3030 3031 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 3032 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 3033 return true; 3034 } 3035 3036 /// \brief Completes the merge of two function declarations that are 3037 /// known to be compatible. 3038 /// 3039 /// This routine handles the merging of attributes and other 3040 /// properties of function declarations from the old declaration to 3041 /// the new declaration, once we know that New is in fact a 3042 /// redeclaration of Old. 3043 /// 3044 /// \returns false 3045 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3046 Scope *S, bool MergeTypeWithOld) { 3047 // Merge the attributes 3048 mergeDeclAttributes(New, Old); 3049 3050 // Merge "pure" flag. 3051 if (Old->isPure()) 3052 New->setPure(); 3053 3054 // Merge "used" flag. 3055 if (Old->getMostRecentDecl()->isUsed(false)) 3056 New->setIsUsed(); 3057 3058 // Merge attributes from the parameters. These can mismatch with K&R 3059 // declarations. 3060 if (New->getNumParams() == Old->getNumParams()) 3061 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 3062 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 3063 *this); 3064 3065 if (getLangOpts().CPlusPlus) 3066 return MergeCXXFunctionDecl(New, Old, S); 3067 3068 // Merge the function types so the we get the composite types for the return 3069 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3070 // was visible. 3071 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3072 if (!Merged.isNull() && MergeTypeWithOld) 3073 New->setType(Merged); 3074 3075 return false; 3076 } 3077 3078 3079 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3080 ObjCMethodDecl *oldMethod) { 3081 3082 // Merge the attributes, including deprecated/unavailable 3083 AvailabilityMergeKind MergeKind = 3084 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3085 : AMK_Override; 3086 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3087 3088 // Merge attributes from the parameters. 3089 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3090 oe = oldMethod->param_end(); 3091 for (ObjCMethodDecl::param_iterator 3092 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3093 ni != ne && oi != oe; ++ni, ++oi) 3094 mergeParamDeclAttributes(*ni, *oi, *this); 3095 3096 CheckObjCMethodOverride(newMethod, oldMethod); 3097 } 3098 3099 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3100 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3101 /// emitting diagnostics as appropriate. 3102 /// 3103 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3104 /// to here in AddInitializerToDecl. We can't check them before the initializer 3105 /// is attached. 3106 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3107 bool MergeTypeWithOld) { 3108 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3109 return; 3110 3111 QualType MergedT; 3112 if (getLangOpts().CPlusPlus) { 3113 if (New->getType()->isUndeducedType()) { 3114 // We don't know what the new type is until the initializer is attached. 3115 return; 3116 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3117 // These could still be something that needs exception specs checked. 3118 return MergeVarDeclExceptionSpecs(New, Old); 3119 } 3120 // C++ [basic.link]p10: 3121 // [...] the types specified by all declarations referring to a given 3122 // object or function shall be identical, except that declarations for an 3123 // array object can specify array types that differ by the presence or 3124 // absence of a major array bound (8.3.4). 3125 else if (Old->getType()->isIncompleteArrayType() && 3126 New->getType()->isArrayType()) { 3127 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3128 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3129 if (Context.hasSameType(OldArray->getElementType(), 3130 NewArray->getElementType())) 3131 MergedT = New->getType(); 3132 } else if (Old->getType()->isArrayType() && 3133 New->getType()->isIncompleteArrayType()) { 3134 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3135 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3136 if (Context.hasSameType(OldArray->getElementType(), 3137 NewArray->getElementType())) 3138 MergedT = Old->getType(); 3139 } else if (New->getType()->isObjCObjectPointerType() && 3140 Old->getType()->isObjCObjectPointerType()) { 3141 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3142 Old->getType()); 3143 } 3144 } else { 3145 // C 6.2.7p2: 3146 // All declarations that refer to the same object or function shall have 3147 // compatible type. 3148 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3149 } 3150 if (MergedT.isNull()) { 3151 // It's OK if we couldn't merge types if either type is dependent, for a 3152 // block-scope variable. In other cases (static data members of class 3153 // templates, variable templates, ...), we require the types to be 3154 // equivalent. 3155 // FIXME: The C++ standard doesn't say anything about this. 3156 if ((New->getType()->isDependentType() || 3157 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3158 // If the old type was dependent, we can't merge with it, so the new type 3159 // becomes dependent for now. We'll reproduce the original type when we 3160 // instantiate the TypeSourceInfo for the variable. 3161 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3162 New->setType(Context.DependentTy); 3163 return; 3164 } 3165 3166 // FIXME: Even if this merging succeeds, some other non-visible declaration 3167 // of this variable might have an incompatible type. For instance: 3168 // 3169 // extern int arr[]; 3170 // void f() { extern int arr[2]; } 3171 // void g() { extern int arr[3]; } 3172 // 3173 // Neither C nor C++ requires a diagnostic for this, but we should still try 3174 // to diagnose it. 3175 Diag(New->getLocation(), diag::err_redefinition_different_type) 3176 << New->getDeclName() << New->getType() << Old->getType(); 3177 Diag(Old->getLocation(), diag::note_previous_definition); 3178 return New->setInvalidDecl(); 3179 } 3180 3181 // Don't actually update the type on the new declaration if the old 3182 // declaration was an extern declaration in a different scope. 3183 if (MergeTypeWithOld) 3184 New->setType(MergedT); 3185 } 3186 3187 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3188 LookupResult &Previous) { 3189 // C11 6.2.7p4: 3190 // For an identifier with internal or external linkage declared 3191 // in a scope in which a prior declaration of that identifier is 3192 // visible, if the prior declaration specifies internal or 3193 // external linkage, the type of the identifier at the later 3194 // declaration becomes the composite type. 3195 // 3196 // If the variable isn't visible, we do not merge with its type. 3197 if (Previous.isShadowed()) 3198 return false; 3199 3200 if (S.getLangOpts().CPlusPlus) { 3201 // C++11 [dcl.array]p3: 3202 // If there is a preceding declaration of the entity in the same 3203 // scope in which the bound was specified, an omitted array bound 3204 // is taken to be the same as in that earlier declaration. 3205 return NewVD->isPreviousDeclInSameBlockScope() || 3206 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3207 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3208 } else { 3209 // If the old declaration was function-local, don't merge with its 3210 // type unless we're in the same function. 3211 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3212 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3213 } 3214 } 3215 3216 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3217 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3218 /// situation, merging decls or emitting diagnostics as appropriate. 3219 /// 3220 /// Tentative definition rules (C99 6.9.2p2) are checked by 3221 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3222 /// definitions here, since the initializer hasn't been attached. 3223 /// 3224 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3225 // If the new decl is already invalid, don't do any other checking. 3226 if (New->isInvalidDecl()) 3227 return; 3228 3229 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3230 3231 // Verify the old decl was also a variable or variable template. 3232 VarDecl *Old = nullptr; 3233 VarTemplateDecl *OldTemplate = nullptr; 3234 if (Previous.isSingleResult()) { 3235 if (NewTemplate) { 3236 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3237 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3238 } else 3239 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3240 } 3241 if (!Old) { 3242 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3243 << New->getDeclName(); 3244 Diag(Previous.getRepresentativeDecl()->getLocation(), 3245 diag::note_previous_definition); 3246 return New->setInvalidDecl(); 3247 } 3248 3249 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3250 return; 3251 3252 // Ensure the template parameters are compatible. 3253 if (NewTemplate && 3254 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3255 OldTemplate->getTemplateParameters(), 3256 /*Complain=*/true, TPL_TemplateMatch)) 3257 return; 3258 3259 // C++ [class.mem]p1: 3260 // A member shall not be declared twice in the member-specification [...] 3261 // 3262 // Here, we need only consider static data members. 3263 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3264 Diag(New->getLocation(), diag::err_duplicate_member) 3265 << New->getIdentifier(); 3266 Diag(Old->getLocation(), diag::note_previous_declaration); 3267 New->setInvalidDecl(); 3268 } 3269 3270 mergeDeclAttributes(New, Old); 3271 // Warn if an already-declared variable is made a weak_import in a subsequent 3272 // declaration 3273 if (New->hasAttr<WeakImportAttr>() && 3274 Old->getStorageClass() == SC_None && 3275 !Old->hasAttr<WeakImportAttr>()) { 3276 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3277 Diag(Old->getLocation(), diag::note_previous_definition); 3278 // Remove weak_import attribute on new declaration. 3279 New->dropAttr<WeakImportAttr>(); 3280 } 3281 3282 // Merge the types. 3283 VarDecl *MostRecent = Old->getMostRecentDecl(); 3284 if (MostRecent != Old) { 3285 MergeVarDeclTypes(New, MostRecent, 3286 mergeTypeWithPrevious(*this, New, MostRecent, Previous)); 3287 if (New->isInvalidDecl()) 3288 return; 3289 } 3290 3291 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3292 if (New->isInvalidDecl()) 3293 return; 3294 3295 diag::kind PrevDiag; 3296 SourceLocation OldLocation; 3297 std::tie(PrevDiag, OldLocation) = 3298 getNoteDiagForInvalidRedeclaration(Old, New); 3299 3300 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3301 if (New->getStorageClass() == SC_Static && 3302 !New->isStaticDataMember() && 3303 Old->hasExternalFormalLinkage()) { 3304 if (getLangOpts().MicrosoftExt) { 3305 Diag(New->getLocation(), diag::ext_static_non_static) 3306 << New->getDeclName(); 3307 Diag(OldLocation, PrevDiag); 3308 } else { 3309 Diag(New->getLocation(), diag::err_static_non_static) 3310 << New->getDeclName(); 3311 Diag(OldLocation, PrevDiag); 3312 return New->setInvalidDecl(); 3313 } 3314 } 3315 // C99 6.2.2p4: 3316 // For an identifier declared with the storage-class specifier 3317 // extern in a scope in which a prior declaration of that 3318 // identifier is visible,23) if the prior declaration specifies 3319 // internal or external linkage, the linkage of the identifier at 3320 // the later declaration is the same as the linkage specified at 3321 // the prior declaration. If no prior declaration is visible, or 3322 // if the prior declaration specifies no linkage, then the 3323 // identifier has external linkage. 3324 if (New->hasExternalStorage() && Old->hasLinkage()) 3325 /* Okay */; 3326 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3327 !New->isStaticDataMember() && 3328 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3329 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3330 Diag(OldLocation, PrevDiag); 3331 return New->setInvalidDecl(); 3332 } 3333 3334 // Check if extern is followed by non-extern and vice-versa. 3335 if (New->hasExternalStorage() && 3336 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) { 3337 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3338 Diag(OldLocation, PrevDiag); 3339 return New->setInvalidDecl(); 3340 } 3341 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() && 3342 !New->hasExternalStorage()) { 3343 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3344 Diag(OldLocation, PrevDiag); 3345 return New->setInvalidDecl(); 3346 } 3347 3348 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3349 3350 // FIXME: The test for external storage here seems wrong? We still 3351 // need to check for mismatches. 3352 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3353 // Don't complain about out-of-line definitions of static members. 3354 !(Old->getLexicalDeclContext()->isRecord() && 3355 !New->getLexicalDeclContext()->isRecord())) { 3356 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3357 Diag(OldLocation, PrevDiag); 3358 return New->setInvalidDecl(); 3359 } 3360 3361 if (New->getTLSKind() != Old->getTLSKind()) { 3362 if (!Old->getTLSKind()) { 3363 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3364 Diag(OldLocation, PrevDiag); 3365 } else if (!New->getTLSKind()) { 3366 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3367 Diag(OldLocation, PrevDiag); 3368 } else { 3369 // Do not allow redeclaration to change the variable between requiring 3370 // static and dynamic initialization. 3371 // FIXME: GCC allows this, but uses the TLS keyword on the first 3372 // declaration to determine the kind. Do we need to be compatible here? 3373 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3374 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3375 Diag(OldLocation, PrevDiag); 3376 } 3377 } 3378 3379 // C++ doesn't have tentative definitions, so go right ahead and check here. 3380 const VarDecl *Def; 3381 if (getLangOpts().CPlusPlus && 3382 New->isThisDeclarationADefinition() == VarDecl::Definition && 3383 (Def = Old->getDefinition())) { 3384 Diag(New->getLocation(), diag::err_redefinition) << New; 3385 Diag(Def->getLocation(), diag::note_previous_definition); 3386 New->setInvalidDecl(); 3387 return; 3388 } 3389 3390 if (haveIncompatibleLanguageLinkages(Old, New)) { 3391 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3392 Diag(OldLocation, PrevDiag); 3393 New->setInvalidDecl(); 3394 return; 3395 } 3396 3397 // Merge "used" flag. 3398 if (Old->getMostRecentDecl()->isUsed(false)) 3399 New->setIsUsed(); 3400 3401 // Keep a chain of previous declarations. 3402 New->setPreviousDecl(Old); 3403 if (NewTemplate) 3404 NewTemplate->setPreviousDecl(OldTemplate); 3405 3406 // Inherit access appropriately. 3407 New->setAccess(Old->getAccess()); 3408 if (NewTemplate) 3409 NewTemplate->setAccess(New->getAccess()); 3410 } 3411 3412 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3413 /// no declarator (e.g. "struct foo;") is parsed. 3414 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3415 DeclSpec &DS) { 3416 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3417 } 3418 3419 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3420 if (!Context.getLangOpts().CPlusPlus) 3421 return; 3422 3423 if (isa<CXXRecordDecl>(Tag->getParent())) { 3424 // If this tag is the direct child of a class, number it if 3425 // it is anonymous. 3426 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3427 return; 3428 MangleNumberingContext &MCtx = 3429 Context.getManglingNumberContext(Tag->getParent()); 3430 Context.setManglingNumber( 3431 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3432 return; 3433 } 3434 3435 // If this tag isn't a direct child of a class, number it if it is local. 3436 Decl *ManglingContextDecl; 3437 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3438 Tag->getDeclContext(), ManglingContextDecl)) { 3439 Context.setManglingNumber( 3440 Tag, 3441 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3442 } 3443 } 3444 3445 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3446 TypedefNameDecl *NewTD) { 3447 // Do nothing if the tag is not anonymous or already has an 3448 // associated typedef (from an earlier typedef in this decl group). 3449 if (TagFromDeclSpec->getIdentifier()) 3450 return; 3451 if (TagFromDeclSpec->getTypedefNameForAnonDecl()) 3452 return; 3453 3454 // A well-formed anonymous tag must always be a TUK_Definition. 3455 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3456 3457 // The type must match the tag exactly; no qualifiers allowed. 3458 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3459 Context.getTagDeclType(TagFromDeclSpec))) 3460 return; 3461 3462 // If we've already computed linkage for the anonymous tag, then 3463 // adding a typedef name for the anonymous decl can change that 3464 // linkage, which might be a serious problem. Diagnose this as 3465 // unsupported and ignore the typedef name. TODO: we should 3466 // pursue this as a language defect and establish a formal rule 3467 // for how to handle it. 3468 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3469 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3470 3471 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3472 tagLoc = getLocForEndOfToken(tagLoc); 3473 3474 llvm::SmallString<40> textToInsert; 3475 textToInsert += ' '; 3476 textToInsert += NewTD->getIdentifier()->getName(); 3477 Diag(tagLoc, diag::note_typedef_changes_linkage) 3478 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3479 return; 3480 } 3481 3482 // Otherwise, set this is the anon-decl typedef for the tag. 3483 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3484 } 3485 3486 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3487 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3488 /// parameters to cope with template friend declarations. 3489 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3490 DeclSpec &DS, 3491 MultiTemplateParamsArg TemplateParams, 3492 bool IsExplicitInstantiation) { 3493 Decl *TagD = nullptr; 3494 TagDecl *Tag = nullptr; 3495 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3496 DS.getTypeSpecType() == DeclSpec::TST_struct || 3497 DS.getTypeSpecType() == DeclSpec::TST_interface || 3498 DS.getTypeSpecType() == DeclSpec::TST_union || 3499 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3500 TagD = DS.getRepAsDecl(); 3501 3502 if (!TagD) // We probably had an error 3503 return nullptr; 3504 3505 // Note that the above type specs guarantee that the 3506 // type rep is a Decl, whereas in many of the others 3507 // it's a Type. 3508 if (isa<TagDecl>(TagD)) 3509 Tag = cast<TagDecl>(TagD); 3510 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3511 Tag = CTD->getTemplatedDecl(); 3512 } 3513 3514 if (Tag) { 3515 handleTagNumbering(Tag, S); 3516 Tag->setFreeStanding(); 3517 if (Tag->isInvalidDecl()) 3518 return Tag; 3519 } 3520 3521 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3522 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3523 // or incomplete types shall not be restrict-qualified." 3524 if (TypeQuals & DeclSpec::TQ_restrict) 3525 Diag(DS.getRestrictSpecLoc(), 3526 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3527 << DS.getSourceRange(); 3528 } 3529 3530 if (DS.isConstexprSpecified()) { 3531 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3532 // and definitions of functions and variables. 3533 if (Tag) 3534 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3535 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3536 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3537 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3538 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3539 else 3540 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3541 // Don't emit warnings after this error. 3542 return TagD; 3543 } 3544 3545 DiagnoseFunctionSpecifiers(DS); 3546 3547 if (DS.isFriendSpecified()) { 3548 // If we're dealing with a decl but not a TagDecl, assume that 3549 // whatever routines created it handled the friendship aspect. 3550 if (TagD && !Tag) 3551 return nullptr; 3552 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3553 } 3554 3555 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3556 bool IsExplicitSpecialization = 3557 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3558 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3559 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3560 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3561 // nested-name-specifier unless it is an explicit instantiation 3562 // or an explicit specialization. 3563 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3564 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3565 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3566 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3567 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3568 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3569 << SS.getRange(); 3570 return nullptr; 3571 } 3572 3573 // Track whether this decl-specifier declares anything. 3574 bool DeclaresAnything = true; 3575 3576 // Handle anonymous struct definitions. 3577 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3578 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3579 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3580 if (getLangOpts().CPlusPlus || 3581 Record->getDeclContext()->isRecord()) 3582 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3583 Context.getPrintingPolicy()); 3584 3585 DeclaresAnything = false; 3586 } 3587 } 3588 3589 // C11 6.7.2.1p2: 3590 // A struct-declaration that does not declare an anonymous structure or 3591 // anonymous union shall contain a struct-declarator-list. 3592 // 3593 // This rule also existed in C89 and C99; the grammar for struct-declaration 3594 // did not permit a struct-declaration without a struct-declarator-list. 3595 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3596 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3597 // Check for Microsoft C extension: anonymous struct/union member. 3598 // Handle 2 kinds of anonymous struct/union: 3599 // struct STRUCT; 3600 // union UNION; 3601 // and 3602 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3603 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3604 if ((Tag && Tag->getDeclName()) || 3605 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3606 RecordDecl *Record = nullptr; 3607 if (Tag) 3608 Record = dyn_cast<RecordDecl>(Tag); 3609 else if (const RecordType *RT = 3610 DS.getRepAsType().get()->getAsStructureType()) 3611 Record = RT->getDecl(); 3612 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3613 Record = UT->getDecl(); 3614 3615 if (Record && getLangOpts().MicrosoftExt) { 3616 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3617 << Record->isUnion() << DS.getSourceRange(); 3618 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3619 } 3620 3621 DeclaresAnything = false; 3622 } 3623 } 3624 3625 // Skip all the checks below if we have a type error. 3626 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3627 (TagD && TagD->isInvalidDecl())) 3628 return TagD; 3629 3630 if (getLangOpts().CPlusPlus && 3631 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3632 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3633 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3634 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3635 DeclaresAnything = false; 3636 3637 if (!DS.isMissingDeclaratorOk()) { 3638 // Customize diagnostic for a typedef missing a name. 3639 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3640 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3641 << DS.getSourceRange(); 3642 else 3643 DeclaresAnything = false; 3644 } 3645 3646 if (DS.isModulePrivateSpecified() && 3647 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3648 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3649 << Tag->getTagKind() 3650 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3651 3652 ActOnDocumentableDecl(TagD); 3653 3654 // C 6.7/2: 3655 // A declaration [...] shall declare at least a declarator [...], a tag, 3656 // or the members of an enumeration. 3657 // C++ [dcl.dcl]p3: 3658 // [If there are no declarators], and except for the declaration of an 3659 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3660 // names into the program, or shall redeclare a name introduced by a 3661 // previous declaration. 3662 if (!DeclaresAnything) { 3663 // In C, we allow this as a (popular) extension / bug. Don't bother 3664 // producing further diagnostics for redundant qualifiers after this. 3665 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3666 return TagD; 3667 } 3668 3669 // C++ [dcl.stc]p1: 3670 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3671 // init-declarator-list of the declaration shall not be empty. 3672 // C++ [dcl.fct.spec]p1: 3673 // If a cv-qualifier appears in a decl-specifier-seq, the 3674 // init-declarator-list of the declaration shall not be empty. 3675 // 3676 // Spurious qualifiers here appear to be valid in C. 3677 unsigned DiagID = diag::warn_standalone_specifier; 3678 if (getLangOpts().CPlusPlus) 3679 DiagID = diag::ext_standalone_specifier; 3680 3681 // Note that a linkage-specification sets a storage class, but 3682 // 'extern "C" struct foo;' is actually valid and not theoretically 3683 // useless. 3684 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3685 if (SCS == DeclSpec::SCS_mutable) 3686 // Since mutable is not a viable storage class specifier in C, there is 3687 // no reason to treat it as an extension. Instead, diagnose as an error. 3688 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3689 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3690 Diag(DS.getStorageClassSpecLoc(), DiagID) 3691 << DeclSpec::getSpecifierName(SCS); 3692 } 3693 3694 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3695 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3696 << DeclSpec::getSpecifierName(TSCS); 3697 if (DS.getTypeQualifiers()) { 3698 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3699 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3700 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3701 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3702 // Restrict is covered above. 3703 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3704 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3705 } 3706 3707 // Warn about ignored type attributes, for example: 3708 // __attribute__((aligned)) struct A; 3709 // Attributes should be placed after tag to apply to type declaration. 3710 if (!DS.getAttributes().empty()) { 3711 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3712 if (TypeSpecType == DeclSpec::TST_class || 3713 TypeSpecType == DeclSpec::TST_struct || 3714 TypeSpecType == DeclSpec::TST_interface || 3715 TypeSpecType == DeclSpec::TST_union || 3716 TypeSpecType == DeclSpec::TST_enum) { 3717 AttributeList* attrs = DS.getAttributes().getList(); 3718 while (attrs) { 3719 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3720 << attrs->getName() 3721 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3722 TypeSpecType == DeclSpec::TST_struct ? 1 : 3723 TypeSpecType == DeclSpec::TST_union ? 2 : 3724 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3725 attrs = attrs->getNext(); 3726 } 3727 } 3728 } 3729 3730 return TagD; 3731 } 3732 3733 /// We are trying to inject an anonymous member into the given scope; 3734 /// check if there's an existing declaration that can't be overloaded. 3735 /// 3736 /// \return true if this is a forbidden redeclaration 3737 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3738 Scope *S, 3739 DeclContext *Owner, 3740 DeclarationName Name, 3741 SourceLocation NameLoc, 3742 unsigned diagnostic) { 3743 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3744 Sema::ForRedeclaration); 3745 if (!SemaRef.LookupName(R, S)) return false; 3746 3747 if (R.getAsSingle<TagDecl>()) 3748 return false; 3749 3750 // Pick a representative declaration. 3751 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3752 assert(PrevDecl && "Expected a non-null Decl"); 3753 3754 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3755 return false; 3756 3757 SemaRef.Diag(NameLoc, diagnostic) << Name; 3758 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3759 3760 return true; 3761 } 3762 3763 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3764 /// anonymous struct or union AnonRecord into the owning context Owner 3765 /// and scope S. This routine will be invoked just after we realize 3766 /// that an unnamed union or struct is actually an anonymous union or 3767 /// struct, e.g., 3768 /// 3769 /// @code 3770 /// union { 3771 /// int i; 3772 /// float f; 3773 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3774 /// // f into the surrounding scope.x 3775 /// @endcode 3776 /// 3777 /// This routine is recursive, injecting the names of nested anonymous 3778 /// structs/unions into the owning context and scope as well. 3779 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3780 DeclContext *Owner, 3781 RecordDecl *AnonRecord, 3782 AccessSpecifier AS, 3783 SmallVectorImpl<NamedDecl *> &Chaining, 3784 bool MSAnonStruct) { 3785 unsigned diagKind 3786 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3787 : diag::err_anonymous_struct_member_redecl; 3788 3789 bool Invalid = false; 3790 3791 // Look every FieldDecl and IndirectFieldDecl with a name. 3792 for (auto *D : AnonRecord->decls()) { 3793 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3794 cast<NamedDecl>(D)->getDeclName()) { 3795 ValueDecl *VD = cast<ValueDecl>(D); 3796 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3797 VD->getLocation(), diagKind)) { 3798 // C++ [class.union]p2: 3799 // The names of the members of an anonymous union shall be 3800 // distinct from the names of any other entity in the 3801 // scope in which the anonymous union is declared. 3802 Invalid = true; 3803 } else { 3804 // C++ [class.union]p2: 3805 // For the purpose of name lookup, after the anonymous union 3806 // definition, the members of the anonymous union are 3807 // considered to have been defined in the scope in which the 3808 // anonymous union is declared. 3809 unsigned OldChainingSize = Chaining.size(); 3810 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3811 Chaining.append(IF->chain_begin(), IF->chain_end()); 3812 else 3813 Chaining.push_back(VD); 3814 3815 assert(Chaining.size() >= 2); 3816 NamedDecl **NamedChain = 3817 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3818 for (unsigned i = 0; i < Chaining.size(); i++) 3819 NamedChain[i] = Chaining[i]; 3820 3821 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 3822 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 3823 VD->getType(), NamedChain, Chaining.size()); 3824 3825 for (const auto *Attr : VD->attrs()) 3826 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 3827 3828 IndirectField->setAccess(AS); 3829 IndirectField->setImplicit(); 3830 SemaRef.PushOnScopeChains(IndirectField, S); 3831 3832 // That includes picking up the appropriate access specifier. 3833 if (AS != AS_none) IndirectField->setAccess(AS); 3834 3835 Chaining.resize(OldChainingSize); 3836 } 3837 } 3838 } 3839 3840 return Invalid; 3841 } 3842 3843 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3844 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3845 /// illegal input values are mapped to SC_None. 3846 static StorageClass 3847 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3848 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3849 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3850 "Parser allowed 'typedef' as storage class VarDecl."); 3851 switch (StorageClassSpec) { 3852 case DeclSpec::SCS_unspecified: return SC_None; 3853 case DeclSpec::SCS_extern: 3854 if (DS.isExternInLinkageSpec()) 3855 return SC_None; 3856 return SC_Extern; 3857 case DeclSpec::SCS_static: return SC_Static; 3858 case DeclSpec::SCS_auto: return SC_Auto; 3859 case DeclSpec::SCS_register: return SC_Register; 3860 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3861 // Illegal SCSs map to None: error reporting is up to the caller. 3862 case DeclSpec::SCS_mutable: // Fall through. 3863 case DeclSpec::SCS_typedef: return SC_None; 3864 } 3865 llvm_unreachable("unknown storage class specifier"); 3866 } 3867 3868 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3869 assert(Record->hasInClassInitializer()); 3870 3871 for (const auto *I : Record->decls()) { 3872 const auto *FD = dyn_cast<FieldDecl>(I); 3873 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3874 FD = IFD->getAnonField(); 3875 if (FD && FD->hasInClassInitializer()) 3876 return FD->getLocation(); 3877 } 3878 3879 llvm_unreachable("couldn't find in-class initializer"); 3880 } 3881 3882 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3883 SourceLocation DefaultInitLoc) { 3884 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3885 return; 3886 3887 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3888 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3889 } 3890 3891 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3892 CXXRecordDecl *AnonUnion) { 3893 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3894 return; 3895 3896 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3897 } 3898 3899 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3900 /// anonymous structure or union. Anonymous unions are a C++ feature 3901 /// (C++ [class.union]) and a C11 feature; anonymous structures 3902 /// are a C11 feature and GNU C++ extension. 3903 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3904 AccessSpecifier AS, 3905 RecordDecl *Record, 3906 const PrintingPolicy &Policy) { 3907 DeclContext *Owner = Record->getDeclContext(); 3908 3909 // Diagnose whether this anonymous struct/union is an extension. 3910 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3911 Diag(Record->getLocation(), diag::ext_anonymous_union); 3912 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3913 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3914 else if (!Record->isUnion() && !getLangOpts().C11) 3915 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3916 3917 // C and C++ require different kinds of checks for anonymous 3918 // structs/unions. 3919 bool Invalid = false; 3920 if (getLangOpts().CPlusPlus) { 3921 const char *PrevSpec = nullptr; 3922 unsigned DiagID; 3923 if (Record->isUnion()) { 3924 // C++ [class.union]p6: 3925 // Anonymous unions declared in a named namespace or in the 3926 // global namespace shall be declared static. 3927 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3928 (isa<TranslationUnitDecl>(Owner) || 3929 (isa<NamespaceDecl>(Owner) && 3930 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3931 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3932 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3933 3934 // Recover by adding 'static'. 3935 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3936 PrevSpec, DiagID, Policy); 3937 } 3938 // C++ [class.union]p6: 3939 // A storage class is not allowed in a declaration of an 3940 // anonymous union in a class scope. 3941 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3942 isa<RecordDecl>(Owner)) { 3943 Diag(DS.getStorageClassSpecLoc(), 3944 diag::err_anonymous_union_with_storage_spec) 3945 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3946 3947 // Recover by removing the storage specifier. 3948 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3949 SourceLocation(), 3950 PrevSpec, DiagID, Context.getPrintingPolicy()); 3951 } 3952 } 3953 3954 // Ignore const/volatile/restrict qualifiers. 3955 if (DS.getTypeQualifiers()) { 3956 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3957 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3958 << Record->isUnion() << "const" 3959 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3960 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3961 Diag(DS.getVolatileSpecLoc(), 3962 diag::ext_anonymous_struct_union_qualified) 3963 << Record->isUnion() << "volatile" 3964 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3965 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3966 Diag(DS.getRestrictSpecLoc(), 3967 diag::ext_anonymous_struct_union_qualified) 3968 << Record->isUnion() << "restrict" 3969 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3970 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3971 Diag(DS.getAtomicSpecLoc(), 3972 diag::ext_anonymous_struct_union_qualified) 3973 << Record->isUnion() << "_Atomic" 3974 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3975 3976 DS.ClearTypeQualifiers(); 3977 } 3978 3979 // C++ [class.union]p2: 3980 // The member-specification of an anonymous union shall only 3981 // define non-static data members. [Note: nested types and 3982 // functions cannot be declared within an anonymous union. ] 3983 for (auto *Mem : Record->decls()) { 3984 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3985 // C++ [class.union]p3: 3986 // An anonymous union shall not have private or protected 3987 // members (clause 11). 3988 assert(FD->getAccess() != AS_none); 3989 if (FD->getAccess() != AS_public) { 3990 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3991 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3992 Invalid = true; 3993 } 3994 3995 // C++ [class.union]p1 3996 // An object of a class with a non-trivial constructor, a non-trivial 3997 // copy constructor, a non-trivial destructor, or a non-trivial copy 3998 // assignment operator cannot be a member of a union, nor can an 3999 // array of such objects. 4000 if (CheckNontrivialField(FD)) 4001 Invalid = true; 4002 } else if (Mem->isImplicit()) { 4003 // Any implicit members are fine. 4004 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4005 // This is a type that showed up in an 4006 // elaborated-type-specifier inside the anonymous struct or 4007 // union, but which actually declares a type outside of the 4008 // anonymous struct or union. It's okay. 4009 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4010 if (!MemRecord->isAnonymousStructOrUnion() && 4011 MemRecord->getDeclName()) { 4012 // Visual C++ allows type definition in anonymous struct or union. 4013 if (getLangOpts().MicrosoftExt) 4014 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4015 << (int)Record->isUnion(); 4016 else { 4017 // This is a nested type declaration. 4018 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4019 << (int)Record->isUnion(); 4020 Invalid = true; 4021 } 4022 } else { 4023 // This is an anonymous type definition within another anonymous type. 4024 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4025 // not part of standard C++. 4026 Diag(MemRecord->getLocation(), 4027 diag::ext_anonymous_record_with_anonymous_type) 4028 << (int)Record->isUnion(); 4029 } 4030 } else if (isa<AccessSpecDecl>(Mem)) { 4031 // Any access specifier is fine. 4032 } else if (isa<StaticAssertDecl>(Mem)) { 4033 // In C++1z, static_assert declarations are also fine. 4034 } else { 4035 // We have something that isn't a non-static data 4036 // member. Complain about it. 4037 unsigned DK = diag::err_anonymous_record_bad_member; 4038 if (isa<TypeDecl>(Mem)) 4039 DK = diag::err_anonymous_record_with_type; 4040 else if (isa<FunctionDecl>(Mem)) 4041 DK = diag::err_anonymous_record_with_function; 4042 else if (isa<VarDecl>(Mem)) 4043 DK = diag::err_anonymous_record_with_static; 4044 4045 // Visual C++ allows type definition in anonymous struct or union. 4046 if (getLangOpts().MicrosoftExt && 4047 DK == diag::err_anonymous_record_with_type) 4048 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4049 << (int)Record->isUnion(); 4050 else { 4051 Diag(Mem->getLocation(), DK) 4052 << (int)Record->isUnion(); 4053 Invalid = true; 4054 } 4055 } 4056 } 4057 4058 // C++11 [class.union]p8 (DR1460): 4059 // At most one variant member of a union may have a 4060 // brace-or-equal-initializer. 4061 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4062 Owner->isRecord()) 4063 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4064 cast<CXXRecordDecl>(Record)); 4065 } 4066 4067 if (!Record->isUnion() && !Owner->isRecord()) { 4068 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4069 << (int)getLangOpts().CPlusPlus; 4070 Invalid = true; 4071 } 4072 4073 // Mock up a declarator. 4074 Declarator Dc(DS, Declarator::MemberContext); 4075 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4076 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4077 4078 // Create a declaration for this anonymous struct/union. 4079 NamedDecl *Anon = nullptr; 4080 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4081 Anon = FieldDecl::Create(Context, OwningClass, 4082 DS.getLocStart(), 4083 Record->getLocation(), 4084 /*IdentifierInfo=*/nullptr, 4085 Context.getTypeDeclType(Record), 4086 TInfo, 4087 /*BitWidth=*/nullptr, /*Mutable=*/false, 4088 /*InitStyle=*/ICIS_NoInit); 4089 Anon->setAccess(AS); 4090 if (getLangOpts().CPlusPlus) 4091 FieldCollector->Add(cast<FieldDecl>(Anon)); 4092 } else { 4093 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4094 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4095 if (SCSpec == DeclSpec::SCS_mutable) { 4096 // mutable can only appear on non-static class members, so it's always 4097 // an error here 4098 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4099 Invalid = true; 4100 SC = SC_None; 4101 } 4102 4103 Anon = VarDecl::Create(Context, Owner, 4104 DS.getLocStart(), 4105 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4106 Context.getTypeDeclType(Record), 4107 TInfo, SC); 4108 4109 // Default-initialize the implicit variable. This initialization will be 4110 // trivial in almost all cases, except if a union member has an in-class 4111 // initializer: 4112 // union { int n = 0; }; 4113 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4114 } 4115 Anon->setImplicit(); 4116 4117 // Mark this as an anonymous struct/union type. 4118 Record->setAnonymousStructOrUnion(true); 4119 4120 // Add the anonymous struct/union object to the current 4121 // context. We'll be referencing this object when we refer to one of 4122 // its members. 4123 Owner->addDecl(Anon); 4124 4125 // Inject the members of the anonymous struct/union into the owning 4126 // context and into the identifier resolver chain for name lookup 4127 // purposes. 4128 SmallVector<NamedDecl*, 2> Chain; 4129 Chain.push_back(Anon); 4130 4131 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 4132 Chain, false)) 4133 Invalid = true; 4134 4135 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4136 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4137 Decl *ManglingContextDecl; 4138 if (MangleNumberingContext *MCtx = 4139 getCurrentMangleNumberContext(NewVD->getDeclContext(), 4140 ManglingContextDecl)) { 4141 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 4142 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4143 } 4144 } 4145 } 4146 4147 if (Invalid) 4148 Anon->setInvalidDecl(); 4149 4150 return Anon; 4151 } 4152 4153 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4154 /// Microsoft C anonymous structure. 4155 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4156 /// Example: 4157 /// 4158 /// struct A { int a; }; 4159 /// struct B { struct A; int b; }; 4160 /// 4161 /// void foo() { 4162 /// B var; 4163 /// var.a = 3; 4164 /// } 4165 /// 4166 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4167 RecordDecl *Record) { 4168 assert(Record && "expected a record!"); 4169 4170 // Mock up a declarator. 4171 Declarator Dc(DS, Declarator::TypeNameContext); 4172 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4173 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4174 4175 auto *ParentDecl = cast<RecordDecl>(CurContext); 4176 QualType RecTy = Context.getTypeDeclType(Record); 4177 4178 // Create a declaration for this anonymous struct. 4179 NamedDecl *Anon = FieldDecl::Create(Context, 4180 ParentDecl, 4181 DS.getLocStart(), 4182 DS.getLocStart(), 4183 /*IdentifierInfo=*/nullptr, 4184 RecTy, 4185 TInfo, 4186 /*BitWidth=*/nullptr, /*Mutable=*/false, 4187 /*InitStyle=*/ICIS_NoInit); 4188 Anon->setImplicit(); 4189 4190 // Add the anonymous struct object to the current context. 4191 CurContext->addDecl(Anon); 4192 4193 // Inject the members of the anonymous struct into the current 4194 // context and into the identifier resolver chain for name lookup 4195 // purposes. 4196 SmallVector<NamedDecl*, 2> Chain; 4197 Chain.push_back(Anon); 4198 4199 RecordDecl *RecordDef = Record->getDefinition(); 4200 if (RequireCompleteType(Anon->getLocation(), RecTy, 4201 diag::err_field_incomplete) || 4202 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4203 AS_none, Chain, true)) { 4204 Anon->setInvalidDecl(); 4205 ParentDecl->setInvalidDecl(); 4206 } 4207 4208 return Anon; 4209 } 4210 4211 /// GetNameForDeclarator - Determine the full declaration name for the 4212 /// given Declarator. 4213 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4214 return GetNameFromUnqualifiedId(D.getName()); 4215 } 4216 4217 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4218 DeclarationNameInfo 4219 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4220 DeclarationNameInfo NameInfo; 4221 NameInfo.setLoc(Name.StartLocation); 4222 4223 switch (Name.getKind()) { 4224 4225 case UnqualifiedId::IK_ImplicitSelfParam: 4226 case UnqualifiedId::IK_Identifier: 4227 NameInfo.setName(Name.Identifier); 4228 NameInfo.setLoc(Name.StartLocation); 4229 return NameInfo; 4230 4231 case UnqualifiedId::IK_OperatorFunctionId: 4232 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4233 Name.OperatorFunctionId.Operator)); 4234 NameInfo.setLoc(Name.StartLocation); 4235 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4236 = Name.OperatorFunctionId.SymbolLocations[0]; 4237 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4238 = Name.EndLocation.getRawEncoding(); 4239 return NameInfo; 4240 4241 case UnqualifiedId::IK_LiteralOperatorId: 4242 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4243 Name.Identifier)); 4244 NameInfo.setLoc(Name.StartLocation); 4245 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4246 return NameInfo; 4247 4248 case UnqualifiedId::IK_ConversionFunctionId: { 4249 TypeSourceInfo *TInfo; 4250 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4251 if (Ty.isNull()) 4252 return DeclarationNameInfo(); 4253 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4254 Context.getCanonicalType(Ty))); 4255 NameInfo.setLoc(Name.StartLocation); 4256 NameInfo.setNamedTypeInfo(TInfo); 4257 return NameInfo; 4258 } 4259 4260 case UnqualifiedId::IK_ConstructorName: { 4261 TypeSourceInfo *TInfo; 4262 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4263 if (Ty.isNull()) 4264 return DeclarationNameInfo(); 4265 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4266 Context.getCanonicalType(Ty))); 4267 NameInfo.setLoc(Name.StartLocation); 4268 NameInfo.setNamedTypeInfo(TInfo); 4269 return NameInfo; 4270 } 4271 4272 case UnqualifiedId::IK_ConstructorTemplateId: { 4273 // In well-formed code, we can only have a constructor 4274 // template-id that refers to the current context, so go there 4275 // to find the actual type being constructed. 4276 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4277 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4278 return DeclarationNameInfo(); 4279 4280 // Determine the type of the class being constructed. 4281 QualType CurClassType = Context.getTypeDeclType(CurClass); 4282 4283 // FIXME: Check two things: that the template-id names the same type as 4284 // CurClassType, and that the template-id does not occur when the name 4285 // was qualified. 4286 4287 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4288 Context.getCanonicalType(CurClassType))); 4289 NameInfo.setLoc(Name.StartLocation); 4290 // FIXME: should we retrieve TypeSourceInfo? 4291 NameInfo.setNamedTypeInfo(nullptr); 4292 return NameInfo; 4293 } 4294 4295 case UnqualifiedId::IK_DestructorName: { 4296 TypeSourceInfo *TInfo; 4297 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4298 if (Ty.isNull()) 4299 return DeclarationNameInfo(); 4300 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4301 Context.getCanonicalType(Ty))); 4302 NameInfo.setLoc(Name.StartLocation); 4303 NameInfo.setNamedTypeInfo(TInfo); 4304 return NameInfo; 4305 } 4306 4307 case UnqualifiedId::IK_TemplateId: { 4308 TemplateName TName = Name.TemplateId->Template.get(); 4309 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4310 return Context.getNameForTemplate(TName, TNameLoc); 4311 } 4312 4313 } // switch (Name.getKind()) 4314 4315 llvm_unreachable("Unknown name kind"); 4316 } 4317 4318 static QualType getCoreType(QualType Ty) { 4319 do { 4320 if (Ty->isPointerType() || Ty->isReferenceType()) 4321 Ty = Ty->getPointeeType(); 4322 else if (Ty->isArrayType()) 4323 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4324 else 4325 return Ty.withoutLocalFastQualifiers(); 4326 } while (true); 4327 } 4328 4329 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4330 /// and Definition have "nearly" matching parameters. This heuristic is 4331 /// used to improve diagnostics in the case where an out-of-line function 4332 /// definition doesn't match any declaration within the class or namespace. 4333 /// Also sets Params to the list of indices to the parameters that differ 4334 /// between the declaration and the definition. If hasSimilarParameters 4335 /// returns true and Params is empty, then all of the parameters match. 4336 static bool hasSimilarParameters(ASTContext &Context, 4337 FunctionDecl *Declaration, 4338 FunctionDecl *Definition, 4339 SmallVectorImpl<unsigned> &Params) { 4340 Params.clear(); 4341 if (Declaration->param_size() != Definition->param_size()) 4342 return false; 4343 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4344 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4345 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4346 4347 // The parameter types are identical 4348 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4349 continue; 4350 4351 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4352 QualType DefParamBaseTy = getCoreType(DefParamTy); 4353 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4354 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4355 4356 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4357 (DeclTyName && DeclTyName == DefTyName)) 4358 Params.push_back(Idx); 4359 else // The two parameters aren't even close 4360 return false; 4361 } 4362 4363 return true; 4364 } 4365 4366 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4367 /// declarator needs to be rebuilt in the current instantiation. 4368 /// Any bits of declarator which appear before the name are valid for 4369 /// consideration here. That's specifically the type in the decl spec 4370 /// and the base type in any member-pointer chunks. 4371 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4372 DeclarationName Name) { 4373 // The types we specifically need to rebuild are: 4374 // - typenames, typeofs, and decltypes 4375 // - types which will become injected class names 4376 // Of course, we also need to rebuild any type referencing such a 4377 // type. It's safest to just say "dependent", but we call out a 4378 // few cases here. 4379 4380 DeclSpec &DS = D.getMutableDeclSpec(); 4381 switch (DS.getTypeSpecType()) { 4382 case DeclSpec::TST_typename: 4383 case DeclSpec::TST_typeofType: 4384 case DeclSpec::TST_underlyingType: 4385 case DeclSpec::TST_atomic: { 4386 // Grab the type from the parser. 4387 TypeSourceInfo *TSI = nullptr; 4388 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4389 if (T.isNull() || !T->isDependentType()) break; 4390 4391 // Make sure there's a type source info. This isn't really much 4392 // of a waste; most dependent types should have type source info 4393 // attached already. 4394 if (!TSI) 4395 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4396 4397 // Rebuild the type in the current instantiation. 4398 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4399 if (!TSI) return true; 4400 4401 // Store the new type back in the decl spec. 4402 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4403 DS.UpdateTypeRep(LocType); 4404 break; 4405 } 4406 4407 case DeclSpec::TST_decltype: 4408 case DeclSpec::TST_typeofExpr: { 4409 Expr *E = DS.getRepAsExpr(); 4410 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4411 if (Result.isInvalid()) return true; 4412 DS.UpdateExprRep(Result.get()); 4413 break; 4414 } 4415 4416 default: 4417 // Nothing to do for these decl specs. 4418 break; 4419 } 4420 4421 // It doesn't matter what order we do this in. 4422 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4423 DeclaratorChunk &Chunk = D.getTypeObject(I); 4424 4425 // The only type information in the declarator which can come 4426 // before the declaration name is the base type of a member 4427 // pointer. 4428 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4429 continue; 4430 4431 // Rebuild the scope specifier in-place. 4432 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4433 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4434 return true; 4435 } 4436 4437 return false; 4438 } 4439 4440 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4441 D.setFunctionDefinitionKind(FDK_Declaration); 4442 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4443 4444 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4445 Dcl && Dcl->getDeclContext()->isFileContext()) 4446 Dcl->setTopLevelDeclInObjCContainer(); 4447 4448 return Dcl; 4449 } 4450 4451 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4452 /// If T is the name of a class, then each of the following shall have a 4453 /// name different from T: 4454 /// - every static data member of class T; 4455 /// - every member function of class T 4456 /// - every member of class T that is itself a type; 4457 /// \returns true if the declaration name violates these rules. 4458 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4459 DeclarationNameInfo NameInfo) { 4460 DeclarationName Name = NameInfo.getName(); 4461 4462 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4463 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4464 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4465 return true; 4466 } 4467 4468 return false; 4469 } 4470 4471 /// \brief Diagnose a declaration whose declarator-id has the given 4472 /// nested-name-specifier. 4473 /// 4474 /// \param SS The nested-name-specifier of the declarator-id. 4475 /// 4476 /// \param DC The declaration context to which the nested-name-specifier 4477 /// resolves. 4478 /// 4479 /// \param Name The name of the entity being declared. 4480 /// 4481 /// \param Loc The location of the name of the entity being declared. 4482 /// 4483 /// \returns true if we cannot safely recover from this error, false otherwise. 4484 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4485 DeclarationName Name, 4486 SourceLocation Loc) { 4487 DeclContext *Cur = CurContext; 4488 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4489 Cur = Cur->getParent(); 4490 4491 // If the user provided a superfluous scope specifier that refers back to the 4492 // class in which the entity is already declared, diagnose and ignore it. 4493 // 4494 // class X { 4495 // void X::f(); 4496 // }; 4497 // 4498 // Note, it was once ill-formed to give redundant qualification in all 4499 // contexts, but that rule was removed by DR482. 4500 if (Cur->Equals(DC)) { 4501 if (Cur->isRecord()) { 4502 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4503 : diag::err_member_extra_qualification) 4504 << Name << FixItHint::CreateRemoval(SS.getRange()); 4505 SS.clear(); 4506 } else { 4507 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4508 } 4509 return false; 4510 } 4511 4512 // Check whether the qualifying scope encloses the scope of the original 4513 // declaration. 4514 if (!Cur->Encloses(DC)) { 4515 if (Cur->isRecord()) 4516 Diag(Loc, diag::err_member_qualification) 4517 << Name << SS.getRange(); 4518 else if (isa<TranslationUnitDecl>(DC)) 4519 Diag(Loc, diag::err_invalid_declarator_global_scope) 4520 << Name << SS.getRange(); 4521 else if (isa<FunctionDecl>(Cur)) 4522 Diag(Loc, diag::err_invalid_declarator_in_function) 4523 << Name << SS.getRange(); 4524 else if (isa<BlockDecl>(Cur)) 4525 Diag(Loc, diag::err_invalid_declarator_in_block) 4526 << Name << SS.getRange(); 4527 else 4528 Diag(Loc, diag::err_invalid_declarator_scope) 4529 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4530 4531 return true; 4532 } 4533 4534 if (Cur->isRecord()) { 4535 // Cannot qualify members within a class. 4536 Diag(Loc, diag::err_member_qualification) 4537 << Name << SS.getRange(); 4538 SS.clear(); 4539 4540 // C++ constructors and destructors with incorrect scopes can break 4541 // our AST invariants by having the wrong underlying types. If 4542 // that's the case, then drop this declaration entirely. 4543 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4544 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4545 !Context.hasSameType(Name.getCXXNameType(), 4546 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4547 return true; 4548 4549 return false; 4550 } 4551 4552 // C++11 [dcl.meaning]p1: 4553 // [...] "The nested-name-specifier of the qualified declarator-id shall 4554 // not begin with a decltype-specifer" 4555 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4556 while (SpecLoc.getPrefix()) 4557 SpecLoc = SpecLoc.getPrefix(); 4558 if (dyn_cast_or_null<DecltypeType>( 4559 SpecLoc.getNestedNameSpecifier()->getAsType())) 4560 Diag(Loc, diag::err_decltype_in_declarator) 4561 << SpecLoc.getTypeLoc().getSourceRange(); 4562 4563 return false; 4564 } 4565 4566 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4567 MultiTemplateParamsArg TemplateParamLists) { 4568 // TODO: consider using NameInfo for diagnostic. 4569 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4570 DeclarationName Name = NameInfo.getName(); 4571 4572 // All of these full declarators require an identifier. If it doesn't have 4573 // one, the ParsedFreeStandingDeclSpec action should be used. 4574 if (!Name) { 4575 if (!D.isInvalidType()) // Reject this if we think it is valid. 4576 Diag(D.getDeclSpec().getLocStart(), 4577 diag::err_declarator_need_ident) 4578 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4579 return nullptr; 4580 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4581 return nullptr; 4582 4583 // The scope passed in may not be a decl scope. Zip up the scope tree until 4584 // we find one that is. 4585 while ((S->getFlags() & Scope::DeclScope) == 0 || 4586 (S->getFlags() & Scope::TemplateParamScope) != 0) 4587 S = S->getParent(); 4588 4589 DeclContext *DC = CurContext; 4590 if (D.getCXXScopeSpec().isInvalid()) 4591 D.setInvalidType(); 4592 else if (D.getCXXScopeSpec().isSet()) { 4593 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4594 UPPC_DeclarationQualifier)) 4595 return nullptr; 4596 4597 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4598 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4599 if (!DC || isa<EnumDecl>(DC)) { 4600 // If we could not compute the declaration context, it's because the 4601 // declaration context is dependent but does not refer to a class, 4602 // class template, or class template partial specialization. Complain 4603 // and return early, to avoid the coming semantic disaster. 4604 Diag(D.getIdentifierLoc(), 4605 diag::err_template_qualified_declarator_no_match) 4606 << D.getCXXScopeSpec().getScopeRep() 4607 << D.getCXXScopeSpec().getRange(); 4608 return nullptr; 4609 } 4610 bool IsDependentContext = DC->isDependentContext(); 4611 4612 if (!IsDependentContext && 4613 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4614 return nullptr; 4615 4616 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4617 Diag(D.getIdentifierLoc(), 4618 diag::err_member_def_undefined_record) 4619 << Name << DC << D.getCXXScopeSpec().getRange(); 4620 D.setInvalidType(); 4621 } else if (!D.getDeclSpec().isFriendSpecified()) { 4622 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4623 Name, D.getIdentifierLoc())) { 4624 if (DC->isRecord()) 4625 return nullptr; 4626 4627 D.setInvalidType(); 4628 } 4629 } 4630 4631 // Check whether we need to rebuild the type of the given 4632 // declaration in the current instantiation. 4633 if (EnteringContext && IsDependentContext && 4634 TemplateParamLists.size() != 0) { 4635 ContextRAII SavedContext(*this, DC); 4636 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4637 D.setInvalidType(); 4638 } 4639 } 4640 4641 if (DiagnoseClassNameShadow(DC, NameInfo)) 4642 // If this is a typedef, we'll end up spewing multiple diagnostics. 4643 // Just return early; it's safer. 4644 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4645 return nullptr; 4646 4647 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4648 QualType R = TInfo->getType(); 4649 4650 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4651 UPPC_DeclarationType)) 4652 D.setInvalidType(); 4653 4654 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4655 ForRedeclaration); 4656 4657 // See if this is a redefinition of a variable in the same scope. 4658 if (!D.getCXXScopeSpec().isSet()) { 4659 bool IsLinkageLookup = false; 4660 bool CreateBuiltins = false; 4661 4662 // If the declaration we're planning to build will be a function 4663 // or object with linkage, then look for another declaration with 4664 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4665 // 4666 // If the declaration we're planning to build will be declared with 4667 // external linkage in the translation unit, create any builtin with 4668 // the same name. 4669 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4670 /* Do nothing*/; 4671 else if (CurContext->isFunctionOrMethod() && 4672 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4673 R->isFunctionType())) { 4674 IsLinkageLookup = true; 4675 CreateBuiltins = 4676 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4677 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4678 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4679 CreateBuiltins = true; 4680 4681 if (IsLinkageLookup) 4682 Previous.clear(LookupRedeclarationWithLinkage); 4683 4684 LookupName(Previous, S, CreateBuiltins); 4685 } else { // Something like "int foo::x;" 4686 LookupQualifiedName(Previous, DC); 4687 4688 // C++ [dcl.meaning]p1: 4689 // When the declarator-id is qualified, the declaration shall refer to a 4690 // previously declared member of the class or namespace to which the 4691 // qualifier refers (or, in the case of a namespace, of an element of the 4692 // inline namespace set of that namespace (7.3.1)) or to a specialization 4693 // thereof; [...] 4694 // 4695 // Note that we already checked the context above, and that we do not have 4696 // enough information to make sure that Previous contains the declaration 4697 // we want to match. For example, given: 4698 // 4699 // class X { 4700 // void f(); 4701 // void f(float); 4702 // }; 4703 // 4704 // void X::f(int) { } // ill-formed 4705 // 4706 // In this case, Previous will point to the overload set 4707 // containing the two f's declared in X, but neither of them 4708 // matches. 4709 4710 // C++ [dcl.meaning]p1: 4711 // [...] the member shall not merely have been introduced by a 4712 // using-declaration in the scope of the class or namespace nominated by 4713 // the nested-name-specifier of the declarator-id. 4714 RemoveUsingDecls(Previous); 4715 } 4716 4717 if (Previous.isSingleResult() && 4718 Previous.getFoundDecl()->isTemplateParameter()) { 4719 // Maybe we will complain about the shadowed template parameter. 4720 if (!D.isInvalidType()) 4721 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4722 Previous.getFoundDecl()); 4723 4724 // Just pretend that we didn't see the previous declaration. 4725 Previous.clear(); 4726 } 4727 4728 // In C++, the previous declaration we find might be a tag type 4729 // (class or enum). In this case, the new declaration will hide the 4730 // tag type. Note that this does does not apply if we're declaring a 4731 // typedef (C++ [dcl.typedef]p4). 4732 if (Previous.isSingleTagDecl() && 4733 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4734 Previous.clear(); 4735 4736 // Check that there are no default arguments other than in the parameters 4737 // of a function declaration (C++ only). 4738 if (getLangOpts().CPlusPlus) 4739 CheckExtraCXXDefaultArguments(D); 4740 4741 NamedDecl *New; 4742 4743 bool AddToScope = true; 4744 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4745 if (TemplateParamLists.size()) { 4746 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4747 return nullptr; 4748 } 4749 4750 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4751 } else if (R->isFunctionType()) { 4752 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4753 TemplateParamLists, 4754 AddToScope); 4755 } else { 4756 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4757 AddToScope); 4758 } 4759 4760 if (!New) 4761 return nullptr; 4762 4763 // If this has an identifier and is not an invalid redeclaration or 4764 // function template specialization, add it to the scope stack. 4765 if (New->getDeclName() && AddToScope && 4766 !(D.isRedeclaration() && New->isInvalidDecl())) { 4767 // Only make a locally-scoped extern declaration visible if it is the first 4768 // declaration of this entity. Qualified lookup for such an entity should 4769 // only find this declaration if there is no visible declaration of it. 4770 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4771 PushOnScopeChains(New, S, AddToContext); 4772 if (!AddToContext) 4773 CurContext->addHiddenDecl(New); 4774 } 4775 4776 return New; 4777 } 4778 4779 /// Helper method to turn variable array types into constant array 4780 /// types in certain situations which would otherwise be errors (for 4781 /// GCC compatibility). 4782 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4783 ASTContext &Context, 4784 bool &SizeIsNegative, 4785 llvm::APSInt &Oversized) { 4786 // This method tries to turn a variable array into a constant 4787 // array even when the size isn't an ICE. This is necessary 4788 // for compatibility with code that depends on gcc's buggy 4789 // constant expression folding, like struct {char x[(int)(char*)2];} 4790 SizeIsNegative = false; 4791 Oversized = 0; 4792 4793 if (T->isDependentType()) 4794 return QualType(); 4795 4796 QualifierCollector Qs; 4797 const Type *Ty = Qs.strip(T); 4798 4799 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4800 QualType Pointee = PTy->getPointeeType(); 4801 QualType FixedType = 4802 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4803 Oversized); 4804 if (FixedType.isNull()) return FixedType; 4805 FixedType = Context.getPointerType(FixedType); 4806 return Qs.apply(Context, FixedType); 4807 } 4808 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4809 QualType Inner = PTy->getInnerType(); 4810 QualType FixedType = 4811 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4812 Oversized); 4813 if (FixedType.isNull()) return FixedType; 4814 FixedType = Context.getParenType(FixedType); 4815 return Qs.apply(Context, FixedType); 4816 } 4817 4818 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4819 if (!VLATy) 4820 return QualType(); 4821 // FIXME: We should probably handle this case 4822 if (VLATy->getElementType()->isVariablyModifiedType()) 4823 return QualType(); 4824 4825 llvm::APSInt Res; 4826 if (!VLATy->getSizeExpr() || 4827 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4828 return QualType(); 4829 4830 // Check whether the array size is negative. 4831 if (Res.isSigned() && Res.isNegative()) { 4832 SizeIsNegative = true; 4833 return QualType(); 4834 } 4835 4836 // Check whether the array is too large to be addressed. 4837 unsigned ActiveSizeBits 4838 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4839 Res); 4840 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4841 Oversized = Res; 4842 return QualType(); 4843 } 4844 4845 return Context.getConstantArrayType(VLATy->getElementType(), 4846 Res, ArrayType::Normal, 0); 4847 } 4848 4849 static void 4850 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4851 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4852 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4853 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4854 DstPTL.getPointeeLoc()); 4855 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4856 return; 4857 } 4858 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4859 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4860 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4861 DstPTL.getInnerLoc()); 4862 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4863 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4864 return; 4865 } 4866 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4867 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4868 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4869 TypeLoc DstElemTL = DstATL.getElementLoc(); 4870 DstElemTL.initializeFullCopy(SrcElemTL); 4871 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4872 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4873 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4874 } 4875 4876 /// Helper method to turn variable array types into constant array 4877 /// types in certain situations which would otherwise be errors (for 4878 /// GCC compatibility). 4879 static TypeSourceInfo* 4880 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4881 ASTContext &Context, 4882 bool &SizeIsNegative, 4883 llvm::APSInt &Oversized) { 4884 QualType FixedTy 4885 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4886 SizeIsNegative, Oversized); 4887 if (FixedTy.isNull()) 4888 return nullptr; 4889 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4890 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4891 FixedTInfo->getTypeLoc()); 4892 return FixedTInfo; 4893 } 4894 4895 /// \brief Register the given locally-scoped extern "C" declaration so 4896 /// that it can be found later for redeclarations. We include any extern "C" 4897 /// declaration that is not visible in the translation unit here, not just 4898 /// function-scope declarations. 4899 void 4900 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4901 if (!getLangOpts().CPlusPlus && 4902 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4903 // Don't need to track declarations in the TU in C. 4904 return; 4905 4906 // Note that we have a locally-scoped external with this name. 4907 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 4908 } 4909 4910 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4911 // FIXME: We can have multiple results via __attribute__((overloadable)). 4912 auto Result = Context.getExternCContextDecl()->lookup(Name); 4913 return Result.empty() ? nullptr : *Result.begin(); 4914 } 4915 4916 /// \brief Diagnose function specifiers on a declaration of an identifier that 4917 /// does not identify a function. 4918 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4919 // FIXME: We should probably indicate the identifier in question to avoid 4920 // confusion for constructs like "inline int a(), b;" 4921 if (DS.isInlineSpecified()) 4922 Diag(DS.getInlineSpecLoc(), 4923 diag::err_inline_non_function); 4924 4925 if (DS.isVirtualSpecified()) 4926 Diag(DS.getVirtualSpecLoc(), 4927 diag::err_virtual_non_function); 4928 4929 if (DS.isExplicitSpecified()) 4930 Diag(DS.getExplicitSpecLoc(), 4931 diag::err_explicit_non_function); 4932 4933 if (DS.isNoreturnSpecified()) 4934 Diag(DS.getNoreturnSpecLoc(), 4935 diag::err_noreturn_non_function); 4936 } 4937 4938 NamedDecl* 4939 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4940 TypeSourceInfo *TInfo, LookupResult &Previous) { 4941 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4942 if (D.getCXXScopeSpec().isSet()) { 4943 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4944 << D.getCXXScopeSpec().getRange(); 4945 D.setInvalidType(); 4946 // Pretend we didn't see the scope specifier. 4947 DC = CurContext; 4948 Previous.clear(); 4949 } 4950 4951 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4952 4953 if (D.getDeclSpec().isConstexprSpecified()) 4954 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4955 << 1; 4956 4957 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4958 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4959 << D.getName().getSourceRange(); 4960 return nullptr; 4961 } 4962 4963 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4964 if (!NewTD) return nullptr; 4965 4966 // Handle attributes prior to checking for duplicates in MergeVarDecl 4967 ProcessDeclAttributes(S, NewTD, D); 4968 4969 CheckTypedefForVariablyModifiedType(S, NewTD); 4970 4971 bool Redeclaration = D.isRedeclaration(); 4972 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4973 D.setRedeclaration(Redeclaration); 4974 return ND; 4975 } 4976 4977 void 4978 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4979 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4980 // then it shall have block scope. 4981 // Note that variably modified types must be fixed before merging the decl so 4982 // that redeclarations will match. 4983 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4984 QualType T = TInfo->getType(); 4985 if (T->isVariablyModifiedType()) { 4986 getCurFunction()->setHasBranchProtectedScope(); 4987 4988 if (S->getFnParent() == nullptr) { 4989 bool SizeIsNegative; 4990 llvm::APSInt Oversized; 4991 TypeSourceInfo *FixedTInfo = 4992 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4993 SizeIsNegative, 4994 Oversized); 4995 if (FixedTInfo) { 4996 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4997 NewTD->setTypeSourceInfo(FixedTInfo); 4998 } else { 4999 if (SizeIsNegative) 5000 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5001 else if (T->isVariableArrayType()) 5002 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5003 else if (Oversized.getBoolValue()) 5004 Diag(NewTD->getLocation(), diag::err_array_too_large) 5005 << Oversized.toString(10); 5006 else 5007 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5008 NewTD->setInvalidDecl(); 5009 } 5010 } 5011 } 5012 } 5013 5014 5015 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5016 /// declares a typedef-name, either using the 'typedef' type specifier or via 5017 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5018 NamedDecl* 5019 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5020 LookupResult &Previous, bool &Redeclaration) { 5021 // Merge the decl with the existing one if appropriate. If the decl is 5022 // in an outer scope, it isn't the same thing. 5023 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5024 /*AllowInlineNamespace*/false); 5025 filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous); 5026 if (!Previous.empty()) { 5027 Redeclaration = true; 5028 MergeTypedefNameDecl(NewTD, Previous); 5029 } 5030 5031 // If this is the C FILE type, notify the AST context. 5032 if (IdentifierInfo *II = NewTD->getIdentifier()) 5033 if (!NewTD->isInvalidDecl() && 5034 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5035 if (II->isStr("FILE")) 5036 Context.setFILEDecl(NewTD); 5037 else if (II->isStr("jmp_buf")) 5038 Context.setjmp_bufDecl(NewTD); 5039 else if (II->isStr("sigjmp_buf")) 5040 Context.setsigjmp_bufDecl(NewTD); 5041 else if (II->isStr("ucontext_t")) 5042 Context.setucontext_tDecl(NewTD); 5043 } 5044 5045 return NewTD; 5046 } 5047 5048 /// \brief Determines whether the given declaration is an out-of-scope 5049 /// previous declaration. 5050 /// 5051 /// This routine should be invoked when name lookup has found a 5052 /// previous declaration (PrevDecl) that is not in the scope where a 5053 /// new declaration by the same name is being introduced. If the new 5054 /// declaration occurs in a local scope, previous declarations with 5055 /// linkage may still be considered previous declarations (C99 5056 /// 6.2.2p4-5, C++ [basic.link]p6). 5057 /// 5058 /// \param PrevDecl the previous declaration found by name 5059 /// lookup 5060 /// 5061 /// \param DC the context in which the new declaration is being 5062 /// declared. 5063 /// 5064 /// \returns true if PrevDecl is an out-of-scope previous declaration 5065 /// for a new delcaration with the same name. 5066 static bool 5067 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5068 ASTContext &Context) { 5069 if (!PrevDecl) 5070 return false; 5071 5072 if (!PrevDecl->hasLinkage()) 5073 return false; 5074 5075 if (Context.getLangOpts().CPlusPlus) { 5076 // C++ [basic.link]p6: 5077 // If there is a visible declaration of an entity with linkage 5078 // having the same name and type, ignoring entities declared 5079 // outside the innermost enclosing namespace scope, the block 5080 // scope declaration declares that same entity and receives the 5081 // linkage of the previous declaration. 5082 DeclContext *OuterContext = DC->getRedeclContext(); 5083 if (!OuterContext->isFunctionOrMethod()) 5084 // This rule only applies to block-scope declarations. 5085 return false; 5086 5087 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5088 if (PrevOuterContext->isRecord()) 5089 // We found a member function: ignore it. 5090 return false; 5091 5092 // Find the innermost enclosing namespace for the new and 5093 // previous declarations. 5094 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5095 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5096 5097 // The previous declaration is in a different namespace, so it 5098 // isn't the same function. 5099 if (!OuterContext->Equals(PrevOuterContext)) 5100 return false; 5101 } 5102 5103 return true; 5104 } 5105 5106 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5107 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5108 if (!SS.isSet()) return; 5109 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5110 } 5111 5112 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5113 QualType type = decl->getType(); 5114 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5115 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5116 // Various kinds of declaration aren't allowed to be __autoreleasing. 5117 unsigned kind = -1U; 5118 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5119 if (var->hasAttr<BlocksAttr>()) 5120 kind = 0; // __block 5121 else if (!var->hasLocalStorage()) 5122 kind = 1; // global 5123 } else if (isa<ObjCIvarDecl>(decl)) { 5124 kind = 3; // ivar 5125 } else if (isa<FieldDecl>(decl)) { 5126 kind = 2; // field 5127 } 5128 5129 if (kind != -1U) { 5130 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5131 << kind; 5132 } 5133 } else if (lifetime == Qualifiers::OCL_None) { 5134 // Try to infer lifetime. 5135 if (!type->isObjCLifetimeType()) 5136 return false; 5137 5138 lifetime = type->getObjCARCImplicitLifetime(); 5139 type = Context.getLifetimeQualifiedType(type, lifetime); 5140 decl->setType(type); 5141 } 5142 5143 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5144 // Thread-local variables cannot have lifetime. 5145 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5146 var->getTLSKind()) { 5147 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5148 << var->getType(); 5149 return true; 5150 } 5151 } 5152 5153 return false; 5154 } 5155 5156 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5157 // Ensure that an auto decl is deduced otherwise the checks below might cache 5158 // the wrong linkage. 5159 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5160 5161 // 'weak' only applies to declarations with external linkage. 5162 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5163 if (!ND.isExternallyVisible()) { 5164 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5165 ND.dropAttr<WeakAttr>(); 5166 } 5167 } 5168 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5169 if (ND.isExternallyVisible()) { 5170 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5171 ND.dropAttr<WeakRefAttr>(); 5172 ND.dropAttr<AliasAttr>(); 5173 } 5174 } 5175 5176 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5177 if (VD->hasInit()) { 5178 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5179 assert(VD->isThisDeclarationADefinition() && 5180 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5181 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD; 5182 VD->dropAttr<AliasAttr>(); 5183 } 5184 } 5185 } 5186 5187 // 'selectany' only applies to externally visible varable declarations. 5188 // It does not apply to functions. 5189 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5190 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5191 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 5192 ND.dropAttr<SelectAnyAttr>(); 5193 } 5194 } 5195 5196 // dll attributes require external linkage. 5197 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5198 if (!ND.isExternallyVisible()) { 5199 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5200 << &ND << Attr; 5201 ND.setInvalidDecl(); 5202 } 5203 } 5204 } 5205 5206 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5207 NamedDecl *NewDecl, 5208 bool IsSpecialization) { 5209 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5210 OldDecl = OldTD->getTemplatedDecl(); 5211 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5212 NewDecl = NewTD->getTemplatedDecl(); 5213 5214 if (!OldDecl || !NewDecl) 5215 return; 5216 5217 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5218 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5219 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5220 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5221 5222 // dllimport and dllexport are inheritable attributes so we have to exclude 5223 // inherited attribute instances. 5224 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5225 (NewExportAttr && !NewExportAttr->isInherited()); 5226 5227 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5228 // the only exception being explicit specializations. 5229 // Implicitly generated declarations are also excluded for now because there 5230 // is no other way to switch these to use dllimport or dllexport. 5231 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5232 5233 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5234 // If the declaration hasn't been used yet, allow with a warning for 5235 // free functions and global variables. 5236 bool JustWarn = false; 5237 if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) { 5238 auto *VD = dyn_cast<VarDecl>(OldDecl); 5239 if (VD && !VD->getDescribedVarTemplate()) 5240 JustWarn = true; 5241 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5242 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5243 JustWarn = true; 5244 } 5245 5246 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5247 : diag::err_attribute_dll_redeclaration; 5248 S.Diag(NewDecl->getLocation(), DiagID) 5249 << NewDecl 5250 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5251 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5252 if (!JustWarn) { 5253 NewDecl->setInvalidDecl(); 5254 return; 5255 } 5256 } 5257 5258 // A redeclaration is not allowed to drop a dllimport attribute, the only 5259 // exceptions being inline function definitions, local extern declarations, 5260 // and qualified friend declarations. 5261 // NB: MSVC converts such a declaration to dllexport. 5262 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5263 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5264 // Ignore static data because out-of-line definitions are diagnosed 5265 // separately. 5266 IsStaticDataMember = VD->isStaticDataMember(); 5267 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5268 IsInline = FD->isInlined(); 5269 IsQualifiedFriend = FD->getQualifier() && 5270 FD->getFriendObjectKind() == Decl::FOK_Declared; 5271 } 5272 5273 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5274 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5275 S.Diag(NewDecl->getLocation(), 5276 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5277 << NewDecl << OldImportAttr; 5278 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5279 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5280 OldDecl->dropAttr<DLLImportAttr>(); 5281 NewDecl->dropAttr<DLLImportAttr>(); 5282 } else if (IsInline && OldImportAttr && 5283 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5284 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5285 OldDecl->dropAttr<DLLImportAttr>(); 5286 NewDecl->dropAttr<DLLImportAttr>(); 5287 S.Diag(NewDecl->getLocation(), 5288 diag::warn_dllimport_dropped_from_inline_function) 5289 << NewDecl << OldImportAttr; 5290 } 5291 } 5292 5293 /// Given that we are within the definition of the given function, 5294 /// will that definition behave like C99's 'inline', where the 5295 /// definition is discarded except for optimization purposes? 5296 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5297 // Try to avoid calling GetGVALinkageForFunction. 5298 5299 // All cases of this require the 'inline' keyword. 5300 if (!FD->isInlined()) return false; 5301 5302 // This is only possible in C++ with the gnu_inline attribute. 5303 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5304 return false; 5305 5306 // Okay, go ahead and call the relatively-more-expensive function. 5307 5308 #ifndef NDEBUG 5309 // AST quite reasonably asserts that it's working on a function 5310 // definition. We don't really have a way to tell it that we're 5311 // currently defining the function, so just lie to it in +Asserts 5312 // builds. This is an awful hack. 5313 FD->setLazyBody(1); 5314 #endif 5315 5316 bool isC99Inline = 5317 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5318 5319 #ifndef NDEBUG 5320 FD->setLazyBody(0); 5321 #endif 5322 5323 return isC99Inline; 5324 } 5325 5326 /// Determine whether a variable is extern "C" prior to attaching 5327 /// an initializer. We can't just call isExternC() here, because that 5328 /// will also compute and cache whether the declaration is externally 5329 /// visible, which might change when we attach the initializer. 5330 /// 5331 /// This can only be used if the declaration is known to not be a 5332 /// redeclaration of an internal linkage declaration. 5333 /// 5334 /// For instance: 5335 /// 5336 /// auto x = []{}; 5337 /// 5338 /// Attaching the initializer here makes this declaration not externally 5339 /// visible, because its type has internal linkage. 5340 /// 5341 /// FIXME: This is a hack. 5342 template<typename T> 5343 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5344 if (S.getLangOpts().CPlusPlus) { 5345 // In C++, the overloadable attribute negates the effects of extern "C". 5346 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5347 return false; 5348 } 5349 return D->isExternC(); 5350 } 5351 5352 static bool shouldConsiderLinkage(const VarDecl *VD) { 5353 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5354 if (DC->isFunctionOrMethod()) 5355 return VD->hasExternalStorage(); 5356 if (DC->isFileContext()) 5357 return true; 5358 if (DC->isRecord()) 5359 return false; 5360 llvm_unreachable("Unexpected context"); 5361 } 5362 5363 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5364 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5365 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5366 return true; 5367 if (DC->isRecord()) 5368 return false; 5369 llvm_unreachable("Unexpected context"); 5370 } 5371 5372 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5373 AttributeList::Kind Kind) { 5374 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5375 if (L->getKind() == Kind) 5376 return true; 5377 return false; 5378 } 5379 5380 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5381 AttributeList::Kind Kind) { 5382 // Check decl attributes on the DeclSpec. 5383 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5384 return true; 5385 5386 // Walk the declarator structure, checking decl attributes that were in a type 5387 // position to the decl itself. 5388 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5389 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5390 return true; 5391 } 5392 5393 // Finally, check attributes on the decl itself. 5394 return hasParsedAttr(S, PD.getAttributes(), Kind); 5395 } 5396 5397 /// Adjust the \c DeclContext for a function or variable that might be a 5398 /// function-local external declaration. 5399 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5400 if (!DC->isFunctionOrMethod()) 5401 return false; 5402 5403 // If this is a local extern function or variable declared within a function 5404 // template, don't add it into the enclosing namespace scope until it is 5405 // instantiated; it might have a dependent type right now. 5406 if (DC->isDependentContext()) 5407 return true; 5408 5409 // C++11 [basic.link]p7: 5410 // When a block scope declaration of an entity with linkage is not found to 5411 // refer to some other declaration, then that entity is a member of the 5412 // innermost enclosing namespace. 5413 // 5414 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5415 // semantically-enclosing namespace, not a lexically-enclosing one. 5416 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5417 DC = DC->getParent(); 5418 return true; 5419 } 5420 5421 NamedDecl * 5422 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5423 TypeSourceInfo *TInfo, LookupResult &Previous, 5424 MultiTemplateParamsArg TemplateParamLists, 5425 bool &AddToScope) { 5426 QualType R = TInfo->getType(); 5427 DeclarationName Name = GetNameForDeclarator(D).getName(); 5428 5429 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5430 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5431 5432 // dllimport globals without explicit storage class are treated as extern. We 5433 // have to change the storage class this early to get the right DeclContext. 5434 if (SC == SC_None && !DC->isRecord() && 5435 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5436 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5437 SC = SC_Extern; 5438 5439 DeclContext *OriginalDC = DC; 5440 bool IsLocalExternDecl = SC == SC_Extern && 5441 adjustContextForLocalExternDecl(DC); 5442 5443 if (getLangOpts().OpenCL) { 5444 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5445 QualType NR = R; 5446 while (NR->isPointerType()) { 5447 if (NR->isFunctionPointerType()) { 5448 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5449 D.setInvalidType(); 5450 break; 5451 } 5452 NR = NR->getPointeeType(); 5453 } 5454 5455 if (!getOpenCLOptions().cl_khr_fp16) { 5456 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5457 // half array type (unless the cl_khr_fp16 extension is enabled). 5458 if (Context.getBaseElementType(R)->isHalfType()) { 5459 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5460 D.setInvalidType(); 5461 } 5462 } 5463 } 5464 5465 if (SCSpec == DeclSpec::SCS_mutable) { 5466 // mutable can only appear on non-static class members, so it's always 5467 // an error here 5468 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5469 D.setInvalidType(); 5470 SC = SC_None; 5471 } 5472 5473 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5474 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5475 D.getDeclSpec().getStorageClassSpecLoc())) { 5476 // In C++11, the 'register' storage class specifier is deprecated. 5477 // Suppress the warning in system macros, it's used in macros in some 5478 // popular C system headers, such as in glibc's htonl() macro. 5479 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5480 diag::warn_deprecated_register) 5481 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5482 } 5483 5484 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5485 if (!II) { 5486 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5487 << Name; 5488 return nullptr; 5489 } 5490 5491 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5492 5493 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5494 // C99 6.9p2: The storage-class specifiers auto and register shall not 5495 // appear in the declaration specifiers in an external declaration. 5496 // Global Register+Asm is a GNU extension we support. 5497 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5498 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5499 D.setInvalidType(); 5500 } 5501 } 5502 5503 if (getLangOpts().OpenCL) { 5504 // Set up the special work-group-local storage class for variables in the 5505 // OpenCL __local address space. 5506 if (R.getAddressSpace() == LangAS::opencl_local) { 5507 SC = SC_OpenCLWorkGroupLocal; 5508 } 5509 5510 // OpenCL v1.2 s6.9.b p4: 5511 // The sampler type cannot be used with the __local and __global address 5512 // space qualifiers. 5513 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5514 R.getAddressSpace() == LangAS::opencl_global)) { 5515 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5516 } 5517 5518 // OpenCL 1.2 spec, p6.9 r: 5519 // The event type cannot be used to declare a program scope variable. 5520 // The event type cannot be used with the __local, __constant and __global 5521 // address space qualifiers. 5522 if (R->isEventT()) { 5523 if (S->getParent() == nullptr) { 5524 Diag(D.getLocStart(), diag::err_event_t_global_var); 5525 D.setInvalidType(); 5526 } 5527 5528 if (R.getAddressSpace()) { 5529 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5530 D.setInvalidType(); 5531 } 5532 } 5533 } 5534 5535 bool IsExplicitSpecialization = false; 5536 bool IsVariableTemplateSpecialization = false; 5537 bool IsPartialSpecialization = false; 5538 bool IsVariableTemplate = false; 5539 VarDecl *NewVD = nullptr; 5540 VarTemplateDecl *NewTemplate = nullptr; 5541 TemplateParameterList *TemplateParams = nullptr; 5542 if (!getLangOpts().CPlusPlus) { 5543 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5544 D.getIdentifierLoc(), II, 5545 R, TInfo, SC); 5546 5547 if (D.isInvalidType()) 5548 NewVD->setInvalidDecl(); 5549 } else { 5550 bool Invalid = false; 5551 5552 if (DC->isRecord() && !CurContext->isRecord()) { 5553 // This is an out-of-line definition of a static data member. 5554 switch (SC) { 5555 case SC_None: 5556 break; 5557 case SC_Static: 5558 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5559 diag::err_static_out_of_line) 5560 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5561 break; 5562 case SC_Auto: 5563 case SC_Register: 5564 case SC_Extern: 5565 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5566 // to names of variables declared in a block or to function parameters. 5567 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5568 // of class members 5569 5570 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5571 diag::err_storage_class_for_static_member) 5572 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5573 break; 5574 case SC_PrivateExtern: 5575 llvm_unreachable("C storage class in c++!"); 5576 case SC_OpenCLWorkGroupLocal: 5577 llvm_unreachable("OpenCL storage class in c++!"); 5578 } 5579 } 5580 5581 if (SC == SC_Static && CurContext->isRecord()) { 5582 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5583 if (RD->isLocalClass()) 5584 Diag(D.getIdentifierLoc(), 5585 diag::err_static_data_member_not_allowed_in_local_class) 5586 << Name << RD->getDeclName(); 5587 5588 // C++98 [class.union]p1: If a union contains a static data member, 5589 // the program is ill-formed. C++11 drops this restriction. 5590 if (RD->isUnion()) 5591 Diag(D.getIdentifierLoc(), 5592 getLangOpts().CPlusPlus11 5593 ? diag::warn_cxx98_compat_static_data_member_in_union 5594 : diag::ext_static_data_member_in_union) << Name; 5595 // We conservatively disallow static data members in anonymous structs. 5596 else if (!RD->getDeclName()) 5597 Diag(D.getIdentifierLoc(), 5598 diag::err_static_data_member_not_allowed_in_anon_struct) 5599 << Name << RD->isUnion(); 5600 } 5601 } 5602 5603 // Match up the template parameter lists with the scope specifier, then 5604 // determine whether we have a template or a template specialization. 5605 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5606 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5607 D.getCXXScopeSpec(), 5608 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5609 ? D.getName().TemplateId 5610 : nullptr, 5611 TemplateParamLists, 5612 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5613 5614 if (TemplateParams) { 5615 if (!TemplateParams->size() && 5616 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5617 // There is an extraneous 'template<>' for this variable. Complain 5618 // about it, but allow the declaration of the variable. 5619 Diag(TemplateParams->getTemplateLoc(), 5620 diag::err_template_variable_noparams) 5621 << II 5622 << SourceRange(TemplateParams->getTemplateLoc(), 5623 TemplateParams->getRAngleLoc()); 5624 TemplateParams = nullptr; 5625 } else { 5626 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5627 // This is an explicit specialization or a partial specialization. 5628 // FIXME: Check that we can declare a specialization here. 5629 IsVariableTemplateSpecialization = true; 5630 IsPartialSpecialization = TemplateParams->size() > 0; 5631 } else { // if (TemplateParams->size() > 0) 5632 // This is a template declaration. 5633 IsVariableTemplate = true; 5634 5635 // Check that we can declare a template here. 5636 if (CheckTemplateDeclScope(S, TemplateParams)) 5637 return nullptr; 5638 5639 // Only C++1y supports variable templates (N3651). 5640 Diag(D.getIdentifierLoc(), 5641 getLangOpts().CPlusPlus14 5642 ? diag::warn_cxx11_compat_variable_template 5643 : diag::ext_variable_template); 5644 } 5645 } 5646 } else { 5647 assert( 5648 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 5649 "should have a 'template<>' for this decl"); 5650 } 5651 5652 if (IsVariableTemplateSpecialization) { 5653 SourceLocation TemplateKWLoc = 5654 TemplateParamLists.size() > 0 5655 ? TemplateParamLists[0]->getTemplateLoc() 5656 : SourceLocation(); 5657 DeclResult Res = ActOnVarTemplateSpecialization( 5658 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5659 IsPartialSpecialization); 5660 if (Res.isInvalid()) 5661 return nullptr; 5662 NewVD = cast<VarDecl>(Res.get()); 5663 AddToScope = false; 5664 } else 5665 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5666 D.getIdentifierLoc(), II, R, TInfo, SC); 5667 5668 // If this is supposed to be a variable template, create it as such. 5669 if (IsVariableTemplate) { 5670 NewTemplate = 5671 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5672 TemplateParams, NewVD); 5673 NewVD->setDescribedVarTemplate(NewTemplate); 5674 } 5675 5676 // If this decl has an auto type in need of deduction, make a note of the 5677 // Decl so we can diagnose uses of it in its own initializer. 5678 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5679 ParsingInitForAutoVars.insert(NewVD); 5680 5681 if (D.isInvalidType() || Invalid) { 5682 NewVD->setInvalidDecl(); 5683 if (NewTemplate) 5684 NewTemplate->setInvalidDecl(); 5685 } 5686 5687 SetNestedNameSpecifier(NewVD, D); 5688 5689 // If we have any template parameter lists that don't directly belong to 5690 // the variable (matching the scope specifier), store them. 5691 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5692 if (TemplateParamLists.size() > VDTemplateParamLists) 5693 NewVD->setTemplateParameterListsInfo( 5694 Context, TemplateParamLists.size() - VDTemplateParamLists, 5695 TemplateParamLists.data()); 5696 5697 if (D.getDeclSpec().isConstexprSpecified()) 5698 NewVD->setConstexpr(true); 5699 } 5700 5701 // Set the lexical context. If the declarator has a C++ scope specifier, the 5702 // lexical context will be different from the semantic context. 5703 NewVD->setLexicalDeclContext(CurContext); 5704 if (NewTemplate) 5705 NewTemplate->setLexicalDeclContext(CurContext); 5706 5707 if (IsLocalExternDecl) 5708 NewVD->setLocalExternDecl(); 5709 5710 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5711 // C++11 [dcl.stc]p4: 5712 // When thread_local is applied to a variable of block scope the 5713 // storage-class-specifier static is implied if it does not appear 5714 // explicitly. 5715 // Core issue: 'static' is not implied if the variable is declared 5716 // 'extern'. 5717 if (NewVD->hasLocalStorage() && 5718 (SCSpec != DeclSpec::SCS_unspecified || 5719 TSCS != DeclSpec::TSCS_thread_local || 5720 !DC->isFunctionOrMethod())) 5721 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5722 diag::err_thread_non_global) 5723 << DeclSpec::getSpecifierName(TSCS); 5724 else if (!Context.getTargetInfo().isTLSSupported()) 5725 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5726 diag::err_thread_unsupported); 5727 else 5728 NewVD->setTSCSpec(TSCS); 5729 } 5730 5731 // C99 6.7.4p3 5732 // An inline definition of a function with external linkage shall 5733 // not contain a definition of a modifiable object with static or 5734 // thread storage duration... 5735 // We only apply this when the function is required to be defined 5736 // elsewhere, i.e. when the function is not 'extern inline'. Note 5737 // that a local variable with thread storage duration still has to 5738 // be marked 'static'. Also note that it's possible to get these 5739 // semantics in C++ using __attribute__((gnu_inline)). 5740 if (SC == SC_Static && S->getFnParent() != nullptr && 5741 !NewVD->getType().isConstQualified()) { 5742 FunctionDecl *CurFD = getCurFunctionDecl(); 5743 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5744 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5745 diag::warn_static_local_in_extern_inline); 5746 MaybeSuggestAddingStaticToDecl(CurFD); 5747 } 5748 } 5749 5750 if (D.getDeclSpec().isModulePrivateSpecified()) { 5751 if (IsVariableTemplateSpecialization) 5752 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5753 << (IsPartialSpecialization ? 1 : 0) 5754 << FixItHint::CreateRemoval( 5755 D.getDeclSpec().getModulePrivateSpecLoc()); 5756 else if (IsExplicitSpecialization) 5757 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5758 << 2 5759 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5760 else if (NewVD->hasLocalStorage()) 5761 Diag(NewVD->getLocation(), diag::err_module_private_local) 5762 << 0 << NewVD->getDeclName() 5763 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5764 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5765 else { 5766 NewVD->setModulePrivate(); 5767 if (NewTemplate) 5768 NewTemplate->setModulePrivate(); 5769 } 5770 } 5771 5772 // Handle attributes prior to checking for duplicates in MergeVarDecl 5773 ProcessDeclAttributes(S, NewVD, D); 5774 5775 if (getLangOpts().CUDA) { 5776 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5777 // storage [duration]." 5778 if (SC == SC_None && S->getFnParent() != nullptr && 5779 (NewVD->hasAttr<CUDASharedAttr>() || 5780 NewVD->hasAttr<CUDAConstantAttr>())) { 5781 NewVD->setStorageClass(SC_Static); 5782 } 5783 } 5784 5785 // Ensure that dllimport globals without explicit storage class are treated as 5786 // extern. The storage class is set above using parsed attributes. Now we can 5787 // check the VarDecl itself. 5788 assert(!NewVD->hasAttr<DLLImportAttr>() || 5789 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5790 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5791 5792 // In auto-retain/release, infer strong retension for variables of 5793 // retainable type. 5794 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5795 NewVD->setInvalidDecl(); 5796 5797 // Handle GNU asm-label extension (encoded as an attribute). 5798 if (Expr *E = (Expr*)D.getAsmLabel()) { 5799 // The parser guarantees this is a string. 5800 StringLiteral *SE = cast<StringLiteral>(E); 5801 StringRef Label = SE->getString(); 5802 if (S->getFnParent() != nullptr) { 5803 switch (SC) { 5804 case SC_None: 5805 case SC_Auto: 5806 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5807 break; 5808 case SC_Register: 5809 // Local Named register 5810 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5811 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5812 break; 5813 case SC_Static: 5814 case SC_Extern: 5815 case SC_PrivateExtern: 5816 case SC_OpenCLWorkGroupLocal: 5817 break; 5818 } 5819 } else if (SC == SC_Register) { 5820 // Global Named register 5821 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5822 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5823 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5824 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5825 NewVD->setInvalidDecl(true); 5826 } 5827 } 5828 5829 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5830 Context, Label, 0)); 5831 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5832 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5833 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5834 if (I != ExtnameUndeclaredIdentifiers.end()) { 5835 NewVD->addAttr(I->second); 5836 ExtnameUndeclaredIdentifiers.erase(I); 5837 } 5838 } 5839 5840 // Diagnose shadowed variables before filtering for scope. 5841 if (D.getCXXScopeSpec().isEmpty()) 5842 CheckShadow(S, NewVD, Previous); 5843 5844 // Don't consider existing declarations that are in a different 5845 // scope and are out-of-semantic-context declarations (if the new 5846 // declaration has linkage). 5847 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5848 D.getCXXScopeSpec().isNotEmpty() || 5849 IsExplicitSpecialization || 5850 IsVariableTemplateSpecialization); 5851 5852 // Check whether the previous declaration is in the same block scope. This 5853 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5854 if (getLangOpts().CPlusPlus && 5855 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5856 NewVD->setPreviousDeclInSameBlockScope( 5857 Previous.isSingleResult() && !Previous.isShadowed() && 5858 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5859 5860 if (!getLangOpts().CPlusPlus) { 5861 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5862 } else { 5863 // If this is an explicit specialization of a static data member, check it. 5864 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5865 CheckMemberSpecialization(NewVD, Previous)) 5866 NewVD->setInvalidDecl(); 5867 5868 // Merge the decl with the existing one if appropriate. 5869 if (!Previous.empty()) { 5870 if (Previous.isSingleResult() && 5871 isa<FieldDecl>(Previous.getFoundDecl()) && 5872 D.getCXXScopeSpec().isSet()) { 5873 // The user tried to define a non-static data member 5874 // out-of-line (C++ [dcl.meaning]p1). 5875 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5876 << D.getCXXScopeSpec().getRange(); 5877 Previous.clear(); 5878 NewVD->setInvalidDecl(); 5879 } 5880 } else if (D.getCXXScopeSpec().isSet()) { 5881 // No previous declaration in the qualifying scope. 5882 Diag(D.getIdentifierLoc(), diag::err_no_member) 5883 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5884 << D.getCXXScopeSpec().getRange(); 5885 NewVD->setInvalidDecl(); 5886 } 5887 5888 if (!IsVariableTemplateSpecialization) 5889 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5890 5891 if (NewTemplate) { 5892 VarTemplateDecl *PrevVarTemplate = 5893 NewVD->getPreviousDecl() 5894 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5895 : nullptr; 5896 5897 // Check the template parameter list of this declaration, possibly 5898 // merging in the template parameter list from the previous variable 5899 // template declaration. 5900 if (CheckTemplateParameterList( 5901 TemplateParams, 5902 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5903 : nullptr, 5904 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5905 DC->isDependentContext()) 5906 ? TPC_ClassTemplateMember 5907 : TPC_VarTemplate)) 5908 NewVD->setInvalidDecl(); 5909 5910 // If we are providing an explicit specialization of a static variable 5911 // template, make a note of that. 5912 if (PrevVarTemplate && 5913 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5914 PrevVarTemplate->setMemberSpecialization(); 5915 } 5916 } 5917 5918 ProcessPragmaWeak(S, NewVD); 5919 5920 // If this is the first declaration of an extern C variable, update 5921 // the map of such variables. 5922 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5923 isIncompleteDeclExternC(*this, NewVD)) 5924 RegisterLocallyScopedExternCDecl(NewVD, S); 5925 5926 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5927 Decl *ManglingContextDecl; 5928 if (MangleNumberingContext *MCtx = 5929 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5930 ManglingContextDecl)) { 5931 Context.setManglingNumber( 5932 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5933 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5934 } 5935 } 5936 5937 if (D.isRedeclaration() && !Previous.empty()) { 5938 checkDLLAttributeRedeclaration( 5939 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5940 IsExplicitSpecialization); 5941 } 5942 5943 if (NewTemplate) { 5944 if (NewVD->isInvalidDecl()) 5945 NewTemplate->setInvalidDecl(); 5946 ActOnDocumentableDecl(NewTemplate); 5947 return NewTemplate; 5948 } 5949 5950 return NewVD; 5951 } 5952 5953 /// \brief Diagnose variable or built-in function shadowing. Implements 5954 /// -Wshadow. 5955 /// 5956 /// This method is called whenever a VarDecl is added to a "useful" 5957 /// scope. 5958 /// 5959 /// \param S the scope in which the shadowing name is being declared 5960 /// \param R the lookup of the name 5961 /// 5962 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5963 // Return if warning is ignored. 5964 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 5965 return; 5966 5967 // Don't diagnose declarations at file scope. 5968 if (D->hasGlobalStorage()) 5969 return; 5970 5971 DeclContext *NewDC = D->getDeclContext(); 5972 5973 // Only diagnose if we're shadowing an unambiguous field or variable. 5974 if (R.getResultKind() != LookupResult::Found) 5975 return; 5976 5977 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5978 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5979 return; 5980 5981 // Fields are not shadowed by variables in C++ static methods. 5982 if (isa<FieldDecl>(ShadowedDecl)) 5983 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5984 if (MD->isStatic()) 5985 return; 5986 5987 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5988 if (shadowedVar->isExternC()) { 5989 // For shadowing external vars, make sure that we point to the global 5990 // declaration, not a locally scoped extern declaration. 5991 for (auto I : shadowedVar->redecls()) 5992 if (I->isFileVarDecl()) { 5993 ShadowedDecl = I; 5994 break; 5995 } 5996 } 5997 5998 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5999 6000 // Only warn about certain kinds of shadowing for class members. 6001 if (NewDC && NewDC->isRecord()) { 6002 // In particular, don't warn about shadowing non-class members. 6003 if (!OldDC->isRecord()) 6004 return; 6005 6006 // TODO: should we warn about static data members shadowing 6007 // static data members from base classes? 6008 6009 // TODO: don't diagnose for inaccessible shadowed members. 6010 // This is hard to do perfectly because we might friend the 6011 // shadowing context, but that's just a false negative. 6012 } 6013 6014 // Determine what kind of declaration we're shadowing. 6015 unsigned Kind; 6016 if (isa<RecordDecl>(OldDC)) { 6017 if (isa<FieldDecl>(ShadowedDecl)) 6018 Kind = 3; // field 6019 else 6020 Kind = 2; // static data member 6021 } else if (OldDC->isFileContext()) 6022 Kind = 1; // global 6023 else 6024 Kind = 0; // local 6025 6026 DeclarationName Name = R.getLookupName(); 6027 6028 // Emit warning and note. 6029 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6030 return; 6031 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6032 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6033 } 6034 6035 /// \brief Check -Wshadow without the advantage of a previous lookup. 6036 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6037 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6038 return; 6039 6040 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6041 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6042 LookupName(R, S); 6043 CheckShadow(S, D, R); 6044 } 6045 6046 /// Check for conflict between this global or extern "C" declaration and 6047 /// previous global or extern "C" declarations. This is only used in C++. 6048 template<typename T> 6049 static bool checkGlobalOrExternCConflict( 6050 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6051 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6052 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6053 6054 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6055 // The common case: this global doesn't conflict with any extern "C" 6056 // declaration. 6057 return false; 6058 } 6059 6060 if (Prev) { 6061 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6062 // Both the old and new declarations have C language linkage. This is a 6063 // redeclaration. 6064 Previous.clear(); 6065 Previous.addDecl(Prev); 6066 return true; 6067 } 6068 6069 // This is a global, non-extern "C" declaration, and there is a previous 6070 // non-global extern "C" declaration. Diagnose if this is a variable 6071 // declaration. 6072 if (!isa<VarDecl>(ND)) 6073 return false; 6074 } else { 6075 // The declaration is extern "C". Check for any declaration in the 6076 // translation unit which might conflict. 6077 if (IsGlobal) { 6078 // We have already performed the lookup into the translation unit. 6079 IsGlobal = false; 6080 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6081 I != E; ++I) { 6082 if (isa<VarDecl>(*I)) { 6083 Prev = *I; 6084 break; 6085 } 6086 } 6087 } else { 6088 DeclContext::lookup_result R = 6089 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6090 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6091 I != E; ++I) { 6092 if (isa<VarDecl>(*I)) { 6093 Prev = *I; 6094 break; 6095 } 6096 // FIXME: If we have any other entity with this name in global scope, 6097 // the declaration is ill-formed, but that is a defect: it breaks the 6098 // 'stat' hack, for instance. Only variables can have mangled name 6099 // clashes with extern "C" declarations, so only they deserve a 6100 // diagnostic. 6101 } 6102 } 6103 6104 if (!Prev) 6105 return false; 6106 } 6107 6108 // Use the first declaration's location to ensure we point at something which 6109 // is lexically inside an extern "C" linkage-spec. 6110 assert(Prev && "should have found a previous declaration to diagnose"); 6111 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6112 Prev = FD->getFirstDecl(); 6113 else 6114 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6115 6116 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6117 << IsGlobal << ND; 6118 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6119 << IsGlobal; 6120 return false; 6121 } 6122 6123 /// Apply special rules for handling extern "C" declarations. Returns \c true 6124 /// if we have found that this is a redeclaration of some prior entity. 6125 /// 6126 /// Per C++ [dcl.link]p6: 6127 /// Two declarations [for a function or variable] with C language linkage 6128 /// with the same name that appear in different scopes refer to the same 6129 /// [entity]. An entity with C language linkage shall not be declared with 6130 /// the same name as an entity in global scope. 6131 template<typename T> 6132 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6133 LookupResult &Previous) { 6134 if (!S.getLangOpts().CPlusPlus) { 6135 // In C, when declaring a global variable, look for a corresponding 'extern' 6136 // variable declared in function scope. We don't need this in C++, because 6137 // we find local extern decls in the surrounding file-scope DeclContext. 6138 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6139 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6140 Previous.clear(); 6141 Previous.addDecl(Prev); 6142 return true; 6143 } 6144 } 6145 return false; 6146 } 6147 6148 // A declaration in the translation unit can conflict with an extern "C" 6149 // declaration. 6150 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6151 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6152 6153 // An extern "C" declaration can conflict with a declaration in the 6154 // translation unit or can be a redeclaration of an extern "C" declaration 6155 // in another scope. 6156 if (isIncompleteDeclExternC(S,ND)) 6157 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6158 6159 // Neither global nor extern "C": nothing to do. 6160 return false; 6161 } 6162 6163 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6164 // If the decl is already known invalid, don't check it. 6165 if (NewVD->isInvalidDecl()) 6166 return; 6167 6168 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6169 QualType T = TInfo->getType(); 6170 6171 // Defer checking an 'auto' type until its initializer is attached. 6172 if (T->isUndeducedType()) 6173 return; 6174 6175 if (NewVD->hasAttrs()) 6176 CheckAlignasUnderalignment(NewVD); 6177 6178 if (T->isObjCObjectType()) { 6179 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6180 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6181 T = Context.getObjCObjectPointerType(T); 6182 NewVD->setType(T); 6183 } 6184 6185 // Emit an error if an address space was applied to decl with local storage. 6186 // This includes arrays of objects with address space qualifiers, but not 6187 // automatic variables that point to other address spaces. 6188 // ISO/IEC TR 18037 S5.1.2 6189 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6190 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6191 NewVD->setInvalidDecl(); 6192 return; 6193 } 6194 6195 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6196 // __constant address space. 6197 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 6198 && T.getAddressSpace() != LangAS::opencl_constant 6199 && !T->isSamplerT()){ 6200 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 6201 NewVD->setInvalidDecl(); 6202 return; 6203 } 6204 6205 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6206 // scope. 6207 if ((getLangOpts().OpenCLVersion >= 120) 6208 && NewVD->isStaticLocal()) { 6209 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6210 NewVD->setInvalidDecl(); 6211 return; 6212 } 6213 6214 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6215 && !NewVD->hasAttr<BlocksAttr>()) { 6216 if (getLangOpts().getGC() != LangOptions::NonGC) 6217 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6218 else { 6219 assert(!getLangOpts().ObjCAutoRefCount); 6220 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6221 } 6222 } 6223 6224 bool isVM = T->isVariablyModifiedType(); 6225 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6226 NewVD->hasAttr<BlocksAttr>()) 6227 getCurFunction()->setHasBranchProtectedScope(); 6228 6229 if ((isVM && NewVD->hasLinkage()) || 6230 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6231 bool SizeIsNegative; 6232 llvm::APSInt Oversized; 6233 TypeSourceInfo *FixedTInfo = 6234 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6235 SizeIsNegative, Oversized); 6236 if (!FixedTInfo && T->isVariableArrayType()) { 6237 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6238 // FIXME: This won't give the correct result for 6239 // int a[10][n]; 6240 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6241 6242 if (NewVD->isFileVarDecl()) 6243 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6244 << SizeRange; 6245 else if (NewVD->isStaticLocal()) 6246 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6247 << SizeRange; 6248 else 6249 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6250 << SizeRange; 6251 NewVD->setInvalidDecl(); 6252 return; 6253 } 6254 6255 if (!FixedTInfo) { 6256 if (NewVD->isFileVarDecl()) 6257 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6258 else 6259 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6260 NewVD->setInvalidDecl(); 6261 return; 6262 } 6263 6264 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6265 NewVD->setType(FixedTInfo->getType()); 6266 NewVD->setTypeSourceInfo(FixedTInfo); 6267 } 6268 6269 if (T->isVoidType()) { 6270 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6271 // of objects and functions. 6272 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6273 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6274 << T; 6275 NewVD->setInvalidDecl(); 6276 return; 6277 } 6278 } 6279 6280 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6281 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6282 NewVD->setInvalidDecl(); 6283 return; 6284 } 6285 6286 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6287 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6288 NewVD->setInvalidDecl(); 6289 return; 6290 } 6291 6292 if (NewVD->isConstexpr() && !T->isDependentType() && 6293 RequireLiteralType(NewVD->getLocation(), T, 6294 diag::err_constexpr_var_non_literal)) { 6295 NewVD->setInvalidDecl(); 6296 return; 6297 } 6298 } 6299 6300 /// \brief Perform semantic checking on a newly-created variable 6301 /// declaration. 6302 /// 6303 /// This routine performs all of the type-checking required for a 6304 /// variable declaration once it has been built. It is used both to 6305 /// check variables after they have been parsed and their declarators 6306 /// have been translated into a declaration, and to check variables 6307 /// that have been instantiated from a template. 6308 /// 6309 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6310 /// 6311 /// Returns true if the variable declaration is a redeclaration. 6312 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6313 CheckVariableDeclarationType(NewVD); 6314 6315 // If the decl is already known invalid, don't check it. 6316 if (NewVD->isInvalidDecl()) 6317 return false; 6318 6319 // If we did not find anything by this name, look for a non-visible 6320 // extern "C" declaration with the same name. 6321 if (Previous.empty() && 6322 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6323 Previous.setShadowed(); 6324 6325 // Filter out any non-conflicting previous declarations. 6326 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 6327 6328 if (!Previous.empty()) { 6329 MergeVarDecl(NewVD, Previous); 6330 return true; 6331 } 6332 return false; 6333 } 6334 6335 /// \brief Data used with FindOverriddenMethod 6336 struct FindOverriddenMethodData { 6337 Sema *S; 6338 CXXMethodDecl *Method; 6339 }; 6340 6341 /// \brief Member lookup function that determines whether a given C++ 6342 /// method overrides a method in a base class, to be used with 6343 /// CXXRecordDecl::lookupInBases(). 6344 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6345 CXXBasePath &Path, 6346 void *UserData) { 6347 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6348 6349 FindOverriddenMethodData *Data 6350 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6351 6352 DeclarationName Name = Data->Method->getDeclName(); 6353 6354 // FIXME: Do we care about other names here too? 6355 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6356 // We really want to find the base class destructor here. 6357 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6358 CanQualType CT = Data->S->Context.getCanonicalType(T); 6359 6360 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6361 } 6362 6363 for (Path.Decls = BaseRecord->lookup(Name); 6364 !Path.Decls.empty(); 6365 Path.Decls = Path.Decls.slice(1)) { 6366 NamedDecl *D = Path.Decls.front(); 6367 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6368 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6369 return true; 6370 } 6371 } 6372 6373 return false; 6374 } 6375 6376 namespace { 6377 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6378 } 6379 /// \brief Report an error regarding overriding, along with any relevant 6380 /// overriden methods. 6381 /// 6382 /// \param DiagID the primary error to report. 6383 /// \param MD the overriding method. 6384 /// \param OEK which overrides to include as notes. 6385 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6386 OverrideErrorKind OEK = OEK_All) { 6387 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6388 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6389 E = MD->end_overridden_methods(); 6390 I != E; ++I) { 6391 // This check (& the OEK parameter) could be replaced by a predicate, but 6392 // without lambdas that would be overkill. This is still nicer than writing 6393 // out the diag loop 3 times. 6394 if ((OEK == OEK_All) || 6395 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6396 (OEK == OEK_Deleted && (*I)->isDeleted())) 6397 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6398 } 6399 } 6400 6401 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6402 /// and if so, check that it's a valid override and remember it. 6403 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6404 // Look for methods in base classes that this method might override. 6405 CXXBasePaths Paths; 6406 FindOverriddenMethodData Data; 6407 Data.Method = MD; 6408 Data.S = this; 6409 bool hasDeletedOverridenMethods = false; 6410 bool hasNonDeletedOverridenMethods = false; 6411 bool AddedAny = false; 6412 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6413 for (auto *I : Paths.found_decls()) { 6414 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6415 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6416 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6417 !CheckOverridingFunctionAttributes(MD, OldMD) && 6418 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6419 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6420 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6421 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6422 AddedAny = true; 6423 } 6424 } 6425 } 6426 } 6427 6428 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6429 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6430 } 6431 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6432 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6433 } 6434 6435 return AddedAny; 6436 } 6437 6438 namespace { 6439 // Struct for holding all of the extra arguments needed by 6440 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6441 struct ActOnFDArgs { 6442 Scope *S; 6443 Declarator &D; 6444 MultiTemplateParamsArg TemplateParamLists; 6445 bool AddToScope; 6446 }; 6447 } 6448 6449 namespace { 6450 6451 // Callback to only accept typo corrections that have a non-zero edit distance. 6452 // Also only accept corrections that have the same parent decl. 6453 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6454 public: 6455 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6456 CXXRecordDecl *Parent) 6457 : Context(Context), OriginalFD(TypoFD), 6458 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6459 6460 bool ValidateCandidate(const TypoCorrection &candidate) override { 6461 if (candidate.getEditDistance() == 0) 6462 return false; 6463 6464 SmallVector<unsigned, 1> MismatchedParams; 6465 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6466 CDeclEnd = candidate.end(); 6467 CDecl != CDeclEnd; ++CDecl) { 6468 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6469 6470 if (FD && !FD->hasBody() && 6471 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6472 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6473 CXXRecordDecl *Parent = MD->getParent(); 6474 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6475 return true; 6476 } else if (!ExpectedParent) { 6477 return true; 6478 } 6479 } 6480 } 6481 6482 return false; 6483 } 6484 6485 private: 6486 ASTContext &Context; 6487 FunctionDecl *OriginalFD; 6488 CXXRecordDecl *ExpectedParent; 6489 }; 6490 6491 } 6492 6493 /// \brief Generate diagnostics for an invalid function redeclaration. 6494 /// 6495 /// This routine handles generating the diagnostic messages for an invalid 6496 /// function redeclaration, including finding possible similar declarations 6497 /// or performing typo correction if there are no previous declarations with 6498 /// the same name. 6499 /// 6500 /// Returns a NamedDecl iff typo correction was performed and substituting in 6501 /// the new declaration name does not cause new errors. 6502 static NamedDecl *DiagnoseInvalidRedeclaration( 6503 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6504 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6505 DeclarationName Name = NewFD->getDeclName(); 6506 DeclContext *NewDC = NewFD->getDeclContext(); 6507 SmallVector<unsigned, 1> MismatchedParams; 6508 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6509 TypoCorrection Correction; 6510 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6511 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6512 : diag::err_member_decl_does_not_match; 6513 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6514 IsLocalFriend ? Sema::LookupLocalFriendName 6515 : Sema::LookupOrdinaryName, 6516 Sema::ForRedeclaration); 6517 6518 NewFD->setInvalidDecl(); 6519 if (IsLocalFriend) 6520 SemaRef.LookupName(Prev, S); 6521 else 6522 SemaRef.LookupQualifiedName(Prev, NewDC); 6523 assert(!Prev.isAmbiguous() && 6524 "Cannot have an ambiguity in previous-declaration lookup"); 6525 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6526 if (!Prev.empty()) { 6527 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6528 Func != FuncEnd; ++Func) { 6529 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6530 if (FD && 6531 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6532 // Add 1 to the index so that 0 can mean the mismatch didn't 6533 // involve a parameter 6534 unsigned ParamNum = 6535 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6536 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6537 } 6538 } 6539 // If the qualified name lookup yielded nothing, try typo correction 6540 } else if ((Correction = SemaRef.CorrectTypo( 6541 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6542 &ExtraArgs.D.getCXXScopeSpec(), 6543 llvm::make_unique<DifferentNameValidatorCCC>( 6544 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 6545 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6546 // Set up everything for the call to ActOnFunctionDeclarator 6547 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6548 ExtraArgs.D.getIdentifierLoc()); 6549 Previous.clear(); 6550 Previous.setLookupName(Correction.getCorrection()); 6551 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6552 CDeclEnd = Correction.end(); 6553 CDecl != CDeclEnd; ++CDecl) { 6554 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6555 if (FD && !FD->hasBody() && 6556 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6557 Previous.addDecl(FD); 6558 } 6559 } 6560 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6561 6562 NamedDecl *Result; 6563 // Retry building the function declaration with the new previous 6564 // declarations, and with errors suppressed. 6565 { 6566 // Trap errors. 6567 Sema::SFINAETrap Trap(SemaRef); 6568 6569 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6570 // pieces need to verify the typo-corrected C++ declaration and hopefully 6571 // eliminate the need for the parameter pack ExtraArgs. 6572 Result = SemaRef.ActOnFunctionDeclarator( 6573 ExtraArgs.S, ExtraArgs.D, 6574 Correction.getCorrectionDecl()->getDeclContext(), 6575 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6576 ExtraArgs.AddToScope); 6577 6578 if (Trap.hasErrorOccurred()) 6579 Result = nullptr; 6580 } 6581 6582 if (Result) { 6583 // Determine which correction we picked. 6584 Decl *Canonical = Result->getCanonicalDecl(); 6585 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6586 I != E; ++I) 6587 if ((*I)->getCanonicalDecl() == Canonical) 6588 Correction.setCorrectionDecl(*I); 6589 6590 SemaRef.diagnoseTypo( 6591 Correction, 6592 SemaRef.PDiag(IsLocalFriend 6593 ? diag::err_no_matching_local_friend_suggest 6594 : diag::err_member_decl_does_not_match_suggest) 6595 << Name << NewDC << IsDefinition); 6596 return Result; 6597 } 6598 6599 // Pretend the typo correction never occurred 6600 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6601 ExtraArgs.D.getIdentifierLoc()); 6602 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6603 Previous.clear(); 6604 Previous.setLookupName(Name); 6605 } 6606 6607 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6608 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6609 6610 bool NewFDisConst = false; 6611 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6612 NewFDisConst = NewMD->isConst(); 6613 6614 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6615 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6616 NearMatch != NearMatchEnd; ++NearMatch) { 6617 FunctionDecl *FD = NearMatch->first; 6618 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6619 bool FDisConst = MD && MD->isConst(); 6620 bool IsMember = MD || !IsLocalFriend; 6621 6622 // FIXME: These notes are poorly worded for the local friend case. 6623 if (unsigned Idx = NearMatch->second) { 6624 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6625 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6626 if (Loc.isInvalid()) Loc = FD->getLocation(); 6627 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6628 : diag::note_local_decl_close_param_match) 6629 << Idx << FDParam->getType() 6630 << NewFD->getParamDecl(Idx - 1)->getType(); 6631 } else if (FDisConst != NewFDisConst) { 6632 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6633 << NewFDisConst << FD->getSourceRange().getEnd(); 6634 } else 6635 SemaRef.Diag(FD->getLocation(), 6636 IsMember ? diag::note_member_def_close_match 6637 : diag::note_local_decl_close_match); 6638 } 6639 return nullptr; 6640 } 6641 6642 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 6643 switch (D.getDeclSpec().getStorageClassSpec()) { 6644 default: llvm_unreachable("Unknown storage class!"); 6645 case DeclSpec::SCS_auto: 6646 case DeclSpec::SCS_register: 6647 case DeclSpec::SCS_mutable: 6648 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6649 diag::err_typecheck_sclass_func); 6650 D.setInvalidType(); 6651 break; 6652 case DeclSpec::SCS_unspecified: break; 6653 case DeclSpec::SCS_extern: 6654 if (D.getDeclSpec().isExternInLinkageSpec()) 6655 return SC_None; 6656 return SC_Extern; 6657 case DeclSpec::SCS_static: { 6658 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6659 // C99 6.7.1p5: 6660 // The declaration of an identifier for a function that has 6661 // block scope shall have no explicit storage-class specifier 6662 // other than extern 6663 // See also (C++ [dcl.stc]p4). 6664 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6665 diag::err_static_block_func); 6666 break; 6667 } else 6668 return SC_Static; 6669 } 6670 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6671 } 6672 6673 // No explicit storage class has already been returned 6674 return SC_None; 6675 } 6676 6677 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6678 DeclContext *DC, QualType &R, 6679 TypeSourceInfo *TInfo, 6680 StorageClass SC, 6681 bool &IsVirtualOkay) { 6682 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6683 DeclarationName Name = NameInfo.getName(); 6684 6685 FunctionDecl *NewFD = nullptr; 6686 bool isInline = D.getDeclSpec().isInlineSpecified(); 6687 6688 if (!SemaRef.getLangOpts().CPlusPlus) { 6689 // Determine whether the function was written with a 6690 // prototype. This true when: 6691 // - there is a prototype in the declarator, or 6692 // - the type R of the function is some kind of typedef or other reference 6693 // to a type name (which eventually refers to a function type). 6694 bool HasPrototype = 6695 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6696 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6697 6698 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6699 D.getLocStart(), NameInfo, R, 6700 TInfo, SC, isInline, 6701 HasPrototype, false); 6702 if (D.isInvalidType()) 6703 NewFD->setInvalidDecl(); 6704 6705 return NewFD; 6706 } 6707 6708 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6709 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6710 6711 // Check that the return type is not an abstract class type. 6712 // For record types, this is done by the AbstractClassUsageDiagnoser once 6713 // the class has been completely parsed. 6714 if (!DC->isRecord() && 6715 SemaRef.RequireNonAbstractType( 6716 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6717 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6718 D.setInvalidType(); 6719 6720 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6721 // This is a C++ constructor declaration. 6722 assert(DC->isRecord() && 6723 "Constructors can only be declared in a member context"); 6724 6725 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6726 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6727 D.getLocStart(), NameInfo, 6728 R, TInfo, isExplicit, isInline, 6729 /*isImplicitlyDeclared=*/false, 6730 isConstexpr); 6731 6732 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6733 // This is a C++ destructor declaration. 6734 if (DC->isRecord()) { 6735 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6736 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6737 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6738 SemaRef.Context, Record, 6739 D.getLocStart(), 6740 NameInfo, R, TInfo, isInline, 6741 /*isImplicitlyDeclared=*/false); 6742 6743 // If the class is complete, then we now create the implicit exception 6744 // specification. If the class is incomplete or dependent, we can't do 6745 // it yet. 6746 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6747 Record->getDefinition() && !Record->isBeingDefined() && 6748 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6749 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6750 } 6751 6752 IsVirtualOkay = true; 6753 return NewDD; 6754 6755 } else { 6756 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6757 D.setInvalidType(); 6758 6759 // Create a FunctionDecl to satisfy the function definition parsing 6760 // code path. 6761 return FunctionDecl::Create(SemaRef.Context, DC, 6762 D.getLocStart(), 6763 D.getIdentifierLoc(), Name, R, TInfo, 6764 SC, isInline, 6765 /*hasPrototype=*/true, isConstexpr); 6766 } 6767 6768 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6769 if (!DC->isRecord()) { 6770 SemaRef.Diag(D.getIdentifierLoc(), 6771 diag::err_conv_function_not_member); 6772 return nullptr; 6773 } 6774 6775 SemaRef.CheckConversionDeclarator(D, R, SC); 6776 IsVirtualOkay = true; 6777 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6778 D.getLocStart(), NameInfo, 6779 R, TInfo, isInline, isExplicit, 6780 isConstexpr, SourceLocation()); 6781 6782 } else if (DC->isRecord()) { 6783 // If the name of the function is the same as the name of the record, 6784 // then this must be an invalid constructor that has a return type. 6785 // (The parser checks for a return type and makes the declarator a 6786 // constructor if it has no return type). 6787 if (Name.getAsIdentifierInfo() && 6788 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6789 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6790 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6791 << SourceRange(D.getIdentifierLoc()); 6792 return nullptr; 6793 } 6794 6795 // This is a C++ method declaration. 6796 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6797 cast<CXXRecordDecl>(DC), 6798 D.getLocStart(), NameInfo, R, 6799 TInfo, SC, isInline, 6800 isConstexpr, SourceLocation()); 6801 IsVirtualOkay = !Ret->isStatic(); 6802 return Ret; 6803 } else { 6804 bool isFriend = 6805 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 6806 if (!isFriend && SemaRef.CurContext->isRecord()) 6807 return nullptr; 6808 6809 // Determine whether the function was written with a 6810 // prototype. This true when: 6811 // - we're in C++ (where every function has a prototype), 6812 return FunctionDecl::Create(SemaRef.Context, DC, 6813 D.getLocStart(), 6814 NameInfo, R, TInfo, SC, isInline, 6815 true/*HasPrototype*/, isConstexpr); 6816 } 6817 } 6818 6819 enum OpenCLParamType { 6820 ValidKernelParam, 6821 PtrPtrKernelParam, 6822 PtrKernelParam, 6823 PrivatePtrKernelParam, 6824 InvalidKernelParam, 6825 RecordKernelParam 6826 }; 6827 6828 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6829 if (PT->isPointerType()) { 6830 QualType PointeeType = PT->getPointeeType(); 6831 if (PointeeType->isPointerType()) 6832 return PtrPtrKernelParam; 6833 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6834 : PtrKernelParam; 6835 } 6836 6837 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6838 // be used as builtin types. 6839 6840 if (PT->isImageType()) 6841 return PtrKernelParam; 6842 6843 if (PT->isBooleanType()) 6844 return InvalidKernelParam; 6845 6846 if (PT->isEventT()) 6847 return InvalidKernelParam; 6848 6849 if (PT->isHalfType()) 6850 return InvalidKernelParam; 6851 6852 if (PT->isRecordType()) 6853 return RecordKernelParam; 6854 6855 return ValidKernelParam; 6856 } 6857 6858 static void checkIsValidOpenCLKernelParameter( 6859 Sema &S, 6860 Declarator &D, 6861 ParmVarDecl *Param, 6862 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 6863 QualType PT = Param->getType(); 6864 6865 // Cache the valid types we encounter to avoid rechecking structs that are 6866 // used again 6867 if (ValidTypes.count(PT.getTypePtr())) 6868 return; 6869 6870 switch (getOpenCLKernelParameterType(PT)) { 6871 case PtrPtrKernelParam: 6872 // OpenCL v1.2 s6.9.a: 6873 // A kernel function argument cannot be declared as a 6874 // pointer to a pointer type. 6875 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6876 D.setInvalidType(); 6877 return; 6878 6879 case PrivatePtrKernelParam: 6880 // OpenCL v1.2 s6.9.a: 6881 // A kernel function argument cannot be declared as a 6882 // pointer to the private address space. 6883 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6884 D.setInvalidType(); 6885 return; 6886 6887 // OpenCL v1.2 s6.9.k: 6888 // Arguments to kernel functions in a program cannot be declared with the 6889 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6890 // uintptr_t or a struct and/or union that contain fields declared to be 6891 // one of these built-in scalar types. 6892 6893 case InvalidKernelParam: 6894 // OpenCL v1.2 s6.8 n: 6895 // A kernel function argument cannot be declared 6896 // of event_t type. 6897 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6898 D.setInvalidType(); 6899 return; 6900 6901 case PtrKernelParam: 6902 case ValidKernelParam: 6903 ValidTypes.insert(PT.getTypePtr()); 6904 return; 6905 6906 case RecordKernelParam: 6907 break; 6908 } 6909 6910 // Track nested structs we will inspect 6911 SmallVector<const Decl *, 4> VisitStack; 6912 6913 // Track where we are in the nested structs. Items will migrate from 6914 // VisitStack to HistoryStack as we do the DFS for bad field. 6915 SmallVector<const FieldDecl *, 4> HistoryStack; 6916 HistoryStack.push_back(nullptr); 6917 6918 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6919 VisitStack.push_back(PD); 6920 6921 assert(VisitStack.back() && "First decl null?"); 6922 6923 do { 6924 const Decl *Next = VisitStack.pop_back_val(); 6925 if (!Next) { 6926 assert(!HistoryStack.empty()); 6927 // Found a marker, we have gone up a level 6928 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6929 ValidTypes.insert(Hist->getType().getTypePtr()); 6930 6931 continue; 6932 } 6933 6934 // Adds everything except the original parameter declaration (which is not a 6935 // field itself) to the history stack. 6936 const RecordDecl *RD; 6937 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6938 HistoryStack.push_back(Field); 6939 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6940 } else { 6941 RD = cast<RecordDecl>(Next); 6942 } 6943 6944 // Add a null marker so we know when we've gone back up a level 6945 VisitStack.push_back(nullptr); 6946 6947 for (const auto *FD : RD->fields()) { 6948 QualType QT = FD->getType(); 6949 6950 if (ValidTypes.count(QT.getTypePtr())) 6951 continue; 6952 6953 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6954 if (ParamType == ValidKernelParam) 6955 continue; 6956 6957 if (ParamType == RecordKernelParam) { 6958 VisitStack.push_back(FD); 6959 continue; 6960 } 6961 6962 // OpenCL v1.2 s6.9.p: 6963 // Arguments to kernel functions that are declared to be a struct or union 6964 // do not allow OpenCL objects to be passed as elements of the struct or 6965 // union. 6966 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6967 ParamType == PrivatePtrKernelParam) { 6968 S.Diag(Param->getLocation(), 6969 diag::err_record_with_pointers_kernel_param) 6970 << PT->isUnionType() 6971 << PT; 6972 } else { 6973 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6974 } 6975 6976 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6977 << PD->getDeclName(); 6978 6979 // We have an error, now let's go back up through history and show where 6980 // the offending field came from 6981 for (ArrayRef<const FieldDecl *>::const_iterator 6982 I = HistoryStack.begin() + 1, 6983 E = HistoryStack.end(); 6984 I != E; ++I) { 6985 const FieldDecl *OuterField = *I; 6986 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6987 << OuterField->getType(); 6988 } 6989 6990 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6991 << QT->isPointerType() 6992 << QT; 6993 D.setInvalidType(); 6994 return; 6995 } 6996 } while (!VisitStack.empty()); 6997 } 6998 6999 NamedDecl* 7000 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7001 TypeSourceInfo *TInfo, LookupResult &Previous, 7002 MultiTemplateParamsArg TemplateParamLists, 7003 bool &AddToScope) { 7004 QualType R = TInfo->getType(); 7005 7006 assert(R.getTypePtr()->isFunctionType()); 7007 7008 // TODO: consider using NameInfo for diagnostic. 7009 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7010 DeclarationName Name = NameInfo.getName(); 7011 StorageClass SC = getFunctionStorageClass(*this, D); 7012 7013 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7014 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7015 diag::err_invalid_thread) 7016 << DeclSpec::getSpecifierName(TSCS); 7017 7018 if (D.isFirstDeclarationOfMember()) 7019 adjustMemberFunctionCC(R, D.isStaticMember()); 7020 7021 bool isFriend = false; 7022 FunctionTemplateDecl *FunctionTemplate = nullptr; 7023 bool isExplicitSpecialization = false; 7024 bool isFunctionTemplateSpecialization = false; 7025 7026 bool isDependentClassScopeExplicitSpecialization = false; 7027 bool HasExplicitTemplateArgs = false; 7028 TemplateArgumentListInfo TemplateArgs; 7029 7030 bool isVirtualOkay = false; 7031 7032 DeclContext *OriginalDC = DC; 7033 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7034 7035 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7036 isVirtualOkay); 7037 if (!NewFD) return nullptr; 7038 7039 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7040 NewFD->setTopLevelDeclInObjCContainer(); 7041 7042 // Set the lexical context. If this is a function-scope declaration, or has a 7043 // C++ scope specifier, or is the object of a friend declaration, the lexical 7044 // context will be different from the semantic context. 7045 NewFD->setLexicalDeclContext(CurContext); 7046 7047 if (IsLocalExternDecl) 7048 NewFD->setLocalExternDecl(); 7049 7050 if (getLangOpts().CPlusPlus) { 7051 bool isInline = D.getDeclSpec().isInlineSpecified(); 7052 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7053 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7054 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7055 isFriend = D.getDeclSpec().isFriendSpecified(); 7056 if (isFriend && !isInline && D.isFunctionDefinition()) { 7057 // C++ [class.friend]p5 7058 // A function can be defined in a friend declaration of a 7059 // class . . . . Such a function is implicitly inline. 7060 NewFD->setImplicitlyInline(); 7061 } 7062 7063 // If this is a method defined in an __interface, and is not a constructor 7064 // or an overloaded operator, then set the pure flag (isVirtual will already 7065 // return true). 7066 if (const CXXRecordDecl *Parent = 7067 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7068 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7069 NewFD->setPure(true); 7070 } 7071 7072 SetNestedNameSpecifier(NewFD, D); 7073 isExplicitSpecialization = false; 7074 isFunctionTemplateSpecialization = false; 7075 if (D.isInvalidType()) 7076 NewFD->setInvalidDecl(); 7077 7078 // Match up the template parameter lists with the scope specifier, then 7079 // determine whether we have a template or a template specialization. 7080 bool Invalid = false; 7081 if (TemplateParameterList *TemplateParams = 7082 MatchTemplateParametersToScopeSpecifier( 7083 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7084 D.getCXXScopeSpec(), 7085 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7086 ? D.getName().TemplateId 7087 : nullptr, 7088 TemplateParamLists, isFriend, isExplicitSpecialization, 7089 Invalid)) { 7090 if (TemplateParams->size() > 0) { 7091 // This is a function template 7092 7093 // Check that we can declare a template here. 7094 if (CheckTemplateDeclScope(S, TemplateParams)) 7095 NewFD->setInvalidDecl(); 7096 7097 // A destructor cannot be a template. 7098 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7099 Diag(NewFD->getLocation(), diag::err_destructor_template); 7100 NewFD->setInvalidDecl(); 7101 } 7102 7103 // If we're adding a template to a dependent context, we may need to 7104 // rebuilding some of the types used within the template parameter list, 7105 // now that we know what the current instantiation is. 7106 if (DC->isDependentContext()) { 7107 ContextRAII SavedContext(*this, DC); 7108 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7109 Invalid = true; 7110 } 7111 7112 7113 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7114 NewFD->getLocation(), 7115 Name, TemplateParams, 7116 NewFD); 7117 FunctionTemplate->setLexicalDeclContext(CurContext); 7118 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7119 7120 // For source fidelity, store the other template param lists. 7121 if (TemplateParamLists.size() > 1) { 7122 NewFD->setTemplateParameterListsInfo(Context, 7123 TemplateParamLists.size() - 1, 7124 TemplateParamLists.data()); 7125 } 7126 } else { 7127 // This is a function template specialization. 7128 isFunctionTemplateSpecialization = true; 7129 // For source fidelity, store all the template param lists. 7130 if (TemplateParamLists.size() > 0) 7131 NewFD->setTemplateParameterListsInfo(Context, 7132 TemplateParamLists.size(), 7133 TemplateParamLists.data()); 7134 7135 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7136 if (isFriend) { 7137 // We want to remove the "template<>", found here. 7138 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7139 7140 // If we remove the template<> and the name is not a 7141 // template-id, we're actually silently creating a problem: 7142 // the friend declaration will refer to an untemplated decl, 7143 // and clearly the user wants a template specialization. So 7144 // we need to insert '<>' after the name. 7145 SourceLocation InsertLoc; 7146 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7147 InsertLoc = D.getName().getSourceRange().getEnd(); 7148 InsertLoc = getLocForEndOfToken(InsertLoc); 7149 } 7150 7151 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7152 << Name << RemoveRange 7153 << FixItHint::CreateRemoval(RemoveRange) 7154 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7155 } 7156 } 7157 } 7158 else { 7159 // All template param lists were matched against the scope specifier: 7160 // this is NOT (an explicit specialization of) a template. 7161 if (TemplateParamLists.size() > 0) 7162 // For source fidelity, store all the template param lists. 7163 NewFD->setTemplateParameterListsInfo(Context, 7164 TemplateParamLists.size(), 7165 TemplateParamLists.data()); 7166 } 7167 7168 if (Invalid) { 7169 NewFD->setInvalidDecl(); 7170 if (FunctionTemplate) 7171 FunctionTemplate->setInvalidDecl(); 7172 } 7173 7174 // C++ [dcl.fct.spec]p5: 7175 // The virtual specifier shall only be used in declarations of 7176 // nonstatic class member functions that appear within a 7177 // member-specification of a class declaration; see 10.3. 7178 // 7179 if (isVirtual && !NewFD->isInvalidDecl()) { 7180 if (!isVirtualOkay) { 7181 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7182 diag::err_virtual_non_function); 7183 } else if (!CurContext->isRecord()) { 7184 // 'virtual' was specified outside of the class. 7185 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7186 diag::err_virtual_out_of_class) 7187 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7188 } else if (NewFD->getDescribedFunctionTemplate()) { 7189 // C++ [temp.mem]p3: 7190 // A member function template shall not be virtual. 7191 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7192 diag::err_virtual_member_function_template) 7193 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7194 } else { 7195 // Okay: Add virtual to the method. 7196 NewFD->setVirtualAsWritten(true); 7197 } 7198 7199 if (getLangOpts().CPlusPlus14 && 7200 NewFD->getReturnType()->isUndeducedType()) 7201 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7202 } 7203 7204 if (getLangOpts().CPlusPlus14 && 7205 (NewFD->isDependentContext() || 7206 (isFriend && CurContext->isDependentContext())) && 7207 NewFD->getReturnType()->isUndeducedType()) { 7208 // If the function template is referenced directly (for instance, as a 7209 // member of the current instantiation), pretend it has a dependent type. 7210 // This is not really justified by the standard, but is the only sane 7211 // thing to do. 7212 // FIXME: For a friend function, we have not marked the function as being 7213 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7214 const FunctionProtoType *FPT = 7215 NewFD->getType()->castAs<FunctionProtoType>(); 7216 QualType Result = 7217 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7218 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7219 FPT->getExtProtoInfo())); 7220 } 7221 7222 // C++ [dcl.fct.spec]p3: 7223 // The inline specifier shall not appear on a block scope function 7224 // declaration. 7225 if (isInline && !NewFD->isInvalidDecl()) { 7226 if (CurContext->isFunctionOrMethod()) { 7227 // 'inline' is not allowed on block scope function declaration. 7228 Diag(D.getDeclSpec().getInlineSpecLoc(), 7229 diag::err_inline_declaration_block_scope) << Name 7230 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7231 } 7232 } 7233 7234 // C++ [dcl.fct.spec]p6: 7235 // The explicit specifier shall be used only in the declaration of a 7236 // constructor or conversion function within its class definition; 7237 // see 12.3.1 and 12.3.2. 7238 if (isExplicit && !NewFD->isInvalidDecl()) { 7239 if (!CurContext->isRecord()) { 7240 // 'explicit' was specified outside of the class. 7241 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7242 diag::err_explicit_out_of_class) 7243 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7244 } else if (!isa<CXXConstructorDecl>(NewFD) && 7245 !isa<CXXConversionDecl>(NewFD)) { 7246 // 'explicit' was specified on a function that wasn't a constructor 7247 // or conversion function. 7248 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7249 diag::err_explicit_non_ctor_or_conv_function) 7250 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7251 } 7252 } 7253 7254 if (isConstexpr) { 7255 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7256 // are implicitly inline. 7257 NewFD->setImplicitlyInline(); 7258 7259 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7260 // be either constructors or to return a literal type. Therefore, 7261 // destructors cannot be declared constexpr. 7262 if (isa<CXXDestructorDecl>(NewFD)) 7263 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7264 } 7265 7266 // If __module_private__ was specified, mark the function accordingly. 7267 if (D.getDeclSpec().isModulePrivateSpecified()) { 7268 if (isFunctionTemplateSpecialization) { 7269 SourceLocation ModulePrivateLoc 7270 = D.getDeclSpec().getModulePrivateSpecLoc(); 7271 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7272 << 0 7273 << FixItHint::CreateRemoval(ModulePrivateLoc); 7274 } else { 7275 NewFD->setModulePrivate(); 7276 if (FunctionTemplate) 7277 FunctionTemplate->setModulePrivate(); 7278 } 7279 } 7280 7281 if (isFriend) { 7282 if (FunctionTemplate) { 7283 FunctionTemplate->setObjectOfFriendDecl(); 7284 FunctionTemplate->setAccess(AS_public); 7285 } 7286 NewFD->setObjectOfFriendDecl(); 7287 NewFD->setAccess(AS_public); 7288 } 7289 7290 // If a function is defined as defaulted or deleted, mark it as such now. 7291 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7292 // definition kind to FDK_Definition. 7293 switch (D.getFunctionDefinitionKind()) { 7294 case FDK_Declaration: 7295 case FDK_Definition: 7296 break; 7297 7298 case FDK_Defaulted: 7299 NewFD->setDefaulted(); 7300 break; 7301 7302 case FDK_Deleted: 7303 NewFD->setDeletedAsWritten(); 7304 break; 7305 } 7306 7307 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7308 D.isFunctionDefinition()) { 7309 // C++ [class.mfct]p2: 7310 // A member function may be defined (8.4) in its class definition, in 7311 // which case it is an inline member function (7.1.2) 7312 NewFD->setImplicitlyInline(); 7313 } 7314 7315 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7316 !CurContext->isRecord()) { 7317 // C++ [class.static]p1: 7318 // A data or function member of a class may be declared static 7319 // in a class definition, in which case it is a static member of 7320 // the class. 7321 7322 // Complain about the 'static' specifier if it's on an out-of-line 7323 // member function definition. 7324 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7325 diag::err_static_out_of_line) 7326 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7327 } 7328 7329 // C++11 [except.spec]p15: 7330 // A deallocation function with no exception-specification is treated 7331 // as if it were specified with noexcept(true). 7332 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7333 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7334 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7335 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7336 NewFD->setType(Context.getFunctionType( 7337 FPT->getReturnType(), FPT->getParamTypes(), 7338 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7339 } 7340 7341 // Filter out previous declarations that don't match the scope. 7342 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7343 D.getCXXScopeSpec().isNotEmpty() || 7344 isExplicitSpecialization || 7345 isFunctionTemplateSpecialization); 7346 7347 // Handle GNU asm-label extension (encoded as an attribute). 7348 if (Expr *E = (Expr*) D.getAsmLabel()) { 7349 // The parser guarantees this is a string. 7350 StringLiteral *SE = cast<StringLiteral>(E); 7351 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7352 SE->getString(), 0)); 7353 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7354 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7355 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7356 if (I != ExtnameUndeclaredIdentifiers.end()) { 7357 NewFD->addAttr(I->second); 7358 ExtnameUndeclaredIdentifiers.erase(I); 7359 } 7360 } 7361 7362 // Copy the parameter declarations from the declarator D to the function 7363 // declaration NewFD, if they are available. First scavenge them into Params. 7364 SmallVector<ParmVarDecl*, 16> Params; 7365 if (D.isFunctionDeclarator()) { 7366 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7367 7368 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7369 // function that takes no arguments, not a function that takes a 7370 // single void argument. 7371 // We let through "const void" here because Sema::GetTypeForDeclarator 7372 // already checks for that case. 7373 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7374 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7375 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7376 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7377 Param->setDeclContext(NewFD); 7378 Params.push_back(Param); 7379 7380 if (Param->isInvalidDecl()) 7381 NewFD->setInvalidDecl(); 7382 } 7383 } 7384 7385 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7386 // When we're declaring a function with a typedef, typeof, etc as in the 7387 // following example, we'll need to synthesize (unnamed) 7388 // parameters for use in the declaration. 7389 // 7390 // @code 7391 // typedef void fn(int); 7392 // fn f; 7393 // @endcode 7394 7395 // Synthesize a parameter for each argument type. 7396 for (const auto &AI : FT->param_types()) { 7397 ParmVarDecl *Param = 7398 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7399 Param->setScopeInfo(0, Params.size()); 7400 Params.push_back(Param); 7401 } 7402 } else { 7403 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7404 "Should not need args for typedef of non-prototype fn"); 7405 } 7406 7407 // Finally, we know we have the right number of parameters, install them. 7408 NewFD->setParams(Params); 7409 7410 // Find all anonymous symbols defined during the declaration of this function 7411 // and add to NewFD. This lets us track decls such 'enum Y' in: 7412 // 7413 // void f(enum Y {AA} x) {} 7414 // 7415 // which would otherwise incorrectly end up in the translation unit scope. 7416 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7417 DeclsInPrototypeScope.clear(); 7418 7419 if (D.getDeclSpec().isNoreturnSpecified()) 7420 NewFD->addAttr( 7421 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7422 Context, 0)); 7423 7424 // Functions returning a variably modified type violate C99 6.7.5.2p2 7425 // because all functions have linkage. 7426 if (!NewFD->isInvalidDecl() && 7427 NewFD->getReturnType()->isVariablyModifiedType()) { 7428 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7429 NewFD->setInvalidDecl(); 7430 } 7431 7432 // Apply an implicit SectionAttr if #pragma code_seg is active. 7433 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 7434 !NewFD->hasAttr<SectionAttr>()) { 7435 NewFD->addAttr( 7436 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7437 CodeSegStack.CurrentValue->getString(), 7438 CodeSegStack.CurrentPragmaLocation)); 7439 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7440 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 7441 ASTContext::PSF_Read, 7442 NewFD)) 7443 NewFD->dropAttr<SectionAttr>(); 7444 } 7445 7446 // Handle attributes. 7447 ProcessDeclAttributes(S, NewFD, D); 7448 7449 QualType RetType = NewFD->getReturnType(); 7450 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7451 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7452 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7453 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7454 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7455 // Attach WarnUnusedResult to functions returning types with that attribute. 7456 // Don't apply the attribute to that type's own non-static member functions 7457 // (to avoid warning on things like assignment operators) 7458 if (!MD || MD->getParent() != Ret) 7459 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7460 } 7461 7462 if (getLangOpts().OpenCL) { 7463 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7464 // type declaration will generate a compilation error. 7465 unsigned AddressSpace = RetType.getAddressSpace(); 7466 if (AddressSpace == LangAS::opencl_local || 7467 AddressSpace == LangAS::opencl_global || 7468 AddressSpace == LangAS::opencl_constant) { 7469 Diag(NewFD->getLocation(), 7470 diag::err_opencl_return_value_with_address_space); 7471 NewFD->setInvalidDecl(); 7472 } 7473 } 7474 7475 if (!getLangOpts().CPlusPlus) { 7476 // Perform semantic checking on the function declaration. 7477 bool isExplicitSpecialization=false; 7478 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7479 CheckMain(NewFD, D.getDeclSpec()); 7480 7481 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7482 CheckMSVCRTEntryPoint(NewFD); 7483 7484 if (!NewFD->isInvalidDecl()) 7485 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7486 isExplicitSpecialization)); 7487 else if (!Previous.empty()) 7488 // Recover gracefully from an invalid redeclaration. 7489 D.setRedeclaration(true); 7490 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7491 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7492 "previous declaration set still overloaded"); 7493 7494 // Diagnose no-prototype function declarations with calling conventions that 7495 // don't support variadic calls. Only do this in C and do it after merging 7496 // possibly prototyped redeclarations. 7497 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 7498 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 7499 CallingConv CC = FT->getExtInfo().getCC(); 7500 if (!supportsVariadicCall(CC)) { 7501 // Windows system headers sometimes accidentally use stdcall without 7502 // (void) parameters, so we relax this to a warning. 7503 int DiagID = 7504 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 7505 Diag(NewFD->getLocation(), DiagID) 7506 << FunctionType::getNameForCallConv(CC); 7507 } 7508 } 7509 } else { 7510 // C++11 [replacement.functions]p3: 7511 // The program's definitions shall not be specified as inline. 7512 // 7513 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7514 // 7515 // Suppress the diagnostic if the function is __attribute__((used)), since 7516 // that forces an external definition to be emitted. 7517 if (D.getDeclSpec().isInlineSpecified() && 7518 NewFD->isReplaceableGlobalAllocationFunction() && 7519 !NewFD->hasAttr<UsedAttr>()) 7520 Diag(D.getDeclSpec().getInlineSpecLoc(), 7521 diag::ext_operator_new_delete_declared_inline) 7522 << NewFD->getDeclName(); 7523 7524 // If the declarator is a template-id, translate the parser's template 7525 // argument list into our AST format. 7526 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7527 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7528 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7529 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7530 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7531 TemplateId->NumArgs); 7532 translateTemplateArguments(TemplateArgsPtr, 7533 TemplateArgs); 7534 7535 HasExplicitTemplateArgs = true; 7536 7537 if (NewFD->isInvalidDecl()) { 7538 HasExplicitTemplateArgs = false; 7539 } else if (FunctionTemplate) { 7540 // Function template with explicit template arguments. 7541 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7542 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7543 7544 HasExplicitTemplateArgs = false; 7545 } else { 7546 assert((isFunctionTemplateSpecialization || 7547 D.getDeclSpec().isFriendSpecified()) && 7548 "should have a 'template<>' for this decl"); 7549 // "friend void foo<>(int);" is an implicit specialization decl. 7550 isFunctionTemplateSpecialization = true; 7551 } 7552 } else if (isFriend && isFunctionTemplateSpecialization) { 7553 // This combination is only possible in a recovery case; the user 7554 // wrote something like: 7555 // template <> friend void foo(int); 7556 // which we're recovering from as if the user had written: 7557 // friend void foo<>(int); 7558 // Go ahead and fake up a template id. 7559 HasExplicitTemplateArgs = true; 7560 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7561 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7562 } 7563 7564 // If it's a friend (and only if it's a friend), it's possible 7565 // that either the specialized function type or the specialized 7566 // template is dependent, and therefore matching will fail. In 7567 // this case, don't check the specialization yet. 7568 bool InstantiationDependent = false; 7569 if (isFunctionTemplateSpecialization && isFriend && 7570 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7571 TemplateSpecializationType::anyDependentTemplateArguments( 7572 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7573 InstantiationDependent))) { 7574 assert(HasExplicitTemplateArgs && 7575 "friend function specialization without template args"); 7576 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7577 Previous)) 7578 NewFD->setInvalidDecl(); 7579 } else if (isFunctionTemplateSpecialization) { 7580 if (CurContext->isDependentContext() && CurContext->isRecord() 7581 && !isFriend) { 7582 isDependentClassScopeExplicitSpecialization = true; 7583 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7584 diag::ext_function_specialization_in_class : 7585 diag::err_function_specialization_in_class) 7586 << NewFD->getDeclName(); 7587 } else if (CheckFunctionTemplateSpecialization(NewFD, 7588 (HasExplicitTemplateArgs ? &TemplateArgs 7589 : nullptr), 7590 Previous)) 7591 NewFD->setInvalidDecl(); 7592 7593 // C++ [dcl.stc]p1: 7594 // A storage-class-specifier shall not be specified in an explicit 7595 // specialization (14.7.3) 7596 FunctionTemplateSpecializationInfo *Info = 7597 NewFD->getTemplateSpecializationInfo(); 7598 if (Info && SC != SC_None) { 7599 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7600 Diag(NewFD->getLocation(), 7601 diag::err_explicit_specialization_inconsistent_storage_class) 7602 << SC 7603 << FixItHint::CreateRemoval( 7604 D.getDeclSpec().getStorageClassSpecLoc()); 7605 7606 else 7607 Diag(NewFD->getLocation(), 7608 diag::ext_explicit_specialization_storage_class) 7609 << FixItHint::CreateRemoval( 7610 D.getDeclSpec().getStorageClassSpecLoc()); 7611 } 7612 7613 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7614 if (CheckMemberSpecialization(NewFD, Previous)) 7615 NewFD->setInvalidDecl(); 7616 } 7617 7618 // Perform semantic checking on the function declaration. 7619 if (!isDependentClassScopeExplicitSpecialization) { 7620 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7621 CheckMain(NewFD, D.getDeclSpec()); 7622 7623 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7624 CheckMSVCRTEntryPoint(NewFD); 7625 7626 if (!NewFD->isInvalidDecl()) 7627 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7628 isExplicitSpecialization)); 7629 else if (!Previous.empty()) 7630 // Recover gracefully from an invalid redeclaration. 7631 D.setRedeclaration(true); 7632 } 7633 7634 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7635 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7636 "previous declaration set still overloaded"); 7637 7638 NamedDecl *PrincipalDecl = (FunctionTemplate 7639 ? cast<NamedDecl>(FunctionTemplate) 7640 : NewFD); 7641 7642 if (isFriend && D.isRedeclaration()) { 7643 AccessSpecifier Access = AS_public; 7644 if (!NewFD->isInvalidDecl()) 7645 Access = NewFD->getPreviousDecl()->getAccess(); 7646 7647 NewFD->setAccess(Access); 7648 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7649 } 7650 7651 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7652 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7653 PrincipalDecl->setNonMemberOperator(); 7654 7655 // If we have a function template, check the template parameter 7656 // list. This will check and merge default template arguments. 7657 if (FunctionTemplate) { 7658 FunctionTemplateDecl *PrevTemplate = 7659 FunctionTemplate->getPreviousDecl(); 7660 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7661 PrevTemplate ? PrevTemplate->getTemplateParameters() 7662 : nullptr, 7663 D.getDeclSpec().isFriendSpecified() 7664 ? (D.isFunctionDefinition() 7665 ? TPC_FriendFunctionTemplateDefinition 7666 : TPC_FriendFunctionTemplate) 7667 : (D.getCXXScopeSpec().isSet() && 7668 DC && DC->isRecord() && 7669 DC->isDependentContext()) 7670 ? TPC_ClassTemplateMember 7671 : TPC_FunctionTemplate); 7672 } 7673 7674 if (NewFD->isInvalidDecl()) { 7675 // Ignore all the rest of this. 7676 } else if (!D.isRedeclaration()) { 7677 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7678 AddToScope }; 7679 // Fake up an access specifier if it's supposed to be a class member. 7680 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7681 NewFD->setAccess(AS_public); 7682 7683 // Qualified decls generally require a previous declaration. 7684 if (D.getCXXScopeSpec().isSet()) { 7685 // ...with the major exception of templated-scope or 7686 // dependent-scope friend declarations. 7687 7688 // TODO: we currently also suppress this check in dependent 7689 // contexts because (1) the parameter depth will be off when 7690 // matching friend templates and (2) we might actually be 7691 // selecting a friend based on a dependent factor. But there 7692 // are situations where these conditions don't apply and we 7693 // can actually do this check immediately. 7694 if (isFriend && 7695 (TemplateParamLists.size() || 7696 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7697 CurContext->isDependentContext())) { 7698 // ignore these 7699 } else { 7700 // The user tried to provide an out-of-line definition for a 7701 // function that is a member of a class or namespace, but there 7702 // was no such member function declared (C++ [class.mfct]p2, 7703 // C++ [namespace.memdef]p2). For example: 7704 // 7705 // class X { 7706 // void f() const; 7707 // }; 7708 // 7709 // void X::f() { } // ill-formed 7710 // 7711 // Complain about this problem, and attempt to suggest close 7712 // matches (e.g., those that differ only in cv-qualifiers and 7713 // whether the parameter types are references). 7714 7715 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7716 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7717 AddToScope = ExtraArgs.AddToScope; 7718 return Result; 7719 } 7720 } 7721 7722 // Unqualified local friend declarations are required to resolve 7723 // to something. 7724 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7725 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7726 *this, Previous, NewFD, ExtraArgs, true, S)) { 7727 AddToScope = ExtraArgs.AddToScope; 7728 return Result; 7729 } 7730 } 7731 7732 } else if (!D.isFunctionDefinition() && 7733 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7734 !isFriend && !isFunctionTemplateSpecialization && 7735 !isExplicitSpecialization) { 7736 // An out-of-line member function declaration must also be a 7737 // definition (C++ [class.mfct]p2). 7738 // Note that this is not the case for explicit specializations of 7739 // function templates or member functions of class templates, per 7740 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7741 // extension for compatibility with old SWIG code which likes to 7742 // generate them. 7743 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7744 << D.getCXXScopeSpec().getRange(); 7745 } 7746 } 7747 7748 ProcessPragmaWeak(S, NewFD); 7749 checkAttributesAfterMerging(*this, *NewFD); 7750 7751 AddKnownFunctionAttributes(NewFD); 7752 7753 if (NewFD->hasAttr<OverloadableAttr>() && 7754 !NewFD->getType()->getAs<FunctionProtoType>()) { 7755 Diag(NewFD->getLocation(), 7756 diag::err_attribute_overloadable_no_prototype) 7757 << NewFD; 7758 7759 // Turn this into a variadic function with no parameters. 7760 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7761 FunctionProtoType::ExtProtoInfo EPI( 7762 Context.getDefaultCallingConvention(true, false)); 7763 EPI.Variadic = true; 7764 EPI.ExtInfo = FT->getExtInfo(); 7765 7766 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7767 NewFD->setType(R); 7768 } 7769 7770 // If there's a #pragma GCC visibility in scope, and this isn't a class 7771 // member, set the visibility of this function. 7772 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7773 AddPushedVisibilityAttribute(NewFD); 7774 7775 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7776 // marking the function. 7777 AddCFAuditedAttribute(NewFD); 7778 7779 // If this is a function definition, check if we have to apply optnone due to 7780 // a pragma. 7781 if(D.isFunctionDefinition()) 7782 AddRangeBasedOptnone(NewFD); 7783 7784 // If this is the first declaration of an extern C variable, update 7785 // the map of such variables. 7786 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7787 isIncompleteDeclExternC(*this, NewFD)) 7788 RegisterLocallyScopedExternCDecl(NewFD, S); 7789 7790 // Set this FunctionDecl's range up to the right paren. 7791 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7792 7793 if (D.isRedeclaration() && !Previous.empty()) { 7794 checkDLLAttributeRedeclaration( 7795 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7796 isExplicitSpecialization || isFunctionTemplateSpecialization); 7797 } 7798 7799 if (getLangOpts().CPlusPlus) { 7800 if (FunctionTemplate) { 7801 if (NewFD->isInvalidDecl()) 7802 FunctionTemplate->setInvalidDecl(); 7803 return FunctionTemplate; 7804 } 7805 } 7806 7807 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7808 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7809 if ((getLangOpts().OpenCLVersion >= 120) 7810 && (SC == SC_Static)) { 7811 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7812 D.setInvalidType(); 7813 } 7814 7815 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7816 if (!NewFD->getReturnType()->isVoidType()) { 7817 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 7818 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 7819 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 7820 : FixItHint()); 7821 D.setInvalidType(); 7822 } 7823 7824 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7825 for (auto Param : NewFD->params()) 7826 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7827 } 7828 7829 MarkUnusedFileScopedDecl(NewFD); 7830 7831 if (getLangOpts().CUDA) 7832 if (IdentifierInfo *II = NewFD->getIdentifier()) 7833 if (!NewFD->isInvalidDecl() && 7834 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7835 if (II->isStr("cudaConfigureCall")) { 7836 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7837 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7838 7839 Context.setcudaConfigureCallDecl(NewFD); 7840 } 7841 } 7842 7843 // Here we have an function template explicit specialization at class scope. 7844 // The actually specialization will be postponed to template instatiation 7845 // time via the ClassScopeFunctionSpecializationDecl node. 7846 if (isDependentClassScopeExplicitSpecialization) { 7847 ClassScopeFunctionSpecializationDecl *NewSpec = 7848 ClassScopeFunctionSpecializationDecl::Create( 7849 Context, CurContext, SourceLocation(), 7850 cast<CXXMethodDecl>(NewFD), 7851 HasExplicitTemplateArgs, TemplateArgs); 7852 CurContext->addDecl(NewSpec); 7853 AddToScope = false; 7854 } 7855 7856 return NewFD; 7857 } 7858 7859 /// \brief Perform semantic checking of a new function declaration. 7860 /// 7861 /// Performs semantic analysis of the new function declaration 7862 /// NewFD. This routine performs all semantic checking that does not 7863 /// require the actual declarator involved in the declaration, and is 7864 /// used both for the declaration of functions as they are parsed 7865 /// (called via ActOnDeclarator) and for the declaration of functions 7866 /// that have been instantiated via C++ template instantiation (called 7867 /// via InstantiateDecl). 7868 /// 7869 /// \param IsExplicitSpecialization whether this new function declaration is 7870 /// an explicit specialization of the previous declaration. 7871 /// 7872 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7873 /// 7874 /// \returns true if the function declaration is a redeclaration. 7875 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7876 LookupResult &Previous, 7877 bool IsExplicitSpecialization) { 7878 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7879 "Variably modified return types are not handled here"); 7880 7881 // Determine whether the type of this function should be merged with 7882 // a previous visible declaration. This never happens for functions in C++, 7883 // and always happens in C if the previous declaration was visible. 7884 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7885 !Previous.isShadowed(); 7886 7887 // Filter out any non-conflicting previous declarations. 7888 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7889 7890 bool Redeclaration = false; 7891 NamedDecl *OldDecl = nullptr; 7892 7893 // Merge or overload the declaration with an existing declaration of 7894 // the same name, if appropriate. 7895 if (!Previous.empty()) { 7896 // Determine whether NewFD is an overload of PrevDecl or 7897 // a declaration that requires merging. If it's an overload, 7898 // there's no more work to do here; we'll just add the new 7899 // function to the scope. 7900 if (!AllowOverloadingOfFunction(Previous, Context)) { 7901 NamedDecl *Candidate = Previous.getFoundDecl(); 7902 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7903 Redeclaration = true; 7904 OldDecl = Candidate; 7905 } 7906 } else { 7907 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7908 /*NewIsUsingDecl*/ false)) { 7909 case Ovl_Match: 7910 Redeclaration = true; 7911 break; 7912 7913 case Ovl_NonFunction: 7914 Redeclaration = true; 7915 break; 7916 7917 case Ovl_Overload: 7918 Redeclaration = false; 7919 break; 7920 } 7921 7922 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7923 // If a function name is overloadable in C, then every function 7924 // with that name must be marked "overloadable". 7925 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7926 << Redeclaration << NewFD; 7927 NamedDecl *OverloadedDecl = nullptr; 7928 if (Redeclaration) 7929 OverloadedDecl = OldDecl; 7930 else if (!Previous.empty()) 7931 OverloadedDecl = Previous.getRepresentativeDecl(); 7932 if (OverloadedDecl) 7933 Diag(OverloadedDecl->getLocation(), 7934 diag::note_attribute_overloadable_prev_overload); 7935 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7936 } 7937 } 7938 } 7939 7940 // Check for a previous extern "C" declaration with this name. 7941 if (!Redeclaration && 7942 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7943 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7944 if (!Previous.empty()) { 7945 // This is an extern "C" declaration with the same name as a previous 7946 // declaration, and thus redeclares that entity... 7947 Redeclaration = true; 7948 OldDecl = Previous.getFoundDecl(); 7949 MergeTypeWithPrevious = false; 7950 7951 // ... except in the presence of __attribute__((overloadable)). 7952 if (OldDecl->hasAttr<OverloadableAttr>()) { 7953 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7954 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7955 << Redeclaration << NewFD; 7956 Diag(Previous.getFoundDecl()->getLocation(), 7957 diag::note_attribute_overloadable_prev_overload); 7958 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7959 } 7960 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7961 Redeclaration = false; 7962 OldDecl = nullptr; 7963 } 7964 } 7965 } 7966 } 7967 7968 // C++11 [dcl.constexpr]p8: 7969 // A constexpr specifier for a non-static member function that is not 7970 // a constructor declares that member function to be const. 7971 // 7972 // This needs to be delayed until we know whether this is an out-of-line 7973 // definition of a static member function. 7974 // 7975 // This rule is not present in C++1y, so we produce a backwards 7976 // compatibility warning whenever it happens in C++11. 7977 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7978 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 7979 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7980 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7981 CXXMethodDecl *OldMD = nullptr; 7982 if (OldDecl) 7983 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 7984 if (!OldMD || !OldMD->isStatic()) { 7985 const FunctionProtoType *FPT = 7986 MD->getType()->castAs<FunctionProtoType>(); 7987 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7988 EPI.TypeQuals |= Qualifiers::Const; 7989 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7990 FPT->getParamTypes(), EPI)); 7991 7992 // Warn that we did this, if we're not performing template instantiation. 7993 // In that case, we'll have warned already when the template was defined. 7994 if (ActiveTemplateInstantiations.empty()) { 7995 SourceLocation AddConstLoc; 7996 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7997 .IgnoreParens().getAs<FunctionTypeLoc>()) 7998 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 7999 8000 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8001 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8002 } 8003 } 8004 } 8005 8006 if (Redeclaration) { 8007 // NewFD and OldDecl represent declarations that need to be 8008 // merged. 8009 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8010 NewFD->setInvalidDecl(); 8011 return Redeclaration; 8012 } 8013 8014 Previous.clear(); 8015 Previous.addDecl(OldDecl); 8016 8017 if (FunctionTemplateDecl *OldTemplateDecl 8018 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8019 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8020 FunctionTemplateDecl *NewTemplateDecl 8021 = NewFD->getDescribedFunctionTemplate(); 8022 assert(NewTemplateDecl && "Template/non-template mismatch"); 8023 if (CXXMethodDecl *Method 8024 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8025 Method->setAccess(OldTemplateDecl->getAccess()); 8026 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8027 } 8028 8029 // If this is an explicit specialization of a member that is a function 8030 // template, mark it as a member specialization. 8031 if (IsExplicitSpecialization && 8032 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8033 NewTemplateDecl->setMemberSpecialization(); 8034 assert(OldTemplateDecl->isMemberSpecialization()); 8035 } 8036 8037 } else { 8038 // This needs to happen first so that 'inline' propagates. 8039 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8040 8041 if (isa<CXXMethodDecl>(NewFD)) 8042 NewFD->setAccess(OldDecl->getAccess()); 8043 } 8044 } 8045 8046 // Semantic checking for this function declaration (in isolation). 8047 8048 if (getLangOpts().CPlusPlus) { 8049 // C++-specific checks. 8050 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8051 CheckConstructor(Constructor); 8052 } else if (CXXDestructorDecl *Destructor = 8053 dyn_cast<CXXDestructorDecl>(NewFD)) { 8054 CXXRecordDecl *Record = Destructor->getParent(); 8055 QualType ClassType = Context.getTypeDeclType(Record); 8056 8057 // FIXME: Shouldn't we be able to perform this check even when the class 8058 // type is dependent? Both gcc and edg can handle that. 8059 if (!ClassType->isDependentType()) { 8060 DeclarationName Name 8061 = Context.DeclarationNames.getCXXDestructorName( 8062 Context.getCanonicalType(ClassType)); 8063 if (NewFD->getDeclName() != Name) { 8064 Diag(NewFD->getLocation(), diag::err_destructor_name); 8065 NewFD->setInvalidDecl(); 8066 return Redeclaration; 8067 } 8068 } 8069 } else if (CXXConversionDecl *Conversion 8070 = dyn_cast<CXXConversionDecl>(NewFD)) { 8071 ActOnConversionDeclarator(Conversion); 8072 } 8073 8074 // Find any virtual functions that this function overrides. 8075 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8076 if (!Method->isFunctionTemplateSpecialization() && 8077 !Method->getDescribedFunctionTemplate() && 8078 Method->isCanonicalDecl()) { 8079 if (AddOverriddenMethods(Method->getParent(), Method)) { 8080 // If the function was marked as "static", we have a problem. 8081 if (NewFD->getStorageClass() == SC_Static) { 8082 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8083 } 8084 } 8085 } 8086 8087 if (Method->isStatic()) 8088 checkThisInStaticMemberFunctionType(Method); 8089 } 8090 8091 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8092 if (NewFD->isOverloadedOperator() && 8093 CheckOverloadedOperatorDeclaration(NewFD)) { 8094 NewFD->setInvalidDecl(); 8095 return Redeclaration; 8096 } 8097 8098 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8099 if (NewFD->getLiteralIdentifier() && 8100 CheckLiteralOperatorDeclaration(NewFD)) { 8101 NewFD->setInvalidDecl(); 8102 return Redeclaration; 8103 } 8104 8105 // In C++, check default arguments now that we have merged decls. Unless 8106 // the lexical context is the class, because in this case this is done 8107 // during delayed parsing anyway. 8108 if (!CurContext->isRecord()) 8109 CheckCXXDefaultArguments(NewFD); 8110 8111 // If this function declares a builtin function, check the type of this 8112 // declaration against the expected type for the builtin. 8113 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8114 ASTContext::GetBuiltinTypeError Error; 8115 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8116 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8117 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8118 // The type of this function differs from the type of the builtin, 8119 // so forget about the builtin entirely. 8120 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 8121 } 8122 } 8123 8124 // If this function is declared as being extern "C", then check to see if 8125 // the function returns a UDT (class, struct, or union type) that is not C 8126 // compatible, and if it does, warn the user. 8127 // But, issue any diagnostic on the first declaration only. 8128 if (Previous.empty() && NewFD->isExternC()) { 8129 QualType R = NewFD->getReturnType(); 8130 if (R->isIncompleteType() && !R->isVoidType()) 8131 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8132 << NewFD << R; 8133 else if (!R.isPODType(Context) && !R->isVoidType() && 8134 !R->isObjCObjectPointerType()) 8135 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8136 } 8137 } 8138 return Redeclaration; 8139 } 8140 8141 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8142 // C++11 [basic.start.main]p3: 8143 // A program that [...] declares main to be inline, static or 8144 // constexpr is ill-formed. 8145 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8146 // appear in a declaration of main. 8147 // static main is not an error under C99, but we should warn about it. 8148 // We accept _Noreturn main as an extension. 8149 if (FD->getStorageClass() == SC_Static) 8150 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8151 ? diag::err_static_main : diag::warn_static_main) 8152 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8153 if (FD->isInlineSpecified()) 8154 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8155 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8156 if (DS.isNoreturnSpecified()) { 8157 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8158 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8159 Diag(NoreturnLoc, diag::ext_noreturn_main); 8160 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8161 << FixItHint::CreateRemoval(NoreturnRange); 8162 } 8163 if (FD->isConstexpr()) { 8164 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8165 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8166 FD->setConstexpr(false); 8167 } 8168 8169 if (getLangOpts().OpenCL) { 8170 Diag(FD->getLocation(), diag::err_opencl_no_main) 8171 << FD->hasAttr<OpenCLKernelAttr>(); 8172 FD->setInvalidDecl(); 8173 return; 8174 } 8175 8176 QualType T = FD->getType(); 8177 assert(T->isFunctionType() && "function decl is not of function type"); 8178 const FunctionType* FT = T->castAs<FunctionType>(); 8179 8180 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8181 // In C with GNU extensions we allow main() to have non-integer return 8182 // type, but we should warn about the extension, and we disable the 8183 // implicit-return-zero rule. 8184 8185 // GCC in C mode accepts qualified 'int'. 8186 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8187 FD->setHasImplicitReturnZero(true); 8188 else { 8189 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8190 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8191 if (RTRange.isValid()) 8192 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8193 << FixItHint::CreateReplacement(RTRange, "int"); 8194 } 8195 } else { 8196 // In C and C++, main magically returns 0 if you fall off the end; 8197 // set the flag which tells us that. 8198 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8199 8200 // All the standards say that main() should return 'int'. 8201 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8202 FD->setHasImplicitReturnZero(true); 8203 else { 8204 // Otherwise, this is just a flat-out error. 8205 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8206 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8207 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8208 : FixItHint()); 8209 FD->setInvalidDecl(true); 8210 } 8211 } 8212 8213 // Treat protoless main() as nullary. 8214 if (isa<FunctionNoProtoType>(FT)) return; 8215 8216 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8217 unsigned nparams = FTP->getNumParams(); 8218 assert(FD->getNumParams() == nparams); 8219 8220 bool HasExtraParameters = (nparams > 3); 8221 8222 // Darwin passes an undocumented fourth argument of type char**. If 8223 // other platforms start sprouting these, the logic below will start 8224 // getting shifty. 8225 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8226 HasExtraParameters = false; 8227 8228 if (HasExtraParameters) { 8229 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8230 FD->setInvalidDecl(true); 8231 nparams = 3; 8232 } 8233 8234 // FIXME: a lot of the following diagnostics would be improved 8235 // if we had some location information about types. 8236 8237 QualType CharPP = 8238 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8239 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8240 8241 for (unsigned i = 0; i < nparams; ++i) { 8242 QualType AT = FTP->getParamType(i); 8243 8244 bool mismatch = true; 8245 8246 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8247 mismatch = false; 8248 else if (Expected[i] == CharPP) { 8249 // As an extension, the following forms are okay: 8250 // char const ** 8251 // char const * const * 8252 // char * const * 8253 8254 QualifierCollector qs; 8255 const PointerType* PT; 8256 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8257 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8258 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8259 Context.CharTy)) { 8260 qs.removeConst(); 8261 mismatch = !qs.empty(); 8262 } 8263 } 8264 8265 if (mismatch) { 8266 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8267 // TODO: suggest replacing given type with expected type 8268 FD->setInvalidDecl(true); 8269 } 8270 } 8271 8272 if (nparams == 1 && !FD->isInvalidDecl()) { 8273 Diag(FD->getLocation(), diag::warn_main_one_arg); 8274 } 8275 8276 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8277 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8278 FD->setInvalidDecl(); 8279 } 8280 } 8281 8282 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8283 QualType T = FD->getType(); 8284 assert(T->isFunctionType() && "function decl is not of function type"); 8285 const FunctionType *FT = T->castAs<FunctionType>(); 8286 8287 // Set an implicit return of 'zero' if the function can return some integral, 8288 // enumeration, pointer or nullptr type. 8289 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8290 FT->getReturnType()->isAnyPointerType() || 8291 FT->getReturnType()->isNullPtrType()) 8292 // DllMain is exempt because a return value of zero means it failed. 8293 if (FD->getName() != "DllMain") 8294 FD->setHasImplicitReturnZero(true); 8295 8296 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8297 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8298 FD->setInvalidDecl(); 8299 } 8300 } 8301 8302 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8303 // FIXME: Need strict checking. In C89, we need to check for 8304 // any assignment, increment, decrement, function-calls, or 8305 // commas outside of a sizeof. In C99, it's the same list, 8306 // except that the aforementioned are allowed in unevaluated 8307 // expressions. Everything else falls under the 8308 // "may accept other forms of constant expressions" exception. 8309 // (We never end up here for C++, so the constant expression 8310 // rules there don't matter.) 8311 const Expr *Culprit; 8312 if (Init->isConstantInitializer(Context, false, &Culprit)) 8313 return false; 8314 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8315 << Culprit->getSourceRange(); 8316 return true; 8317 } 8318 8319 namespace { 8320 // Visits an initialization expression to see if OrigDecl is evaluated in 8321 // its own initialization and throws a warning if it does. 8322 class SelfReferenceChecker 8323 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8324 Sema &S; 8325 Decl *OrigDecl; 8326 bool isRecordType; 8327 bool isPODType; 8328 bool isReferenceType; 8329 8330 bool isInitList; 8331 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8332 public: 8333 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8334 8335 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8336 S(S), OrigDecl(OrigDecl) { 8337 isPODType = false; 8338 isRecordType = false; 8339 isReferenceType = false; 8340 isInitList = false; 8341 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8342 isPODType = VD->getType().isPODType(S.Context); 8343 isRecordType = VD->getType()->isRecordType(); 8344 isReferenceType = VD->getType()->isReferenceType(); 8345 } 8346 } 8347 8348 // For most expressions, just call the visitor. For initializer lists, 8349 // track the index of the field being initialized since fields are 8350 // initialized in order allowing use of previously initialized fields. 8351 void CheckExpr(Expr *E) { 8352 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8353 if (!InitList) { 8354 Visit(E); 8355 return; 8356 } 8357 8358 // Track and increment the index here. 8359 isInitList = true; 8360 InitFieldIndex.push_back(0); 8361 for (auto Child : InitList->children()) { 8362 CheckExpr(cast<Expr>(Child)); 8363 ++InitFieldIndex.back(); 8364 } 8365 InitFieldIndex.pop_back(); 8366 } 8367 8368 // Returns true if MemberExpr is checked and no futher checking is needed. 8369 // Returns false if additional checking is required. 8370 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8371 llvm::SmallVector<FieldDecl*, 4> Fields; 8372 Expr *Base = E; 8373 bool ReferenceField = false; 8374 8375 // Get the field memebers used. 8376 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8377 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8378 if (!FD) 8379 return false; 8380 Fields.push_back(FD); 8381 if (FD->getType()->isReferenceType()) 8382 ReferenceField = true; 8383 Base = ME->getBase()->IgnoreParenImpCasts(); 8384 } 8385 8386 // Keep checking only if the base Decl is the same. 8387 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8388 if (!DRE || DRE->getDecl() != OrigDecl) 8389 return false; 8390 8391 // A reference field can be bound to an unininitialized field. 8392 if (CheckReference && !ReferenceField) 8393 return true; 8394 8395 // Convert FieldDecls to their index number. 8396 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8397 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) { 8398 UsedFieldIndex.push_back((*I)->getFieldIndex()); 8399 } 8400 8401 // See if a warning is needed by checking the first difference in index 8402 // numbers. If field being used has index less than the field being 8403 // initialized, then the use is safe. 8404 for (auto UsedIter = UsedFieldIndex.begin(), 8405 UsedEnd = UsedFieldIndex.end(), 8406 OrigIter = InitFieldIndex.begin(), 8407 OrigEnd = InitFieldIndex.end(); 8408 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8409 if (*UsedIter < *OrigIter) 8410 return true; 8411 if (*UsedIter > *OrigIter) 8412 break; 8413 } 8414 8415 // TODO: Add a different warning which will print the field names. 8416 HandleDeclRefExpr(DRE); 8417 return true; 8418 } 8419 8420 // For most expressions, the cast is directly above the DeclRefExpr. 8421 // For conditional operators, the cast can be outside the conditional 8422 // operator if both expressions are DeclRefExpr's. 8423 void HandleValue(Expr *E) { 8424 E = E->IgnoreParens(); 8425 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8426 HandleDeclRefExpr(DRE); 8427 return; 8428 } 8429 8430 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8431 Visit(CO->getCond()); 8432 HandleValue(CO->getTrueExpr()); 8433 HandleValue(CO->getFalseExpr()); 8434 return; 8435 } 8436 8437 if (BinaryConditionalOperator *BCO = 8438 dyn_cast<BinaryConditionalOperator>(E)) { 8439 Visit(BCO->getCond()); 8440 HandleValue(BCO->getFalseExpr()); 8441 return; 8442 } 8443 8444 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8445 HandleValue(OVE->getSourceExpr()); 8446 return; 8447 } 8448 8449 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8450 if (BO->getOpcode() == BO_Comma) { 8451 Visit(BO->getLHS()); 8452 HandleValue(BO->getRHS()); 8453 return; 8454 } 8455 } 8456 8457 if (isa<MemberExpr>(E)) { 8458 if (isInitList) { 8459 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8460 false /*CheckReference*/)) 8461 return; 8462 } 8463 8464 Expr *Base = E->IgnoreParenImpCasts(); 8465 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8466 // Check for static member variables and don't warn on them. 8467 if (!isa<FieldDecl>(ME->getMemberDecl())) 8468 return; 8469 Base = ME->getBase()->IgnoreParenImpCasts(); 8470 } 8471 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8472 HandleDeclRefExpr(DRE); 8473 return; 8474 } 8475 8476 Visit(E); 8477 } 8478 8479 // Reference types not handled in HandleValue are handled here since all 8480 // uses of references are bad, not just r-value uses. 8481 void VisitDeclRefExpr(DeclRefExpr *E) { 8482 if (isReferenceType) 8483 HandleDeclRefExpr(E); 8484 } 8485 8486 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8487 if (E->getCastKind() == CK_LValueToRValue) { 8488 HandleValue(E->getSubExpr()); 8489 return; 8490 } 8491 8492 Inherited::VisitImplicitCastExpr(E); 8493 } 8494 8495 void VisitMemberExpr(MemberExpr *E) { 8496 if (isInitList) { 8497 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 8498 return; 8499 } 8500 8501 // Don't warn on arrays since they can be treated as pointers. 8502 if (E->getType()->canDecayToPointerType()) return; 8503 8504 // Warn when a non-static method call is followed by non-static member 8505 // field accesses, which is followed by a DeclRefExpr. 8506 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8507 bool Warn = (MD && !MD->isStatic()); 8508 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8509 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8510 if (!isa<FieldDecl>(ME->getMemberDecl())) 8511 Warn = false; 8512 Base = ME->getBase()->IgnoreParenImpCasts(); 8513 } 8514 8515 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8516 if (Warn) 8517 HandleDeclRefExpr(DRE); 8518 return; 8519 } 8520 8521 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8522 // Visit that expression. 8523 Visit(Base); 8524 } 8525 8526 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8527 Expr *Callee = E->getCallee(); 8528 8529 if (isa<UnresolvedLookupExpr>(Callee)) 8530 return Inherited::VisitCXXOperatorCallExpr(E); 8531 8532 Visit(Callee); 8533 for (auto Arg: E->arguments()) 8534 HandleValue(Arg->IgnoreParenImpCasts()); 8535 } 8536 8537 void VisitUnaryOperator(UnaryOperator *E) { 8538 // For POD record types, addresses of its own members are well-defined. 8539 if (E->getOpcode() == UO_AddrOf && isRecordType && 8540 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8541 if (!isPODType) 8542 HandleValue(E->getSubExpr()); 8543 return; 8544 } 8545 8546 if (E->isIncrementDecrementOp()) { 8547 HandleValue(E->getSubExpr()); 8548 return; 8549 } 8550 8551 Inherited::VisitUnaryOperator(E); 8552 } 8553 8554 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8555 8556 void VisitCXXConstructExpr(CXXConstructExpr *E) { 8557 if (E->getConstructor()->isCopyConstructor()) { 8558 Expr *ArgExpr = E->getArg(0); 8559 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 8560 if (ILE->getNumInits() == 1) 8561 ArgExpr = ILE->getInit(0); 8562 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8563 if (ICE->getCastKind() == CK_NoOp) 8564 ArgExpr = ICE->getSubExpr(); 8565 HandleValue(ArgExpr); 8566 return; 8567 } 8568 Inherited::VisitCXXConstructExpr(E); 8569 } 8570 8571 void VisitCallExpr(CallExpr *E) { 8572 // Treat std::move as a use. 8573 if (E->getNumArgs() == 1) { 8574 if (FunctionDecl *FD = E->getDirectCallee()) { 8575 if (FD->isInStdNamespace() && FD->getIdentifier() && 8576 FD->getIdentifier()->isStr("move")) { 8577 HandleValue(E->getArg(0)); 8578 return; 8579 } 8580 } 8581 } 8582 8583 Inherited::VisitCallExpr(E); 8584 } 8585 8586 void VisitBinaryOperator(BinaryOperator *E) { 8587 if (E->isCompoundAssignmentOp()) { 8588 HandleValue(E->getLHS()); 8589 Visit(E->getRHS()); 8590 return; 8591 } 8592 8593 Inherited::VisitBinaryOperator(E); 8594 } 8595 8596 // A custom visitor for BinaryConditionalOperator is needed because the 8597 // regular visitor would check the condition and true expression separately 8598 // but both point to the same place giving duplicate diagnostics. 8599 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 8600 Visit(E->getCond()); 8601 Visit(E->getFalseExpr()); 8602 } 8603 8604 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8605 Decl* ReferenceDecl = DRE->getDecl(); 8606 if (OrigDecl != ReferenceDecl) return; 8607 unsigned diag; 8608 if (isReferenceType) { 8609 diag = diag::warn_uninit_self_reference_in_reference_init; 8610 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8611 diag = diag::warn_static_self_reference_in_init; 8612 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 8613 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 8614 DRE->getDecl()->getType()->isRecordType()) { 8615 diag = diag::warn_uninit_self_reference_in_init; 8616 } else { 8617 // Local variables will be handled by the CFG analysis. 8618 return; 8619 } 8620 8621 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8622 S.PDiag(diag) 8623 << DRE->getNameInfo().getName() 8624 << OrigDecl->getLocation() 8625 << DRE->getSourceRange()); 8626 } 8627 }; 8628 8629 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8630 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8631 bool DirectInit) { 8632 // Parameters arguments are occassionially constructed with itself, 8633 // for instance, in recursive functions. Skip them. 8634 if (isa<ParmVarDecl>(OrigDecl)) 8635 return; 8636 8637 E = E->IgnoreParens(); 8638 8639 // Skip checking T a = a where T is not a record or reference type. 8640 // Doing so is a way to silence uninitialized warnings. 8641 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8642 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8643 if (ICE->getCastKind() == CK_LValueToRValue) 8644 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8645 if (DRE->getDecl() == OrigDecl) 8646 return; 8647 8648 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 8649 } 8650 } 8651 8652 /// AddInitializerToDecl - Adds the initializer Init to the 8653 /// declaration dcl. If DirectInit is true, this is C++ direct 8654 /// initialization rather than copy initialization. 8655 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8656 bool DirectInit, bool TypeMayContainAuto) { 8657 // If there is no declaration, there was an error parsing it. Just ignore 8658 // the initializer. 8659 if (!RealDecl || RealDecl->isInvalidDecl()) { 8660 CorrectDelayedTyposInExpr(Init); 8661 return; 8662 } 8663 8664 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8665 // With declarators parsed the way they are, the parser cannot 8666 // distinguish between a normal initializer and a pure-specifier. 8667 // Thus this grotesque test. 8668 IntegerLiteral *IL; 8669 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8670 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8671 CheckPureMethod(Method, Init->getSourceRange()); 8672 else { 8673 Diag(Method->getLocation(), diag::err_member_function_initialization) 8674 << Method->getDeclName() << Init->getSourceRange(); 8675 Method->setInvalidDecl(); 8676 } 8677 return; 8678 } 8679 8680 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8681 if (!VDecl) { 8682 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8683 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8684 RealDecl->setInvalidDecl(); 8685 return; 8686 } 8687 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8688 8689 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8690 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8691 Expr *DeduceInit = Init; 8692 // Initializer could be a C++ direct-initializer. Deduction only works if it 8693 // contains exactly one expression. 8694 if (CXXDirectInit) { 8695 if (CXXDirectInit->getNumExprs() == 0) { 8696 // It isn't possible to write this directly, but it is possible to 8697 // end up in this situation with "auto x(some_pack...);" 8698 Diag(CXXDirectInit->getLocStart(), 8699 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8700 : diag::err_auto_var_init_no_expression) 8701 << VDecl->getDeclName() << VDecl->getType() 8702 << VDecl->getSourceRange(); 8703 RealDecl->setInvalidDecl(); 8704 return; 8705 } else if (CXXDirectInit->getNumExprs() > 1) { 8706 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8707 VDecl->isInitCapture() 8708 ? diag::err_init_capture_multiple_expressions 8709 : diag::err_auto_var_init_multiple_expressions) 8710 << VDecl->getDeclName() << VDecl->getType() 8711 << VDecl->getSourceRange(); 8712 RealDecl->setInvalidDecl(); 8713 return; 8714 } else { 8715 DeduceInit = CXXDirectInit->getExpr(0); 8716 if (isa<InitListExpr>(DeduceInit)) 8717 Diag(CXXDirectInit->getLocStart(), 8718 diag::err_auto_var_init_paren_braces) 8719 << VDecl->getDeclName() << VDecl->getType() 8720 << VDecl->getSourceRange(); 8721 } 8722 } 8723 8724 // Expressions default to 'id' when we're in a debugger. 8725 bool DefaultedToAuto = false; 8726 if (getLangOpts().DebuggerCastResultToId && 8727 Init->getType() == Context.UnknownAnyTy) { 8728 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8729 if (Result.isInvalid()) { 8730 VDecl->setInvalidDecl(); 8731 return; 8732 } 8733 Init = Result.get(); 8734 DefaultedToAuto = true; 8735 } 8736 8737 QualType DeducedType; 8738 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8739 DAR_Failed) 8740 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8741 if (DeducedType.isNull()) { 8742 RealDecl->setInvalidDecl(); 8743 return; 8744 } 8745 VDecl->setType(DeducedType); 8746 assert(VDecl->isLinkageValid()); 8747 8748 // In ARC, infer lifetime. 8749 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8750 VDecl->setInvalidDecl(); 8751 8752 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8753 // 'id' instead of a specific object type prevents most of our usual checks. 8754 // We only want to warn outside of template instantiations, though: 8755 // inside a template, the 'id' could have come from a parameter. 8756 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8757 DeducedType->isObjCIdType()) { 8758 SourceLocation Loc = 8759 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8760 Diag(Loc, diag::warn_auto_var_is_id) 8761 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8762 } 8763 8764 // If this is a redeclaration, check that the type we just deduced matches 8765 // the previously declared type. 8766 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8767 // We never need to merge the type, because we cannot form an incomplete 8768 // array of auto, nor deduce such a type. 8769 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8770 } 8771 8772 // Check the deduced type is valid for a variable declaration. 8773 CheckVariableDeclarationType(VDecl); 8774 if (VDecl->isInvalidDecl()) 8775 return; 8776 8777 // If all looks well, warn if this is a case that will change meaning when 8778 // we implement N3922. 8779 if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) { 8780 Diag(Init->getLocStart(), 8781 diag::warn_auto_var_direct_list_init) 8782 << FixItHint::CreateInsertion(Init->getLocStart(), "="); 8783 } 8784 } 8785 8786 // dllimport cannot be used on variable definitions. 8787 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8788 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8789 VDecl->setInvalidDecl(); 8790 return; 8791 } 8792 8793 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8794 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8795 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8796 VDecl->setInvalidDecl(); 8797 return; 8798 } 8799 8800 if (!VDecl->getType()->isDependentType()) { 8801 // A definition must end up with a complete type, which means it must be 8802 // complete with the restriction that an array type might be completed by 8803 // the initializer; note that later code assumes this restriction. 8804 QualType BaseDeclType = VDecl->getType(); 8805 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8806 BaseDeclType = Array->getElementType(); 8807 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8808 diag::err_typecheck_decl_incomplete_type)) { 8809 RealDecl->setInvalidDecl(); 8810 return; 8811 } 8812 8813 // The variable can not have an abstract class type. 8814 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8815 diag::err_abstract_type_in_decl, 8816 AbstractVariableType)) 8817 VDecl->setInvalidDecl(); 8818 } 8819 8820 const VarDecl *Def; 8821 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8822 Diag(VDecl->getLocation(), diag::err_redefinition) 8823 << VDecl->getDeclName(); 8824 Diag(Def->getLocation(), diag::note_previous_definition); 8825 VDecl->setInvalidDecl(); 8826 return; 8827 } 8828 8829 const VarDecl *PrevInit = nullptr; 8830 if (getLangOpts().CPlusPlus) { 8831 // C++ [class.static.data]p4 8832 // If a static data member is of const integral or const 8833 // enumeration type, its declaration in the class definition can 8834 // specify a constant-initializer which shall be an integral 8835 // constant expression (5.19). In that case, the member can appear 8836 // in integral constant expressions. The member shall still be 8837 // defined in a namespace scope if it is used in the program and the 8838 // namespace scope definition shall not contain an initializer. 8839 // 8840 // We already performed a redefinition check above, but for static 8841 // data members we also need to check whether there was an in-class 8842 // declaration with an initializer. 8843 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8844 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8845 << VDecl->getDeclName(); 8846 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8847 return; 8848 } 8849 8850 if (VDecl->hasLocalStorage()) 8851 getCurFunction()->setHasBranchProtectedScope(); 8852 8853 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8854 VDecl->setInvalidDecl(); 8855 return; 8856 } 8857 } 8858 8859 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8860 // a kernel function cannot be initialized." 8861 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8862 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8863 VDecl->setInvalidDecl(); 8864 return; 8865 } 8866 8867 // Get the decls type and save a reference for later, since 8868 // CheckInitializerTypes may change it. 8869 QualType DclT = VDecl->getType(), SavT = DclT; 8870 8871 // Expressions default to 'id' when we're in a debugger 8872 // and we are assigning it to a variable of Objective-C pointer type. 8873 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8874 Init->getType() == Context.UnknownAnyTy) { 8875 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8876 if (Result.isInvalid()) { 8877 VDecl->setInvalidDecl(); 8878 return; 8879 } 8880 Init = Result.get(); 8881 } 8882 8883 // Perform the initialization. 8884 if (!VDecl->isInvalidDecl()) { 8885 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8886 InitializationKind Kind 8887 = DirectInit ? 8888 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8889 Init->getLocStart(), 8890 Init->getLocEnd()) 8891 : InitializationKind::CreateDirectList( 8892 VDecl->getLocation()) 8893 : InitializationKind::CreateCopy(VDecl->getLocation(), 8894 Init->getLocStart()); 8895 8896 MultiExprArg Args = Init; 8897 if (CXXDirectInit) 8898 Args = MultiExprArg(CXXDirectInit->getExprs(), 8899 CXXDirectInit->getNumExprs()); 8900 8901 // Try to correct any TypoExprs in the initialization arguments. 8902 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 8903 ExprResult Res = 8904 CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) { 8905 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 8906 return Init.Failed() ? ExprError() : E; 8907 }); 8908 if (Res.isInvalid()) { 8909 VDecl->setInvalidDecl(); 8910 } else if (Res.get() != Args[Idx]) { 8911 Args[Idx] = Res.get(); 8912 } 8913 } 8914 if (VDecl->isInvalidDecl()) 8915 return; 8916 8917 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8918 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8919 if (Result.isInvalid()) { 8920 VDecl->setInvalidDecl(); 8921 return; 8922 } 8923 8924 Init = Result.getAs<Expr>(); 8925 } 8926 8927 // Check for self-references within variable initializers. 8928 // Variables declared within a function/method body (except for references) 8929 // are handled by a dataflow analysis. 8930 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8931 VDecl->getType()->isReferenceType()) { 8932 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8933 } 8934 8935 // If the type changed, it means we had an incomplete type that was 8936 // completed by the initializer. For example: 8937 // int ary[] = { 1, 3, 5 }; 8938 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8939 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8940 VDecl->setType(DclT); 8941 8942 if (!VDecl->isInvalidDecl()) { 8943 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8944 8945 if (VDecl->hasAttr<BlocksAttr>()) 8946 checkRetainCycles(VDecl, Init); 8947 8948 // It is safe to assign a weak reference into a strong variable. 8949 // Although this code can still have problems: 8950 // id x = self.weakProp; 8951 // id y = self.weakProp; 8952 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8953 // paths through the function. This should be revisited if 8954 // -Wrepeated-use-of-weak is made flow-sensitive. 8955 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 8956 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 8957 Init->getLocStart())) 8958 getCurFunction()->markSafeWeakUse(Init); 8959 } 8960 8961 // The initialization is usually a full-expression. 8962 // 8963 // FIXME: If this is a braced initialization of an aggregate, it is not 8964 // an expression, and each individual field initializer is a separate 8965 // full-expression. For instance, in: 8966 // 8967 // struct Temp { ~Temp(); }; 8968 // struct S { S(Temp); }; 8969 // struct T { S a, b; } t = { Temp(), Temp() } 8970 // 8971 // we should destroy the first Temp before constructing the second. 8972 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8973 false, 8974 VDecl->isConstexpr()); 8975 if (Result.isInvalid()) { 8976 VDecl->setInvalidDecl(); 8977 return; 8978 } 8979 Init = Result.get(); 8980 8981 // Attach the initializer to the decl. 8982 VDecl->setInit(Init); 8983 8984 if (VDecl->isLocalVarDecl()) { 8985 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8986 // static storage duration shall be constant expressions or string literals. 8987 // C++ does not have this restriction. 8988 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8989 const Expr *Culprit; 8990 if (VDecl->getStorageClass() == SC_Static) 8991 CheckForConstantInitializer(Init, DclT); 8992 // C89 is stricter than C99 for non-static aggregate types. 8993 // C89 6.5.7p3: All the expressions [...] in an initializer list 8994 // for an object that has aggregate or union type shall be 8995 // constant expressions. 8996 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8997 isa<InitListExpr>(Init) && 8998 !Init->isConstantInitializer(Context, false, &Culprit)) 8999 Diag(Culprit->getExprLoc(), 9000 diag::ext_aggregate_init_not_constant) 9001 << Culprit->getSourceRange(); 9002 } 9003 } else if (VDecl->isStaticDataMember() && 9004 VDecl->getLexicalDeclContext()->isRecord()) { 9005 // This is an in-class initialization for a static data member, e.g., 9006 // 9007 // struct S { 9008 // static const int value = 17; 9009 // }; 9010 9011 // C++ [class.mem]p4: 9012 // A member-declarator can contain a constant-initializer only 9013 // if it declares a static member (9.4) of const integral or 9014 // const enumeration type, see 9.4.2. 9015 // 9016 // C++11 [class.static.data]p3: 9017 // If a non-volatile const static data member is of integral or 9018 // enumeration type, its declaration in the class definition can 9019 // specify a brace-or-equal-initializer in which every initalizer-clause 9020 // that is an assignment-expression is a constant expression. A static 9021 // data member of literal type can be declared in the class definition 9022 // with the constexpr specifier; if so, its declaration shall specify a 9023 // brace-or-equal-initializer in which every initializer-clause that is 9024 // an assignment-expression is a constant expression. 9025 9026 // Do nothing on dependent types. 9027 if (DclT->isDependentType()) { 9028 9029 // Allow any 'static constexpr' members, whether or not they are of literal 9030 // type. We separately check that every constexpr variable is of literal 9031 // type. 9032 } else if (VDecl->isConstexpr()) { 9033 9034 // Require constness. 9035 } else if (!DclT.isConstQualified()) { 9036 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9037 << Init->getSourceRange(); 9038 VDecl->setInvalidDecl(); 9039 9040 // We allow integer constant expressions in all cases. 9041 } else if (DclT->isIntegralOrEnumerationType()) { 9042 // Check whether the expression is a constant expression. 9043 SourceLocation Loc; 9044 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9045 // In C++11, a non-constexpr const static data member with an 9046 // in-class initializer cannot be volatile. 9047 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9048 else if (Init->isValueDependent()) 9049 ; // Nothing to check. 9050 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9051 ; // Ok, it's an ICE! 9052 else if (Init->isEvaluatable(Context)) { 9053 // If we can constant fold the initializer through heroics, accept it, 9054 // but report this as a use of an extension for -pedantic. 9055 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9056 << Init->getSourceRange(); 9057 } else { 9058 // Otherwise, this is some crazy unknown case. Report the issue at the 9059 // location provided by the isIntegerConstantExpr failed check. 9060 Diag(Loc, diag::err_in_class_initializer_non_constant) 9061 << Init->getSourceRange(); 9062 VDecl->setInvalidDecl(); 9063 } 9064 9065 // We allow foldable floating-point constants as an extension. 9066 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9067 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9068 // it anyway and provide a fixit to add the 'constexpr'. 9069 if (getLangOpts().CPlusPlus11) { 9070 Diag(VDecl->getLocation(), 9071 diag::ext_in_class_initializer_float_type_cxx11) 9072 << DclT << Init->getSourceRange(); 9073 Diag(VDecl->getLocStart(), 9074 diag::note_in_class_initializer_float_type_cxx11) 9075 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9076 } else { 9077 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9078 << DclT << Init->getSourceRange(); 9079 9080 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9081 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9082 << Init->getSourceRange(); 9083 VDecl->setInvalidDecl(); 9084 } 9085 } 9086 9087 // Suggest adding 'constexpr' in C++11 for literal types. 9088 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9089 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9090 << DclT << Init->getSourceRange() 9091 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9092 VDecl->setConstexpr(true); 9093 9094 } else { 9095 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9096 << DclT << Init->getSourceRange(); 9097 VDecl->setInvalidDecl(); 9098 } 9099 } else if (VDecl->isFileVarDecl()) { 9100 if (VDecl->getStorageClass() == SC_Extern && 9101 (!getLangOpts().CPlusPlus || 9102 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 9103 VDecl->isExternC())) && 9104 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9105 Diag(VDecl->getLocation(), diag::warn_extern_init); 9106 9107 // C99 6.7.8p4. All file scoped initializers need to be constant. 9108 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9109 CheckForConstantInitializer(Init, DclT); 9110 } 9111 9112 // We will represent direct-initialization similarly to copy-initialization: 9113 // int x(1); -as-> int x = 1; 9114 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9115 // 9116 // Clients that want to distinguish between the two forms, can check for 9117 // direct initializer using VarDecl::getInitStyle(). 9118 // A major benefit is that clients that don't particularly care about which 9119 // exactly form was it (like the CodeGen) can handle both cases without 9120 // special case code. 9121 9122 // C++ 8.5p11: 9123 // The form of initialization (using parentheses or '=') is generally 9124 // insignificant, but does matter when the entity being initialized has a 9125 // class type. 9126 if (CXXDirectInit) { 9127 assert(DirectInit && "Call-style initializer must be direct init."); 9128 VDecl->setInitStyle(VarDecl::CallInit); 9129 } else if (DirectInit) { 9130 // This must be list-initialization. No other way is direct-initialization. 9131 VDecl->setInitStyle(VarDecl::ListInit); 9132 } 9133 9134 CheckCompleteVariableDeclaration(VDecl); 9135 } 9136 9137 /// ActOnInitializerError - Given that there was an error parsing an 9138 /// initializer for the given declaration, try to return to some form 9139 /// of sanity. 9140 void Sema::ActOnInitializerError(Decl *D) { 9141 // Our main concern here is re-establishing invariants like "a 9142 // variable's type is either dependent or complete". 9143 if (!D || D->isInvalidDecl()) return; 9144 9145 VarDecl *VD = dyn_cast<VarDecl>(D); 9146 if (!VD) return; 9147 9148 // Auto types are meaningless if we can't make sense of the initializer. 9149 if (ParsingInitForAutoVars.count(D)) { 9150 D->setInvalidDecl(); 9151 return; 9152 } 9153 9154 QualType Ty = VD->getType(); 9155 if (Ty->isDependentType()) return; 9156 9157 // Require a complete type. 9158 if (RequireCompleteType(VD->getLocation(), 9159 Context.getBaseElementType(Ty), 9160 diag::err_typecheck_decl_incomplete_type)) { 9161 VD->setInvalidDecl(); 9162 return; 9163 } 9164 9165 // Require a non-abstract type. 9166 if (RequireNonAbstractType(VD->getLocation(), Ty, 9167 diag::err_abstract_type_in_decl, 9168 AbstractVariableType)) { 9169 VD->setInvalidDecl(); 9170 return; 9171 } 9172 9173 // Don't bother complaining about constructors or destructors, 9174 // though. 9175 } 9176 9177 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9178 bool TypeMayContainAuto) { 9179 // If there is no declaration, there was an error parsing it. Just ignore it. 9180 if (!RealDecl) 9181 return; 9182 9183 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9184 QualType Type = Var->getType(); 9185 9186 // C++11 [dcl.spec.auto]p3 9187 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9188 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9189 << Var->getDeclName() << Type; 9190 Var->setInvalidDecl(); 9191 return; 9192 } 9193 9194 // C++11 [class.static.data]p3: A static data member can be declared with 9195 // the constexpr specifier; if so, its declaration shall specify 9196 // a brace-or-equal-initializer. 9197 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9198 // the definition of a variable [...] or the declaration of a static data 9199 // member. 9200 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9201 if (Var->isStaticDataMember()) 9202 Diag(Var->getLocation(), 9203 diag::err_constexpr_static_mem_var_requires_init) 9204 << Var->getDeclName(); 9205 else 9206 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9207 Var->setInvalidDecl(); 9208 return; 9209 } 9210 9211 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9212 // be initialized. 9213 if (!Var->isInvalidDecl() && 9214 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9215 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9216 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9217 Var->setInvalidDecl(); 9218 return; 9219 } 9220 9221 switch (Var->isThisDeclarationADefinition()) { 9222 case VarDecl::Definition: 9223 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9224 break; 9225 9226 // We have an out-of-line definition of a static data member 9227 // that has an in-class initializer, so we type-check this like 9228 // a declaration. 9229 // 9230 // Fall through 9231 9232 case VarDecl::DeclarationOnly: 9233 // It's only a declaration. 9234 9235 // Block scope. C99 6.7p7: If an identifier for an object is 9236 // declared with no linkage (C99 6.2.2p6), the type for the 9237 // object shall be complete. 9238 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9239 !Var->hasLinkage() && !Var->isInvalidDecl() && 9240 RequireCompleteType(Var->getLocation(), Type, 9241 diag::err_typecheck_decl_incomplete_type)) 9242 Var->setInvalidDecl(); 9243 9244 // Make sure that the type is not abstract. 9245 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9246 RequireNonAbstractType(Var->getLocation(), Type, 9247 diag::err_abstract_type_in_decl, 9248 AbstractVariableType)) 9249 Var->setInvalidDecl(); 9250 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9251 Var->getStorageClass() == SC_PrivateExtern) { 9252 Diag(Var->getLocation(), diag::warn_private_extern); 9253 Diag(Var->getLocation(), diag::note_private_extern); 9254 } 9255 9256 return; 9257 9258 case VarDecl::TentativeDefinition: 9259 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9260 // object that has file scope without an initializer, and without a 9261 // storage-class specifier or with the storage-class specifier "static", 9262 // constitutes a tentative definition. Note: A tentative definition with 9263 // external linkage is valid (C99 6.2.2p5). 9264 if (!Var->isInvalidDecl()) { 9265 if (const IncompleteArrayType *ArrayT 9266 = Context.getAsIncompleteArrayType(Type)) { 9267 if (RequireCompleteType(Var->getLocation(), 9268 ArrayT->getElementType(), 9269 diag::err_illegal_decl_array_incomplete_type)) 9270 Var->setInvalidDecl(); 9271 } else if (Var->getStorageClass() == SC_Static) { 9272 // C99 6.9.2p3: If the declaration of an identifier for an object is 9273 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9274 // declared type shall not be an incomplete type. 9275 // NOTE: code such as the following 9276 // static struct s; 9277 // struct s { int a; }; 9278 // is accepted by gcc. Hence here we issue a warning instead of 9279 // an error and we do not invalidate the static declaration. 9280 // NOTE: to avoid multiple warnings, only check the first declaration. 9281 if (Var->isFirstDecl()) 9282 RequireCompleteType(Var->getLocation(), Type, 9283 diag::ext_typecheck_decl_incomplete_type); 9284 } 9285 } 9286 9287 // Record the tentative definition; we're done. 9288 if (!Var->isInvalidDecl()) 9289 TentativeDefinitions.push_back(Var); 9290 return; 9291 } 9292 9293 // Provide a specific diagnostic for uninitialized variable 9294 // definitions with incomplete array type. 9295 if (Type->isIncompleteArrayType()) { 9296 Diag(Var->getLocation(), 9297 diag::err_typecheck_incomplete_array_needs_initializer); 9298 Var->setInvalidDecl(); 9299 return; 9300 } 9301 9302 // Provide a specific diagnostic for uninitialized variable 9303 // definitions with reference type. 9304 if (Type->isReferenceType()) { 9305 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9306 << Var->getDeclName() 9307 << SourceRange(Var->getLocation(), Var->getLocation()); 9308 Var->setInvalidDecl(); 9309 return; 9310 } 9311 9312 // Do not attempt to type-check the default initializer for a 9313 // variable with dependent type. 9314 if (Type->isDependentType()) 9315 return; 9316 9317 if (Var->isInvalidDecl()) 9318 return; 9319 9320 if (!Var->hasAttr<AliasAttr>()) { 9321 if (RequireCompleteType(Var->getLocation(), 9322 Context.getBaseElementType(Type), 9323 diag::err_typecheck_decl_incomplete_type)) { 9324 Var->setInvalidDecl(); 9325 return; 9326 } 9327 } else { 9328 return; 9329 } 9330 9331 // The variable can not have an abstract class type. 9332 if (RequireNonAbstractType(Var->getLocation(), Type, 9333 diag::err_abstract_type_in_decl, 9334 AbstractVariableType)) { 9335 Var->setInvalidDecl(); 9336 return; 9337 } 9338 9339 // Check for jumps past the implicit initializer. C++0x 9340 // clarifies that this applies to a "variable with automatic 9341 // storage duration", not a "local variable". 9342 // C++11 [stmt.dcl]p3 9343 // A program that jumps from a point where a variable with automatic 9344 // storage duration is not in scope to a point where it is in scope is 9345 // ill-formed unless the variable has scalar type, class type with a 9346 // trivial default constructor and a trivial destructor, a cv-qualified 9347 // version of one of these types, or an array of one of the preceding 9348 // types and is declared without an initializer. 9349 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9350 if (const RecordType *Record 9351 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9352 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9353 // Mark the function for further checking even if the looser rules of 9354 // C++11 do not require such checks, so that we can diagnose 9355 // incompatibilities with C++98. 9356 if (!CXXRecord->isPOD()) 9357 getCurFunction()->setHasBranchProtectedScope(); 9358 } 9359 } 9360 9361 // C++03 [dcl.init]p9: 9362 // If no initializer is specified for an object, and the 9363 // object is of (possibly cv-qualified) non-POD class type (or 9364 // array thereof), the object shall be default-initialized; if 9365 // the object is of const-qualified type, the underlying class 9366 // type shall have a user-declared default 9367 // constructor. Otherwise, if no initializer is specified for 9368 // a non- static object, the object and its subobjects, if 9369 // any, have an indeterminate initial value); if the object 9370 // or any of its subobjects are of const-qualified type, the 9371 // program is ill-formed. 9372 // C++0x [dcl.init]p11: 9373 // If no initializer is specified for an object, the object is 9374 // default-initialized; [...]. 9375 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9376 InitializationKind Kind 9377 = InitializationKind::CreateDefault(Var->getLocation()); 9378 9379 InitializationSequence InitSeq(*this, Entity, Kind, None); 9380 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9381 if (Init.isInvalid()) 9382 Var->setInvalidDecl(); 9383 else if (Init.get()) { 9384 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9385 // This is important for template substitution. 9386 Var->setInitStyle(VarDecl::CallInit); 9387 } 9388 9389 CheckCompleteVariableDeclaration(Var); 9390 } 9391 } 9392 9393 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9394 VarDecl *VD = dyn_cast<VarDecl>(D); 9395 if (!VD) { 9396 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9397 D->setInvalidDecl(); 9398 return; 9399 } 9400 9401 VD->setCXXForRangeDecl(true); 9402 9403 // for-range-declaration cannot be given a storage class specifier. 9404 int Error = -1; 9405 switch (VD->getStorageClass()) { 9406 case SC_None: 9407 break; 9408 case SC_Extern: 9409 Error = 0; 9410 break; 9411 case SC_Static: 9412 Error = 1; 9413 break; 9414 case SC_PrivateExtern: 9415 Error = 2; 9416 break; 9417 case SC_Auto: 9418 Error = 3; 9419 break; 9420 case SC_Register: 9421 Error = 4; 9422 break; 9423 case SC_OpenCLWorkGroupLocal: 9424 llvm_unreachable("Unexpected storage class"); 9425 } 9426 if (Error != -1) { 9427 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9428 << VD->getDeclName() << Error; 9429 D->setInvalidDecl(); 9430 } 9431 } 9432 9433 StmtResult 9434 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9435 IdentifierInfo *Ident, 9436 ParsedAttributes &Attrs, 9437 SourceLocation AttrEnd) { 9438 // C++1y [stmt.iter]p1: 9439 // A range-based for statement of the form 9440 // for ( for-range-identifier : for-range-initializer ) statement 9441 // is equivalent to 9442 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9443 DeclSpec DS(Attrs.getPool().getFactory()); 9444 9445 const char *PrevSpec; 9446 unsigned DiagID; 9447 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 9448 getPrintingPolicy()); 9449 9450 Declarator D(DS, Declarator::ForContext); 9451 D.SetIdentifier(Ident, IdentLoc); 9452 D.takeAttributes(Attrs, AttrEnd); 9453 9454 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 9455 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 9456 EmptyAttrs, IdentLoc); 9457 Decl *Var = ActOnDeclarator(S, D); 9458 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 9459 FinalizeDeclaration(Var); 9460 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 9461 AttrEnd.isValid() ? AttrEnd : IdentLoc); 9462 } 9463 9464 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 9465 if (var->isInvalidDecl()) return; 9466 9467 // In ARC, don't allow jumps past the implicit initialization of a 9468 // local retaining variable. 9469 if (getLangOpts().ObjCAutoRefCount && 9470 var->hasLocalStorage()) { 9471 switch (var->getType().getObjCLifetime()) { 9472 case Qualifiers::OCL_None: 9473 case Qualifiers::OCL_ExplicitNone: 9474 case Qualifiers::OCL_Autoreleasing: 9475 break; 9476 9477 case Qualifiers::OCL_Weak: 9478 case Qualifiers::OCL_Strong: 9479 getCurFunction()->setHasBranchProtectedScope(); 9480 break; 9481 } 9482 } 9483 9484 // Warn about externally-visible variables being defined without a 9485 // prior declaration. We only want to do this for global 9486 // declarations, but we also specifically need to avoid doing it for 9487 // class members because the linkage of an anonymous class can 9488 // change if it's later given a typedef name. 9489 if (var->isThisDeclarationADefinition() && 9490 var->getDeclContext()->getRedeclContext()->isFileContext() && 9491 var->isExternallyVisible() && var->hasLinkage() && 9492 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9493 var->getLocation())) { 9494 // Find a previous declaration that's not a definition. 9495 VarDecl *prev = var->getPreviousDecl(); 9496 while (prev && prev->isThisDeclarationADefinition()) 9497 prev = prev->getPreviousDecl(); 9498 9499 if (!prev) 9500 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9501 } 9502 9503 if (var->getTLSKind() == VarDecl::TLS_Static) { 9504 const Expr *Culprit; 9505 if (var->getType().isDestructedType()) { 9506 // GNU C++98 edits for __thread, [basic.start.term]p3: 9507 // The type of an object with thread storage duration shall not 9508 // have a non-trivial destructor. 9509 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9510 if (getLangOpts().CPlusPlus11) 9511 Diag(var->getLocation(), diag::note_use_thread_local); 9512 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9513 !var->getInit()->isConstantInitializer( 9514 Context, var->getType()->isReferenceType(), &Culprit)) { 9515 // GNU C++98 edits for __thread, [basic.start.init]p4: 9516 // An object of thread storage duration shall not require dynamic 9517 // initialization. 9518 // FIXME: Need strict checking here. 9519 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9520 << Culprit->getSourceRange(); 9521 if (getLangOpts().CPlusPlus11) 9522 Diag(var->getLocation(), diag::note_use_thread_local); 9523 } 9524 9525 } 9526 9527 // Apply section attributes and pragmas to global variables. 9528 bool GlobalStorage = var->hasGlobalStorage(); 9529 if (GlobalStorage && var->isThisDeclarationADefinition() && 9530 ActiveTemplateInstantiations.empty()) { 9531 PragmaStack<StringLiteral *> *Stack = nullptr; 9532 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 9533 if (var->getType().isConstQualified()) 9534 Stack = &ConstSegStack; 9535 else if (!var->getInit()) { 9536 Stack = &BSSSegStack; 9537 SectionFlags |= ASTContext::PSF_Write; 9538 } else { 9539 Stack = &DataSegStack; 9540 SectionFlags |= ASTContext::PSF_Write; 9541 } 9542 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 9543 var->addAttr(SectionAttr::CreateImplicit( 9544 Context, SectionAttr::Declspec_allocate, 9545 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 9546 } 9547 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9548 if (UnifySection(SA->getName(), SectionFlags, var)) 9549 var->dropAttr<SectionAttr>(); 9550 9551 // Apply the init_seg attribute if this has an initializer. If the 9552 // initializer turns out to not be dynamic, we'll end up ignoring this 9553 // attribute. 9554 if (CurInitSeg && var->getInit()) 9555 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 9556 CurInitSegLoc)); 9557 } 9558 9559 // All the following checks are C++ only. 9560 if (!getLangOpts().CPlusPlus) return; 9561 9562 QualType type = var->getType(); 9563 if (type->isDependentType()) return; 9564 9565 // __block variables might require us to capture a copy-initializer. 9566 if (var->hasAttr<BlocksAttr>()) { 9567 // It's currently invalid to ever have a __block variable with an 9568 // array type; should we diagnose that here? 9569 9570 // Regardless, we don't want to ignore array nesting when 9571 // constructing this copy. 9572 if (type->isStructureOrClassType()) { 9573 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9574 SourceLocation poi = var->getLocation(); 9575 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9576 ExprResult result 9577 = PerformMoveOrCopyInitialization( 9578 InitializedEntity::InitializeBlock(poi, type, false), 9579 var, var->getType(), varRef, /*AllowNRVO=*/true); 9580 if (!result.isInvalid()) { 9581 result = MaybeCreateExprWithCleanups(result); 9582 Expr *init = result.getAs<Expr>(); 9583 Context.setBlockVarCopyInits(var, init); 9584 } 9585 } 9586 } 9587 9588 Expr *Init = var->getInit(); 9589 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 9590 QualType baseType = Context.getBaseElementType(type); 9591 9592 if (!var->getDeclContext()->isDependentContext() && 9593 Init && !Init->isValueDependent()) { 9594 if (IsGlobal && !var->isConstexpr() && 9595 !getDiagnostics().isIgnored(diag::warn_global_constructor, 9596 var->getLocation())) { 9597 // Warn about globals which don't have a constant initializer. Don't 9598 // warn about globals with a non-trivial destructor because we already 9599 // warned about them. 9600 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9601 if (!(RD && !RD->hasTrivialDestructor()) && 9602 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9603 Diag(var->getLocation(), diag::warn_global_constructor) 9604 << Init->getSourceRange(); 9605 } 9606 9607 if (var->isConstexpr()) { 9608 SmallVector<PartialDiagnosticAt, 8> Notes; 9609 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9610 SourceLocation DiagLoc = var->getLocation(); 9611 // If the note doesn't add any useful information other than a source 9612 // location, fold it into the primary diagnostic. 9613 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9614 diag::note_invalid_subexpr_in_const_expr) { 9615 DiagLoc = Notes[0].first; 9616 Notes.clear(); 9617 } 9618 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9619 << var << Init->getSourceRange(); 9620 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9621 Diag(Notes[I].first, Notes[I].second); 9622 } 9623 } else if (var->isUsableInConstantExpressions(Context)) { 9624 // Check whether the initializer of a const variable of integral or 9625 // enumeration type is an ICE now, since we can't tell whether it was 9626 // initialized by a constant expression if we check later. 9627 var->checkInitIsICE(); 9628 } 9629 } 9630 9631 // Require the destructor. 9632 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9633 FinalizeVarWithDestructor(var, recordType); 9634 } 9635 9636 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9637 /// any semantic actions necessary after any initializer has been attached. 9638 void 9639 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9640 // Note that we are no longer parsing the initializer for this declaration. 9641 ParsingInitForAutoVars.erase(ThisDecl); 9642 9643 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9644 if (!VD) 9645 return; 9646 9647 checkAttributesAfterMerging(*this, *VD); 9648 9649 // Static locals inherit dll attributes from their function. 9650 if (VD->isStaticLocal()) { 9651 if (FunctionDecl *FD = 9652 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 9653 if (Attr *A = getDLLAttr(FD)) { 9654 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 9655 NewAttr->setInherited(true); 9656 VD->addAttr(NewAttr); 9657 } 9658 } 9659 } 9660 9661 // Grab the dllimport or dllexport attribute off of the VarDecl. 9662 const InheritableAttr *DLLAttr = getDLLAttr(VD); 9663 9664 // Imported static data members cannot be defined out-of-line. 9665 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 9666 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9667 VD->isThisDeclarationADefinition()) { 9668 // We allow definitions of dllimport class template static data members 9669 // with a warning. 9670 CXXRecordDecl *Context = 9671 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9672 bool IsClassTemplateMember = 9673 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9674 Context->getDescribedClassTemplate(); 9675 9676 Diag(VD->getLocation(), 9677 IsClassTemplateMember 9678 ? diag::warn_attribute_dllimport_static_field_definition 9679 : diag::err_attribute_dllimport_static_field_definition); 9680 Diag(IA->getLocation(), diag::note_attribute); 9681 if (!IsClassTemplateMember) 9682 VD->setInvalidDecl(); 9683 } 9684 } 9685 9686 // dllimport/dllexport variables cannot be thread local, their TLS index 9687 // isn't exported with the variable. 9688 if (DLLAttr && VD->getTLSKind()) { 9689 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 9690 << DLLAttr; 9691 VD->setInvalidDecl(); 9692 } 9693 9694 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9695 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9696 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9697 VD->dropAttr<UsedAttr>(); 9698 } 9699 } 9700 9701 const DeclContext *DC = VD->getDeclContext(); 9702 // If there's a #pragma GCC visibility in scope, and this isn't a class 9703 // member, set the visibility of this variable. 9704 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9705 AddPushedVisibilityAttribute(VD); 9706 9707 // FIXME: Warn on unused templates. 9708 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9709 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9710 MarkUnusedFileScopedDecl(VD); 9711 9712 // Now we have parsed the initializer and can update the table of magic 9713 // tag values. 9714 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9715 !VD->getType()->isIntegralOrEnumerationType()) 9716 return; 9717 9718 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9719 const Expr *MagicValueExpr = VD->getInit(); 9720 if (!MagicValueExpr) { 9721 continue; 9722 } 9723 llvm::APSInt MagicValueInt; 9724 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9725 Diag(I->getRange().getBegin(), 9726 diag::err_type_tag_for_datatype_not_ice) 9727 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9728 continue; 9729 } 9730 if (MagicValueInt.getActiveBits() > 64) { 9731 Diag(I->getRange().getBegin(), 9732 diag::err_type_tag_for_datatype_too_large) 9733 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9734 continue; 9735 } 9736 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9737 RegisterTypeTagForDatatype(I->getArgumentKind(), 9738 MagicValue, 9739 I->getMatchingCType(), 9740 I->getLayoutCompatible(), 9741 I->getMustBeNull()); 9742 } 9743 } 9744 9745 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9746 ArrayRef<Decl *> Group) { 9747 SmallVector<Decl*, 8> Decls; 9748 9749 if (DS.isTypeSpecOwned()) 9750 Decls.push_back(DS.getRepAsDecl()); 9751 9752 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9753 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9754 if (Decl *D = Group[i]) { 9755 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9756 if (!FirstDeclaratorInGroup) 9757 FirstDeclaratorInGroup = DD; 9758 Decls.push_back(D); 9759 } 9760 9761 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9762 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9763 handleTagNumbering(Tag, S); 9764 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9765 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9766 } 9767 } 9768 9769 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9770 } 9771 9772 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9773 /// group, performing any necessary semantic checking. 9774 Sema::DeclGroupPtrTy 9775 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 9776 bool TypeMayContainAuto) { 9777 // C++0x [dcl.spec.auto]p7: 9778 // If the type deduced for the template parameter U is not the same in each 9779 // deduction, the program is ill-formed. 9780 // FIXME: When initializer-list support is added, a distinction is needed 9781 // between the deduced type U and the deduced type which 'auto' stands for. 9782 // auto a = 0, b = { 1, 2, 3 }; 9783 // is legal because the deduced type U is 'int' in both cases. 9784 if (TypeMayContainAuto && Group.size() > 1) { 9785 QualType Deduced; 9786 CanQualType DeducedCanon; 9787 VarDecl *DeducedDecl = nullptr; 9788 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9789 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9790 AutoType *AT = D->getType()->getContainedAutoType(); 9791 // Don't reissue diagnostics when instantiating a template. 9792 if (AT && D->isInvalidDecl()) 9793 break; 9794 QualType U = AT ? AT->getDeducedType() : QualType(); 9795 if (!U.isNull()) { 9796 CanQualType UCanon = Context.getCanonicalType(U); 9797 if (Deduced.isNull()) { 9798 Deduced = U; 9799 DeducedCanon = UCanon; 9800 DeducedDecl = D; 9801 } else if (DeducedCanon != UCanon) { 9802 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9803 diag::err_auto_different_deductions) 9804 << (AT->isDecltypeAuto() ? 1 : 0) 9805 << Deduced << DeducedDecl->getDeclName() 9806 << U << D->getDeclName() 9807 << DeducedDecl->getInit()->getSourceRange() 9808 << D->getInit()->getSourceRange(); 9809 D->setInvalidDecl(); 9810 break; 9811 } 9812 } 9813 } 9814 } 9815 } 9816 9817 ActOnDocumentableDecls(Group); 9818 9819 return DeclGroupPtrTy::make( 9820 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9821 } 9822 9823 void Sema::ActOnDocumentableDecl(Decl *D) { 9824 ActOnDocumentableDecls(D); 9825 } 9826 9827 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9828 // Don't parse the comment if Doxygen diagnostics are ignored. 9829 if (Group.empty() || !Group[0]) 9830 return; 9831 9832 if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation())) 9833 return; 9834 9835 if (Group.size() >= 2) { 9836 // This is a decl group. Normally it will contain only declarations 9837 // produced from declarator list. But in case we have any definitions or 9838 // additional declaration references: 9839 // 'typedef struct S {} S;' 9840 // 'typedef struct S *S;' 9841 // 'struct S *pS;' 9842 // FinalizeDeclaratorGroup adds these as separate declarations. 9843 Decl *MaybeTagDecl = Group[0]; 9844 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9845 Group = Group.slice(1); 9846 } 9847 } 9848 9849 // See if there are any new comments that are not attached to a decl. 9850 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9851 if (!Comments.empty() && 9852 !Comments.back()->isAttached()) { 9853 // There is at least one comment that not attached to a decl. 9854 // Maybe it should be attached to one of these decls? 9855 // 9856 // Note that this way we pick up not only comments that precede the 9857 // declaration, but also comments that *follow* the declaration -- thanks to 9858 // the lookahead in the lexer: we've consumed the semicolon and looked 9859 // ahead through comments. 9860 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9861 Context.getCommentForDecl(Group[i], &PP); 9862 } 9863 } 9864 9865 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9866 /// to introduce parameters into function prototype scope. 9867 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9868 const DeclSpec &DS = D.getDeclSpec(); 9869 9870 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9871 9872 // C++03 [dcl.stc]p2 also permits 'auto'. 9873 StorageClass SC = SC_None; 9874 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9875 SC = SC_Register; 9876 } else if (getLangOpts().CPlusPlus && 9877 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9878 SC = SC_Auto; 9879 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9880 Diag(DS.getStorageClassSpecLoc(), 9881 diag::err_invalid_storage_class_in_func_decl); 9882 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9883 } 9884 9885 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9886 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9887 << DeclSpec::getSpecifierName(TSCS); 9888 if (DS.isConstexprSpecified()) 9889 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9890 << 0; 9891 9892 DiagnoseFunctionSpecifiers(DS); 9893 9894 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9895 QualType parmDeclType = TInfo->getType(); 9896 9897 if (getLangOpts().CPlusPlus) { 9898 // Check that there are no default arguments inside the type of this 9899 // parameter. 9900 CheckExtraCXXDefaultArguments(D); 9901 9902 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9903 if (D.getCXXScopeSpec().isSet()) { 9904 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9905 << D.getCXXScopeSpec().getRange(); 9906 D.getCXXScopeSpec().clear(); 9907 } 9908 } 9909 9910 // Ensure we have a valid name 9911 IdentifierInfo *II = nullptr; 9912 if (D.hasName()) { 9913 II = D.getIdentifier(); 9914 if (!II) { 9915 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9916 << GetNameForDeclarator(D).getName(); 9917 D.setInvalidType(true); 9918 } 9919 } 9920 9921 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9922 if (II) { 9923 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9924 ForRedeclaration); 9925 LookupName(R, S); 9926 if (R.isSingleResult()) { 9927 NamedDecl *PrevDecl = R.getFoundDecl(); 9928 if (PrevDecl->isTemplateParameter()) { 9929 // Maybe we will complain about the shadowed template parameter. 9930 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9931 // Just pretend that we didn't see the previous declaration. 9932 PrevDecl = nullptr; 9933 } else if (S->isDeclScope(PrevDecl)) { 9934 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9935 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9936 9937 // Recover by removing the name 9938 II = nullptr; 9939 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 9940 D.setInvalidType(true); 9941 } 9942 } 9943 } 9944 9945 // Temporarily put parameter variables in the translation unit, not 9946 // the enclosing context. This prevents them from accidentally 9947 // looking like class members in C++. 9948 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9949 D.getLocStart(), 9950 D.getIdentifierLoc(), II, 9951 parmDeclType, TInfo, 9952 SC); 9953 9954 if (D.isInvalidType()) 9955 New->setInvalidDecl(); 9956 9957 assert(S->isFunctionPrototypeScope()); 9958 assert(S->getFunctionPrototypeDepth() >= 1); 9959 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9960 S->getNextFunctionPrototypeIndex()); 9961 9962 // Add the parameter declaration into this scope. 9963 S->AddDecl(New); 9964 if (II) 9965 IdResolver.AddDecl(New); 9966 9967 ProcessDeclAttributes(S, New, D); 9968 9969 if (D.getDeclSpec().isModulePrivateSpecified()) 9970 Diag(New->getLocation(), diag::err_module_private_local) 9971 << 1 << New->getDeclName() 9972 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9973 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9974 9975 if (New->hasAttr<BlocksAttr>()) { 9976 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9977 } 9978 return New; 9979 } 9980 9981 /// \brief Synthesizes a variable for a parameter arising from a 9982 /// typedef. 9983 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9984 SourceLocation Loc, 9985 QualType T) { 9986 /* FIXME: setting StartLoc == Loc. 9987 Would it be worth to modify callers so as to provide proper source 9988 location for the unnamed parameters, embedding the parameter's type? */ 9989 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 9990 T, Context.getTrivialTypeSourceInfo(T, Loc), 9991 SC_None, nullptr); 9992 Param->setImplicit(); 9993 return Param; 9994 } 9995 9996 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9997 ParmVarDecl * const *ParamEnd) { 9998 // Don't diagnose unused-parameter errors in template instantiations; we 9999 // will already have done so in the template itself. 10000 if (!ActiveTemplateInstantiations.empty()) 10001 return; 10002 10003 for (; Param != ParamEnd; ++Param) { 10004 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 10005 !(*Param)->hasAttr<UnusedAttr>()) { 10006 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 10007 << (*Param)->getDeclName(); 10008 } 10009 } 10010 } 10011 10012 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 10013 ParmVarDecl * const *ParamEnd, 10014 QualType ReturnTy, 10015 NamedDecl *D) { 10016 if (LangOpts.NumLargeByValueCopy == 0) // No check. 10017 return; 10018 10019 // Warn if the return value is pass-by-value and larger than the specified 10020 // threshold. 10021 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 10022 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 10023 if (Size > LangOpts.NumLargeByValueCopy) 10024 Diag(D->getLocation(), diag::warn_return_value_size) 10025 << D->getDeclName() << Size; 10026 } 10027 10028 // Warn if any parameter is pass-by-value and larger than the specified 10029 // threshold. 10030 for (; Param != ParamEnd; ++Param) { 10031 QualType T = (*Param)->getType(); 10032 if (T->isDependentType() || !T.isPODType(Context)) 10033 continue; 10034 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 10035 if (Size > LangOpts.NumLargeByValueCopy) 10036 Diag((*Param)->getLocation(), diag::warn_parameter_size) 10037 << (*Param)->getDeclName() << Size; 10038 } 10039 } 10040 10041 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 10042 SourceLocation NameLoc, IdentifierInfo *Name, 10043 QualType T, TypeSourceInfo *TSInfo, 10044 StorageClass SC) { 10045 // In ARC, infer a lifetime qualifier for appropriate parameter types. 10046 if (getLangOpts().ObjCAutoRefCount && 10047 T.getObjCLifetime() == Qualifiers::OCL_None && 10048 T->isObjCLifetimeType()) { 10049 10050 Qualifiers::ObjCLifetime lifetime; 10051 10052 // Special cases for arrays: 10053 // - if it's const, use __unsafe_unretained 10054 // - otherwise, it's an error 10055 if (T->isArrayType()) { 10056 if (!T.isConstQualified()) { 10057 DelayedDiagnostics.add( 10058 sema::DelayedDiagnostic::makeForbiddenType( 10059 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 10060 } 10061 lifetime = Qualifiers::OCL_ExplicitNone; 10062 } else { 10063 lifetime = T->getObjCARCImplicitLifetime(); 10064 } 10065 T = Context.getLifetimeQualifiedType(T, lifetime); 10066 } 10067 10068 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 10069 Context.getAdjustedParameterType(T), 10070 TSInfo, SC, nullptr); 10071 10072 // Parameters can not be abstract class types. 10073 // For record types, this is done by the AbstractClassUsageDiagnoser once 10074 // the class has been completely parsed. 10075 if (!CurContext->isRecord() && 10076 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 10077 AbstractParamType)) 10078 New->setInvalidDecl(); 10079 10080 // Parameter declarators cannot be interface types. All ObjC objects are 10081 // passed by reference. 10082 if (T->isObjCObjectType()) { 10083 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 10084 Diag(NameLoc, 10085 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 10086 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 10087 T = Context.getObjCObjectPointerType(T); 10088 New->setType(T); 10089 } 10090 10091 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 10092 // duration shall not be qualified by an address-space qualifier." 10093 // Since all parameters have automatic store duration, they can not have 10094 // an address space. 10095 if (T.getAddressSpace() != 0) { 10096 // OpenCL allows function arguments declared to be an array of a type 10097 // to be qualified with an address space. 10098 if (!(getLangOpts().OpenCL && T->isArrayType())) { 10099 Diag(NameLoc, diag::err_arg_with_address_space); 10100 New->setInvalidDecl(); 10101 } 10102 } 10103 10104 return New; 10105 } 10106 10107 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 10108 SourceLocation LocAfterDecls) { 10109 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10110 10111 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 10112 // for a K&R function. 10113 if (!FTI.hasPrototype) { 10114 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10115 --i; 10116 if (FTI.Params[i].Param == nullptr) { 10117 SmallString<256> Code; 10118 llvm::raw_svector_ostream(Code) 10119 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10120 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10121 << FTI.Params[i].Ident 10122 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 10123 10124 // Implicitly declare the argument as type 'int' for lack of a better 10125 // type. 10126 AttributeFactory attrs; 10127 DeclSpec DS(attrs); 10128 const char* PrevSpec; // unused 10129 unsigned DiagID; // unused 10130 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10131 DiagID, Context.getPrintingPolicy()); 10132 // Use the identifier location for the type source range. 10133 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10134 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10135 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10136 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10137 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10138 } 10139 } 10140 } 10141 } 10142 10143 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 10144 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10145 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10146 Scope *ParentScope = FnBodyScope->getParent(); 10147 10148 D.setFunctionDefinitionKind(FDK_Definition); 10149 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 10150 return ActOnStartOfFunctionDef(FnBodyScope, DP); 10151 } 10152 10153 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10154 Consumer.HandleInlineMethodDefinition(D); 10155 } 10156 10157 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10158 const FunctionDecl*& PossibleZeroParamPrototype) { 10159 // Don't warn about invalid declarations. 10160 if (FD->isInvalidDecl()) 10161 return false; 10162 10163 // Or declarations that aren't global. 10164 if (!FD->isGlobal()) 10165 return false; 10166 10167 // Don't warn about C++ member functions. 10168 if (isa<CXXMethodDecl>(FD)) 10169 return false; 10170 10171 // Don't warn about 'main'. 10172 if (FD->isMain()) 10173 return false; 10174 10175 // Don't warn about inline functions. 10176 if (FD->isInlined()) 10177 return false; 10178 10179 // Don't warn about function templates. 10180 if (FD->getDescribedFunctionTemplate()) 10181 return false; 10182 10183 // Don't warn about function template specializations. 10184 if (FD->isFunctionTemplateSpecialization()) 10185 return false; 10186 10187 // Don't warn for OpenCL kernels. 10188 if (FD->hasAttr<OpenCLKernelAttr>()) 10189 return false; 10190 10191 // Don't warn on explicitly deleted functions. 10192 if (FD->isDeleted()) 10193 return false; 10194 10195 bool MissingPrototype = true; 10196 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10197 Prev; Prev = Prev->getPreviousDecl()) { 10198 // Ignore any declarations that occur in function or method 10199 // scope, because they aren't visible from the header. 10200 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10201 continue; 10202 10203 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10204 if (FD->getNumParams() == 0) 10205 PossibleZeroParamPrototype = Prev; 10206 break; 10207 } 10208 10209 return MissingPrototype; 10210 } 10211 10212 void 10213 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10214 const FunctionDecl *EffectiveDefinition) { 10215 // Don't complain if we're in GNU89 mode and the previous definition 10216 // was an extern inline function. 10217 const FunctionDecl *Definition = EffectiveDefinition; 10218 if (!Definition) 10219 if (!FD->isDefined(Definition)) 10220 return; 10221 10222 if (canRedefineFunction(Definition, getLangOpts())) 10223 return; 10224 10225 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10226 Definition->getStorageClass() == SC_Extern) 10227 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10228 << FD->getDeclName() << getLangOpts().CPlusPlus; 10229 else 10230 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10231 10232 Diag(Definition->getLocation(), diag::note_previous_definition); 10233 FD->setInvalidDecl(); 10234 } 10235 10236 10237 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10238 Sema &S) { 10239 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10240 10241 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10242 LSI->CallOperator = CallOperator; 10243 LSI->Lambda = LambdaClass; 10244 LSI->ReturnType = CallOperator->getReturnType(); 10245 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10246 10247 if (LCD == LCD_None) 10248 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10249 else if (LCD == LCD_ByCopy) 10250 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10251 else if (LCD == LCD_ByRef) 10252 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10253 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10254 10255 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10256 LSI->Mutable = !CallOperator->isConst(); 10257 10258 // Add the captures to the LSI so they can be noted as already 10259 // captured within tryCaptureVar. 10260 auto I = LambdaClass->field_begin(); 10261 for (const auto &C : LambdaClass->captures()) { 10262 if (C.capturesVariable()) { 10263 VarDecl *VD = C.getCapturedVar(); 10264 if (VD->isInitCapture()) 10265 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10266 QualType CaptureType = VD->getType(); 10267 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10268 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10269 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 10270 /*EllipsisLoc*/C.isPackExpansion() 10271 ? C.getEllipsisLoc() : SourceLocation(), 10272 CaptureType, /*Expr*/ nullptr); 10273 10274 } else if (C.capturesThis()) { 10275 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10276 S.getCurrentThisType(), /*Expr*/ nullptr); 10277 } else { 10278 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10279 } 10280 ++I; 10281 } 10282 } 10283 10284 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 10285 // Clear the last template instantiation error context. 10286 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10287 10288 if (!D) 10289 return D; 10290 FunctionDecl *FD = nullptr; 10291 10292 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10293 FD = FunTmpl->getTemplatedDecl(); 10294 else 10295 FD = cast<FunctionDecl>(D); 10296 // If we are instantiating a generic lambda call operator, push 10297 // a LambdaScopeInfo onto the function stack. But use the information 10298 // that's already been calculated (ActOnLambdaExpr) to prime the current 10299 // LambdaScopeInfo. 10300 // When the template operator is being specialized, the LambdaScopeInfo, 10301 // has to be properly restored so that tryCaptureVariable doesn't try 10302 // and capture any new variables. In addition when calculating potential 10303 // captures during transformation of nested lambdas, it is necessary to 10304 // have the LSI properly restored. 10305 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10306 assert(ActiveTemplateInstantiations.size() && 10307 "There should be an active template instantiation on the stack " 10308 "when instantiating a generic lambda!"); 10309 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10310 } 10311 else 10312 // Enter a new function scope 10313 PushFunctionScope(); 10314 10315 // See if this is a redefinition. 10316 if (!FD->isLateTemplateParsed()) 10317 CheckForFunctionRedefinition(FD); 10318 10319 // Builtin functions cannot be defined. 10320 if (unsigned BuiltinID = FD->getBuiltinID()) { 10321 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10322 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10323 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10324 FD->setInvalidDecl(); 10325 } 10326 } 10327 10328 // The return type of a function definition must be complete 10329 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10330 QualType ResultType = FD->getReturnType(); 10331 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10332 !FD->isInvalidDecl() && 10333 RequireCompleteType(FD->getLocation(), ResultType, 10334 diag::err_func_def_incomplete_result)) 10335 FD->setInvalidDecl(); 10336 10337 if (FnBodyScope) 10338 PushDeclContext(FnBodyScope, FD); 10339 10340 // Check the validity of our function parameters 10341 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10342 /*CheckParameterNames=*/true); 10343 10344 // Introduce our parameters into the function scope 10345 for (auto Param : FD->params()) { 10346 Param->setOwningFunction(FD); 10347 10348 // If this has an identifier, add it to the scope stack. 10349 if (Param->getIdentifier() && FnBodyScope) { 10350 CheckShadow(FnBodyScope, Param); 10351 10352 PushOnScopeChains(Param, FnBodyScope); 10353 } 10354 } 10355 10356 // If we had any tags defined in the function prototype, 10357 // introduce them into the function scope. 10358 if (FnBodyScope) { 10359 for (ArrayRef<NamedDecl *>::iterator 10360 I = FD->getDeclsInPrototypeScope().begin(), 10361 E = FD->getDeclsInPrototypeScope().end(); 10362 I != E; ++I) { 10363 NamedDecl *D = *I; 10364 10365 // Some of these decls (like enums) may have been pinned to the 10366 // translation unit for lack of a real context earlier. If so, remove 10367 // from the translation unit and reattach to the current context. 10368 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 10369 // Is the decl actually in the context? 10370 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 10371 if (DI == D) { 10372 Context.getTranslationUnitDecl()->removeDecl(D); 10373 break; 10374 } 10375 } 10376 // Either way, reassign the lexical decl context to our FunctionDecl. 10377 D->setLexicalDeclContext(CurContext); 10378 } 10379 10380 // If the decl has a non-null name, make accessible in the current scope. 10381 if (!D->getName().empty()) 10382 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 10383 10384 // Similarly, dive into enums and fish their constants out, making them 10385 // accessible in this scope. 10386 if (auto *ED = dyn_cast<EnumDecl>(D)) { 10387 for (auto *EI : ED->enumerators()) 10388 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 10389 } 10390 } 10391 } 10392 10393 // Ensure that the function's exception specification is instantiated. 10394 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 10395 ResolveExceptionSpec(D->getLocation(), FPT); 10396 10397 // dllimport cannot be applied to non-inline function definitions. 10398 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 10399 !FD->isTemplateInstantiation()) { 10400 assert(!FD->hasAttr<DLLExportAttr>()); 10401 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 10402 FD->setInvalidDecl(); 10403 return D; 10404 } 10405 // We want to attach documentation to original Decl (which might be 10406 // a function template). 10407 ActOnDocumentableDecl(D); 10408 if (getCurLexicalContext()->isObjCContainer() && 10409 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 10410 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 10411 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 10412 10413 return D; 10414 } 10415 10416 /// \brief Given the set of return statements within a function body, 10417 /// compute the variables that are subject to the named return value 10418 /// optimization. 10419 /// 10420 /// Each of the variables that is subject to the named return value 10421 /// optimization will be marked as NRVO variables in the AST, and any 10422 /// return statement that has a marked NRVO variable as its NRVO candidate can 10423 /// use the named return value optimization. 10424 /// 10425 /// This function applies a very simplistic algorithm for NRVO: if every return 10426 /// statement in the scope of a variable has the same NRVO candidate, that 10427 /// candidate is an NRVO variable. 10428 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 10429 ReturnStmt **Returns = Scope->Returns.data(); 10430 10431 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 10432 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 10433 if (!NRVOCandidate->isNRVOVariable()) 10434 Returns[I]->setNRVOCandidate(nullptr); 10435 } 10436 } 10437 } 10438 10439 bool Sema::canDelayFunctionBody(const Declarator &D) { 10440 // We can't delay parsing the body of a constexpr function template (yet). 10441 if (D.getDeclSpec().isConstexprSpecified()) 10442 return false; 10443 10444 // We can't delay parsing the body of a function template with a deduced 10445 // return type (yet). 10446 if (D.getDeclSpec().containsPlaceholderType()) { 10447 // If the placeholder introduces a non-deduced trailing return type, 10448 // we can still delay parsing it. 10449 if (D.getNumTypeObjects()) { 10450 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 10451 if (Outer.Kind == DeclaratorChunk::Function && 10452 Outer.Fun.hasTrailingReturnType()) { 10453 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 10454 return Ty.isNull() || !Ty->isUndeducedType(); 10455 } 10456 } 10457 return false; 10458 } 10459 10460 return true; 10461 } 10462 10463 bool Sema::canSkipFunctionBody(Decl *D) { 10464 // We cannot skip the body of a function (or function template) which is 10465 // constexpr, since we may need to evaluate its body in order to parse the 10466 // rest of the file. 10467 // We cannot skip the body of a function with an undeduced return type, 10468 // because any callers of that function need to know the type. 10469 if (const FunctionDecl *FD = D->getAsFunction()) 10470 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 10471 return false; 10472 return Consumer.shouldSkipFunctionBody(D); 10473 } 10474 10475 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 10476 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 10477 FD->setHasSkippedBody(); 10478 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10479 MD->setHasSkippedBody(); 10480 return ActOnFinishFunctionBody(Decl, nullptr); 10481 } 10482 10483 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10484 return ActOnFinishFunctionBody(D, BodyArg, false); 10485 } 10486 10487 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10488 bool IsInstantiation) { 10489 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10490 10491 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10492 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10493 10494 if (FD) { 10495 FD->setBody(Body); 10496 10497 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body && 10498 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10499 // If the function has a deduced result type but contains no 'return' 10500 // statements, the result type as written must be exactly 'auto', and 10501 // the deduced result type is 'void'. 10502 if (!FD->getReturnType()->getAs<AutoType>()) { 10503 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10504 << FD->getReturnType(); 10505 FD->setInvalidDecl(); 10506 } else { 10507 // Substitute 'void' for the 'auto' in the type. 10508 TypeLoc ResultType = getReturnTypeLoc(FD); 10509 Context.adjustDeducedFunctionResultType( 10510 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10511 } 10512 } 10513 10514 // The only way to be included in UndefinedButUsed is if there is an 10515 // ODR use before the definition. Avoid the expensive map lookup if this 10516 // is the first declaration. 10517 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 10518 if (!FD->isExternallyVisible()) 10519 UndefinedButUsed.erase(FD); 10520 else if (FD->isInlined() && 10521 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10522 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 10523 UndefinedButUsed.erase(FD); 10524 } 10525 10526 // If the function implicitly returns zero (like 'main') or is naked, 10527 // don't complain about missing return statements. 10528 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 10529 WP.disableCheckFallThrough(); 10530 10531 // MSVC permits the use of pure specifier (=0) on function definition, 10532 // defined at class scope, warn about this non-standard construct. 10533 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10534 Diag(FD->getLocation(), diag::ext_pure_function_definition); 10535 10536 if (!FD->isInvalidDecl()) { 10537 // Don't diagnose unused parameters of defaulted or deleted functions. 10538 if (!FD->isDeleted() && !FD->isDefaulted()) 10539 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10540 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10541 FD->getReturnType(), FD); 10542 10543 // If this is a structor, we need a vtable. 10544 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10545 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10546 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 10547 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 10548 10549 // Try to apply the named return value optimization. We have to check 10550 // if we can do this here because lambdas keep return statements around 10551 // to deduce an implicit return type. 10552 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10553 !FD->isDependentContext()) 10554 computeNRVO(Body, getCurFunction()); 10555 } 10556 10557 // GNU warning -Wmissing-prototypes: 10558 // Warn if a global function is defined without a previous 10559 // prototype declaration. This warning is issued even if the 10560 // definition itself provides a prototype. The aim is to detect 10561 // global functions that fail to be declared in header files. 10562 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 10563 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 10564 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 10565 10566 if (PossibleZeroParamPrototype) { 10567 // We found a declaration that is not a prototype, 10568 // but that could be a zero-parameter prototype 10569 if (TypeSourceInfo *TI = 10570 PossibleZeroParamPrototype->getTypeSourceInfo()) { 10571 TypeLoc TL = TI->getTypeLoc(); 10572 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 10573 Diag(PossibleZeroParamPrototype->getLocation(), 10574 diag::note_declaration_not_a_prototype) 10575 << PossibleZeroParamPrototype 10576 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 10577 } 10578 } 10579 } 10580 10581 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 10582 const CXXMethodDecl *KeyFunction; 10583 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 10584 MD->isVirtual() && 10585 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 10586 MD == KeyFunction->getCanonicalDecl()) { 10587 // Update the key-function state if necessary for this ABI. 10588 if (FD->isInlined() && 10589 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 10590 Context.setNonKeyFunction(MD); 10591 10592 // If the newly-chosen key function is already defined, then we 10593 // need to mark the vtable as used retroactively. 10594 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 10595 const FunctionDecl *Definition; 10596 if (KeyFunction && KeyFunction->isDefined(Definition)) 10597 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 10598 } else { 10599 // We just defined they key function; mark the vtable as used. 10600 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 10601 } 10602 } 10603 } 10604 10605 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10606 "Function parsing confused"); 10607 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10608 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10609 MD->setBody(Body); 10610 if (!MD->isInvalidDecl()) { 10611 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10612 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10613 MD->getReturnType(), MD); 10614 10615 if (Body) 10616 computeNRVO(Body, getCurFunction()); 10617 } 10618 if (getCurFunction()->ObjCShouldCallSuper) { 10619 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10620 << MD->getSelector().getAsString(); 10621 getCurFunction()->ObjCShouldCallSuper = false; 10622 } 10623 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10624 const ObjCMethodDecl *InitMethod = nullptr; 10625 bool isDesignated = 10626 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10627 assert(isDesignated && InitMethod); 10628 (void)isDesignated; 10629 10630 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10631 auto IFace = MD->getClassInterface(); 10632 if (!IFace) 10633 return false; 10634 auto SuperD = IFace->getSuperClass(); 10635 if (!SuperD) 10636 return false; 10637 return SuperD->getIdentifier() == 10638 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10639 }; 10640 // Don't issue this warning for unavailable inits or direct subclasses 10641 // of NSObject. 10642 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10643 Diag(MD->getLocation(), 10644 diag::warn_objc_designated_init_missing_super_call); 10645 Diag(InitMethod->getLocation(), 10646 diag::note_objc_designated_init_marked_here); 10647 } 10648 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10649 } 10650 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10651 // Don't issue this warning for unavaialable inits. 10652 if (!MD->isUnavailable()) 10653 Diag(MD->getLocation(), 10654 diag::warn_objc_secondary_init_missing_init_call); 10655 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10656 } 10657 } else { 10658 return nullptr; 10659 } 10660 10661 assert(!getCurFunction()->ObjCShouldCallSuper && 10662 "This should only be set for ObjC methods, which should have been " 10663 "handled in the block above."); 10664 10665 // Verify and clean out per-function state. 10666 if (Body && (!FD || !FD->isDefaulted())) { 10667 // C++ constructors that have function-try-blocks can't have return 10668 // statements in the handlers of that block. (C++ [except.handle]p14) 10669 // Verify this. 10670 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10671 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10672 10673 // Verify that gotos and switch cases don't jump into scopes illegally. 10674 if (getCurFunction()->NeedsScopeChecking() && 10675 !PP.isCodeCompletionEnabled()) 10676 DiagnoseInvalidJumps(Body); 10677 10678 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10679 if (!Destructor->getParent()->isDependentType()) 10680 CheckDestructor(Destructor); 10681 10682 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10683 Destructor->getParent()); 10684 } 10685 10686 // If any errors have occurred, clear out any temporaries that may have 10687 // been leftover. This ensures that these temporaries won't be picked up for 10688 // deletion in some later function. 10689 if (getDiagnostics().hasErrorOccurred() || 10690 getDiagnostics().getSuppressAllDiagnostics()) { 10691 DiscardCleanupsInEvaluationContext(); 10692 } 10693 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10694 !isa<FunctionTemplateDecl>(dcl)) { 10695 // Since the body is valid, issue any analysis-based warnings that are 10696 // enabled. 10697 ActivePolicy = &WP; 10698 } 10699 10700 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10701 (!CheckConstexprFunctionDecl(FD) || 10702 !CheckConstexprFunctionBody(FD, Body))) 10703 FD->setInvalidDecl(); 10704 10705 if (FD && FD->hasAttr<NakedAttr>()) { 10706 for (const Stmt *S : Body->children()) { 10707 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 10708 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 10709 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 10710 FD->setInvalidDecl(); 10711 break; 10712 } 10713 } 10714 } 10715 10716 assert(ExprCleanupObjects.size() == 10717 ExprEvalContexts.back().NumCleanupObjects && 10718 "Leftover temporaries in function"); 10719 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10720 assert(MaybeODRUseExprs.empty() && 10721 "Leftover expressions for odr-use checking"); 10722 } 10723 10724 if (!IsInstantiation) 10725 PopDeclContext(); 10726 10727 PopFunctionScopeInfo(ActivePolicy, dcl); 10728 // If any errors have occurred, clear out any temporaries that may have 10729 // been leftover. This ensures that these temporaries won't be picked up for 10730 // deletion in some later function. 10731 if (getDiagnostics().hasErrorOccurred()) { 10732 DiscardCleanupsInEvaluationContext(); 10733 } 10734 10735 return dcl; 10736 } 10737 10738 10739 /// When we finish delayed parsing of an attribute, we must attach it to the 10740 /// relevant Decl. 10741 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10742 ParsedAttributes &Attrs) { 10743 // Always attach attributes to the underlying decl. 10744 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10745 D = TD->getTemplatedDecl(); 10746 ProcessDeclAttributeList(S, D, Attrs.getList()); 10747 10748 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10749 if (Method->isStatic()) 10750 checkThisInStaticMemberFunctionAttributes(Method); 10751 } 10752 10753 10754 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10755 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10756 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10757 IdentifierInfo &II, Scope *S) { 10758 // Before we produce a declaration for an implicitly defined 10759 // function, see whether there was a locally-scoped declaration of 10760 // this name as a function or variable. If so, use that 10761 // (non-visible) declaration, and complain about it. 10762 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10763 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10764 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10765 return ExternCPrev; 10766 } 10767 10768 // Extension in C99. Legal in C90, but warn about it. 10769 unsigned diag_id; 10770 if (II.getName().startswith("__builtin_")) 10771 diag_id = diag::warn_builtin_unknown; 10772 else if (getLangOpts().C99) 10773 diag_id = diag::ext_implicit_function_decl; 10774 else 10775 diag_id = diag::warn_implicit_function_decl; 10776 Diag(Loc, diag_id) << &II; 10777 10778 // Because typo correction is expensive, only do it if the implicit 10779 // function declaration is going to be treated as an error. 10780 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10781 TypoCorrection Corrected; 10782 if (S && 10783 (Corrected = CorrectTypo( 10784 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 10785 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 10786 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10787 /*ErrorRecovery*/false); 10788 } 10789 10790 // Set a Declarator for the implicit definition: int foo(); 10791 const char *Dummy; 10792 AttributeFactory attrFactory; 10793 DeclSpec DS(attrFactory); 10794 unsigned DiagID; 10795 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10796 Context.getPrintingPolicy()); 10797 (void)Error; // Silence warning. 10798 assert(!Error && "Error setting up implicit decl!"); 10799 SourceLocation NoLoc; 10800 Declarator D(DS, Declarator::BlockContext); 10801 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10802 /*IsAmbiguous=*/false, 10803 /*LParenLoc=*/NoLoc, 10804 /*Params=*/nullptr, 10805 /*NumParams=*/0, 10806 /*EllipsisLoc=*/NoLoc, 10807 /*RParenLoc=*/NoLoc, 10808 /*TypeQuals=*/0, 10809 /*RefQualifierIsLvalueRef=*/true, 10810 /*RefQualifierLoc=*/NoLoc, 10811 /*ConstQualifierLoc=*/NoLoc, 10812 /*VolatileQualifierLoc=*/NoLoc, 10813 /*RestrictQualifierLoc=*/NoLoc, 10814 /*MutableLoc=*/NoLoc, 10815 EST_None, 10816 /*ESpecLoc=*/NoLoc, 10817 /*Exceptions=*/nullptr, 10818 /*ExceptionRanges=*/nullptr, 10819 /*NumExceptions=*/0, 10820 /*NoexceptExpr=*/nullptr, 10821 /*ExceptionSpecTokens=*/nullptr, 10822 Loc, Loc, D), 10823 DS.getAttributes(), 10824 SourceLocation()); 10825 D.SetIdentifier(&II, Loc); 10826 10827 // Insert this function into translation-unit scope. 10828 10829 DeclContext *PrevDC = CurContext; 10830 CurContext = Context.getTranslationUnitDecl(); 10831 10832 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10833 FD->setImplicit(); 10834 10835 CurContext = PrevDC; 10836 10837 AddKnownFunctionAttributes(FD); 10838 10839 return FD; 10840 } 10841 10842 /// \brief Adds any function attributes that we know a priori based on 10843 /// the declaration of this function. 10844 /// 10845 /// These attributes can apply both to implicitly-declared builtins 10846 /// (like __builtin___printf_chk) or to library-declared functions 10847 /// like NSLog or printf. 10848 /// 10849 /// We need to check for duplicate attributes both here and where user-written 10850 /// attributes are applied to declarations. 10851 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10852 if (FD->isInvalidDecl()) 10853 return; 10854 10855 // If this is a built-in function, map its builtin attributes to 10856 // actual attributes. 10857 if (unsigned BuiltinID = FD->getBuiltinID()) { 10858 // Handle printf-formatting attributes. 10859 unsigned FormatIdx; 10860 bool HasVAListArg; 10861 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10862 if (!FD->hasAttr<FormatAttr>()) { 10863 const char *fmt = "printf"; 10864 unsigned int NumParams = FD->getNumParams(); 10865 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10866 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10867 fmt = "NSString"; 10868 FD->addAttr(FormatAttr::CreateImplicit(Context, 10869 &Context.Idents.get(fmt), 10870 FormatIdx+1, 10871 HasVAListArg ? 0 : FormatIdx+2, 10872 FD->getLocation())); 10873 } 10874 } 10875 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10876 HasVAListArg)) { 10877 if (!FD->hasAttr<FormatAttr>()) 10878 FD->addAttr(FormatAttr::CreateImplicit(Context, 10879 &Context.Idents.get("scanf"), 10880 FormatIdx+1, 10881 HasVAListArg ? 0 : FormatIdx+2, 10882 FD->getLocation())); 10883 } 10884 10885 // Mark const if we don't care about errno and that is the only 10886 // thing preventing the function from being const. This allows 10887 // IRgen to use LLVM intrinsics for such functions. 10888 if (!getLangOpts().MathErrno && 10889 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10890 if (!FD->hasAttr<ConstAttr>()) 10891 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10892 } 10893 10894 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10895 !FD->hasAttr<ReturnsTwiceAttr>()) 10896 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10897 FD->getLocation())); 10898 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10899 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10900 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10901 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10902 } 10903 10904 IdentifierInfo *Name = FD->getIdentifier(); 10905 if (!Name) 10906 return; 10907 if ((!getLangOpts().CPlusPlus && 10908 FD->getDeclContext()->isTranslationUnit()) || 10909 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10910 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10911 LinkageSpecDecl::lang_c)) { 10912 // Okay: this could be a libc/libm/Objective-C function we know 10913 // about. 10914 } else 10915 return; 10916 10917 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10918 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10919 // target-specific builtins, perhaps? 10920 if (!FD->hasAttr<FormatAttr>()) 10921 FD->addAttr(FormatAttr::CreateImplicit(Context, 10922 &Context.Idents.get("printf"), 2, 10923 Name->isStr("vasprintf") ? 0 : 3, 10924 FD->getLocation())); 10925 } 10926 10927 if (Name->isStr("__CFStringMakeConstantString")) { 10928 // We already have a __builtin___CFStringMakeConstantString, 10929 // but builds that use -fno-constant-cfstrings don't go through that. 10930 if (!FD->hasAttr<FormatArgAttr>()) 10931 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10932 FD->getLocation())); 10933 } 10934 } 10935 10936 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10937 TypeSourceInfo *TInfo) { 10938 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10939 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10940 10941 if (!TInfo) { 10942 assert(D.isInvalidType() && "no declarator info for valid type"); 10943 TInfo = Context.getTrivialTypeSourceInfo(T); 10944 } 10945 10946 // Scope manipulation handled by caller. 10947 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10948 D.getLocStart(), 10949 D.getIdentifierLoc(), 10950 D.getIdentifier(), 10951 TInfo); 10952 10953 // Bail out immediately if we have an invalid declaration. 10954 if (D.isInvalidType()) { 10955 NewTD->setInvalidDecl(); 10956 return NewTD; 10957 } 10958 10959 if (D.getDeclSpec().isModulePrivateSpecified()) { 10960 if (CurContext->isFunctionOrMethod()) 10961 Diag(NewTD->getLocation(), diag::err_module_private_local) 10962 << 2 << NewTD->getDeclName() 10963 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10964 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10965 else 10966 NewTD->setModulePrivate(); 10967 } 10968 10969 // C++ [dcl.typedef]p8: 10970 // If the typedef declaration defines an unnamed class (or 10971 // enum), the first typedef-name declared by the declaration 10972 // to be that class type (or enum type) is used to denote the 10973 // class type (or enum type) for linkage purposes only. 10974 // We need to check whether the type was declared in the declaration. 10975 switch (D.getDeclSpec().getTypeSpecType()) { 10976 case TST_enum: 10977 case TST_struct: 10978 case TST_interface: 10979 case TST_union: 10980 case TST_class: { 10981 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10982 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 10983 break; 10984 } 10985 10986 default: 10987 break; 10988 } 10989 10990 return NewTD; 10991 } 10992 10993 10994 /// \brief Check that this is a valid underlying type for an enum declaration. 10995 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10996 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10997 QualType T = TI->getType(); 10998 10999 if (T->isDependentType()) 11000 return false; 11001 11002 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 11003 if (BT->isInteger()) 11004 return false; 11005 11006 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 11007 return true; 11008 } 11009 11010 /// Check whether this is a valid redeclaration of a previous enumeration. 11011 /// \return true if the redeclaration was invalid. 11012 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 11013 QualType EnumUnderlyingTy, 11014 const EnumDecl *Prev) { 11015 bool IsFixed = !EnumUnderlyingTy.isNull(); 11016 11017 if (IsScoped != Prev->isScoped()) { 11018 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 11019 << Prev->isScoped(); 11020 Diag(Prev->getLocation(), diag::note_previous_declaration); 11021 return true; 11022 } 11023 11024 if (IsFixed && Prev->isFixed()) { 11025 if (!EnumUnderlyingTy->isDependentType() && 11026 !Prev->getIntegerType()->isDependentType() && 11027 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 11028 Prev->getIntegerType())) { 11029 // TODO: Highlight the underlying type of the redeclaration. 11030 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 11031 << EnumUnderlyingTy << Prev->getIntegerType(); 11032 Diag(Prev->getLocation(), diag::note_previous_declaration) 11033 << Prev->getIntegerTypeRange(); 11034 return true; 11035 } 11036 } else if (IsFixed != Prev->isFixed()) { 11037 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 11038 << Prev->isFixed(); 11039 Diag(Prev->getLocation(), diag::note_previous_declaration); 11040 return true; 11041 } 11042 11043 return false; 11044 } 11045 11046 /// \brief Get diagnostic %select index for tag kind for 11047 /// redeclaration diagnostic message. 11048 /// WARNING: Indexes apply to particular diagnostics only! 11049 /// 11050 /// \returns diagnostic %select index. 11051 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 11052 switch (Tag) { 11053 case TTK_Struct: return 0; 11054 case TTK_Interface: return 1; 11055 case TTK_Class: return 2; 11056 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 11057 } 11058 } 11059 11060 /// \brief Determine if tag kind is a class-key compatible with 11061 /// class for redeclaration (class, struct, or __interface). 11062 /// 11063 /// \returns true iff the tag kind is compatible. 11064 static bool isClassCompatTagKind(TagTypeKind Tag) 11065 { 11066 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 11067 } 11068 11069 /// \brief Determine whether a tag with a given kind is acceptable 11070 /// as a redeclaration of the given tag declaration. 11071 /// 11072 /// \returns true if the new tag kind is acceptable, false otherwise. 11073 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 11074 TagTypeKind NewTag, bool isDefinition, 11075 SourceLocation NewTagLoc, 11076 const IdentifierInfo &Name) { 11077 // C++ [dcl.type.elab]p3: 11078 // The class-key or enum keyword present in the 11079 // elaborated-type-specifier shall agree in kind with the 11080 // declaration to which the name in the elaborated-type-specifier 11081 // refers. This rule also applies to the form of 11082 // elaborated-type-specifier that declares a class-name or 11083 // friend class since it can be construed as referring to the 11084 // definition of the class. Thus, in any 11085 // elaborated-type-specifier, the enum keyword shall be used to 11086 // refer to an enumeration (7.2), the union class-key shall be 11087 // used to refer to a union (clause 9), and either the class or 11088 // struct class-key shall be used to refer to a class (clause 9) 11089 // declared using the class or struct class-key. 11090 TagTypeKind OldTag = Previous->getTagKind(); 11091 if (!isDefinition || !isClassCompatTagKind(NewTag)) 11092 if (OldTag == NewTag) 11093 return true; 11094 11095 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 11096 // Warn about the struct/class tag mismatch. 11097 bool isTemplate = false; 11098 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 11099 isTemplate = Record->getDescribedClassTemplate(); 11100 11101 if (!ActiveTemplateInstantiations.empty()) { 11102 // In a template instantiation, do not offer fix-its for tag mismatches 11103 // since they usually mess up the template instead of fixing the problem. 11104 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11105 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11106 << getRedeclDiagFromTagKind(OldTag); 11107 return true; 11108 } 11109 11110 if (isDefinition) { 11111 // On definitions, check previous tags and issue a fix-it for each 11112 // one that doesn't match the current tag. 11113 if (Previous->getDefinition()) { 11114 // Don't suggest fix-its for redefinitions. 11115 return true; 11116 } 11117 11118 bool previousMismatch = false; 11119 for (auto I : Previous->redecls()) { 11120 if (I->getTagKind() != NewTag) { 11121 if (!previousMismatch) { 11122 previousMismatch = true; 11123 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11124 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11125 << getRedeclDiagFromTagKind(I->getTagKind()); 11126 } 11127 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11128 << getRedeclDiagFromTagKind(NewTag) 11129 << FixItHint::CreateReplacement(I->getInnerLocStart(), 11130 TypeWithKeyword::getTagTypeKindName(NewTag)); 11131 } 11132 } 11133 return true; 11134 } 11135 11136 // Check for a previous definition. If current tag and definition 11137 // are same type, do nothing. If no definition, but disagree with 11138 // with previous tag type, give a warning, but no fix-it. 11139 const TagDecl *Redecl = Previous->getDefinition() ? 11140 Previous->getDefinition() : Previous; 11141 if (Redecl->getTagKind() == NewTag) { 11142 return true; 11143 } 11144 11145 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11146 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11147 << getRedeclDiagFromTagKind(OldTag); 11148 Diag(Redecl->getLocation(), diag::note_previous_use); 11149 11150 // If there is a previous definition, suggest a fix-it. 11151 if (Previous->getDefinition()) { 11152 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11153 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11154 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11155 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11156 } 11157 11158 return true; 11159 } 11160 return false; 11161 } 11162 11163 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11164 /// from an outer enclosing namespace or file scope inside a friend declaration. 11165 /// This should provide the commented out code in the following snippet: 11166 /// namespace N { 11167 /// struct X; 11168 /// namespace M { 11169 /// struct Y { friend struct /*N::*/ X; }; 11170 /// } 11171 /// } 11172 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11173 SourceLocation NameLoc) { 11174 // While the decl is in a namespace, do repeated lookup of that name and see 11175 // if we get the same namespace back. If we do not, continue until 11176 // translation unit scope, at which point we have a fully qualified NNS. 11177 SmallVector<IdentifierInfo *, 4> Namespaces; 11178 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11179 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11180 // This tag should be declared in a namespace, which can only be enclosed by 11181 // other namespaces. Bail if there's an anonymous namespace in the chain. 11182 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11183 if (!Namespace || Namespace->isAnonymousNamespace()) 11184 return FixItHint(); 11185 IdentifierInfo *II = Namespace->getIdentifier(); 11186 Namespaces.push_back(II); 11187 NamedDecl *Lookup = SemaRef.LookupSingleName( 11188 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11189 if (Lookup == Namespace) 11190 break; 11191 } 11192 11193 // Once we have all the namespaces, reverse them to go outermost first, and 11194 // build an NNS. 11195 SmallString<64> Insertion; 11196 llvm::raw_svector_ostream OS(Insertion); 11197 if (DC->isTranslationUnit()) 11198 OS << "::"; 11199 std::reverse(Namespaces.begin(), Namespaces.end()); 11200 for (auto *II : Namespaces) 11201 OS << II->getName() << "::"; 11202 OS.flush(); 11203 return FixItHint::CreateInsertion(NameLoc, Insertion); 11204 } 11205 11206 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 11207 /// former case, Name will be non-null. In the later case, Name will be null. 11208 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11209 /// reference/declaration/definition of a tag. 11210 /// 11211 /// IsTypeSpecifier is true if this is a type-specifier (or 11212 /// trailing-type-specifier) other than one in an alias-declaration. 11213 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11214 SourceLocation KWLoc, CXXScopeSpec &SS, 11215 IdentifierInfo *Name, SourceLocation NameLoc, 11216 AttributeList *Attr, AccessSpecifier AS, 11217 SourceLocation ModulePrivateLoc, 11218 MultiTemplateParamsArg TemplateParameterLists, 11219 bool &OwnedDecl, bool &IsDependent, 11220 SourceLocation ScopedEnumKWLoc, 11221 bool ScopedEnumUsesClassTag, 11222 TypeResult UnderlyingType, 11223 bool IsTypeSpecifier) { 11224 // If this is not a definition, it must have a name. 11225 IdentifierInfo *OrigName = Name; 11226 assert((Name != nullptr || TUK == TUK_Definition) && 11227 "Nameless record must be a definition!"); 11228 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11229 11230 OwnedDecl = false; 11231 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11232 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11233 11234 // FIXME: Check explicit specializations more carefully. 11235 bool isExplicitSpecialization = false; 11236 bool Invalid = false; 11237 11238 // We only need to do this matching if we have template parameters 11239 // or a scope specifier, which also conveniently avoids this work 11240 // for non-C++ cases. 11241 if (TemplateParameterLists.size() > 0 || 11242 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11243 if (TemplateParameterList *TemplateParams = 11244 MatchTemplateParametersToScopeSpecifier( 11245 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11246 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11247 if (Kind == TTK_Enum) { 11248 Diag(KWLoc, diag::err_enum_template); 11249 return nullptr; 11250 } 11251 11252 if (TemplateParams->size() > 0) { 11253 // This is a declaration or definition of a class template (which may 11254 // be a member of another template). 11255 11256 if (Invalid) 11257 return nullptr; 11258 11259 OwnedDecl = false; 11260 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11261 SS, Name, NameLoc, Attr, 11262 TemplateParams, AS, 11263 ModulePrivateLoc, 11264 /*FriendLoc*/SourceLocation(), 11265 TemplateParameterLists.size()-1, 11266 TemplateParameterLists.data()); 11267 return Result.get(); 11268 } else { 11269 // The "template<>" header is extraneous. 11270 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11271 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11272 isExplicitSpecialization = true; 11273 } 11274 } 11275 } 11276 11277 // Figure out the underlying type if this a enum declaration. We need to do 11278 // this early, because it's needed to detect if this is an incompatible 11279 // redeclaration. 11280 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 11281 11282 if (Kind == TTK_Enum) { 11283 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 11284 // No underlying type explicitly specified, or we failed to parse the 11285 // type, default to int. 11286 EnumUnderlying = Context.IntTy.getTypePtr(); 11287 else if (UnderlyingType.get()) { 11288 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 11289 // integral type; any cv-qualification is ignored. 11290 TypeSourceInfo *TI = nullptr; 11291 GetTypeFromParser(UnderlyingType.get(), &TI); 11292 EnumUnderlying = TI; 11293 11294 if (CheckEnumUnderlyingType(TI)) 11295 // Recover by falling back to int. 11296 EnumUnderlying = Context.IntTy.getTypePtr(); 11297 11298 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 11299 UPPC_FixedUnderlyingType)) 11300 EnumUnderlying = Context.IntTy.getTypePtr(); 11301 11302 } else if (getLangOpts().MSVCCompat) 11303 // Microsoft enums are always of int type. 11304 EnumUnderlying = Context.IntTy.getTypePtr(); 11305 } 11306 11307 DeclContext *SearchDC = CurContext; 11308 DeclContext *DC = CurContext; 11309 bool isStdBadAlloc = false; 11310 11311 RedeclarationKind Redecl = ForRedeclaration; 11312 if (TUK == TUK_Friend || TUK == TUK_Reference) 11313 Redecl = NotForRedeclaration; 11314 11315 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 11316 if (Name && SS.isNotEmpty()) { 11317 // We have a nested-name tag ('struct foo::bar'). 11318 11319 // Check for invalid 'foo::'. 11320 if (SS.isInvalid()) { 11321 Name = nullptr; 11322 goto CreateNewDecl; 11323 } 11324 11325 // If this is a friend or a reference to a class in a dependent 11326 // context, don't try to make a decl for it. 11327 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11328 DC = computeDeclContext(SS, false); 11329 if (!DC) { 11330 IsDependent = true; 11331 return nullptr; 11332 } 11333 } else { 11334 DC = computeDeclContext(SS, true); 11335 if (!DC) { 11336 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 11337 << SS.getRange(); 11338 return nullptr; 11339 } 11340 } 11341 11342 if (RequireCompleteDeclContext(SS, DC)) 11343 return nullptr; 11344 11345 SearchDC = DC; 11346 // Look-up name inside 'foo::'. 11347 LookupQualifiedName(Previous, DC); 11348 11349 if (Previous.isAmbiguous()) 11350 return nullptr; 11351 11352 if (Previous.empty()) { 11353 // Name lookup did not find anything. However, if the 11354 // nested-name-specifier refers to the current instantiation, 11355 // and that current instantiation has any dependent base 11356 // classes, we might find something at instantiation time: treat 11357 // this as a dependent elaborated-type-specifier. 11358 // But this only makes any sense for reference-like lookups. 11359 if (Previous.wasNotFoundInCurrentInstantiation() && 11360 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11361 IsDependent = true; 11362 return nullptr; 11363 } 11364 11365 // A tag 'foo::bar' must already exist. 11366 Diag(NameLoc, diag::err_not_tag_in_scope) 11367 << Kind << Name << DC << SS.getRange(); 11368 Name = nullptr; 11369 Invalid = true; 11370 goto CreateNewDecl; 11371 } 11372 } else if (Name) { 11373 // If this is a named struct, check to see if there was a previous forward 11374 // declaration or definition. 11375 // FIXME: We're looking into outer scopes here, even when we 11376 // shouldn't be. Doing so can result in ambiguities that we 11377 // shouldn't be diagnosing. 11378 LookupName(Previous, S); 11379 11380 // When declaring or defining a tag, ignore ambiguities introduced 11381 // by types using'ed into this scope. 11382 if (Previous.isAmbiguous() && 11383 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 11384 LookupResult::Filter F = Previous.makeFilter(); 11385 while (F.hasNext()) { 11386 NamedDecl *ND = F.next(); 11387 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 11388 F.erase(); 11389 } 11390 F.done(); 11391 } 11392 11393 // C++11 [namespace.memdef]p3: 11394 // If the name in a friend declaration is neither qualified nor 11395 // a template-id and the declaration is a function or an 11396 // elaborated-type-specifier, the lookup to determine whether 11397 // the entity has been previously declared shall not consider 11398 // any scopes outside the innermost enclosing namespace. 11399 // 11400 // MSVC doesn't implement the above rule for types, so a friend tag 11401 // declaration may be a redeclaration of a type declared in an enclosing 11402 // scope. They do implement this rule for friend functions. 11403 // 11404 // Does it matter that this should be by scope instead of by 11405 // semantic context? 11406 if (!Previous.empty() && TUK == TUK_Friend) { 11407 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 11408 LookupResult::Filter F = Previous.makeFilter(); 11409 bool FriendSawTagOutsideEnclosingNamespace = false; 11410 while (F.hasNext()) { 11411 NamedDecl *ND = F.next(); 11412 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11413 if (DC->isFileContext() && 11414 !EnclosingNS->Encloses(ND->getDeclContext())) { 11415 if (getLangOpts().MSVCCompat) 11416 FriendSawTagOutsideEnclosingNamespace = true; 11417 else 11418 F.erase(); 11419 } 11420 } 11421 F.done(); 11422 11423 // Diagnose this MSVC extension in the easy case where lookup would have 11424 // unambiguously found something outside the enclosing namespace. 11425 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 11426 NamedDecl *ND = Previous.getFoundDecl(); 11427 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 11428 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 11429 } 11430 } 11431 11432 // Note: there used to be some attempt at recovery here. 11433 if (Previous.isAmbiguous()) 11434 return nullptr; 11435 11436 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 11437 // FIXME: This makes sure that we ignore the contexts associated 11438 // with C structs, unions, and enums when looking for a matching 11439 // tag declaration or definition. See the similar lookup tweak 11440 // in Sema::LookupName; is there a better way to deal with this? 11441 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 11442 SearchDC = SearchDC->getParent(); 11443 } 11444 } 11445 11446 if (Previous.isSingleResult() && 11447 Previous.getFoundDecl()->isTemplateParameter()) { 11448 // Maybe we will complain about the shadowed template parameter. 11449 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 11450 // Just pretend that we didn't see the previous declaration. 11451 Previous.clear(); 11452 } 11453 11454 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 11455 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 11456 // This is a declaration of or a reference to "std::bad_alloc". 11457 isStdBadAlloc = true; 11458 11459 if (Previous.empty() && StdBadAlloc) { 11460 // std::bad_alloc has been implicitly declared (but made invisible to 11461 // name lookup). Fill in this implicit declaration as the previous 11462 // declaration, so that the declarations get chained appropriately. 11463 Previous.addDecl(getStdBadAlloc()); 11464 } 11465 } 11466 11467 // If we didn't find a previous declaration, and this is a reference 11468 // (or friend reference), move to the correct scope. In C++, we 11469 // also need to do a redeclaration lookup there, just in case 11470 // there's a shadow friend decl. 11471 if (Name && Previous.empty() && 11472 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11473 if (Invalid) goto CreateNewDecl; 11474 assert(SS.isEmpty()); 11475 11476 if (TUK == TUK_Reference) { 11477 // C++ [basic.scope.pdecl]p5: 11478 // -- for an elaborated-type-specifier of the form 11479 // 11480 // class-key identifier 11481 // 11482 // if the elaborated-type-specifier is used in the 11483 // decl-specifier-seq or parameter-declaration-clause of a 11484 // function defined in namespace scope, the identifier is 11485 // declared as a class-name in the namespace that contains 11486 // the declaration; otherwise, except as a friend 11487 // declaration, the identifier is declared in the smallest 11488 // non-class, non-function-prototype scope that contains the 11489 // declaration. 11490 // 11491 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 11492 // C structs and unions. 11493 // 11494 // It is an error in C++ to declare (rather than define) an enum 11495 // type, including via an elaborated type specifier. We'll 11496 // diagnose that later; for now, declare the enum in the same 11497 // scope as we would have picked for any other tag type. 11498 // 11499 // GNU C also supports this behavior as part of its incomplete 11500 // enum types extension, while GNU C++ does not. 11501 // 11502 // Find the context where we'll be declaring the tag. 11503 // FIXME: We would like to maintain the current DeclContext as the 11504 // lexical context, 11505 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 11506 SearchDC = SearchDC->getParent(); 11507 11508 // Find the scope where we'll be declaring the tag. 11509 while (S->isClassScope() || 11510 (getLangOpts().CPlusPlus && 11511 S->isFunctionPrototypeScope()) || 11512 ((S->getFlags() & Scope::DeclScope) == 0) || 11513 (S->getEntity() && S->getEntity()->isTransparentContext())) 11514 S = S->getParent(); 11515 } else { 11516 assert(TUK == TUK_Friend); 11517 // C++ [namespace.memdef]p3: 11518 // If a friend declaration in a non-local class first declares a 11519 // class or function, the friend class or function is a member of 11520 // the innermost enclosing namespace. 11521 SearchDC = SearchDC->getEnclosingNamespaceContext(); 11522 } 11523 11524 // In C++, we need to do a redeclaration lookup to properly 11525 // diagnose some problems. 11526 if (getLangOpts().CPlusPlus) { 11527 Previous.setRedeclarationKind(ForRedeclaration); 11528 LookupQualifiedName(Previous, SearchDC); 11529 } 11530 } 11531 11532 if (!Previous.empty()) { 11533 NamedDecl *PrevDecl = Previous.getFoundDecl(); 11534 NamedDecl *DirectPrevDecl = 11535 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 11536 11537 // It's okay to have a tag decl in the same scope as a typedef 11538 // which hides a tag decl in the same scope. Finding this 11539 // insanity with a redeclaration lookup can only actually happen 11540 // in C++. 11541 // 11542 // This is also okay for elaborated-type-specifiers, which is 11543 // technically forbidden by the current standard but which is 11544 // okay according to the likely resolution of an open issue; 11545 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 11546 if (getLangOpts().CPlusPlus) { 11547 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11548 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 11549 TagDecl *Tag = TT->getDecl(); 11550 if (Tag->getDeclName() == Name && 11551 Tag->getDeclContext()->getRedeclContext() 11552 ->Equals(TD->getDeclContext()->getRedeclContext())) { 11553 PrevDecl = Tag; 11554 Previous.clear(); 11555 Previous.addDecl(Tag); 11556 Previous.resolveKind(); 11557 } 11558 } 11559 } 11560 } 11561 11562 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 11563 // If this is a use of a previous tag, or if the tag is already declared 11564 // in the same scope (so that the definition/declaration completes or 11565 // rementions the tag), reuse the decl. 11566 if (TUK == TUK_Reference || TUK == TUK_Friend || 11567 isDeclInScope(DirectPrevDecl, SearchDC, S, 11568 SS.isNotEmpty() || isExplicitSpecialization)) { 11569 // Make sure that this wasn't declared as an enum and now used as a 11570 // struct or something similar. 11571 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 11572 TUK == TUK_Definition, KWLoc, 11573 *Name)) { 11574 bool SafeToContinue 11575 = (PrevTagDecl->getTagKind() != TTK_Enum && 11576 Kind != TTK_Enum); 11577 if (SafeToContinue) 11578 Diag(KWLoc, diag::err_use_with_wrong_tag) 11579 << Name 11580 << FixItHint::CreateReplacement(SourceRange(KWLoc), 11581 PrevTagDecl->getKindName()); 11582 else 11583 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 11584 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 11585 11586 if (SafeToContinue) 11587 Kind = PrevTagDecl->getTagKind(); 11588 else { 11589 // Recover by making this an anonymous redefinition. 11590 Name = nullptr; 11591 Previous.clear(); 11592 Invalid = true; 11593 } 11594 } 11595 11596 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 11597 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 11598 11599 // If this is an elaborated-type-specifier for a scoped enumeration, 11600 // the 'class' keyword is not necessary and not permitted. 11601 if (TUK == TUK_Reference || TUK == TUK_Friend) { 11602 if (ScopedEnum) 11603 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 11604 << PrevEnum->isScoped() 11605 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 11606 return PrevTagDecl; 11607 } 11608 11609 QualType EnumUnderlyingTy; 11610 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11611 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 11612 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 11613 EnumUnderlyingTy = QualType(T, 0); 11614 11615 // All conflicts with previous declarations are recovered by 11616 // returning the previous declaration, unless this is a definition, 11617 // in which case we want the caller to bail out. 11618 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11619 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11620 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11621 } 11622 11623 // C++11 [class.mem]p1: 11624 // A member shall not be declared twice in the member-specification, 11625 // except that a nested class or member class template can be declared 11626 // and then later defined. 11627 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11628 S->isDeclScope(PrevDecl)) { 11629 Diag(NameLoc, diag::ext_member_redeclared); 11630 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11631 } 11632 11633 if (!Invalid) { 11634 // If this is a use, just return the declaration we found, unless 11635 // we have attributes. 11636 11637 // FIXME: In the future, return a variant or some other clue 11638 // for the consumer of this Decl to know it doesn't own it. 11639 // For our current ASTs this shouldn't be a problem, but will 11640 // need to be changed with DeclGroups. 11641 if (!Attr && 11642 ((TUK == TUK_Reference && 11643 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11644 || TUK == TUK_Friend)) 11645 return PrevTagDecl; 11646 11647 // Diagnose attempts to redefine a tag. 11648 if (TUK == TUK_Definition) { 11649 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 11650 // If we're defining a specialization and the previous definition 11651 // is from an implicit instantiation, don't emit an error 11652 // here; we'll catch this in the general case below. 11653 bool IsExplicitSpecializationAfterInstantiation = false; 11654 if (isExplicitSpecialization) { 11655 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11656 IsExplicitSpecializationAfterInstantiation = 11657 RD->getTemplateSpecializationKind() != 11658 TSK_ExplicitSpecialization; 11659 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11660 IsExplicitSpecializationAfterInstantiation = 11661 ED->getTemplateSpecializationKind() != 11662 TSK_ExplicitSpecialization; 11663 } 11664 11665 if (!IsExplicitSpecializationAfterInstantiation) { 11666 // A redeclaration in function prototype scope in C isn't 11667 // visible elsewhere, so merely issue a warning. 11668 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11669 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11670 else 11671 Diag(NameLoc, diag::err_redefinition) << Name; 11672 Diag(Def->getLocation(), diag::note_previous_definition); 11673 // If this is a redefinition, recover by making this 11674 // struct be anonymous, which will make any later 11675 // references get the previous definition. 11676 Name = nullptr; 11677 Previous.clear(); 11678 Invalid = true; 11679 } 11680 } else { 11681 // If the type is currently being defined, complain 11682 // about a nested redefinition. 11683 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 11684 if (TD->isBeingDefined()) { 11685 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11686 Diag(PrevTagDecl->getLocation(), 11687 diag::note_previous_definition); 11688 Name = nullptr; 11689 Previous.clear(); 11690 Invalid = true; 11691 } 11692 } 11693 11694 // Okay, this is definition of a previously declared or referenced 11695 // tag. We're going to create a new Decl for it. 11696 } 11697 11698 // Okay, we're going to make a redeclaration. If this is some kind 11699 // of reference, make sure we build the redeclaration in the same DC 11700 // as the original, and ignore the current access specifier. 11701 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11702 SearchDC = PrevTagDecl->getDeclContext(); 11703 AS = AS_none; 11704 } 11705 } 11706 // If we get here we have (another) forward declaration or we 11707 // have a definition. Just create a new decl. 11708 11709 } else { 11710 // If we get here, this is a definition of a new tag type in a nested 11711 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11712 // new decl/type. We set PrevDecl to NULL so that the entities 11713 // have distinct types. 11714 Previous.clear(); 11715 } 11716 // If we get here, we're going to create a new Decl. If PrevDecl 11717 // is non-NULL, it's a definition of the tag declared by 11718 // PrevDecl. If it's NULL, we have a new definition. 11719 11720 11721 // Otherwise, PrevDecl is not a tag, but was found with tag 11722 // lookup. This is only actually possible in C++, where a few 11723 // things like templates still live in the tag namespace. 11724 } else { 11725 // Use a better diagnostic if an elaborated-type-specifier 11726 // found the wrong kind of type on the first 11727 // (non-redeclaration) lookup. 11728 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11729 !Previous.isForRedeclaration()) { 11730 unsigned Kind = 0; 11731 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11732 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11733 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11734 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11735 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11736 Invalid = true; 11737 11738 // Otherwise, only diagnose if the declaration is in scope. 11739 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11740 SS.isNotEmpty() || isExplicitSpecialization)) { 11741 // do nothing 11742 11743 // Diagnose implicit declarations introduced by elaborated types. 11744 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11745 unsigned Kind = 0; 11746 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11747 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11748 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11749 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11750 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11751 Invalid = true; 11752 11753 // Otherwise it's a declaration. Call out a particularly common 11754 // case here. 11755 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11756 unsigned Kind = 0; 11757 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11758 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11759 << Name << Kind << TND->getUnderlyingType(); 11760 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11761 Invalid = true; 11762 11763 // Otherwise, diagnose. 11764 } else { 11765 // The tag name clashes with something else in the target scope, 11766 // issue an error and recover by making this tag be anonymous. 11767 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11768 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11769 Name = nullptr; 11770 Invalid = true; 11771 } 11772 11773 // The existing declaration isn't relevant to us; we're in a 11774 // new scope, so clear out the previous declaration. 11775 Previous.clear(); 11776 } 11777 } 11778 11779 CreateNewDecl: 11780 11781 TagDecl *PrevDecl = nullptr; 11782 if (Previous.isSingleResult()) 11783 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11784 11785 // If there is an identifier, use the location of the identifier as the 11786 // location of the decl, otherwise use the location of the struct/union 11787 // keyword. 11788 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11789 11790 // Otherwise, create a new declaration. If there is a previous 11791 // declaration of the same entity, the two will be linked via 11792 // PrevDecl. 11793 TagDecl *New; 11794 11795 bool IsForwardReference = false; 11796 if (Kind == TTK_Enum) { 11797 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11798 // enum X { A, B, C } D; D should chain to X. 11799 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11800 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11801 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11802 // If this is an undefined enum, warn. 11803 if (TUK != TUK_Definition && !Invalid) { 11804 TagDecl *Def; 11805 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11806 cast<EnumDecl>(New)->isFixed()) { 11807 // C++0x: 7.2p2: opaque-enum-declaration. 11808 // Conflicts are diagnosed above. Do nothing. 11809 } 11810 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11811 Diag(Loc, diag::ext_forward_ref_enum_def) 11812 << New; 11813 Diag(Def->getLocation(), diag::note_previous_definition); 11814 } else { 11815 unsigned DiagID = diag::ext_forward_ref_enum; 11816 if (getLangOpts().MSVCCompat) 11817 DiagID = diag::ext_ms_forward_ref_enum; 11818 else if (getLangOpts().CPlusPlus) 11819 DiagID = diag::err_forward_ref_enum; 11820 Diag(Loc, DiagID); 11821 11822 // If this is a forward-declared reference to an enumeration, make a 11823 // note of it; we won't actually be introducing the declaration into 11824 // the declaration context. 11825 if (TUK == TUK_Reference) 11826 IsForwardReference = true; 11827 } 11828 } 11829 11830 if (EnumUnderlying) { 11831 EnumDecl *ED = cast<EnumDecl>(New); 11832 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11833 ED->setIntegerTypeSourceInfo(TI); 11834 else 11835 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11836 ED->setPromotionType(ED->getIntegerType()); 11837 } 11838 11839 } else { 11840 // struct/union/class 11841 11842 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11843 // struct X { int A; } D; D should chain to X. 11844 if (getLangOpts().CPlusPlus) { 11845 // FIXME: Look for a way to use RecordDecl for simple structs. 11846 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11847 cast_or_null<CXXRecordDecl>(PrevDecl)); 11848 11849 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11850 StdBadAlloc = cast<CXXRecordDecl>(New); 11851 } else 11852 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11853 cast_or_null<RecordDecl>(PrevDecl)); 11854 } 11855 11856 // C++11 [dcl.type]p3: 11857 // A type-specifier-seq shall not define a class or enumeration [...]. 11858 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11859 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11860 << Context.getTagDeclType(New); 11861 Invalid = true; 11862 } 11863 11864 // Maybe add qualifier info. 11865 if (SS.isNotEmpty()) { 11866 if (SS.isSet()) { 11867 // If this is either a declaration or a definition, check the 11868 // nested-name-specifier against the current context. We don't do this 11869 // for explicit specializations, because they have similar checking 11870 // (with more specific diagnostics) in the call to 11871 // CheckMemberSpecialization, below. 11872 if (!isExplicitSpecialization && 11873 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11874 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 11875 Invalid = true; 11876 11877 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11878 if (TemplateParameterLists.size() > 0) { 11879 New->setTemplateParameterListsInfo(Context, 11880 TemplateParameterLists.size(), 11881 TemplateParameterLists.data()); 11882 } 11883 } 11884 else 11885 Invalid = true; 11886 } 11887 11888 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11889 // Add alignment attributes if necessary; these attributes are checked when 11890 // the ASTContext lays out the structure. 11891 // 11892 // It is important for implementing the correct semantics that this 11893 // happen here (in act on tag decl). The #pragma pack stack is 11894 // maintained as a result of parser callbacks which can occur at 11895 // many points during the parsing of a struct declaration (because 11896 // the #pragma tokens are effectively skipped over during the 11897 // parsing of the struct). 11898 if (TUK == TUK_Definition) { 11899 AddAlignmentAttributesForRecord(RD); 11900 AddMsStructLayoutForRecord(RD); 11901 } 11902 } 11903 11904 if (ModulePrivateLoc.isValid()) { 11905 if (isExplicitSpecialization) 11906 Diag(New->getLocation(), diag::err_module_private_specialization) 11907 << 2 11908 << FixItHint::CreateRemoval(ModulePrivateLoc); 11909 // __module_private__ does not apply to local classes. However, we only 11910 // diagnose this as an error when the declaration specifiers are 11911 // freestanding. Here, we just ignore the __module_private__. 11912 else if (!SearchDC->isFunctionOrMethod()) 11913 New->setModulePrivate(); 11914 } 11915 11916 // If this is a specialization of a member class (of a class template), 11917 // check the specialization. 11918 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11919 Invalid = true; 11920 11921 // If we're declaring or defining a tag in function prototype scope in C, 11922 // note that this type can only be used within the function and add it to 11923 // the list of decls to inject into the function definition scope. 11924 if ((Name || Kind == TTK_Enum) && 11925 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11926 if (getLangOpts().CPlusPlus) { 11927 // C++ [dcl.fct]p6: 11928 // Types shall not be defined in return or parameter types. 11929 if (TUK == TUK_Definition && !IsTypeSpecifier) { 11930 Diag(Loc, diag::err_type_defined_in_param_type) 11931 << Name; 11932 Invalid = true; 11933 } 11934 } else { 11935 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11936 } 11937 DeclsInPrototypeScope.push_back(New); 11938 } 11939 11940 if (Invalid) 11941 New->setInvalidDecl(); 11942 11943 if (Attr) 11944 ProcessDeclAttributeList(S, New, Attr); 11945 11946 // Set the lexical context. If the tag has a C++ scope specifier, the 11947 // lexical context will be different from the semantic context. 11948 New->setLexicalDeclContext(CurContext); 11949 11950 // Mark this as a friend decl if applicable. 11951 // In Microsoft mode, a friend declaration also acts as a forward 11952 // declaration so we always pass true to setObjectOfFriendDecl to make 11953 // the tag name visible. 11954 if (TUK == TUK_Friend) 11955 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 11956 11957 // Set the access specifier. 11958 if (!Invalid && SearchDC->isRecord()) 11959 SetMemberAccessSpecifier(New, PrevDecl, AS); 11960 11961 if (TUK == TUK_Definition) 11962 New->startDefinition(); 11963 11964 // If this has an identifier, add it to the scope stack. 11965 if (TUK == TUK_Friend) { 11966 // We might be replacing an existing declaration in the lookup tables; 11967 // if so, borrow its access specifier. 11968 if (PrevDecl) 11969 New->setAccess(PrevDecl->getAccess()); 11970 11971 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11972 DC->makeDeclVisibleInContext(New); 11973 if (Name) // can be null along some error paths 11974 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11975 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11976 } else if (Name) { 11977 S = getNonFieldDeclScope(S); 11978 PushOnScopeChains(New, S, !IsForwardReference); 11979 if (IsForwardReference) 11980 SearchDC->makeDeclVisibleInContext(New); 11981 11982 } else { 11983 CurContext->addDecl(New); 11984 } 11985 11986 // If this is the C FILE type, notify the AST context. 11987 if (IdentifierInfo *II = New->getIdentifier()) 11988 if (!New->isInvalidDecl() && 11989 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11990 II->isStr("FILE")) 11991 Context.setFILEDecl(New); 11992 11993 if (PrevDecl) 11994 mergeDeclAttributes(New, PrevDecl); 11995 11996 // If there's a #pragma GCC visibility in scope, set the visibility of this 11997 // record. 11998 AddPushedVisibilityAttribute(New); 11999 12000 OwnedDecl = true; 12001 // In C++, don't return an invalid declaration. We can't recover well from 12002 // the cases where we make the type anonymous. 12003 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 12004 } 12005 12006 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 12007 AdjustDeclIfTemplate(TagD); 12008 TagDecl *Tag = cast<TagDecl>(TagD); 12009 12010 // Enter the tag context. 12011 PushDeclContext(S, Tag); 12012 12013 ActOnDocumentableDecl(TagD); 12014 12015 // If there's a #pragma GCC visibility in scope, set the visibility of this 12016 // record. 12017 AddPushedVisibilityAttribute(Tag); 12018 } 12019 12020 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 12021 assert(isa<ObjCContainerDecl>(IDecl) && 12022 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 12023 DeclContext *OCD = cast<DeclContext>(IDecl); 12024 assert(getContainingDC(OCD) == CurContext && 12025 "The next DeclContext should be lexically contained in the current one."); 12026 CurContext = OCD; 12027 return IDecl; 12028 } 12029 12030 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 12031 SourceLocation FinalLoc, 12032 bool IsFinalSpelledSealed, 12033 SourceLocation LBraceLoc) { 12034 AdjustDeclIfTemplate(TagD); 12035 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 12036 12037 FieldCollector->StartClass(); 12038 12039 if (!Record->getIdentifier()) 12040 return; 12041 12042 if (FinalLoc.isValid()) 12043 Record->addAttr(new (Context) 12044 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 12045 12046 // C++ [class]p2: 12047 // [...] The class-name is also inserted into the scope of the 12048 // class itself; this is known as the injected-class-name. For 12049 // purposes of access checking, the injected-class-name is treated 12050 // as if it were a public member name. 12051 CXXRecordDecl *InjectedClassName 12052 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 12053 Record->getLocStart(), Record->getLocation(), 12054 Record->getIdentifier(), 12055 /*PrevDecl=*/nullptr, 12056 /*DelayTypeCreation=*/true); 12057 Context.getTypeDeclType(InjectedClassName, Record); 12058 InjectedClassName->setImplicit(); 12059 InjectedClassName->setAccess(AS_public); 12060 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 12061 InjectedClassName->setDescribedClassTemplate(Template); 12062 PushOnScopeChains(InjectedClassName, S); 12063 assert(InjectedClassName->isInjectedClassName() && 12064 "Broken injected-class-name"); 12065 } 12066 12067 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 12068 SourceLocation RBraceLoc) { 12069 AdjustDeclIfTemplate(TagD); 12070 TagDecl *Tag = cast<TagDecl>(TagD); 12071 Tag->setRBraceLoc(RBraceLoc); 12072 12073 // Make sure we "complete" the definition even it is invalid. 12074 if (Tag->isBeingDefined()) { 12075 assert(Tag->isInvalidDecl() && "We should already have completed it"); 12076 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12077 RD->completeDefinition(); 12078 } 12079 12080 if (isa<CXXRecordDecl>(Tag)) 12081 FieldCollector->FinishClass(); 12082 12083 // Exit this scope of this tag's definition. 12084 PopDeclContext(); 12085 12086 if (getCurLexicalContext()->isObjCContainer() && 12087 Tag->getDeclContext()->isFileContext()) 12088 Tag->setTopLevelDeclInObjCContainer(); 12089 12090 // Notify the consumer that we've defined a tag. 12091 if (!Tag->isInvalidDecl()) 12092 Consumer.HandleTagDeclDefinition(Tag); 12093 } 12094 12095 void Sema::ActOnObjCContainerFinishDefinition() { 12096 // Exit this scope of this interface definition. 12097 PopDeclContext(); 12098 } 12099 12100 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 12101 assert(DC == CurContext && "Mismatch of container contexts"); 12102 OriginalLexicalContext = DC; 12103 ActOnObjCContainerFinishDefinition(); 12104 } 12105 12106 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 12107 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 12108 OriginalLexicalContext = nullptr; 12109 } 12110 12111 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 12112 AdjustDeclIfTemplate(TagD); 12113 TagDecl *Tag = cast<TagDecl>(TagD); 12114 Tag->setInvalidDecl(); 12115 12116 // Make sure we "complete" the definition even it is invalid. 12117 if (Tag->isBeingDefined()) { 12118 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12119 RD->completeDefinition(); 12120 } 12121 12122 // We're undoing ActOnTagStartDefinition here, not 12123 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 12124 // the FieldCollector. 12125 12126 PopDeclContext(); 12127 } 12128 12129 // Note that FieldName may be null for anonymous bitfields. 12130 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 12131 IdentifierInfo *FieldName, 12132 QualType FieldTy, bool IsMsStruct, 12133 Expr *BitWidth, bool *ZeroWidth) { 12134 // Default to true; that shouldn't confuse checks for emptiness 12135 if (ZeroWidth) 12136 *ZeroWidth = true; 12137 12138 // C99 6.7.2.1p4 - verify the field type. 12139 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 12140 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 12141 // Handle incomplete types with specific error. 12142 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12143 return ExprError(); 12144 if (FieldName) 12145 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12146 << FieldName << FieldTy << BitWidth->getSourceRange(); 12147 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12148 << FieldTy << BitWidth->getSourceRange(); 12149 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12150 UPPC_BitFieldWidth)) 12151 return ExprError(); 12152 12153 // If the bit-width is type- or value-dependent, don't try to check 12154 // it now. 12155 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12156 return BitWidth; 12157 12158 llvm::APSInt Value; 12159 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12160 if (ICE.isInvalid()) 12161 return ICE; 12162 BitWidth = ICE.get(); 12163 12164 if (Value != 0 && ZeroWidth) 12165 *ZeroWidth = false; 12166 12167 // Zero-width bitfield is ok for anonymous field. 12168 if (Value == 0 && FieldName) 12169 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12170 12171 if (Value.isSigned() && Value.isNegative()) { 12172 if (FieldName) 12173 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12174 << FieldName << Value.toString(10); 12175 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12176 << Value.toString(10); 12177 } 12178 12179 if (!FieldTy->isDependentType()) { 12180 uint64_t TypeSize = Context.getTypeSize(FieldTy); 12181 if (Value.getZExtValue() > TypeSize) { 12182 if (!getLangOpts().CPlusPlus || IsMsStruct || 12183 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12184 if (FieldName) 12185 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 12186 << FieldName << (unsigned)Value.getZExtValue() 12187 << (unsigned)TypeSize; 12188 12189 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 12190 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12191 } 12192 12193 if (FieldName) 12194 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 12195 << FieldName << (unsigned)Value.getZExtValue() 12196 << (unsigned)TypeSize; 12197 else 12198 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 12199 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12200 } 12201 } 12202 12203 return BitWidth; 12204 } 12205 12206 /// ActOnField - Each field of a C struct/union is passed into this in order 12207 /// to create a FieldDecl object for it. 12208 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 12209 Declarator &D, Expr *BitfieldWidth) { 12210 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 12211 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 12212 /*InitStyle=*/ICIS_NoInit, AS_public); 12213 return Res; 12214 } 12215 12216 /// HandleField - Analyze a field of a C struct or a C++ data member. 12217 /// 12218 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 12219 SourceLocation DeclStart, 12220 Declarator &D, Expr *BitWidth, 12221 InClassInitStyle InitStyle, 12222 AccessSpecifier AS) { 12223 IdentifierInfo *II = D.getIdentifier(); 12224 SourceLocation Loc = DeclStart; 12225 if (II) Loc = D.getIdentifierLoc(); 12226 12227 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12228 QualType T = TInfo->getType(); 12229 if (getLangOpts().CPlusPlus) { 12230 CheckExtraCXXDefaultArguments(D); 12231 12232 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12233 UPPC_DataMemberType)) { 12234 D.setInvalidType(); 12235 T = Context.IntTy; 12236 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12237 } 12238 } 12239 12240 // TR 18037 does not allow fields to be declared with address spaces. 12241 if (T.getQualifiers().hasAddressSpace()) { 12242 Diag(Loc, diag::err_field_with_address_space); 12243 D.setInvalidType(); 12244 } 12245 12246 // OpenCL 1.2 spec, s6.9 r: 12247 // The event type cannot be used to declare a structure or union field. 12248 if (LangOpts.OpenCL && T->isEventT()) { 12249 Diag(Loc, diag::err_event_t_struct_field); 12250 D.setInvalidType(); 12251 } 12252 12253 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12254 12255 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12256 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12257 diag::err_invalid_thread) 12258 << DeclSpec::getSpecifierName(TSCS); 12259 12260 // Check to see if this name was declared as a member previously 12261 NamedDecl *PrevDecl = nullptr; 12262 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12263 LookupName(Previous, S); 12264 switch (Previous.getResultKind()) { 12265 case LookupResult::Found: 12266 case LookupResult::FoundUnresolvedValue: 12267 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12268 break; 12269 12270 case LookupResult::FoundOverloaded: 12271 PrevDecl = Previous.getRepresentativeDecl(); 12272 break; 12273 12274 case LookupResult::NotFound: 12275 case LookupResult::NotFoundInCurrentInstantiation: 12276 case LookupResult::Ambiguous: 12277 break; 12278 } 12279 Previous.suppressDiagnostics(); 12280 12281 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12282 // Maybe we will complain about the shadowed template parameter. 12283 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12284 // Just pretend that we didn't see the previous declaration. 12285 PrevDecl = nullptr; 12286 } 12287 12288 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12289 PrevDecl = nullptr; 12290 12291 bool Mutable 12292 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 12293 SourceLocation TSSL = D.getLocStart(); 12294 FieldDecl *NewFD 12295 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 12296 TSSL, AS, PrevDecl, &D); 12297 12298 if (NewFD->isInvalidDecl()) 12299 Record->setInvalidDecl(); 12300 12301 if (D.getDeclSpec().isModulePrivateSpecified()) 12302 NewFD->setModulePrivate(); 12303 12304 if (NewFD->isInvalidDecl() && PrevDecl) { 12305 // Don't introduce NewFD into scope; there's already something 12306 // with the same name in the same scope. 12307 } else if (II) { 12308 PushOnScopeChains(NewFD, S); 12309 } else 12310 Record->addDecl(NewFD); 12311 12312 return NewFD; 12313 } 12314 12315 /// \brief Build a new FieldDecl and check its well-formedness. 12316 /// 12317 /// This routine builds a new FieldDecl given the fields name, type, 12318 /// record, etc. \p PrevDecl should refer to any previous declaration 12319 /// with the same name and in the same scope as the field to be 12320 /// created. 12321 /// 12322 /// \returns a new FieldDecl. 12323 /// 12324 /// \todo The Declarator argument is a hack. It will be removed once 12325 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 12326 TypeSourceInfo *TInfo, 12327 RecordDecl *Record, SourceLocation Loc, 12328 bool Mutable, Expr *BitWidth, 12329 InClassInitStyle InitStyle, 12330 SourceLocation TSSL, 12331 AccessSpecifier AS, NamedDecl *PrevDecl, 12332 Declarator *D) { 12333 IdentifierInfo *II = Name.getAsIdentifierInfo(); 12334 bool InvalidDecl = false; 12335 if (D) InvalidDecl = D->isInvalidType(); 12336 12337 // If we receive a broken type, recover by assuming 'int' and 12338 // marking this declaration as invalid. 12339 if (T.isNull()) { 12340 InvalidDecl = true; 12341 T = Context.IntTy; 12342 } 12343 12344 QualType EltTy = Context.getBaseElementType(T); 12345 if (!EltTy->isDependentType()) { 12346 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 12347 // Fields of incomplete type force their record to be invalid. 12348 Record->setInvalidDecl(); 12349 InvalidDecl = true; 12350 } else { 12351 NamedDecl *Def; 12352 EltTy->isIncompleteType(&Def); 12353 if (Def && Def->isInvalidDecl()) { 12354 Record->setInvalidDecl(); 12355 InvalidDecl = true; 12356 } 12357 } 12358 } 12359 12360 // OpenCL v1.2 s6.9.c: bitfields are not supported. 12361 if (BitWidth && getLangOpts().OpenCL) { 12362 Diag(Loc, diag::err_opencl_bitfields); 12363 InvalidDecl = true; 12364 } 12365 12366 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12367 // than a variably modified type. 12368 if (!InvalidDecl && T->isVariablyModifiedType()) { 12369 bool SizeIsNegative; 12370 llvm::APSInt Oversized; 12371 12372 TypeSourceInfo *FixedTInfo = 12373 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 12374 SizeIsNegative, 12375 Oversized); 12376 if (FixedTInfo) { 12377 Diag(Loc, diag::warn_illegal_constant_array_size); 12378 TInfo = FixedTInfo; 12379 T = FixedTInfo->getType(); 12380 } else { 12381 if (SizeIsNegative) 12382 Diag(Loc, diag::err_typecheck_negative_array_size); 12383 else if (Oversized.getBoolValue()) 12384 Diag(Loc, diag::err_array_too_large) 12385 << Oversized.toString(10); 12386 else 12387 Diag(Loc, diag::err_typecheck_field_variable_size); 12388 InvalidDecl = true; 12389 } 12390 } 12391 12392 // Fields can not have abstract class types 12393 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 12394 diag::err_abstract_type_in_decl, 12395 AbstractFieldType)) 12396 InvalidDecl = true; 12397 12398 bool ZeroWidth = false; 12399 // If this is declared as a bit-field, check the bit-field. 12400 if (!InvalidDecl && BitWidth) { 12401 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 12402 &ZeroWidth).get(); 12403 if (!BitWidth) { 12404 InvalidDecl = true; 12405 BitWidth = nullptr; 12406 ZeroWidth = false; 12407 } 12408 } 12409 12410 // Check that 'mutable' is consistent with the type of the declaration. 12411 if (!InvalidDecl && Mutable) { 12412 unsigned DiagID = 0; 12413 if (T->isReferenceType()) 12414 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 12415 : diag::err_mutable_reference; 12416 else if (T.isConstQualified()) 12417 DiagID = diag::err_mutable_const; 12418 12419 if (DiagID) { 12420 SourceLocation ErrLoc = Loc; 12421 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 12422 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 12423 Diag(ErrLoc, DiagID); 12424 if (DiagID != diag::ext_mutable_reference) { 12425 Mutable = false; 12426 InvalidDecl = true; 12427 } 12428 } 12429 } 12430 12431 // C++11 [class.union]p8 (DR1460): 12432 // At most one variant member of a union may have a 12433 // brace-or-equal-initializer. 12434 if (InitStyle != ICIS_NoInit) 12435 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 12436 12437 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 12438 BitWidth, Mutable, InitStyle); 12439 if (InvalidDecl) 12440 NewFD->setInvalidDecl(); 12441 12442 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 12443 Diag(Loc, diag::err_duplicate_member) << II; 12444 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12445 NewFD->setInvalidDecl(); 12446 } 12447 12448 if (!InvalidDecl && getLangOpts().CPlusPlus) { 12449 if (Record->isUnion()) { 12450 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12451 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12452 if (RDecl->getDefinition()) { 12453 // C++ [class.union]p1: An object of a class with a non-trivial 12454 // constructor, a non-trivial copy constructor, a non-trivial 12455 // destructor, or a non-trivial copy assignment operator 12456 // cannot be a member of a union, nor can an array of such 12457 // objects. 12458 if (CheckNontrivialField(NewFD)) 12459 NewFD->setInvalidDecl(); 12460 } 12461 } 12462 12463 // C++ [class.union]p1: If a union contains a member of reference type, 12464 // the program is ill-formed, except when compiling with MSVC extensions 12465 // enabled. 12466 if (EltTy->isReferenceType()) { 12467 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 12468 diag::ext_union_member_of_reference_type : 12469 diag::err_union_member_of_reference_type) 12470 << NewFD->getDeclName() << EltTy; 12471 if (!getLangOpts().MicrosoftExt) 12472 NewFD->setInvalidDecl(); 12473 } 12474 } 12475 } 12476 12477 // FIXME: We need to pass in the attributes given an AST 12478 // representation, not a parser representation. 12479 if (D) { 12480 // FIXME: The current scope is almost... but not entirely... correct here. 12481 ProcessDeclAttributes(getCurScope(), NewFD, *D); 12482 12483 if (NewFD->hasAttrs()) 12484 CheckAlignasUnderalignment(NewFD); 12485 } 12486 12487 // In auto-retain/release, infer strong retension for fields of 12488 // retainable type. 12489 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 12490 NewFD->setInvalidDecl(); 12491 12492 if (T.isObjCGCWeak()) 12493 Diag(Loc, diag::warn_attribute_weak_on_field); 12494 12495 NewFD->setAccess(AS); 12496 return NewFD; 12497 } 12498 12499 bool Sema::CheckNontrivialField(FieldDecl *FD) { 12500 assert(FD); 12501 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 12502 12503 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 12504 return false; 12505 12506 QualType EltTy = Context.getBaseElementType(FD->getType()); 12507 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12508 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12509 if (RDecl->getDefinition()) { 12510 // We check for copy constructors before constructors 12511 // because otherwise we'll never get complaints about 12512 // copy constructors. 12513 12514 CXXSpecialMember member = CXXInvalid; 12515 // We're required to check for any non-trivial constructors. Since the 12516 // implicit default constructor is suppressed if there are any 12517 // user-declared constructors, we just need to check that there is a 12518 // trivial default constructor and a trivial copy constructor. (We don't 12519 // worry about move constructors here, since this is a C++98 check.) 12520 if (RDecl->hasNonTrivialCopyConstructor()) 12521 member = CXXCopyConstructor; 12522 else if (!RDecl->hasTrivialDefaultConstructor()) 12523 member = CXXDefaultConstructor; 12524 else if (RDecl->hasNonTrivialCopyAssignment()) 12525 member = CXXCopyAssignment; 12526 else if (RDecl->hasNonTrivialDestructor()) 12527 member = CXXDestructor; 12528 12529 if (member != CXXInvalid) { 12530 if (!getLangOpts().CPlusPlus11 && 12531 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 12532 // Objective-C++ ARC: it is an error to have a non-trivial field of 12533 // a union. However, system headers in Objective-C programs 12534 // occasionally have Objective-C lifetime objects within unions, 12535 // and rather than cause the program to fail, we make those 12536 // members unavailable. 12537 SourceLocation Loc = FD->getLocation(); 12538 if (getSourceManager().isInSystemHeader(Loc)) { 12539 if (!FD->hasAttr<UnavailableAttr>()) 12540 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12541 "this system field has retaining ownership", 12542 Loc)); 12543 return false; 12544 } 12545 } 12546 12547 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 12548 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 12549 diag::err_illegal_union_or_anon_struct_member) 12550 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 12551 DiagnoseNontrivial(RDecl, member); 12552 return !getLangOpts().CPlusPlus11; 12553 } 12554 } 12555 } 12556 12557 return false; 12558 } 12559 12560 /// TranslateIvarVisibility - Translate visibility from a token ID to an 12561 /// AST enum value. 12562 static ObjCIvarDecl::AccessControl 12563 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 12564 switch (ivarVisibility) { 12565 default: llvm_unreachable("Unknown visitibility kind"); 12566 case tok::objc_private: return ObjCIvarDecl::Private; 12567 case tok::objc_public: return ObjCIvarDecl::Public; 12568 case tok::objc_protected: return ObjCIvarDecl::Protected; 12569 case tok::objc_package: return ObjCIvarDecl::Package; 12570 } 12571 } 12572 12573 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 12574 /// in order to create an IvarDecl object for it. 12575 Decl *Sema::ActOnIvar(Scope *S, 12576 SourceLocation DeclStart, 12577 Declarator &D, Expr *BitfieldWidth, 12578 tok::ObjCKeywordKind Visibility) { 12579 12580 IdentifierInfo *II = D.getIdentifier(); 12581 Expr *BitWidth = (Expr*)BitfieldWidth; 12582 SourceLocation Loc = DeclStart; 12583 if (II) Loc = D.getIdentifierLoc(); 12584 12585 // FIXME: Unnamed fields can be handled in various different ways, for 12586 // example, unnamed unions inject all members into the struct namespace! 12587 12588 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12589 QualType T = TInfo->getType(); 12590 12591 if (BitWidth) { 12592 // 6.7.2.1p3, 6.7.2.1p4 12593 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 12594 if (!BitWidth) 12595 D.setInvalidType(); 12596 } else { 12597 // Not a bitfield. 12598 12599 // validate II. 12600 12601 } 12602 if (T->isReferenceType()) { 12603 Diag(Loc, diag::err_ivar_reference_type); 12604 D.setInvalidType(); 12605 } 12606 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12607 // than a variably modified type. 12608 else if (T->isVariablyModifiedType()) { 12609 Diag(Loc, diag::err_typecheck_ivar_variable_size); 12610 D.setInvalidType(); 12611 } 12612 12613 // Get the visibility (access control) for this ivar. 12614 ObjCIvarDecl::AccessControl ac = 12615 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 12616 : ObjCIvarDecl::None; 12617 // Must set ivar's DeclContext to its enclosing interface. 12618 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 12619 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 12620 return nullptr; 12621 ObjCContainerDecl *EnclosingContext; 12622 if (ObjCImplementationDecl *IMPDecl = 12623 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12624 if (LangOpts.ObjCRuntime.isFragile()) { 12625 // Case of ivar declared in an implementation. Context is that of its class. 12626 EnclosingContext = IMPDecl->getClassInterface(); 12627 assert(EnclosingContext && "Implementation has no class interface!"); 12628 } 12629 else 12630 EnclosingContext = EnclosingDecl; 12631 } else { 12632 if (ObjCCategoryDecl *CDecl = 12633 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12634 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12635 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12636 return nullptr; 12637 } 12638 } 12639 EnclosingContext = EnclosingDecl; 12640 } 12641 12642 // Construct the decl. 12643 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12644 DeclStart, Loc, II, T, 12645 TInfo, ac, (Expr *)BitfieldWidth); 12646 12647 if (II) { 12648 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12649 ForRedeclaration); 12650 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12651 && !isa<TagDecl>(PrevDecl)) { 12652 Diag(Loc, diag::err_duplicate_member) << II; 12653 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12654 NewID->setInvalidDecl(); 12655 } 12656 } 12657 12658 // Process attributes attached to the ivar. 12659 ProcessDeclAttributes(S, NewID, D); 12660 12661 if (D.isInvalidType()) 12662 NewID->setInvalidDecl(); 12663 12664 // In ARC, infer 'retaining' for ivars of retainable type. 12665 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12666 NewID->setInvalidDecl(); 12667 12668 if (D.getDeclSpec().isModulePrivateSpecified()) 12669 NewID->setModulePrivate(); 12670 12671 if (II) { 12672 // FIXME: When interfaces are DeclContexts, we'll need to add 12673 // these to the interface. 12674 S->AddDecl(NewID); 12675 IdResolver.AddDecl(NewID); 12676 } 12677 12678 if (LangOpts.ObjCRuntime.isNonFragile() && 12679 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12680 Diag(Loc, diag::warn_ivars_in_interface); 12681 12682 return NewID; 12683 } 12684 12685 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12686 /// class and class extensions. For every class \@interface and class 12687 /// extension \@interface, if the last ivar is a bitfield of any type, 12688 /// then add an implicit `char :0` ivar to the end of that interface. 12689 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12690 SmallVectorImpl<Decl *> &AllIvarDecls) { 12691 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12692 return; 12693 12694 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12695 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12696 12697 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12698 return; 12699 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12700 if (!ID) { 12701 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12702 if (!CD->IsClassExtension()) 12703 return; 12704 } 12705 // No need to add this to end of @implementation. 12706 else 12707 return; 12708 } 12709 // All conditions are met. Add a new bitfield to the tail end of ivars. 12710 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12711 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12712 12713 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12714 DeclLoc, DeclLoc, nullptr, 12715 Context.CharTy, 12716 Context.getTrivialTypeSourceInfo(Context.CharTy, 12717 DeclLoc), 12718 ObjCIvarDecl::Private, BW, 12719 true); 12720 AllIvarDecls.push_back(Ivar); 12721 } 12722 12723 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12724 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12725 SourceLocation RBrac, AttributeList *Attr) { 12726 assert(EnclosingDecl && "missing record or interface decl"); 12727 12728 // If this is an Objective-C @implementation or category and we have 12729 // new fields here we should reset the layout of the interface since 12730 // it will now change. 12731 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12732 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12733 switch (DC->getKind()) { 12734 default: break; 12735 case Decl::ObjCCategory: 12736 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12737 break; 12738 case Decl::ObjCImplementation: 12739 Context. 12740 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12741 break; 12742 } 12743 } 12744 12745 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12746 12747 // Start counting up the number of named members; make sure to include 12748 // members of anonymous structs and unions in the total. 12749 unsigned NumNamedMembers = 0; 12750 if (Record) { 12751 for (const auto *I : Record->decls()) { 12752 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12753 if (IFD->getDeclName()) 12754 ++NumNamedMembers; 12755 } 12756 } 12757 12758 // Verify that all the fields are okay. 12759 SmallVector<FieldDecl*, 32> RecFields; 12760 12761 bool ARCErrReported = false; 12762 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12763 i != end; ++i) { 12764 FieldDecl *FD = cast<FieldDecl>(*i); 12765 12766 // Get the type for the field. 12767 const Type *FDTy = FD->getType().getTypePtr(); 12768 12769 if (!FD->isAnonymousStructOrUnion()) { 12770 // Remember all fields written by the user. 12771 RecFields.push_back(FD); 12772 } 12773 12774 // If the field is already invalid for some reason, don't emit more 12775 // diagnostics about it. 12776 if (FD->isInvalidDecl()) { 12777 EnclosingDecl->setInvalidDecl(); 12778 continue; 12779 } 12780 12781 // C99 6.7.2.1p2: 12782 // A structure or union shall not contain a member with 12783 // incomplete or function type (hence, a structure shall not 12784 // contain an instance of itself, but may contain a pointer to 12785 // an instance of itself), except that the last member of a 12786 // structure with more than one named member may have incomplete 12787 // array type; such a structure (and any union containing, 12788 // possibly recursively, a member that is such a structure) 12789 // shall not be a member of a structure or an element of an 12790 // array. 12791 if (FDTy->isFunctionType()) { 12792 // Field declared as a function. 12793 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12794 << FD->getDeclName(); 12795 FD->setInvalidDecl(); 12796 EnclosingDecl->setInvalidDecl(); 12797 continue; 12798 } else if (FDTy->isIncompleteArrayType() && Record && 12799 ((i + 1 == Fields.end() && !Record->isUnion()) || 12800 ((getLangOpts().MicrosoftExt || 12801 getLangOpts().CPlusPlus) && 12802 (i + 1 == Fields.end() || Record->isUnion())))) { 12803 // Flexible array member. 12804 // Microsoft and g++ is more permissive regarding flexible array. 12805 // It will accept flexible array in union and also 12806 // as the sole element of a struct/class. 12807 unsigned DiagID = 0; 12808 if (Record->isUnion()) 12809 DiagID = getLangOpts().MicrosoftExt 12810 ? diag::ext_flexible_array_union_ms 12811 : getLangOpts().CPlusPlus 12812 ? diag::ext_flexible_array_union_gnu 12813 : diag::err_flexible_array_union; 12814 else if (Fields.size() == 1) 12815 DiagID = getLangOpts().MicrosoftExt 12816 ? diag::ext_flexible_array_empty_aggregate_ms 12817 : getLangOpts().CPlusPlus 12818 ? diag::ext_flexible_array_empty_aggregate_gnu 12819 : NumNamedMembers < 1 12820 ? diag::err_flexible_array_empty_aggregate 12821 : 0; 12822 12823 if (DiagID) 12824 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12825 << Record->getTagKind(); 12826 // While the layout of types that contain virtual bases is not specified 12827 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12828 // virtual bases after the derived members. This would make a flexible 12829 // array member declared at the end of an object not adjacent to the end 12830 // of the type. 12831 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12832 if (RD->getNumVBases() != 0) 12833 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12834 << FD->getDeclName() << Record->getTagKind(); 12835 if (!getLangOpts().C99) 12836 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12837 << FD->getDeclName() << Record->getTagKind(); 12838 12839 // If the element type has a non-trivial destructor, we would not 12840 // implicitly destroy the elements, so disallow it for now. 12841 // 12842 // FIXME: GCC allows this. We should probably either implicitly delete 12843 // the destructor of the containing class, or just allow this. 12844 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12845 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12846 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12847 << FD->getDeclName() << FD->getType(); 12848 FD->setInvalidDecl(); 12849 EnclosingDecl->setInvalidDecl(); 12850 continue; 12851 } 12852 // Okay, we have a legal flexible array member at the end of the struct. 12853 Record->setHasFlexibleArrayMember(true); 12854 } else if (!FDTy->isDependentType() && 12855 RequireCompleteType(FD->getLocation(), FD->getType(), 12856 diag::err_field_incomplete)) { 12857 // Incomplete type 12858 FD->setInvalidDecl(); 12859 EnclosingDecl->setInvalidDecl(); 12860 continue; 12861 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12862 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 12863 // A type which contains a flexible array member is considered to be a 12864 // flexible array member. 12865 Record->setHasFlexibleArrayMember(true); 12866 if (!Record->isUnion()) { 12867 // If this is a struct/class and this is not the last element, reject 12868 // it. Note that GCC supports variable sized arrays in the middle of 12869 // structures. 12870 if (i + 1 != Fields.end()) 12871 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12872 << FD->getDeclName() << FD->getType(); 12873 else { 12874 // We support flexible arrays at the end of structs in 12875 // other structs as an extension. 12876 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12877 << FD->getDeclName(); 12878 } 12879 } 12880 } 12881 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12882 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12883 diag::err_abstract_type_in_decl, 12884 AbstractIvarType)) { 12885 // Ivars can not have abstract class types 12886 FD->setInvalidDecl(); 12887 } 12888 if (Record && FDTTy->getDecl()->hasObjectMember()) 12889 Record->setHasObjectMember(true); 12890 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12891 Record->setHasVolatileMember(true); 12892 } else if (FDTy->isObjCObjectType()) { 12893 /// A field cannot be an Objective-c object 12894 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12895 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12896 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12897 FD->setType(T); 12898 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12899 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12900 // It's an error in ARC if a field has lifetime. 12901 // We don't want to report this in a system header, though, 12902 // so we just make the field unavailable. 12903 // FIXME: that's really not sufficient; we need to make the type 12904 // itself invalid to, say, initialize or copy. 12905 QualType T = FD->getType(); 12906 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12907 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12908 SourceLocation loc = FD->getLocation(); 12909 if (getSourceManager().isInSystemHeader(loc)) { 12910 if (!FD->hasAttr<UnavailableAttr>()) { 12911 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12912 "this system field has retaining ownership", 12913 loc)); 12914 } 12915 } else { 12916 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12917 << T->isBlockPointerType() << Record->getTagKind(); 12918 } 12919 ARCErrReported = true; 12920 } 12921 } else if (getLangOpts().ObjC1 && 12922 getLangOpts().getGC() != LangOptions::NonGC && 12923 Record && !Record->hasObjectMember()) { 12924 if (FD->getType()->isObjCObjectPointerType() || 12925 FD->getType().isObjCGCStrong()) 12926 Record->setHasObjectMember(true); 12927 else if (Context.getAsArrayType(FD->getType())) { 12928 QualType BaseType = Context.getBaseElementType(FD->getType()); 12929 if (BaseType->isRecordType() && 12930 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12931 Record->setHasObjectMember(true); 12932 else if (BaseType->isObjCObjectPointerType() || 12933 BaseType.isObjCGCStrong()) 12934 Record->setHasObjectMember(true); 12935 } 12936 } 12937 if (Record && FD->getType().isVolatileQualified()) 12938 Record->setHasVolatileMember(true); 12939 // Keep track of the number of named members. 12940 if (FD->getIdentifier()) 12941 ++NumNamedMembers; 12942 } 12943 12944 // Okay, we successfully defined 'Record'. 12945 if (Record) { 12946 bool Completed = false; 12947 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12948 if (!CXXRecord->isInvalidDecl()) { 12949 // Set access bits correctly on the directly-declared conversions. 12950 for (CXXRecordDecl::conversion_iterator 12951 I = CXXRecord->conversion_begin(), 12952 E = CXXRecord->conversion_end(); I != E; ++I) 12953 I.setAccess((*I)->getAccess()); 12954 12955 if (!CXXRecord->isDependentType()) { 12956 if (CXXRecord->hasUserDeclaredDestructor()) { 12957 // Adjust user-defined destructor exception spec. 12958 if (getLangOpts().CPlusPlus11) 12959 AdjustDestructorExceptionSpec(CXXRecord, 12960 CXXRecord->getDestructor()); 12961 } 12962 12963 // Add any implicitly-declared members to this class. 12964 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12965 12966 // If we have virtual base classes, we may end up finding multiple 12967 // final overriders for a given virtual function. Check for this 12968 // problem now. 12969 if (CXXRecord->getNumVBases()) { 12970 CXXFinalOverriderMap FinalOverriders; 12971 CXXRecord->getFinalOverriders(FinalOverriders); 12972 12973 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12974 MEnd = FinalOverriders.end(); 12975 M != MEnd; ++M) { 12976 for (OverridingMethods::iterator SO = M->second.begin(), 12977 SOEnd = M->second.end(); 12978 SO != SOEnd; ++SO) { 12979 assert(SO->second.size() > 0 && 12980 "Virtual function without overridding functions?"); 12981 if (SO->second.size() == 1) 12982 continue; 12983 12984 // C++ [class.virtual]p2: 12985 // In a derived class, if a virtual member function of a base 12986 // class subobject has more than one final overrider the 12987 // program is ill-formed. 12988 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12989 << (const NamedDecl *)M->first << Record; 12990 Diag(M->first->getLocation(), 12991 diag::note_overridden_virtual_function); 12992 for (OverridingMethods::overriding_iterator 12993 OM = SO->second.begin(), 12994 OMEnd = SO->second.end(); 12995 OM != OMEnd; ++OM) 12996 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12997 << (const NamedDecl *)M->first << OM->Method->getParent(); 12998 12999 Record->setInvalidDecl(); 13000 } 13001 } 13002 CXXRecord->completeDefinition(&FinalOverriders); 13003 Completed = true; 13004 } 13005 } 13006 } 13007 } 13008 13009 if (!Completed) 13010 Record->completeDefinition(); 13011 13012 if (Record->hasAttrs()) { 13013 CheckAlignasUnderalignment(Record); 13014 13015 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 13016 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 13017 IA->getRange(), IA->getBestCase(), 13018 IA->getSemanticSpelling()); 13019 } 13020 13021 // Check if the structure/union declaration is a type that can have zero 13022 // size in C. For C this is a language extension, for C++ it may cause 13023 // compatibility problems. 13024 bool CheckForZeroSize; 13025 if (!getLangOpts().CPlusPlus) { 13026 CheckForZeroSize = true; 13027 } else { 13028 // For C++ filter out types that cannot be referenced in C code. 13029 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 13030 CheckForZeroSize = 13031 CXXRecord->getLexicalDeclContext()->isExternCContext() && 13032 !CXXRecord->isDependentType() && 13033 CXXRecord->isCLike(); 13034 } 13035 if (CheckForZeroSize) { 13036 bool ZeroSize = true; 13037 bool IsEmpty = true; 13038 unsigned NonBitFields = 0; 13039 for (RecordDecl::field_iterator I = Record->field_begin(), 13040 E = Record->field_end(); 13041 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 13042 IsEmpty = false; 13043 if (I->isUnnamedBitfield()) { 13044 if (I->getBitWidthValue(Context) > 0) 13045 ZeroSize = false; 13046 } else { 13047 ++NonBitFields; 13048 QualType FieldType = I->getType(); 13049 if (FieldType->isIncompleteType() || 13050 !Context.getTypeSizeInChars(FieldType).isZero()) 13051 ZeroSize = false; 13052 } 13053 } 13054 13055 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 13056 // allowed in C++, but warn if its declaration is inside 13057 // extern "C" block. 13058 if (ZeroSize) { 13059 Diag(RecLoc, getLangOpts().CPlusPlus ? 13060 diag::warn_zero_size_struct_union_in_extern_c : 13061 diag::warn_zero_size_struct_union_compat) 13062 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 13063 } 13064 13065 // Structs without named members are extension in C (C99 6.7.2.1p7), 13066 // but are accepted by GCC. 13067 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 13068 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 13069 diag::ext_no_named_members_in_struct_union) 13070 << Record->isUnion(); 13071 } 13072 } 13073 } else { 13074 ObjCIvarDecl **ClsFields = 13075 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 13076 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 13077 ID->setEndOfDefinitionLoc(RBrac); 13078 // Add ivar's to class's DeclContext. 13079 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13080 ClsFields[i]->setLexicalDeclContext(ID); 13081 ID->addDecl(ClsFields[i]); 13082 } 13083 // Must enforce the rule that ivars in the base classes may not be 13084 // duplicates. 13085 if (ID->getSuperClass()) 13086 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 13087 } else if (ObjCImplementationDecl *IMPDecl = 13088 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13089 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 13090 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 13091 // Ivar declared in @implementation never belongs to the implementation. 13092 // Only it is in implementation's lexical context. 13093 ClsFields[I]->setLexicalDeclContext(IMPDecl); 13094 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 13095 IMPDecl->setIvarLBraceLoc(LBrac); 13096 IMPDecl->setIvarRBraceLoc(RBrac); 13097 } else if (ObjCCategoryDecl *CDecl = 13098 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13099 // case of ivars in class extension; all other cases have been 13100 // reported as errors elsewhere. 13101 // FIXME. Class extension does not have a LocEnd field. 13102 // CDecl->setLocEnd(RBrac); 13103 // Add ivar's to class extension's DeclContext. 13104 // Diagnose redeclaration of private ivars. 13105 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 13106 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13107 if (IDecl) { 13108 if (const ObjCIvarDecl *ClsIvar = 13109 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 13110 Diag(ClsFields[i]->getLocation(), 13111 diag::err_duplicate_ivar_declaration); 13112 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 13113 continue; 13114 } 13115 for (const auto *Ext : IDecl->known_extensions()) { 13116 if (const ObjCIvarDecl *ClsExtIvar 13117 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 13118 Diag(ClsFields[i]->getLocation(), 13119 diag::err_duplicate_ivar_declaration); 13120 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 13121 continue; 13122 } 13123 } 13124 } 13125 ClsFields[i]->setLexicalDeclContext(CDecl); 13126 CDecl->addDecl(ClsFields[i]); 13127 } 13128 CDecl->setIvarLBraceLoc(LBrac); 13129 CDecl->setIvarRBraceLoc(RBrac); 13130 } 13131 } 13132 13133 if (Attr) 13134 ProcessDeclAttributeList(S, Record, Attr); 13135 } 13136 13137 /// \brief Determine whether the given integral value is representable within 13138 /// the given type T. 13139 static bool isRepresentableIntegerValue(ASTContext &Context, 13140 llvm::APSInt &Value, 13141 QualType T) { 13142 assert(T->isIntegralType(Context) && "Integral type required!"); 13143 unsigned BitWidth = Context.getIntWidth(T); 13144 13145 if (Value.isUnsigned() || Value.isNonNegative()) { 13146 if (T->isSignedIntegerOrEnumerationType()) 13147 --BitWidth; 13148 return Value.getActiveBits() <= BitWidth; 13149 } 13150 return Value.getMinSignedBits() <= BitWidth; 13151 } 13152 13153 // \brief Given an integral type, return the next larger integral type 13154 // (or a NULL type of no such type exists). 13155 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13156 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13157 // enum checking below. 13158 assert(T->isIntegralType(Context) && "Integral type required!"); 13159 const unsigned NumTypes = 4; 13160 QualType SignedIntegralTypes[NumTypes] = { 13161 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13162 }; 13163 QualType UnsignedIntegralTypes[NumTypes] = { 13164 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13165 Context.UnsignedLongLongTy 13166 }; 13167 13168 unsigned BitWidth = Context.getTypeSize(T); 13169 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13170 : UnsignedIntegralTypes; 13171 for (unsigned I = 0; I != NumTypes; ++I) 13172 if (Context.getTypeSize(Types[I]) > BitWidth) 13173 return Types[I]; 13174 13175 return QualType(); 13176 } 13177 13178 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13179 EnumConstantDecl *LastEnumConst, 13180 SourceLocation IdLoc, 13181 IdentifierInfo *Id, 13182 Expr *Val) { 13183 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13184 llvm::APSInt EnumVal(IntWidth); 13185 QualType EltTy; 13186 13187 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13188 Val = nullptr; 13189 13190 if (Val) 13191 Val = DefaultLvalueConversion(Val).get(); 13192 13193 if (Val) { 13194 if (Enum->isDependentType() || Val->isTypeDependent()) 13195 EltTy = Context.DependentTy; 13196 else { 13197 SourceLocation ExpLoc; 13198 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 13199 !getLangOpts().MSVCCompat) { 13200 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 13201 // constant-expression in the enumerator-definition shall be a converted 13202 // constant expression of the underlying type. 13203 EltTy = Enum->getIntegerType(); 13204 ExprResult Converted = 13205 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 13206 CCEK_Enumerator); 13207 if (Converted.isInvalid()) 13208 Val = nullptr; 13209 else 13210 Val = Converted.get(); 13211 } else if (!Val->isValueDependent() && 13212 !(Val = VerifyIntegerConstantExpression(Val, 13213 &EnumVal).get())) { 13214 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 13215 } else { 13216 if (Enum->isFixed()) { 13217 EltTy = Enum->getIntegerType(); 13218 13219 // In Obj-C and Microsoft mode, require the enumeration value to be 13220 // representable in the underlying type of the enumeration. In C++11, 13221 // we perform a non-narrowing conversion as part of converted constant 13222 // expression checking. 13223 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13224 if (getLangOpts().MSVCCompat) { 13225 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 13226 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13227 } else 13228 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 13229 } else 13230 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13231 } else if (getLangOpts().CPlusPlus) { 13232 // C++11 [dcl.enum]p5: 13233 // If the underlying type is not fixed, the type of each enumerator 13234 // is the type of its initializing value: 13235 // - If an initializer is specified for an enumerator, the 13236 // initializing value has the same type as the expression. 13237 EltTy = Val->getType(); 13238 } else { 13239 // C99 6.7.2.2p2: 13240 // The expression that defines the value of an enumeration constant 13241 // shall be an integer constant expression that has a value 13242 // representable as an int. 13243 13244 // Complain if the value is not representable in an int. 13245 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 13246 Diag(IdLoc, diag::ext_enum_value_not_int) 13247 << EnumVal.toString(10) << Val->getSourceRange() 13248 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 13249 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 13250 // Force the type of the expression to 'int'. 13251 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 13252 } 13253 EltTy = Val->getType(); 13254 } 13255 } 13256 } 13257 } 13258 13259 if (!Val) { 13260 if (Enum->isDependentType()) 13261 EltTy = Context.DependentTy; 13262 else if (!LastEnumConst) { 13263 // C++0x [dcl.enum]p5: 13264 // If the underlying type is not fixed, the type of each enumerator 13265 // is the type of its initializing value: 13266 // - If no initializer is specified for the first enumerator, the 13267 // initializing value has an unspecified integral type. 13268 // 13269 // GCC uses 'int' for its unspecified integral type, as does 13270 // C99 6.7.2.2p3. 13271 if (Enum->isFixed()) { 13272 EltTy = Enum->getIntegerType(); 13273 } 13274 else { 13275 EltTy = Context.IntTy; 13276 } 13277 } else { 13278 // Assign the last value + 1. 13279 EnumVal = LastEnumConst->getInitVal(); 13280 ++EnumVal; 13281 EltTy = LastEnumConst->getType(); 13282 13283 // Check for overflow on increment. 13284 if (EnumVal < LastEnumConst->getInitVal()) { 13285 // C++0x [dcl.enum]p5: 13286 // If the underlying type is not fixed, the type of each enumerator 13287 // is the type of its initializing value: 13288 // 13289 // - Otherwise the type of the initializing value is the same as 13290 // the type of the initializing value of the preceding enumerator 13291 // unless the incremented value is not representable in that type, 13292 // in which case the type is an unspecified integral type 13293 // sufficient to contain the incremented value. If no such type 13294 // exists, the program is ill-formed. 13295 QualType T = getNextLargerIntegralType(Context, EltTy); 13296 if (T.isNull() || Enum->isFixed()) { 13297 // There is no integral type larger enough to represent this 13298 // value. Complain, then allow the value to wrap around. 13299 EnumVal = LastEnumConst->getInitVal(); 13300 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 13301 ++EnumVal; 13302 if (Enum->isFixed()) 13303 // When the underlying type is fixed, this is ill-formed. 13304 Diag(IdLoc, diag::err_enumerator_wrapped) 13305 << EnumVal.toString(10) 13306 << EltTy; 13307 else 13308 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 13309 << EnumVal.toString(10); 13310 } else { 13311 EltTy = T; 13312 } 13313 13314 // Retrieve the last enumerator's value, extent that type to the 13315 // type that is supposed to be large enough to represent the incremented 13316 // value, then increment. 13317 EnumVal = LastEnumConst->getInitVal(); 13318 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13319 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 13320 ++EnumVal; 13321 13322 // If we're not in C++, diagnose the overflow of enumerator values, 13323 // which in C99 means that the enumerator value is not representable in 13324 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 13325 // permits enumerator values that are representable in some larger 13326 // integral type. 13327 if (!getLangOpts().CPlusPlus && !T.isNull()) 13328 Diag(IdLoc, diag::warn_enum_value_overflow); 13329 } else if (!getLangOpts().CPlusPlus && 13330 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13331 // Enforce C99 6.7.2.2p2 even when we compute the next value. 13332 Diag(IdLoc, diag::ext_enum_value_not_int) 13333 << EnumVal.toString(10) << 1; 13334 } 13335 } 13336 } 13337 13338 if (!EltTy->isDependentType()) { 13339 // Make the enumerator value match the signedness and size of the 13340 // enumerator's type. 13341 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 13342 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13343 } 13344 13345 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 13346 Val, EnumVal); 13347 } 13348 13349 13350 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 13351 SourceLocation IdLoc, IdentifierInfo *Id, 13352 AttributeList *Attr, 13353 SourceLocation EqualLoc, Expr *Val) { 13354 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 13355 EnumConstantDecl *LastEnumConst = 13356 cast_or_null<EnumConstantDecl>(lastEnumConst); 13357 13358 // The scope passed in may not be a decl scope. Zip up the scope tree until 13359 // we find one that is. 13360 S = getNonFieldDeclScope(S); 13361 13362 // Verify that there isn't already something declared with this name in this 13363 // scope. 13364 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 13365 ForRedeclaration); 13366 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13367 // Maybe we will complain about the shadowed template parameter. 13368 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 13369 // Just pretend that we didn't see the previous declaration. 13370 PrevDecl = nullptr; 13371 } 13372 13373 if (PrevDecl) { 13374 // When in C++, we may get a TagDecl with the same name; in this case the 13375 // enum constant will 'hide' the tag. 13376 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 13377 "Received TagDecl when not in C++!"); 13378 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 13379 if (isa<EnumConstantDecl>(PrevDecl)) 13380 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 13381 else 13382 Diag(IdLoc, diag::err_redefinition) << Id; 13383 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13384 return nullptr; 13385 } 13386 } 13387 13388 // C++ [class.mem]p15: 13389 // If T is the name of a class, then each of the following shall have a name 13390 // different from T: 13391 // - every enumerator of every member of class T that is an unscoped 13392 // enumerated type 13393 if (CXXRecordDecl *Record 13394 = dyn_cast<CXXRecordDecl>( 13395 TheEnumDecl->getDeclContext()->getRedeclContext())) 13396 if (!TheEnumDecl->isScoped() && 13397 Record->getIdentifier() && Record->getIdentifier() == Id) 13398 Diag(IdLoc, diag::err_member_name_of_class) << Id; 13399 13400 EnumConstantDecl *New = 13401 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 13402 13403 if (New) { 13404 // Process attributes. 13405 if (Attr) ProcessDeclAttributeList(S, New, Attr); 13406 13407 // Register this decl in the current scope stack. 13408 New->setAccess(TheEnumDecl->getAccess()); 13409 PushOnScopeChains(New, S); 13410 } 13411 13412 ActOnDocumentableDecl(New); 13413 13414 return New; 13415 } 13416 13417 // Returns true when the enum initial expression does not trigger the 13418 // duplicate enum warning. A few common cases are exempted as follows: 13419 // Element2 = Element1 13420 // Element2 = Element1 + 1 13421 // Element2 = Element1 - 1 13422 // Where Element2 and Element1 are from the same enum. 13423 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 13424 Expr *InitExpr = ECD->getInitExpr(); 13425 if (!InitExpr) 13426 return true; 13427 InitExpr = InitExpr->IgnoreImpCasts(); 13428 13429 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 13430 if (!BO->isAdditiveOp()) 13431 return true; 13432 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 13433 if (!IL) 13434 return true; 13435 if (IL->getValue() != 1) 13436 return true; 13437 13438 InitExpr = BO->getLHS(); 13439 } 13440 13441 // This checks if the elements are from the same enum. 13442 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 13443 if (!DRE) 13444 return true; 13445 13446 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 13447 if (!EnumConstant) 13448 return true; 13449 13450 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 13451 Enum) 13452 return true; 13453 13454 return false; 13455 } 13456 13457 struct DupKey { 13458 int64_t val; 13459 bool isTombstoneOrEmptyKey; 13460 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 13461 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 13462 }; 13463 13464 static DupKey GetDupKey(const llvm::APSInt& Val) { 13465 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 13466 false); 13467 } 13468 13469 struct DenseMapInfoDupKey { 13470 static DupKey getEmptyKey() { return DupKey(0, true); } 13471 static DupKey getTombstoneKey() { return DupKey(1, true); } 13472 static unsigned getHashValue(const DupKey Key) { 13473 return (unsigned)(Key.val * 37); 13474 } 13475 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 13476 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 13477 LHS.val == RHS.val; 13478 } 13479 }; 13480 13481 // Emits a warning when an element is implicitly set a value that 13482 // a previous element has already been set to. 13483 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 13484 EnumDecl *Enum, 13485 QualType EnumType) { 13486 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 13487 return; 13488 // Avoid anonymous enums 13489 if (!Enum->getIdentifier()) 13490 return; 13491 13492 // Only check for small enums. 13493 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 13494 return; 13495 13496 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 13497 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 13498 13499 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 13500 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 13501 ValueToVectorMap; 13502 13503 DuplicatesVector DupVector; 13504 ValueToVectorMap EnumMap; 13505 13506 // Populate the EnumMap with all values represented by enum constants without 13507 // an initialier. 13508 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13509 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13510 13511 // Null EnumConstantDecl means a previous diagnostic has been emitted for 13512 // this constant. Skip this enum since it may be ill-formed. 13513 if (!ECD) { 13514 return; 13515 } 13516 13517 if (ECD->getInitExpr()) 13518 continue; 13519 13520 DupKey Key = GetDupKey(ECD->getInitVal()); 13521 DeclOrVector &Entry = EnumMap[Key]; 13522 13523 // First time encountering this value. 13524 if (Entry.isNull()) 13525 Entry = ECD; 13526 } 13527 13528 // Create vectors for any values that has duplicates. 13529 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13530 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 13531 if (!ValidDuplicateEnum(ECD, Enum)) 13532 continue; 13533 13534 DupKey Key = GetDupKey(ECD->getInitVal()); 13535 13536 DeclOrVector& Entry = EnumMap[Key]; 13537 if (Entry.isNull()) 13538 continue; 13539 13540 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 13541 // Ensure constants are different. 13542 if (D == ECD) 13543 continue; 13544 13545 // Create new vector and push values onto it. 13546 ECDVector *Vec = new ECDVector(); 13547 Vec->push_back(D); 13548 Vec->push_back(ECD); 13549 13550 // Update entry to point to the duplicates vector. 13551 Entry = Vec; 13552 13553 // Store the vector somewhere we can consult later for quick emission of 13554 // diagnostics. 13555 DupVector.push_back(Vec); 13556 continue; 13557 } 13558 13559 ECDVector *Vec = Entry.get<ECDVector*>(); 13560 // Make sure constants are not added more than once. 13561 if (*Vec->begin() == ECD) 13562 continue; 13563 13564 Vec->push_back(ECD); 13565 } 13566 13567 // Emit diagnostics. 13568 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 13569 DupVectorEnd = DupVector.end(); 13570 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 13571 ECDVector *Vec = *DupVectorIter; 13572 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 13573 13574 // Emit warning for one enum constant. 13575 ECDVector::iterator I = Vec->begin(); 13576 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 13577 << (*I)->getName() << (*I)->getInitVal().toString(10) 13578 << (*I)->getSourceRange(); 13579 ++I; 13580 13581 // Emit one note for each of the remaining enum constants with 13582 // the same value. 13583 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 13584 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 13585 << (*I)->getName() << (*I)->getInitVal().toString(10) 13586 << (*I)->getSourceRange(); 13587 delete Vec; 13588 } 13589 } 13590 13591 bool 13592 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 13593 bool AllowMask) const { 13594 FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>(); 13595 assert(FEAttr && "looking for value in non-flag enum"); 13596 13597 llvm::APInt FlagMask = ~FEAttr->getFlagBits(); 13598 unsigned Width = FlagMask.getBitWidth(); 13599 13600 // We will try a zero-extended value for the regular check first. 13601 llvm::APInt ExtVal = Val.zextOrSelf(Width); 13602 13603 // A value is in a flag enum if either its bits are a subset of the enum's 13604 // flag bits (the first condition) or we are allowing masks and the same is 13605 // true of its complement (the second condition). When masks are allowed, we 13606 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 13607 // 13608 // While it's true that any value could be used as a mask, the assumption is 13609 // that a mask will have all of the insignificant bits set. Anything else is 13610 // likely a logic error. 13611 if (!(FlagMask & ExtVal)) 13612 return true; 13613 13614 if (AllowMask) { 13615 // Try a one-extended value instead. This can happen if the enum is wider 13616 // than the constant used, in C with extensions to allow for wider enums. 13617 // The mask will still have the correct behaviour, so we give the user the 13618 // benefit of the doubt. 13619 // 13620 // FIXME: This heuristic can cause weird results if the enum was extended 13621 // to a larger type and is signed, because then bit-masks of smaller types 13622 // that get extended will fall out of range (e.g. ~0x1u). We currently don't 13623 // detect that case and will get a false positive for it. In most cases, 13624 // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may 13625 // be fine just to accept this as a warning. 13626 ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth()); 13627 if (!(FlagMask & ~ExtVal)) 13628 return true; 13629 } 13630 13631 return false; 13632 } 13633 13634 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 13635 SourceLocation RBraceLoc, Decl *EnumDeclX, 13636 ArrayRef<Decl *> Elements, 13637 Scope *S, AttributeList *Attr) { 13638 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 13639 QualType EnumType = Context.getTypeDeclType(Enum); 13640 13641 if (Attr) 13642 ProcessDeclAttributeList(S, Enum, Attr); 13643 13644 if (Enum->isDependentType()) { 13645 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13646 EnumConstantDecl *ECD = 13647 cast_or_null<EnumConstantDecl>(Elements[i]); 13648 if (!ECD) continue; 13649 13650 ECD->setType(EnumType); 13651 } 13652 13653 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 13654 return; 13655 } 13656 13657 // TODO: If the result value doesn't fit in an int, it must be a long or long 13658 // long value. ISO C does not support this, but GCC does as an extension, 13659 // emit a warning. 13660 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13661 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 13662 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 13663 13664 // Verify that all the values are okay, compute the size of the values, and 13665 // reverse the list. 13666 unsigned NumNegativeBits = 0; 13667 unsigned NumPositiveBits = 0; 13668 13669 // Keep track of whether all elements have type int. 13670 bool AllElementsInt = true; 13671 13672 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13673 EnumConstantDecl *ECD = 13674 cast_or_null<EnumConstantDecl>(Elements[i]); 13675 if (!ECD) continue; // Already issued a diagnostic. 13676 13677 const llvm::APSInt &InitVal = ECD->getInitVal(); 13678 13679 // Keep track of the size of positive and negative values. 13680 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13681 NumPositiveBits = std::max(NumPositiveBits, 13682 (unsigned)InitVal.getActiveBits()); 13683 else 13684 NumNegativeBits = std::max(NumNegativeBits, 13685 (unsigned)InitVal.getMinSignedBits()); 13686 13687 // Keep track of whether every enum element has type int (very commmon). 13688 if (AllElementsInt) 13689 AllElementsInt = ECD->getType() == Context.IntTy; 13690 } 13691 13692 // Figure out the type that should be used for this enum. 13693 QualType BestType; 13694 unsigned BestWidth; 13695 13696 // C++0x N3000 [conv.prom]p3: 13697 // An rvalue of an unscoped enumeration type whose underlying 13698 // type is not fixed can be converted to an rvalue of the first 13699 // of the following types that can represent all the values of 13700 // the enumeration: int, unsigned int, long int, unsigned long 13701 // int, long long int, or unsigned long long int. 13702 // C99 6.4.4.3p2: 13703 // An identifier declared as an enumeration constant has type int. 13704 // The C99 rule is modified by a gcc extension 13705 QualType BestPromotionType; 13706 13707 bool Packed = Enum->hasAttr<PackedAttr>(); 13708 // -fshort-enums is the equivalent to specifying the packed attribute on all 13709 // enum definitions. 13710 if (LangOpts.ShortEnums) 13711 Packed = true; 13712 13713 if (Enum->isFixed()) { 13714 BestType = Enum->getIntegerType(); 13715 if (BestType->isPromotableIntegerType()) 13716 BestPromotionType = Context.getPromotedIntegerType(BestType); 13717 else 13718 BestPromotionType = BestType; 13719 13720 BestWidth = Context.getIntWidth(BestType); 13721 } 13722 else if (NumNegativeBits) { 13723 // If there is a negative value, figure out the smallest integer type (of 13724 // int/long/longlong) that fits. 13725 // If it's packed, check also if it fits a char or a short. 13726 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13727 BestType = Context.SignedCharTy; 13728 BestWidth = CharWidth; 13729 } else if (Packed && NumNegativeBits <= ShortWidth && 13730 NumPositiveBits < ShortWidth) { 13731 BestType = Context.ShortTy; 13732 BestWidth = ShortWidth; 13733 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13734 BestType = Context.IntTy; 13735 BestWidth = IntWidth; 13736 } else { 13737 BestWidth = Context.getTargetInfo().getLongWidth(); 13738 13739 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13740 BestType = Context.LongTy; 13741 } else { 13742 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13743 13744 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13745 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13746 BestType = Context.LongLongTy; 13747 } 13748 } 13749 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13750 } else { 13751 // If there is no negative value, figure out the smallest type that fits 13752 // all of the enumerator values. 13753 // If it's packed, check also if it fits a char or a short. 13754 if (Packed && NumPositiveBits <= CharWidth) { 13755 BestType = Context.UnsignedCharTy; 13756 BestPromotionType = Context.IntTy; 13757 BestWidth = CharWidth; 13758 } else if (Packed && NumPositiveBits <= ShortWidth) { 13759 BestType = Context.UnsignedShortTy; 13760 BestPromotionType = Context.IntTy; 13761 BestWidth = ShortWidth; 13762 } else if (NumPositiveBits <= IntWidth) { 13763 BestType = Context.UnsignedIntTy; 13764 BestWidth = IntWidth; 13765 BestPromotionType 13766 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13767 ? Context.UnsignedIntTy : Context.IntTy; 13768 } else if (NumPositiveBits <= 13769 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13770 BestType = Context.UnsignedLongTy; 13771 BestPromotionType 13772 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13773 ? Context.UnsignedLongTy : Context.LongTy; 13774 } else { 13775 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13776 assert(NumPositiveBits <= BestWidth && 13777 "How could an initializer get larger than ULL?"); 13778 BestType = Context.UnsignedLongLongTy; 13779 BestPromotionType 13780 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13781 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13782 } 13783 } 13784 13785 FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>(); 13786 if (FEAttr) 13787 FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0); 13788 13789 // Loop over all of the enumerator constants, changing their types to match 13790 // the type of the enum if needed. If we have a flag type, we also prepare the 13791 // FlagBits cache. 13792 for (auto *D : Elements) { 13793 auto *ECD = cast_or_null<EnumConstantDecl>(D); 13794 if (!ECD) continue; // Already issued a diagnostic. 13795 13796 // Standard C says the enumerators have int type, but we allow, as an 13797 // extension, the enumerators to be larger than int size. If each 13798 // enumerator value fits in an int, type it as an int, otherwise type it the 13799 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13800 // that X has type 'int', not 'unsigned'. 13801 13802 // Determine whether the value fits into an int. 13803 llvm::APSInt InitVal = ECD->getInitVal(); 13804 13805 // If it fits into an integer type, force it. Otherwise force it to match 13806 // the enum decl type. 13807 QualType NewTy; 13808 unsigned NewWidth; 13809 bool NewSign; 13810 if (!getLangOpts().CPlusPlus && 13811 !Enum->isFixed() && 13812 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13813 NewTy = Context.IntTy; 13814 NewWidth = IntWidth; 13815 NewSign = true; 13816 } else if (ECD->getType() == BestType) { 13817 // Already the right type! 13818 if (getLangOpts().CPlusPlus) 13819 // C++ [dcl.enum]p4: Following the closing brace of an 13820 // enum-specifier, each enumerator has the type of its 13821 // enumeration. 13822 ECD->setType(EnumType); 13823 goto flagbits; 13824 } else { 13825 NewTy = BestType; 13826 NewWidth = BestWidth; 13827 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13828 } 13829 13830 // Adjust the APSInt value. 13831 InitVal = InitVal.extOrTrunc(NewWidth); 13832 InitVal.setIsSigned(NewSign); 13833 ECD->setInitVal(InitVal); 13834 13835 // Adjust the Expr initializer and type. 13836 if (ECD->getInitExpr() && 13837 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13838 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13839 CK_IntegralCast, 13840 ECD->getInitExpr(), 13841 /*base paths*/ nullptr, 13842 VK_RValue)); 13843 if (getLangOpts().CPlusPlus) 13844 // C++ [dcl.enum]p4: Following the closing brace of an 13845 // enum-specifier, each enumerator has the type of its 13846 // enumeration. 13847 ECD->setType(EnumType); 13848 else 13849 ECD->setType(NewTy); 13850 13851 flagbits: 13852 // Check to see if we have a constant with exactly one bit set. Note that x 13853 // & (x - 1) will be nonzero if and only if x has more than one bit set. 13854 if (FEAttr) { 13855 llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth); 13856 if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) { 13857 FEAttr->getFlagBits() |= ExtVal; 13858 } 13859 } 13860 } 13861 13862 if (FEAttr) { 13863 for (Decl *D : Elements) { 13864 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 13865 if (!ECD) continue; // Already issued a diagnostic. 13866 13867 llvm::APSInt InitVal = ECD->getInitVal(); 13868 if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true)) 13869 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 13870 << ECD << Enum; 13871 } 13872 } 13873 13874 13875 13876 Enum->completeDefinition(BestType, BestPromotionType, 13877 NumPositiveBits, NumNegativeBits); 13878 13879 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13880 13881 // Now that the enum type is defined, ensure it's not been underaligned. 13882 if (Enum->hasAttrs()) 13883 CheckAlignasUnderalignment(Enum); 13884 } 13885 13886 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13887 SourceLocation StartLoc, 13888 SourceLocation EndLoc) { 13889 StringLiteral *AsmString = cast<StringLiteral>(expr); 13890 13891 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13892 AsmString, StartLoc, 13893 EndLoc); 13894 CurContext->addDecl(New); 13895 return New; 13896 } 13897 13898 static void checkModuleImportContext(Sema &S, Module *M, 13899 SourceLocation ImportLoc, 13900 DeclContext *DC) { 13901 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13902 switch (LSD->getLanguage()) { 13903 case LinkageSpecDecl::lang_c: 13904 if (!M->IsExternC) { 13905 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13906 << M->getFullModuleName(); 13907 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13908 return; 13909 } 13910 break; 13911 case LinkageSpecDecl::lang_cxx: 13912 break; 13913 } 13914 DC = LSD->getParent(); 13915 } 13916 13917 while (isa<LinkageSpecDecl>(DC)) 13918 DC = DC->getParent(); 13919 if (!isa<TranslationUnitDecl>(DC)) { 13920 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13921 << M->getFullModuleName() << DC; 13922 S.Diag(cast<Decl>(DC)->getLocStart(), 13923 diag::note_module_import_not_at_top_level) 13924 << DC; 13925 } 13926 } 13927 13928 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13929 SourceLocation ImportLoc, 13930 ModuleIdPath Path) { 13931 Module *Mod = 13932 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 13933 /*IsIncludeDirective=*/false); 13934 if (!Mod) 13935 return true; 13936 13937 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13938 13939 // FIXME: we should support importing a submodule within a different submodule 13940 // of the same top-level module. Until we do, make it an error rather than 13941 // silently ignoring the import. 13942 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 13943 Diag(ImportLoc, diag::err_module_self_import) 13944 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 13945 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule) 13946 Diag(ImportLoc, diag::err_module_import_in_implementation) 13947 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule; 13948 13949 SmallVector<SourceLocation, 2> IdentifierLocs; 13950 Module *ModCheck = Mod; 13951 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13952 // If we've run out of module parents, just drop the remaining identifiers. 13953 // We need the length to be consistent. 13954 if (!ModCheck) 13955 break; 13956 ModCheck = ModCheck->Parent; 13957 13958 IdentifierLocs.push_back(Path[I].second); 13959 } 13960 13961 ImportDecl *Import = ImportDecl::Create(Context, 13962 Context.getTranslationUnitDecl(), 13963 AtLoc.isValid()? AtLoc : ImportLoc, 13964 Mod, IdentifierLocs); 13965 Context.getTranslationUnitDecl()->addDecl(Import); 13966 return Import; 13967 } 13968 13969 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13970 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13971 13972 // FIXME: Should we synthesize an ImportDecl here? 13973 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13974 /*Complain=*/true); 13975 } 13976 13977 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 13978 Module *Mod) { 13979 // Bail if we're not allowed to implicitly import a module here. 13980 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 13981 return; 13982 13983 // Create the implicit import declaration. 13984 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13985 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13986 Loc, Mod, Loc); 13987 TU->addDecl(ImportD); 13988 Consumer.HandleImplicitImportDecl(ImportD); 13989 13990 // Make the module visible. 13991 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13992 /*Complain=*/false); 13993 } 13994 13995 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13996 IdentifierInfo* AliasName, 13997 SourceLocation PragmaLoc, 13998 SourceLocation NameLoc, 13999 SourceLocation AliasNameLoc) { 14000 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 14001 LookupOrdinaryName); 14002 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 14003 AliasName->getName(), 0); 14004 14005 if (PrevDecl) 14006 PrevDecl->addAttr(Attr); 14007 else 14008 (void)ExtnameUndeclaredIdentifiers.insert( 14009 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 14010 } 14011 14012 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 14013 SourceLocation PragmaLoc, 14014 SourceLocation NameLoc) { 14015 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 14016 14017 if (PrevDecl) { 14018 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 14019 } else { 14020 (void)WeakUndeclaredIdentifiers.insert( 14021 std::pair<IdentifierInfo*,WeakInfo> 14022 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 14023 } 14024 } 14025 14026 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 14027 IdentifierInfo* AliasName, 14028 SourceLocation PragmaLoc, 14029 SourceLocation NameLoc, 14030 SourceLocation AliasNameLoc) { 14031 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 14032 LookupOrdinaryName); 14033 WeakInfo W = WeakInfo(Name, NameLoc); 14034 14035 if (PrevDecl) { 14036 if (!PrevDecl->hasAttr<AliasAttr>()) 14037 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 14038 DeclApplyPragmaWeak(TUScope, ND, W); 14039 } else { 14040 (void)WeakUndeclaredIdentifiers.insert( 14041 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 14042 } 14043 } 14044 14045 Decl *Sema::getObjCDeclContext() const { 14046 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 14047 } 14048 14049 AvailabilityResult Sema::getCurContextAvailability() const { 14050 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 14051 if (!D) 14052 return AR_Available; 14053 14054 // If we are within an Objective-C method, we should consult 14055 // both the availability of the method as well as the 14056 // enclosing class. If the class is (say) deprecated, 14057 // the entire method is considered deprecated from the 14058 // purpose of checking if the current context is deprecated. 14059 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 14060 AvailabilityResult R = MD->getAvailability(); 14061 if (R != AR_Available) 14062 return R; 14063 D = MD->getClassInterface(); 14064 } 14065 // If we are within an Objective-c @implementation, it 14066 // gets the same availability context as the @interface. 14067 else if (const ObjCImplementationDecl *ID = 14068 dyn_cast<ObjCImplementationDecl>(D)) { 14069 D = ID->getClassInterface(); 14070 } 14071 // Recover from user error. 14072 return D ? D->getAvailability() : AR_Available; 14073 } 14074