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 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to 3420 // disambiguate entities defined in different scopes. 3421 // While the VS2015 ABI fixes potential miscompiles, it is also breaks 3422 // compatibility. 3423 // We will pick our mangling number depending on which version of MSVC is being 3424 // targeted. 3425 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) { 3426 return LO.isCompatibleWithMSVC(19) ? S->getMSCurManglingNumber() 3427 : S->getMSLastManglingNumber(); 3428 } 3429 3430 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) { 3431 if (!Context.getLangOpts().CPlusPlus) 3432 return; 3433 3434 if (isa<CXXRecordDecl>(Tag->getParent())) { 3435 // If this tag is the direct child of a class, number it if 3436 // it is anonymous. 3437 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3438 return; 3439 MangleNumberingContext &MCtx = 3440 Context.getManglingNumberContext(Tag->getParent()); 3441 Context.setManglingNumber( 3442 Tag, MCtx.getManglingNumber( 3443 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3444 return; 3445 } 3446 3447 // If this tag isn't a direct child of a class, number it if it is local. 3448 Decl *ManglingContextDecl; 3449 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 3450 Tag->getDeclContext(), ManglingContextDecl)) { 3451 Context.setManglingNumber( 3452 Tag, MCtx->getManglingNumber( 3453 Tag, getMSManglingNumber(getLangOpts(), TagScope))); 3454 } 3455 } 3456 3457 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, 3458 TypedefNameDecl *NewTD) { 3459 // Do nothing if the tag is not anonymous or already has an 3460 // associated typedef (from an earlier typedef in this decl group). 3461 if (TagFromDeclSpec->getIdentifier()) 3462 return; 3463 if (TagFromDeclSpec->getTypedefNameForAnonDecl()) 3464 return; 3465 3466 // A well-formed anonymous tag must always be a TUK_Definition. 3467 assert(TagFromDeclSpec->isThisDeclarationADefinition()); 3468 3469 // The type must match the tag exactly; no qualifiers allowed. 3470 if (!Context.hasSameType(NewTD->getUnderlyingType(), 3471 Context.getTagDeclType(TagFromDeclSpec))) 3472 return; 3473 3474 // If we've already computed linkage for the anonymous tag, then 3475 // adding a typedef name for the anonymous decl can change that 3476 // linkage, which might be a serious problem. Diagnose this as 3477 // unsupported and ignore the typedef name. TODO: we should 3478 // pursue this as a language defect and establish a formal rule 3479 // for how to handle it. 3480 if (TagFromDeclSpec->hasLinkageBeenComputed()) { 3481 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage); 3482 3483 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart(); 3484 tagLoc = getLocForEndOfToken(tagLoc); 3485 3486 llvm::SmallString<40> textToInsert; 3487 textToInsert += ' '; 3488 textToInsert += NewTD->getIdentifier()->getName(); 3489 Diag(tagLoc, diag::note_typedef_changes_linkage) 3490 << FixItHint::CreateInsertion(tagLoc, textToInsert); 3491 return; 3492 } 3493 3494 // Otherwise, set this is the anon-decl typedef for the tag. 3495 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 3496 } 3497 3498 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3499 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3500 /// parameters to cope with template friend declarations. 3501 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3502 DeclSpec &DS, 3503 MultiTemplateParamsArg TemplateParams, 3504 bool IsExplicitInstantiation) { 3505 Decl *TagD = nullptr; 3506 TagDecl *Tag = nullptr; 3507 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3508 DS.getTypeSpecType() == DeclSpec::TST_struct || 3509 DS.getTypeSpecType() == DeclSpec::TST_interface || 3510 DS.getTypeSpecType() == DeclSpec::TST_union || 3511 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3512 TagD = DS.getRepAsDecl(); 3513 3514 if (!TagD) // We probably had an error 3515 return nullptr; 3516 3517 // Note that the above type specs guarantee that the 3518 // type rep is a Decl, whereas in many of the others 3519 // it's a Type. 3520 if (isa<TagDecl>(TagD)) 3521 Tag = cast<TagDecl>(TagD); 3522 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3523 Tag = CTD->getTemplatedDecl(); 3524 } 3525 3526 if (Tag) { 3527 handleTagNumbering(Tag, S); 3528 Tag->setFreeStanding(); 3529 if (Tag->isInvalidDecl()) 3530 return Tag; 3531 } 3532 3533 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3534 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3535 // or incomplete types shall not be restrict-qualified." 3536 if (TypeQuals & DeclSpec::TQ_restrict) 3537 Diag(DS.getRestrictSpecLoc(), 3538 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3539 << DS.getSourceRange(); 3540 } 3541 3542 if (DS.isConstexprSpecified()) { 3543 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3544 // and definitions of functions and variables. 3545 if (Tag) 3546 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3547 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3548 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3549 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3550 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3551 else 3552 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3553 // Don't emit warnings after this error. 3554 return TagD; 3555 } 3556 3557 DiagnoseFunctionSpecifiers(DS); 3558 3559 if (DS.isFriendSpecified()) { 3560 // If we're dealing with a decl but not a TagDecl, assume that 3561 // whatever routines created it handled the friendship aspect. 3562 if (TagD && !Tag) 3563 return nullptr; 3564 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3565 } 3566 3567 const CXXScopeSpec &SS = DS.getTypeSpecScope(); 3568 bool IsExplicitSpecialization = 3569 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3570 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3571 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3572 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3573 // nested-name-specifier unless it is an explicit instantiation 3574 // or an explicit specialization. 3575 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3576 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3577 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3578 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3579 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3580 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3581 << SS.getRange(); 3582 return nullptr; 3583 } 3584 3585 // Track whether this decl-specifier declares anything. 3586 bool DeclaresAnything = true; 3587 3588 // Handle anonymous struct definitions. 3589 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3590 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3591 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3592 if (getLangOpts().CPlusPlus || 3593 Record->getDeclContext()->isRecord()) 3594 return BuildAnonymousStructOrUnion(S, DS, AS, Record, 3595 Context.getPrintingPolicy()); 3596 3597 DeclaresAnything = false; 3598 } 3599 } 3600 3601 // C11 6.7.2.1p2: 3602 // A struct-declaration that does not declare an anonymous structure or 3603 // anonymous union shall contain a struct-declarator-list. 3604 // 3605 // This rule also existed in C89 and C99; the grammar for struct-declaration 3606 // did not permit a struct-declaration without a struct-declarator-list. 3607 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3608 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3609 // Check for Microsoft C extension: anonymous struct/union member. 3610 // Handle 2 kinds of anonymous struct/union: 3611 // struct STRUCT; 3612 // union UNION; 3613 // and 3614 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3615 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3616 if ((Tag && Tag->getDeclName()) || 3617 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3618 RecordDecl *Record = nullptr; 3619 if (Tag) 3620 Record = dyn_cast<RecordDecl>(Tag); 3621 else if (const RecordType *RT = 3622 DS.getRepAsType().get()->getAsStructureType()) 3623 Record = RT->getDecl(); 3624 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3625 Record = UT->getDecl(); 3626 3627 if (Record && getLangOpts().MicrosoftExt) { 3628 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3629 << Record->isUnion() << DS.getSourceRange(); 3630 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3631 } 3632 3633 DeclaresAnything = false; 3634 } 3635 } 3636 3637 // Skip all the checks below if we have a type error. 3638 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3639 (TagD && TagD->isInvalidDecl())) 3640 return TagD; 3641 3642 if (getLangOpts().CPlusPlus && 3643 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3644 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3645 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3646 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3647 DeclaresAnything = false; 3648 3649 if (!DS.isMissingDeclaratorOk()) { 3650 // Customize diagnostic for a typedef missing a name. 3651 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3652 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3653 << DS.getSourceRange(); 3654 else 3655 DeclaresAnything = false; 3656 } 3657 3658 if (DS.isModulePrivateSpecified() && 3659 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3660 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3661 << Tag->getTagKind() 3662 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3663 3664 ActOnDocumentableDecl(TagD); 3665 3666 // C 6.7/2: 3667 // A declaration [...] shall declare at least a declarator [...], a tag, 3668 // or the members of an enumeration. 3669 // C++ [dcl.dcl]p3: 3670 // [If there are no declarators], and except for the declaration of an 3671 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3672 // names into the program, or shall redeclare a name introduced by a 3673 // previous declaration. 3674 if (!DeclaresAnything) { 3675 // In C, we allow this as a (popular) extension / bug. Don't bother 3676 // producing further diagnostics for redundant qualifiers after this. 3677 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3678 return TagD; 3679 } 3680 3681 // C++ [dcl.stc]p1: 3682 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3683 // init-declarator-list of the declaration shall not be empty. 3684 // C++ [dcl.fct.spec]p1: 3685 // If a cv-qualifier appears in a decl-specifier-seq, the 3686 // init-declarator-list of the declaration shall not be empty. 3687 // 3688 // Spurious qualifiers here appear to be valid in C. 3689 unsigned DiagID = diag::warn_standalone_specifier; 3690 if (getLangOpts().CPlusPlus) 3691 DiagID = diag::ext_standalone_specifier; 3692 3693 // Note that a linkage-specification sets a storage class, but 3694 // 'extern "C" struct foo;' is actually valid and not theoretically 3695 // useless. 3696 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3697 if (SCS == DeclSpec::SCS_mutable) 3698 // Since mutable is not a viable storage class specifier in C, there is 3699 // no reason to treat it as an extension. Instead, diagnose as an error. 3700 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3701 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3702 Diag(DS.getStorageClassSpecLoc(), DiagID) 3703 << DeclSpec::getSpecifierName(SCS); 3704 } 3705 3706 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3707 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3708 << DeclSpec::getSpecifierName(TSCS); 3709 if (DS.getTypeQualifiers()) { 3710 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3711 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3712 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3713 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3714 // Restrict is covered above. 3715 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3716 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3717 } 3718 3719 // Warn about ignored type attributes, for example: 3720 // __attribute__((aligned)) struct A; 3721 // Attributes should be placed after tag to apply to type declaration. 3722 if (!DS.getAttributes().empty()) { 3723 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3724 if (TypeSpecType == DeclSpec::TST_class || 3725 TypeSpecType == DeclSpec::TST_struct || 3726 TypeSpecType == DeclSpec::TST_interface || 3727 TypeSpecType == DeclSpec::TST_union || 3728 TypeSpecType == DeclSpec::TST_enum) { 3729 AttributeList* attrs = DS.getAttributes().getList(); 3730 while (attrs) { 3731 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3732 << attrs->getName() 3733 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3734 TypeSpecType == DeclSpec::TST_struct ? 1 : 3735 TypeSpecType == DeclSpec::TST_union ? 2 : 3736 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3737 attrs = attrs->getNext(); 3738 } 3739 } 3740 } 3741 3742 return TagD; 3743 } 3744 3745 /// We are trying to inject an anonymous member into the given scope; 3746 /// check if there's an existing declaration that can't be overloaded. 3747 /// 3748 /// \return true if this is a forbidden redeclaration 3749 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3750 Scope *S, 3751 DeclContext *Owner, 3752 DeclarationName Name, 3753 SourceLocation NameLoc, 3754 unsigned diagnostic) { 3755 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3756 Sema::ForRedeclaration); 3757 if (!SemaRef.LookupName(R, S)) return false; 3758 3759 if (R.getAsSingle<TagDecl>()) 3760 return false; 3761 3762 // Pick a representative declaration. 3763 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3764 assert(PrevDecl && "Expected a non-null Decl"); 3765 3766 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3767 return false; 3768 3769 SemaRef.Diag(NameLoc, diagnostic) << Name; 3770 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3771 3772 return true; 3773 } 3774 3775 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3776 /// anonymous struct or union AnonRecord into the owning context Owner 3777 /// and scope S. This routine will be invoked just after we realize 3778 /// that an unnamed union or struct is actually an anonymous union or 3779 /// struct, e.g., 3780 /// 3781 /// @code 3782 /// union { 3783 /// int i; 3784 /// float f; 3785 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3786 /// // f into the surrounding scope.x 3787 /// @endcode 3788 /// 3789 /// This routine is recursive, injecting the names of nested anonymous 3790 /// structs/unions into the owning context and scope as well. 3791 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3792 DeclContext *Owner, 3793 RecordDecl *AnonRecord, 3794 AccessSpecifier AS, 3795 SmallVectorImpl<NamedDecl *> &Chaining, 3796 bool MSAnonStruct) { 3797 unsigned diagKind 3798 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3799 : diag::err_anonymous_struct_member_redecl; 3800 3801 bool Invalid = false; 3802 3803 // Look every FieldDecl and IndirectFieldDecl with a name. 3804 for (auto *D : AnonRecord->decls()) { 3805 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3806 cast<NamedDecl>(D)->getDeclName()) { 3807 ValueDecl *VD = cast<ValueDecl>(D); 3808 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3809 VD->getLocation(), diagKind)) { 3810 // C++ [class.union]p2: 3811 // The names of the members of an anonymous union shall be 3812 // distinct from the names of any other entity in the 3813 // scope in which the anonymous union is declared. 3814 Invalid = true; 3815 } else { 3816 // C++ [class.union]p2: 3817 // For the purpose of name lookup, after the anonymous union 3818 // definition, the members of the anonymous union are 3819 // considered to have been defined in the scope in which the 3820 // anonymous union is declared. 3821 unsigned OldChainingSize = Chaining.size(); 3822 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3823 Chaining.append(IF->chain_begin(), IF->chain_end()); 3824 else 3825 Chaining.push_back(VD); 3826 3827 assert(Chaining.size() >= 2); 3828 NamedDecl **NamedChain = 3829 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3830 for (unsigned i = 0; i < Chaining.size(); i++) 3831 NamedChain[i] = Chaining[i]; 3832 3833 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( 3834 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(), 3835 VD->getType(), NamedChain, Chaining.size()); 3836 3837 for (const auto *Attr : VD->attrs()) 3838 IndirectField->addAttr(Attr->clone(SemaRef.Context)); 3839 3840 IndirectField->setAccess(AS); 3841 IndirectField->setImplicit(); 3842 SemaRef.PushOnScopeChains(IndirectField, S); 3843 3844 // That includes picking up the appropriate access specifier. 3845 if (AS != AS_none) IndirectField->setAccess(AS); 3846 3847 Chaining.resize(OldChainingSize); 3848 } 3849 } 3850 } 3851 3852 return Invalid; 3853 } 3854 3855 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3856 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3857 /// illegal input values are mapped to SC_None. 3858 static StorageClass 3859 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3860 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3861 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3862 "Parser allowed 'typedef' as storage class VarDecl."); 3863 switch (StorageClassSpec) { 3864 case DeclSpec::SCS_unspecified: return SC_None; 3865 case DeclSpec::SCS_extern: 3866 if (DS.isExternInLinkageSpec()) 3867 return SC_None; 3868 return SC_Extern; 3869 case DeclSpec::SCS_static: return SC_Static; 3870 case DeclSpec::SCS_auto: return SC_Auto; 3871 case DeclSpec::SCS_register: return SC_Register; 3872 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3873 // Illegal SCSs map to None: error reporting is up to the caller. 3874 case DeclSpec::SCS_mutable: // Fall through. 3875 case DeclSpec::SCS_typedef: return SC_None; 3876 } 3877 llvm_unreachable("unknown storage class specifier"); 3878 } 3879 3880 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3881 assert(Record->hasInClassInitializer()); 3882 3883 for (const auto *I : Record->decls()) { 3884 const auto *FD = dyn_cast<FieldDecl>(I); 3885 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3886 FD = IFD->getAnonField(); 3887 if (FD && FD->hasInClassInitializer()) 3888 return FD->getLocation(); 3889 } 3890 3891 llvm_unreachable("couldn't find in-class initializer"); 3892 } 3893 3894 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3895 SourceLocation DefaultInitLoc) { 3896 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3897 return; 3898 3899 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3900 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3901 } 3902 3903 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3904 CXXRecordDecl *AnonUnion) { 3905 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3906 return; 3907 3908 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3909 } 3910 3911 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3912 /// anonymous structure or union. Anonymous unions are a C++ feature 3913 /// (C++ [class.union]) and a C11 feature; anonymous structures 3914 /// are a C11 feature and GNU C++ extension. 3915 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3916 AccessSpecifier AS, 3917 RecordDecl *Record, 3918 const PrintingPolicy &Policy) { 3919 DeclContext *Owner = Record->getDeclContext(); 3920 3921 // Diagnose whether this anonymous struct/union is an extension. 3922 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3923 Diag(Record->getLocation(), diag::ext_anonymous_union); 3924 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3925 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3926 else if (!Record->isUnion() && !getLangOpts().C11) 3927 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3928 3929 // C and C++ require different kinds of checks for anonymous 3930 // structs/unions. 3931 bool Invalid = false; 3932 if (getLangOpts().CPlusPlus) { 3933 const char *PrevSpec = nullptr; 3934 unsigned DiagID; 3935 if (Record->isUnion()) { 3936 // C++ [class.union]p6: 3937 // Anonymous unions declared in a named namespace or in the 3938 // global namespace shall be declared static. 3939 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3940 (isa<TranslationUnitDecl>(Owner) || 3941 (isa<NamespaceDecl>(Owner) && 3942 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3943 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3944 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3945 3946 // Recover by adding 'static'. 3947 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3948 PrevSpec, DiagID, Policy); 3949 } 3950 // C++ [class.union]p6: 3951 // A storage class is not allowed in a declaration of an 3952 // anonymous union in a class scope. 3953 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3954 isa<RecordDecl>(Owner)) { 3955 Diag(DS.getStorageClassSpecLoc(), 3956 diag::err_anonymous_union_with_storage_spec) 3957 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3958 3959 // Recover by removing the storage specifier. 3960 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3961 SourceLocation(), 3962 PrevSpec, DiagID, Context.getPrintingPolicy()); 3963 } 3964 } 3965 3966 // Ignore const/volatile/restrict qualifiers. 3967 if (DS.getTypeQualifiers()) { 3968 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3969 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3970 << Record->isUnion() << "const" 3971 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3972 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3973 Diag(DS.getVolatileSpecLoc(), 3974 diag::ext_anonymous_struct_union_qualified) 3975 << Record->isUnion() << "volatile" 3976 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3977 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3978 Diag(DS.getRestrictSpecLoc(), 3979 diag::ext_anonymous_struct_union_qualified) 3980 << Record->isUnion() << "restrict" 3981 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3982 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3983 Diag(DS.getAtomicSpecLoc(), 3984 diag::ext_anonymous_struct_union_qualified) 3985 << Record->isUnion() << "_Atomic" 3986 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3987 3988 DS.ClearTypeQualifiers(); 3989 } 3990 3991 // C++ [class.union]p2: 3992 // The member-specification of an anonymous union shall only 3993 // define non-static data members. [Note: nested types and 3994 // functions cannot be declared within an anonymous union. ] 3995 for (auto *Mem : Record->decls()) { 3996 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3997 // C++ [class.union]p3: 3998 // An anonymous union shall not have private or protected 3999 // members (clause 11). 4000 assert(FD->getAccess() != AS_none); 4001 if (FD->getAccess() != AS_public) { 4002 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 4003 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 4004 Invalid = true; 4005 } 4006 4007 // C++ [class.union]p1 4008 // An object of a class with a non-trivial constructor, a non-trivial 4009 // copy constructor, a non-trivial destructor, or a non-trivial copy 4010 // assignment operator cannot be a member of a union, nor can an 4011 // array of such objects. 4012 if (CheckNontrivialField(FD)) 4013 Invalid = true; 4014 } else if (Mem->isImplicit()) { 4015 // Any implicit members are fine. 4016 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 4017 // This is a type that showed up in an 4018 // elaborated-type-specifier inside the anonymous struct or 4019 // union, but which actually declares a type outside of the 4020 // anonymous struct or union. It's okay. 4021 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 4022 if (!MemRecord->isAnonymousStructOrUnion() && 4023 MemRecord->getDeclName()) { 4024 // Visual C++ allows type definition in anonymous struct or union. 4025 if (getLangOpts().MicrosoftExt) 4026 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 4027 << (int)Record->isUnion(); 4028 else { 4029 // This is a nested type declaration. 4030 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 4031 << (int)Record->isUnion(); 4032 Invalid = true; 4033 } 4034 } else { 4035 // This is an anonymous type definition within another anonymous type. 4036 // This is a popular extension, provided by Plan9, MSVC and GCC, but 4037 // not part of standard C++. 4038 Diag(MemRecord->getLocation(), 4039 diag::ext_anonymous_record_with_anonymous_type) 4040 << (int)Record->isUnion(); 4041 } 4042 } else if (isa<AccessSpecDecl>(Mem)) { 4043 // Any access specifier is fine. 4044 } else if (isa<StaticAssertDecl>(Mem)) { 4045 // In C++1z, static_assert declarations are also fine. 4046 } else { 4047 // We have something that isn't a non-static data 4048 // member. Complain about it. 4049 unsigned DK = diag::err_anonymous_record_bad_member; 4050 if (isa<TypeDecl>(Mem)) 4051 DK = diag::err_anonymous_record_with_type; 4052 else if (isa<FunctionDecl>(Mem)) 4053 DK = diag::err_anonymous_record_with_function; 4054 else if (isa<VarDecl>(Mem)) 4055 DK = diag::err_anonymous_record_with_static; 4056 4057 // Visual C++ allows type definition in anonymous struct or union. 4058 if (getLangOpts().MicrosoftExt && 4059 DK == diag::err_anonymous_record_with_type) 4060 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 4061 << (int)Record->isUnion(); 4062 else { 4063 Diag(Mem->getLocation(), DK) 4064 << (int)Record->isUnion(); 4065 Invalid = true; 4066 } 4067 } 4068 } 4069 4070 // C++11 [class.union]p8 (DR1460): 4071 // At most one variant member of a union may have a 4072 // brace-or-equal-initializer. 4073 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 4074 Owner->isRecord()) 4075 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 4076 cast<CXXRecordDecl>(Record)); 4077 } 4078 4079 if (!Record->isUnion() && !Owner->isRecord()) { 4080 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 4081 << (int)getLangOpts().CPlusPlus; 4082 Invalid = true; 4083 } 4084 4085 // Mock up a declarator. 4086 Declarator Dc(DS, Declarator::MemberContext); 4087 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4088 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 4089 4090 // Create a declaration for this anonymous struct/union. 4091 NamedDecl *Anon = nullptr; 4092 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 4093 Anon = FieldDecl::Create(Context, OwningClass, 4094 DS.getLocStart(), 4095 Record->getLocation(), 4096 /*IdentifierInfo=*/nullptr, 4097 Context.getTypeDeclType(Record), 4098 TInfo, 4099 /*BitWidth=*/nullptr, /*Mutable=*/false, 4100 /*InitStyle=*/ICIS_NoInit); 4101 Anon->setAccess(AS); 4102 if (getLangOpts().CPlusPlus) 4103 FieldCollector->Add(cast<FieldDecl>(Anon)); 4104 } else { 4105 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4106 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4107 if (SCSpec == DeclSpec::SCS_mutable) { 4108 // mutable can only appear on non-static class members, so it's always 4109 // an error here 4110 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4111 Invalid = true; 4112 SC = SC_None; 4113 } 4114 4115 Anon = VarDecl::Create(Context, Owner, 4116 DS.getLocStart(), 4117 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4118 Context.getTypeDeclType(Record), 4119 TInfo, SC); 4120 4121 // Default-initialize the implicit variable. This initialization will be 4122 // trivial in almost all cases, except if a union member has an in-class 4123 // initializer: 4124 // union { int n = 0; }; 4125 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4126 } 4127 Anon->setImplicit(); 4128 4129 // Mark this as an anonymous struct/union type. 4130 Record->setAnonymousStructOrUnion(true); 4131 4132 // Add the anonymous struct/union object to the current 4133 // context. We'll be referencing this object when we refer to one of 4134 // its members. 4135 Owner->addDecl(Anon); 4136 4137 // Inject the members of the anonymous struct/union into the owning 4138 // context and into the identifier resolver chain for name lookup 4139 // purposes. 4140 SmallVector<NamedDecl*, 2> Chain; 4141 Chain.push_back(Anon); 4142 4143 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 4144 Chain, false)) 4145 Invalid = true; 4146 4147 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4148 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4149 Decl *ManglingContextDecl; 4150 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 4151 NewVD->getDeclContext(), ManglingContextDecl)) { 4152 Context.setManglingNumber( 4153 NewVD, MCtx->getManglingNumber( 4154 NewVD, getMSManglingNumber(getLangOpts(), S))); 4155 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4156 } 4157 } 4158 } 4159 4160 if (Invalid) 4161 Anon->setInvalidDecl(); 4162 4163 return Anon; 4164 } 4165 4166 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4167 /// Microsoft C anonymous structure. 4168 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4169 /// Example: 4170 /// 4171 /// struct A { int a; }; 4172 /// struct B { struct A; int b; }; 4173 /// 4174 /// void foo() { 4175 /// B var; 4176 /// var.a = 3; 4177 /// } 4178 /// 4179 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4180 RecordDecl *Record) { 4181 assert(Record && "expected a record!"); 4182 4183 // Mock up a declarator. 4184 Declarator Dc(DS, Declarator::TypeNameContext); 4185 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4186 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4187 4188 auto *ParentDecl = cast<RecordDecl>(CurContext); 4189 QualType RecTy = Context.getTypeDeclType(Record); 4190 4191 // Create a declaration for this anonymous struct. 4192 NamedDecl *Anon = FieldDecl::Create(Context, 4193 ParentDecl, 4194 DS.getLocStart(), 4195 DS.getLocStart(), 4196 /*IdentifierInfo=*/nullptr, 4197 RecTy, 4198 TInfo, 4199 /*BitWidth=*/nullptr, /*Mutable=*/false, 4200 /*InitStyle=*/ICIS_NoInit); 4201 Anon->setImplicit(); 4202 4203 // Add the anonymous struct object to the current context. 4204 CurContext->addDecl(Anon); 4205 4206 // Inject the members of the anonymous struct into the current 4207 // context and into the identifier resolver chain for name lookup 4208 // purposes. 4209 SmallVector<NamedDecl*, 2> Chain; 4210 Chain.push_back(Anon); 4211 4212 RecordDecl *RecordDef = Record->getDefinition(); 4213 if (RequireCompleteType(Anon->getLocation(), RecTy, 4214 diag::err_field_incomplete) || 4215 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4216 AS_none, Chain, true)) { 4217 Anon->setInvalidDecl(); 4218 ParentDecl->setInvalidDecl(); 4219 } 4220 4221 return Anon; 4222 } 4223 4224 /// GetNameForDeclarator - Determine the full declaration name for the 4225 /// given Declarator. 4226 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4227 return GetNameFromUnqualifiedId(D.getName()); 4228 } 4229 4230 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4231 DeclarationNameInfo 4232 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4233 DeclarationNameInfo NameInfo; 4234 NameInfo.setLoc(Name.StartLocation); 4235 4236 switch (Name.getKind()) { 4237 4238 case UnqualifiedId::IK_ImplicitSelfParam: 4239 case UnqualifiedId::IK_Identifier: 4240 NameInfo.setName(Name.Identifier); 4241 NameInfo.setLoc(Name.StartLocation); 4242 return NameInfo; 4243 4244 case UnqualifiedId::IK_OperatorFunctionId: 4245 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4246 Name.OperatorFunctionId.Operator)); 4247 NameInfo.setLoc(Name.StartLocation); 4248 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4249 = Name.OperatorFunctionId.SymbolLocations[0]; 4250 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4251 = Name.EndLocation.getRawEncoding(); 4252 return NameInfo; 4253 4254 case UnqualifiedId::IK_LiteralOperatorId: 4255 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4256 Name.Identifier)); 4257 NameInfo.setLoc(Name.StartLocation); 4258 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4259 return NameInfo; 4260 4261 case UnqualifiedId::IK_ConversionFunctionId: { 4262 TypeSourceInfo *TInfo; 4263 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4264 if (Ty.isNull()) 4265 return DeclarationNameInfo(); 4266 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4267 Context.getCanonicalType(Ty))); 4268 NameInfo.setLoc(Name.StartLocation); 4269 NameInfo.setNamedTypeInfo(TInfo); 4270 return NameInfo; 4271 } 4272 4273 case UnqualifiedId::IK_ConstructorName: { 4274 TypeSourceInfo *TInfo; 4275 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4276 if (Ty.isNull()) 4277 return DeclarationNameInfo(); 4278 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4279 Context.getCanonicalType(Ty))); 4280 NameInfo.setLoc(Name.StartLocation); 4281 NameInfo.setNamedTypeInfo(TInfo); 4282 return NameInfo; 4283 } 4284 4285 case UnqualifiedId::IK_ConstructorTemplateId: { 4286 // In well-formed code, we can only have a constructor 4287 // template-id that refers to the current context, so go there 4288 // to find the actual type being constructed. 4289 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4290 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4291 return DeclarationNameInfo(); 4292 4293 // Determine the type of the class being constructed. 4294 QualType CurClassType = Context.getTypeDeclType(CurClass); 4295 4296 // FIXME: Check two things: that the template-id names the same type as 4297 // CurClassType, and that the template-id does not occur when the name 4298 // was qualified. 4299 4300 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4301 Context.getCanonicalType(CurClassType))); 4302 NameInfo.setLoc(Name.StartLocation); 4303 // FIXME: should we retrieve TypeSourceInfo? 4304 NameInfo.setNamedTypeInfo(nullptr); 4305 return NameInfo; 4306 } 4307 4308 case UnqualifiedId::IK_DestructorName: { 4309 TypeSourceInfo *TInfo; 4310 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4311 if (Ty.isNull()) 4312 return DeclarationNameInfo(); 4313 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4314 Context.getCanonicalType(Ty))); 4315 NameInfo.setLoc(Name.StartLocation); 4316 NameInfo.setNamedTypeInfo(TInfo); 4317 return NameInfo; 4318 } 4319 4320 case UnqualifiedId::IK_TemplateId: { 4321 TemplateName TName = Name.TemplateId->Template.get(); 4322 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4323 return Context.getNameForTemplate(TName, TNameLoc); 4324 } 4325 4326 } // switch (Name.getKind()) 4327 4328 llvm_unreachable("Unknown name kind"); 4329 } 4330 4331 static QualType getCoreType(QualType Ty) { 4332 do { 4333 if (Ty->isPointerType() || Ty->isReferenceType()) 4334 Ty = Ty->getPointeeType(); 4335 else if (Ty->isArrayType()) 4336 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4337 else 4338 return Ty.withoutLocalFastQualifiers(); 4339 } while (true); 4340 } 4341 4342 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4343 /// and Definition have "nearly" matching parameters. This heuristic is 4344 /// used to improve diagnostics in the case where an out-of-line function 4345 /// definition doesn't match any declaration within the class or namespace. 4346 /// Also sets Params to the list of indices to the parameters that differ 4347 /// between the declaration and the definition. If hasSimilarParameters 4348 /// returns true and Params is empty, then all of the parameters match. 4349 static bool hasSimilarParameters(ASTContext &Context, 4350 FunctionDecl *Declaration, 4351 FunctionDecl *Definition, 4352 SmallVectorImpl<unsigned> &Params) { 4353 Params.clear(); 4354 if (Declaration->param_size() != Definition->param_size()) 4355 return false; 4356 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4357 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4358 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4359 4360 // The parameter types are identical 4361 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4362 continue; 4363 4364 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4365 QualType DefParamBaseTy = getCoreType(DefParamTy); 4366 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4367 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4368 4369 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4370 (DeclTyName && DeclTyName == DefTyName)) 4371 Params.push_back(Idx); 4372 else // The two parameters aren't even close 4373 return false; 4374 } 4375 4376 return true; 4377 } 4378 4379 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4380 /// declarator needs to be rebuilt in the current instantiation. 4381 /// Any bits of declarator which appear before the name are valid for 4382 /// consideration here. That's specifically the type in the decl spec 4383 /// and the base type in any member-pointer chunks. 4384 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4385 DeclarationName Name) { 4386 // The types we specifically need to rebuild are: 4387 // - typenames, typeofs, and decltypes 4388 // - types which will become injected class names 4389 // Of course, we also need to rebuild any type referencing such a 4390 // type. It's safest to just say "dependent", but we call out a 4391 // few cases here. 4392 4393 DeclSpec &DS = D.getMutableDeclSpec(); 4394 switch (DS.getTypeSpecType()) { 4395 case DeclSpec::TST_typename: 4396 case DeclSpec::TST_typeofType: 4397 case DeclSpec::TST_underlyingType: 4398 case DeclSpec::TST_atomic: { 4399 // Grab the type from the parser. 4400 TypeSourceInfo *TSI = nullptr; 4401 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4402 if (T.isNull() || !T->isDependentType()) break; 4403 4404 // Make sure there's a type source info. This isn't really much 4405 // of a waste; most dependent types should have type source info 4406 // attached already. 4407 if (!TSI) 4408 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4409 4410 // Rebuild the type in the current instantiation. 4411 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4412 if (!TSI) return true; 4413 4414 // Store the new type back in the decl spec. 4415 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4416 DS.UpdateTypeRep(LocType); 4417 break; 4418 } 4419 4420 case DeclSpec::TST_decltype: 4421 case DeclSpec::TST_typeofExpr: { 4422 Expr *E = DS.getRepAsExpr(); 4423 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4424 if (Result.isInvalid()) return true; 4425 DS.UpdateExprRep(Result.get()); 4426 break; 4427 } 4428 4429 default: 4430 // Nothing to do for these decl specs. 4431 break; 4432 } 4433 4434 // It doesn't matter what order we do this in. 4435 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4436 DeclaratorChunk &Chunk = D.getTypeObject(I); 4437 4438 // The only type information in the declarator which can come 4439 // before the declaration name is the base type of a member 4440 // pointer. 4441 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4442 continue; 4443 4444 // Rebuild the scope specifier in-place. 4445 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4446 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4447 return true; 4448 } 4449 4450 return false; 4451 } 4452 4453 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4454 D.setFunctionDefinitionKind(FDK_Declaration); 4455 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4456 4457 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4458 Dcl && Dcl->getDeclContext()->isFileContext()) 4459 Dcl->setTopLevelDeclInObjCContainer(); 4460 4461 return Dcl; 4462 } 4463 4464 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4465 /// If T is the name of a class, then each of the following shall have a 4466 /// name different from T: 4467 /// - every static data member of class T; 4468 /// - every member function of class T 4469 /// - every member of class T that is itself a type; 4470 /// \returns true if the declaration name violates these rules. 4471 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4472 DeclarationNameInfo NameInfo) { 4473 DeclarationName Name = NameInfo.getName(); 4474 4475 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4476 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4477 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4478 return true; 4479 } 4480 4481 return false; 4482 } 4483 4484 /// \brief Diagnose a declaration whose declarator-id has the given 4485 /// nested-name-specifier. 4486 /// 4487 /// \param SS The nested-name-specifier of the declarator-id. 4488 /// 4489 /// \param DC The declaration context to which the nested-name-specifier 4490 /// resolves. 4491 /// 4492 /// \param Name The name of the entity being declared. 4493 /// 4494 /// \param Loc The location of the name of the entity being declared. 4495 /// 4496 /// \returns true if we cannot safely recover from this error, false otherwise. 4497 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4498 DeclarationName Name, 4499 SourceLocation Loc) { 4500 DeclContext *Cur = CurContext; 4501 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4502 Cur = Cur->getParent(); 4503 4504 // If the user provided a superfluous scope specifier that refers back to the 4505 // class in which the entity is already declared, diagnose and ignore it. 4506 // 4507 // class X { 4508 // void X::f(); 4509 // }; 4510 // 4511 // Note, it was once ill-formed to give redundant qualification in all 4512 // contexts, but that rule was removed by DR482. 4513 if (Cur->Equals(DC)) { 4514 if (Cur->isRecord()) { 4515 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4516 : diag::err_member_extra_qualification) 4517 << Name << FixItHint::CreateRemoval(SS.getRange()); 4518 SS.clear(); 4519 } else { 4520 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4521 } 4522 return false; 4523 } 4524 4525 // Check whether the qualifying scope encloses the scope of the original 4526 // declaration. 4527 if (!Cur->Encloses(DC)) { 4528 if (Cur->isRecord()) 4529 Diag(Loc, diag::err_member_qualification) 4530 << Name << SS.getRange(); 4531 else if (isa<TranslationUnitDecl>(DC)) 4532 Diag(Loc, diag::err_invalid_declarator_global_scope) 4533 << Name << SS.getRange(); 4534 else if (isa<FunctionDecl>(Cur)) 4535 Diag(Loc, diag::err_invalid_declarator_in_function) 4536 << Name << SS.getRange(); 4537 else if (isa<BlockDecl>(Cur)) 4538 Diag(Loc, diag::err_invalid_declarator_in_block) 4539 << Name << SS.getRange(); 4540 else 4541 Diag(Loc, diag::err_invalid_declarator_scope) 4542 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4543 4544 return true; 4545 } 4546 4547 if (Cur->isRecord()) { 4548 // Cannot qualify members within a class. 4549 Diag(Loc, diag::err_member_qualification) 4550 << Name << SS.getRange(); 4551 SS.clear(); 4552 4553 // C++ constructors and destructors with incorrect scopes can break 4554 // our AST invariants by having the wrong underlying types. If 4555 // that's the case, then drop this declaration entirely. 4556 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4557 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4558 !Context.hasSameType(Name.getCXXNameType(), 4559 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4560 return true; 4561 4562 return false; 4563 } 4564 4565 // C++11 [dcl.meaning]p1: 4566 // [...] "The nested-name-specifier of the qualified declarator-id shall 4567 // not begin with a decltype-specifer" 4568 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4569 while (SpecLoc.getPrefix()) 4570 SpecLoc = SpecLoc.getPrefix(); 4571 if (dyn_cast_or_null<DecltypeType>( 4572 SpecLoc.getNestedNameSpecifier()->getAsType())) 4573 Diag(Loc, diag::err_decltype_in_declarator) 4574 << SpecLoc.getTypeLoc().getSourceRange(); 4575 4576 return false; 4577 } 4578 4579 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4580 MultiTemplateParamsArg TemplateParamLists) { 4581 // TODO: consider using NameInfo for diagnostic. 4582 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4583 DeclarationName Name = NameInfo.getName(); 4584 4585 // All of these full declarators require an identifier. If it doesn't have 4586 // one, the ParsedFreeStandingDeclSpec action should be used. 4587 if (!Name) { 4588 if (!D.isInvalidType()) // Reject this if we think it is valid. 4589 Diag(D.getDeclSpec().getLocStart(), 4590 diag::err_declarator_need_ident) 4591 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4592 return nullptr; 4593 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4594 return nullptr; 4595 4596 // The scope passed in may not be a decl scope. Zip up the scope tree until 4597 // we find one that is. 4598 while ((S->getFlags() & Scope::DeclScope) == 0 || 4599 (S->getFlags() & Scope::TemplateParamScope) != 0) 4600 S = S->getParent(); 4601 4602 DeclContext *DC = CurContext; 4603 if (D.getCXXScopeSpec().isInvalid()) 4604 D.setInvalidType(); 4605 else if (D.getCXXScopeSpec().isSet()) { 4606 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4607 UPPC_DeclarationQualifier)) 4608 return nullptr; 4609 4610 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4611 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4612 if (!DC || isa<EnumDecl>(DC)) { 4613 // If we could not compute the declaration context, it's because the 4614 // declaration context is dependent but does not refer to a class, 4615 // class template, or class template partial specialization. Complain 4616 // and return early, to avoid the coming semantic disaster. 4617 Diag(D.getIdentifierLoc(), 4618 diag::err_template_qualified_declarator_no_match) 4619 << D.getCXXScopeSpec().getScopeRep() 4620 << D.getCXXScopeSpec().getRange(); 4621 return nullptr; 4622 } 4623 bool IsDependentContext = DC->isDependentContext(); 4624 4625 if (!IsDependentContext && 4626 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4627 return nullptr; 4628 4629 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4630 Diag(D.getIdentifierLoc(), 4631 diag::err_member_def_undefined_record) 4632 << Name << DC << D.getCXXScopeSpec().getRange(); 4633 D.setInvalidType(); 4634 } else if (!D.getDeclSpec().isFriendSpecified()) { 4635 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4636 Name, D.getIdentifierLoc())) { 4637 if (DC->isRecord()) 4638 return nullptr; 4639 4640 D.setInvalidType(); 4641 } 4642 } 4643 4644 // Check whether we need to rebuild the type of the given 4645 // declaration in the current instantiation. 4646 if (EnteringContext && IsDependentContext && 4647 TemplateParamLists.size() != 0) { 4648 ContextRAII SavedContext(*this, DC); 4649 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4650 D.setInvalidType(); 4651 } 4652 } 4653 4654 if (DiagnoseClassNameShadow(DC, NameInfo)) 4655 // If this is a typedef, we'll end up spewing multiple diagnostics. 4656 // Just return early; it's safer. 4657 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4658 return nullptr; 4659 4660 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4661 QualType R = TInfo->getType(); 4662 4663 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4664 UPPC_DeclarationType)) 4665 D.setInvalidType(); 4666 4667 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4668 ForRedeclaration); 4669 4670 // See if this is a redefinition of a variable in the same scope. 4671 if (!D.getCXXScopeSpec().isSet()) { 4672 bool IsLinkageLookup = false; 4673 bool CreateBuiltins = false; 4674 4675 // If the declaration we're planning to build will be a function 4676 // or object with linkage, then look for another declaration with 4677 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4678 // 4679 // If the declaration we're planning to build will be declared with 4680 // external linkage in the translation unit, create any builtin with 4681 // the same name. 4682 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4683 /* Do nothing*/; 4684 else if (CurContext->isFunctionOrMethod() && 4685 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4686 R->isFunctionType())) { 4687 IsLinkageLookup = true; 4688 CreateBuiltins = 4689 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4690 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4691 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4692 CreateBuiltins = true; 4693 4694 if (IsLinkageLookup) 4695 Previous.clear(LookupRedeclarationWithLinkage); 4696 4697 LookupName(Previous, S, CreateBuiltins); 4698 } else { // Something like "int foo::x;" 4699 LookupQualifiedName(Previous, DC); 4700 4701 // C++ [dcl.meaning]p1: 4702 // When the declarator-id is qualified, the declaration shall refer to a 4703 // previously declared member of the class or namespace to which the 4704 // qualifier refers (or, in the case of a namespace, of an element of the 4705 // inline namespace set of that namespace (7.3.1)) or to a specialization 4706 // thereof; [...] 4707 // 4708 // Note that we already checked the context above, and that we do not have 4709 // enough information to make sure that Previous contains the declaration 4710 // we want to match. For example, given: 4711 // 4712 // class X { 4713 // void f(); 4714 // void f(float); 4715 // }; 4716 // 4717 // void X::f(int) { } // ill-formed 4718 // 4719 // In this case, Previous will point to the overload set 4720 // containing the two f's declared in X, but neither of them 4721 // matches. 4722 4723 // C++ [dcl.meaning]p1: 4724 // [...] the member shall not merely have been introduced by a 4725 // using-declaration in the scope of the class or namespace nominated by 4726 // the nested-name-specifier of the declarator-id. 4727 RemoveUsingDecls(Previous); 4728 } 4729 4730 if (Previous.isSingleResult() && 4731 Previous.getFoundDecl()->isTemplateParameter()) { 4732 // Maybe we will complain about the shadowed template parameter. 4733 if (!D.isInvalidType()) 4734 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4735 Previous.getFoundDecl()); 4736 4737 // Just pretend that we didn't see the previous declaration. 4738 Previous.clear(); 4739 } 4740 4741 // In C++, the previous declaration we find might be a tag type 4742 // (class or enum). In this case, the new declaration will hide the 4743 // tag type. Note that this does does not apply if we're declaring a 4744 // typedef (C++ [dcl.typedef]p4). 4745 if (Previous.isSingleTagDecl() && 4746 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4747 Previous.clear(); 4748 4749 // Check that there are no default arguments other than in the parameters 4750 // of a function declaration (C++ only). 4751 if (getLangOpts().CPlusPlus) 4752 CheckExtraCXXDefaultArguments(D); 4753 4754 NamedDecl *New; 4755 4756 bool AddToScope = true; 4757 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4758 if (TemplateParamLists.size()) { 4759 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4760 return nullptr; 4761 } 4762 4763 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4764 } else if (R->isFunctionType()) { 4765 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4766 TemplateParamLists, 4767 AddToScope); 4768 } else { 4769 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4770 AddToScope); 4771 } 4772 4773 if (!New) 4774 return nullptr; 4775 4776 // If this has an identifier and is not an invalid redeclaration or 4777 // function template specialization, add it to the scope stack. 4778 if (New->getDeclName() && AddToScope && 4779 !(D.isRedeclaration() && New->isInvalidDecl())) { 4780 // Only make a locally-scoped extern declaration visible if it is the first 4781 // declaration of this entity. Qualified lookup for such an entity should 4782 // only find this declaration if there is no visible declaration of it. 4783 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4784 PushOnScopeChains(New, S, AddToContext); 4785 if (!AddToContext) 4786 CurContext->addHiddenDecl(New); 4787 } 4788 4789 return New; 4790 } 4791 4792 /// Helper method to turn variable array types into constant array 4793 /// types in certain situations which would otherwise be errors (for 4794 /// GCC compatibility). 4795 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4796 ASTContext &Context, 4797 bool &SizeIsNegative, 4798 llvm::APSInt &Oversized) { 4799 // This method tries to turn a variable array into a constant 4800 // array even when the size isn't an ICE. This is necessary 4801 // for compatibility with code that depends on gcc's buggy 4802 // constant expression folding, like struct {char x[(int)(char*)2];} 4803 SizeIsNegative = false; 4804 Oversized = 0; 4805 4806 if (T->isDependentType()) 4807 return QualType(); 4808 4809 QualifierCollector Qs; 4810 const Type *Ty = Qs.strip(T); 4811 4812 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4813 QualType Pointee = PTy->getPointeeType(); 4814 QualType FixedType = 4815 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4816 Oversized); 4817 if (FixedType.isNull()) return FixedType; 4818 FixedType = Context.getPointerType(FixedType); 4819 return Qs.apply(Context, FixedType); 4820 } 4821 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4822 QualType Inner = PTy->getInnerType(); 4823 QualType FixedType = 4824 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4825 Oversized); 4826 if (FixedType.isNull()) return FixedType; 4827 FixedType = Context.getParenType(FixedType); 4828 return Qs.apply(Context, FixedType); 4829 } 4830 4831 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4832 if (!VLATy) 4833 return QualType(); 4834 // FIXME: We should probably handle this case 4835 if (VLATy->getElementType()->isVariablyModifiedType()) 4836 return QualType(); 4837 4838 llvm::APSInt Res; 4839 if (!VLATy->getSizeExpr() || 4840 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4841 return QualType(); 4842 4843 // Check whether the array size is negative. 4844 if (Res.isSigned() && Res.isNegative()) { 4845 SizeIsNegative = true; 4846 return QualType(); 4847 } 4848 4849 // Check whether the array is too large to be addressed. 4850 unsigned ActiveSizeBits 4851 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4852 Res); 4853 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4854 Oversized = Res; 4855 return QualType(); 4856 } 4857 4858 return Context.getConstantArrayType(VLATy->getElementType(), 4859 Res, ArrayType::Normal, 0); 4860 } 4861 4862 static void 4863 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4864 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4865 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4866 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4867 DstPTL.getPointeeLoc()); 4868 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4869 return; 4870 } 4871 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4872 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4873 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4874 DstPTL.getInnerLoc()); 4875 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4876 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4877 return; 4878 } 4879 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4880 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4881 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4882 TypeLoc DstElemTL = DstATL.getElementLoc(); 4883 DstElemTL.initializeFullCopy(SrcElemTL); 4884 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4885 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4886 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4887 } 4888 4889 /// Helper method to turn variable array types into constant array 4890 /// types in certain situations which would otherwise be errors (for 4891 /// GCC compatibility). 4892 static TypeSourceInfo* 4893 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4894 ASTContext &Context, 4895 bool &SizeIsNegative, 4896 llvm::APSInt &Oversized) { 4897 QualType FixedTy 4898 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4899 SizeIsNegative, Oversized); 4900 if (FixedTy.isNull()) 4901 return nullptr; 4902 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4903 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4904 FixedTInfo->getTypeLoc()); 4905 return FixedTInfo; 4906 } 4907 4908 /// \brief Register the given locally-scoped extern "C" declaration so 4909 /// that it can be found later for redeclarations. We include any extern "C" 4910 /// declaration that is not visible in the translation unit here, not just 4911 /// function-scope declarations. 4912 void 4913 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4914 if (!getLangOpts().CPlusPlus && 4915 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4916 // Don't need to track declarations in the TU in C. 4917 return; 4918 4919 // Note that we have a locally-scoped external with this name. 4920 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND); 4921 } 4922 4923 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4924 // FIXME: We can have multiple results via __attribute__((overloadable)). 4925 auto Result = Context.getExternCContextDecl()->lookup(Name); 4926 return Result.empty() ? nullptr : *Result.begin(); 4927 } 4928 4929 /// \brief Diagnose function specifiers on a declaration of an identifier that 4930 /// does not identify a function. 4931 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4932 // FIXME: We should probably indicate the identifier in question to avoid 4933 // confusion for constructs like "inline int a(), b;" 4934 if (DS.isInlineSpecified()) 4935 Diag(DS.getInlineSpecLoc(), 4936 diag::err_inline_non_function); 4937 4938 if (DS.isVirtualSpecified()) 4939 Diag(DS.getVirtualSpecLoc(), 4940 diag::err_virtual_non_function); 4941 4942 if (DS.isExplicitSpecified()) 4943 Diag(DS.getExplicitSpecLoc(), 4944 diag::err_explicit_non_function); 4945 4946 if (DS.isNoreturnSpecified()) 4947 Diag(DS.getNoreturnSpecLoc(), 4948 diag::err_noreturn_non_function); 4949 } 4950 4951 NamedDecl* 4952 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4953 TypeSourceInfo *TInfo, LookupResult &Previous) { 4954 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4955 if (D.getCXXScopeSpec().isSet()) { 4956 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4957 << D.getCXXScopeSpec().getRange(); 4958 D.setInvalidType(); 4959 // Pretend we didn't see the scope specifier. 4960 DC = CurContext; 4961 Previous.clear(); 4962 } 4963 4964 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4965 4966 if (D.getDeclSpec().isConstexprSpecified()) 4967 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4968 << 1; 4969 4970 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4971 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4972 << D.getName().getSourceRange(); 4973 return nullptr; 4974 } 4975 4976 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4977 if (!NewTD) return nullptr; 4978 4979 // Handle attributes prior to checking for duplicates in MergeVarDecl 4980 ProcessDeclAttributes(S, NewTD, D); 4981 4982 CheckTypedefForVariablyModifiedType(S, NewTD); 4983 4984 bool Redeclaration = D.isRedeclaration(); 4985 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4986 D.setRedeclaration(Redeclaration); 4987 return ND; 4988 } 4989 4990 void 4991 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4992 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4993 // then it shall have block scope. 4994 // Note that variably modified types must be fixed before merging the decl so 4995 // that redeclarations will match. 4996 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4997 QualType T = TInfo->getType(); 4998 if (T->isVariablyModifiedType()) { 4999 getCurFunction()->setHasBranchProtectedScope(); 5000 5001 if (S->getFnParent() == nullptr) { 5002 bool SizeIsNegative; 5003 llvm::APSInt Oversized; 5004 TypeSourceInfo *FixedTInfo = 5005 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 5006 SizeIsNegative, 5007 Oversized); 5008 if (FixedTInfo) { 5009 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 5010 NewTD->setTypeSourceInfo(FixedTInfo); 5011 } else { 5012 if (SizeIsNegative) 5013 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 5014 else if (T->isVariableArrayType()) 5015 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 5016 else if (Oversized.getBoolValue()) 5017 Diag(NewTD->getLocation(), diag::err_array_too_large) 5018 << Oversized.toString(10); 5019 else 5020 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 5021 NewTD->setInvalidDecl(); 5022 } 5023 } 5024 } 5025 } 5026 5027 5028 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 5029 /// declares a typedef-name, either using the 'typedef' type specifier or via 5030 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 5031 NamedDecl* 5032 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 5033 LookupResult &Previous, bool &Redeclaration) { 5034 // Merge the decl with the existing one if appropriate. If the decl is 5035 // in an outer scope, it isn't the same thing. 5036 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 5037 /*AllowInlineNamespace*/false); 5038 filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous); 5039 if (!Previous.empty()) { 5040 Redeclaration = true; 5041 MergeTypedefNameDecl(NewTD, Previous); 5042 } 5043 5044 // If this is the C FILE type, notify the AST context. 5045 if (IdentifierInfo *II = NewTD->getIdentifier()) 5046 if (!NewTD->isInvalidDecl() && 5047 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 5048 if (II->isStr("FILE")) 5049 Context.setFILEDecl(NewTD); 5050 else if (II->isStr("jmp_buf")) 5051 Context.setjmp_bufDecl(NewTD); 5052 else if (II->isStr("sigjmp_buf")) 5053 Context.setsigjmp_bufDecl(NewTD); 5054 else if (II->isStr("ucontext_t")) 5055 Context.setucontext_tDecl(NewTD); 5056 } 5057 5058 return NewTD; 5059 } 5060 5061 /// \brief Determines whether the given declaration is an out-of-scope 5062 /// previous declaration. 5063 /// 5064 /// This routine should be invoked when name lookup has found a 5065 /// previous declaration (PrevDecl) that is not in the scope where a 5066 /// new declaration by the same name is being introduced. If the new 5067 /// declaration occurs in a local scope, previous declarations with 5068 /// linkage may still be considered previous declarations (C99 5069 /// 6.2.2p4-5, C++ [basic.link]p6). 5070 /// 5071 /// \param PrevDecl the previous declaration found by name 5072 /// lookup 5073 /// 5074 /// \param DC the context in which the new declaration is being 5075 /// declared. 5076 /// 5077 /// \returns true if PrevDecl is an out-of-scope previous declaration 5078 /// for a new delcaration with the same name. 5079 static bool 5080 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 5081 ASTContext &Context) { 5082 if (!PrevDecl) 5083 return false; 5084 5085 if (!PrevDecl->hasLinkage()) 5086 return false; 5087 5088 if (Context.getLangOpts().CPlusPlus) { 5089 // C++ [basic.link]p6: 5090 // If there is a visible declaration of an entity with linkage 5091 // having the same name and type, ignoring entities declared 5092 // outside the innermost enclosing namespace scope, the block 5093 // scope declaration declares that same entity and receives the 5094 // linkage of the previous declaration. 5095 DeclContext *OuterContext = DC->getRedeclContext(); 5096 if (!OuterContext->isFunctionOrMethod()) 5097 // This rule only applies to block-scope declarations. 5098 return false; 5099 5100 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5101 if (PrevOuterContext->isRecord()) 5102 // We found a member function: ignore it. 5103 return false; 5104 5105 // Find the innermost enclosing namespace for the new and 5106 // previous declarations. 5107 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5108 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5109 5110 // The previous declaration is in a different namespace, so it 5111 // isn't the same function. 5112 if (!OuterContext->Equals(PrevOuterContext)) 5113 return false; 5114 } 5115 5116 return true; 5117 } 5118 5119 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5120 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5121 if (!SS.isSet()) return; 5122 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5123 } 5124 5125 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5126 QualType type = decl->getType(); 5127 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5128 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5129 // Various kinds of declaration aren't allowed to be __autoreleasing. 5130 unsigned kind = -1U; 5131 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5132 if (var->hasAttr<BlocksAttr>()) 5133 kind = 0; // __block 5134 else if (!var->hasLocalStorage()) 5135 kind = 1; // global 5136 } else if (isa<ObjCIvarDecl>(decl)) { 5137 kind = 3; // ivar 5138 } else if (isa<FieldDecl>(decl)) { 5139 kind = 2; // field 5140 } 5141 5142 if (kind != -1U) { 5143 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5144 << kind; 5145 } 5146 } else if (lifetime == Qualifiers::OCL_None) { 5147 // Try to infer lifetime. 5148 if (!type->isObjCLifetimeType()) 5149 return false; 5150 5151 lifetime = type->getObjCARCImplicitLifetime(); 5152 type = Context.getLifetimeQualifiedType(type, lifetime); 5153 decl->setType(type); 5154 } 5155 5156 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5157 // Thread-local variables cannot have lifetime. 5158 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5159 var->getTLSKind()) { 5160 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5161 << var->getType(); 5162 return true; 5163 } 5164 } 5165 5166 return false; 5167 } 5168 5169 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5170 // Ensure that an auto decl is deduced otherwise the checks below might cache 5171 // the wrong linkage. 5172 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5173 5174 // 'weak' only applies to declarations with external linkage. 5175 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5176 if (!ND.isExternallyVisible()) { 5177 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5178 ND.dropAttr<WeakAttr>(); 5179 } 5180 } 5181 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5182 if (ND.isExternallyVisible()) { 5183 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5184 ND.dropAttr<WeakRefAttr>(); 5185 ND.dropAttr<AliasAttr>(); 5186 } 5187 } 5188 5189 if (auto *VD = dyn_cast<VarDecl>(&ND)) { 5190 if (VD->hasInit()) { 5191 if (const auto *Attr = VD->getAttr<AliasAttr>()) { 5192 assert(VD->isThisDeclarationADefinition() && 5193 !VD->isExternallyVisible() && "Broken AliasAttr handled late!"); 5194 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD; 5195 VD->dropAttr<AliasAttr>(); 5196 } 5197 } 5198 } 5199 5200 // 'selectany' only applies to externally visible varable declarations. 5201 // It does not apply to functions. 5202 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5203 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5204 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 5205 ND.dropAttr<SelectAnyAttr>(); 5206 } 5207 } 5208 5209 // dll attributes require external linkage. 5210 if (const InheritableAttr *Attr = getDLLAttr(&ND)) { 5211 if (!ND.isExternallyVisible()) { 5212 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5213 << &ND << Attr; 5214 ND.setInvalidDecl(); 5215 } 5216 } 5217 } 5218 5219 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5220 NamedDecl *NewDecl, 5221 bool IsSpecialization) { 5222 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5223 OldDecl = OldTD->getTemplatedDecl(); 5224 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5225 NewDecl = NewTD->getTemplatedDecl(); 5226 5227 if (!OldDecl || !NewDecl) 5228 return; 5229 5230 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5231 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5232 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5233 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5234 5235 // dllimport and dllexport are inheritable attributes so we have to exclude 5236 // inherited attribute instances. 5237 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5238 (NewExportAttr && !NewExportAttr->isInherited()); 5239 5240 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5241 // the only exception being explicit specializations. 5242 // Implicitly generated declarations are also excluded for now because there 5243 // is no other way to switch these to use dllimport or dllexport. 5244 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5245 5246 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5247 // If the declaration hasn't been used yet, allow with a warning for 5248 // free functions and global variables. 5249 bool JustWarn = false; 5250 if (!OldDecl->isUsed() && !OldDecl->isCXXClassMember()) { 5251 auto *VD = dyn_cast<VarDecl>(OldDecl); 5252 if (VD && !VD->getDescribedVarTemplate()) 5253 JustWarn = true; 5254 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5255 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5256 JustWarn = true; 5257 } 5258 5259 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5260 : diag::err_attribute_dll_redeclaration; 5261 S.Diag(NewDecl->getLocation(), DiagID) 5262 << NewDecl 5263 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5264 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5265 if (!JustWarn) { 5266 NewDecl->setInvalidDecl(); 5267 return; 5268 } 5269 } 5270 5271 // A redeclaration is not allowed to drop a dllimport attribute, the only 5272 // exceptions being inline function definitions, local extern declarations, 5273 // and qualified friend declarations. 5274 // NB: MSVC converts such a declaration to dllexport. 5275 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5276 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5277 // Ignore static data because out-of-line definitions are diagnosed 5278 // separately. 5279 IsStaticDataMember = VD->isStaticDataMember(); 5280 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5281 IsInline = FD->isInlined(); 5282 IsQualifiedFriend = FD->getQualifier() && 5283 FD->getFriendObjectKind() == Decl::FOK_Declared; 5284 } 5285 5286 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5287 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5288 S.Diag(NewDecl->getLocation(), 5289 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5290 << NewDecl << OldImportAttr; 5291 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5292 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5293 OldDecl->dropAttr<DLLImportAttr>(); 5294 NewDecl->dropAttr<DLLImportAttr>(); 5295 } else if (IsInline && OldImportAttr && 5296 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5297 // In MinGW, seeing a function declared inline drops the dllimport attribute. 5298 OldDecl->dropAttr<DLLImportAttr>(); 5299 NewDecl->dropAttr<DLLImportAttr>(); 5300 S.Diag(NewDecl->getLocation(), 5301 diag::warn_dllimport_dropped_from_inline_function) 5302 << NewDecl << OldImportAttr; 5303 } 5304 } 5305 5306 /// Given that we are within the definition of the given function, 5307 /// will that definition behave like C99's 'inline', where the 5308 /// definition is discarded except for optimization purposes? 5309 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5310 // Try to avoid calling GetGVALinkageForFunction. 5311 5312 // All cases of this require the 'inline' keyword. 5313 if (!FD->isInlined()) return false; 5314 5315 // This is only possible in C++ with the gnu_inline attribute. 5316 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5317 return false; 5318 5319 // Okay, go ahead and call the relatively-more-expensive function. 5320 5321 #ifndef NDEBUG 5322 // AST quite reasonably asserts that it's working on a function 5323 // definition. We don't really have a way to tell it that we're 5324 // currently defining the function, so just lie to it in +Asserts 5325 // builds. This is an awful hack. 5326 FD->setLazyBody(1); 5327 #endif 5328 5329 bool isC99Inline = 5330 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5331 5332 #ifndef NDEBUG 5333 FD->setLazyBody(0); 5334 #endif 5335 5336 return isC99Inline; 5337 } 5338 5339 /// Determine whether a variable is extern "C" prior to attaching 5340 /// an initializer. We can't just call isExternC() here, because that 5341 /// will also compute and cache whether the declaration is externally 5342 /// visible, which might change when we attach the initializer. 5343 /// 5344 /// This can only be used if the declaration is known to not be a 5345 /// redeclaration of an internal linkage declaration. 5346 /// 5347 /// For instance: 5348 /// 5349 /// auto x = []{}; 5350 /// 5351 /// Attaching the initializer here makes this declaration not externally 5352 /// visible, because its type has internal linkage. 5353 /// 5354 /// FIXME: This is a hack. 5355 template<typename T> 5356 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5357 if (S.getLangOpts().CPlusPlus) { 5358 // In C++, the overloadable attribute negates the effects of extern "C". 5359 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5360 return false; 5361 } 5362 return D->isExternC(); 5363 } 5364 5365 static bool shouldConsiderLinkage(const VarDecl *VD) { 5366 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5367 if (DC->isFunctionOrMethod()) 5368 return VD->hasExternalStorage(); 5369 if (DC->isFileContext()) 5370 return true; 5371 if (DC->isRecord()) 5372 return false; 5373 llvm_unreachable("Unexpected context"); 5374 } 5375 5376 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5377 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5378 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5379 return true; 5380 if (DC->isRecord()) 5381 return false; 5382 llvm_unreachable("Unexpected context"); 5383 } 5384 5385 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5386 AttributeList::Kind Kind) { 5387 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5388 if (L->getKind() == Kind) 5389 return true; 5390 return false; 5391 } 5392 5393 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5394 AttributeList::Kind Kind) { 5395 // Check decl attributes on the DeclSpec. 5396 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5397 return true; 5398 5399 // Walk the declarator structure, checking decl attributes that were in a type 5400 // position to the decl itself. 5401 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5402 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5403 return true; 5404 } 5405 5406 // Finally, check attributes on the decl itself. 5407 return hasParsedAttr(S, PD.getAttributes(), Kind); 5408 } 5409 5410 /// Adjust the \c DeclContext for a function or variable that might be a 5411 /// function-local external declaration. 5412 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5413 if (!DC->isFunctionOrMethod()) 5414 return false; 5415 5416 // If this is a local extern function or variable declared within a function 5417 // template, don't add it into the enclosing namespace scope until it is 5418 // instantiated; it might have a dependent type right now. 5419 if (DC->isDependentContext()) 5420 return true; 5421 5422 // C++11 [basic.link]p7: 5423 // When a block scope declaration of an entity with linkage is not found to 5424 // refer to some other declaration, then that entity is a member of the 5425 // innermost enclosing namespace. 5426 // 5427 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5428 // semantically-enclosing namespace, not a lexically-enclosing one. 5429 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5430 DC = DC->getParent(); 5431 return true; 5432 } 5433 5434 NamedDecl * 5435 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5436 TypeSourceInfo *TInfo, LookupResult &Previous, 5437 MultiTemplateParamsArg TemplateParamLists, 5438 bool &AddToScope) { 5439 QualType R = TInfo->getType(); 5440 DeclarationName Name = GetNameForDeclarator(D).getName(); 5441 5442 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5443 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5444 5445 // dllimport globals without explicit storage class are treated as extern. We 5446 // have to change the storage class this early to get the right DeclContext. 5447 if (SC == SC_None && !DC->isRecord() && 5448 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5449 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5450 SC = SC_Extern; 5451 5452 DeclContext *OriginalDC = DC; 5453 bool IsLocalExternDecl = SC == SC_Extern && 5454 adjustContextForLocalExternDecl(DC); 5455 5456 if (getLangOpts().OpenCL) { 5457 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5458 QualType NR = R; 5459 while (NR->isPointerType()) { 5460 if (NR->isFunctionPointerType()) { 5461 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5462 D.setInvalidType(); 5463 break; 5464 } 5465 NR = NR->getPointeeType(); 5466 } 5467 5468 if (!getOpenCLOptions().cl_khr_fp16) { 5469 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5470 // half array type (unless the cl_khr_fp16 extension is enabled). 5471 if (Context.getBaseElementType(R)->isHalfType()) { 5472 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5473 D.setInvalidType(); 5474 } 5475 } 5476 } 5477 5478 if (SCSpec == DeclSpec::SCS_mutable) { 5479 // mutable can only appear on non-static class members, so it's always 5480 // an error here 5481 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5482 D.setInvalidType(); 5483 SC = SC_None; 5484 } 5485 5486 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5487 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5488 D.getDeclSpec().getStorageClassSpecLoc())) { 5489 // In C++11, the 'register' storage class specifier is deprecated. 5490 // Suppress the warning in system macros, it's used in macros in some 5491 // popular C system headers, such as in glibc's htonl() macro. 5492 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5493 diag::warn_deprecated_register) 5494 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5495 } 5496 5497 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5498 if (!II) { 5499 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5500 << Name; 5501 return nullptr; 5502 } 5503 5504 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5505 5506 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5507 // C99 6.9p2: The storage-class specifiers auto and register shall not 5508 // appear in the declaration specifiers in an external declaration. 5509 // Global Register+Asm is a GNU extension we support. 5510 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5511 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5512 D.setInvalidType(); 5513 } 5514 } 5515 5516 if (getLangOpts().OpenCL) { 5517 // Set up the special work-group-local storage class for variables in the 5518 // OpenCL __local address space. 5519 if (R.getAddressSpace() == LangAS::opencl_local) { 5520 SC = SC_OpenCLWorkGroupLocal; 5521 } 5522 5523 // OpenCL v1.2 s6.9.b p4: 5524 // The sampler type cannot be used with the __local and __global address 5525 // space qualifiers. 5526 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5527 R.getAddressSpace() == LangAS::opencl_global)) { 5528 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5529 } 5530 5531 // OpenCL 1.2 spec, p6.9 r: 5532 // The event type cannot be used to declare a program scope variable. 5533 // The event type cannot be used with the __local, __constant and __global 5534 // address space qualifiers. 5535 if (R->isEventT()) { 5536 if (S->getParent() == nullptr) { 5537 Diag(D.getLocStart(), diag::err_event_t_global_var); 5538 D.setInvalidType(); 5539 } 5540 5541 if (R.getAddressSpace()) { 5542 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5543 D.setInvalidType(); 5544 } 5545 } 5546 } 5547 5548 bool IsExplicitSpecialization = false; 5549 bool IsVariableTemplateSpecialization = false; 5550 bool IsPartialSpecialization = false; 5551 bool IsVariableTemplate = false; 5552 VarDecl *NewVD = nullptr; 5553 VarTemplateDecl *NewTemplate = nullptr; 5554 TemplateParameterList *TemplateParams = nullptr; 5555 if (!getLangOpts().CPlusPlus) { 5556 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5557 D.getIdentifierLoc(), II, 5558 R, TInfo, SC); 5559 5560 if (D.isInvalidType()) 5561 NewVD->setInvalidDecl(); 5562 } else { 5563 bool Invalid = false; 5564 5565 if (DC->isRecord() && !CurContext->isRecord()) { 5566 // This is an out-of-line definition of a static data member. 5567 switch (SC) { 5568 case SC_None: 5569 break; 5570 case SC_Static: 5571 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5572 diag::err_static_out_of_line) 5573 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5574 break; 5575 case SC_Auto: 5576 case SC_Register: 5577 case SC_Extern: 5578 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5579 // to names of variables declared in a block or to function parameters. 5580 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5581 // of class members 5582 5583 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5584 diag::err_storage_class_for_static_member) 5585 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5586 break; 5587 case SC_PrivateExtern: 5588 llvm_unreachable("C storage class in c++!"); 5589 case SC_OpenCLWorkGroupLocal: 5590 llvm_unreachable("OpenCL storage class in c++!"); 5591 } 5592 } 5593 5594 if (SC == SC_Static && CurContext->isRecord()) { 5595 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5596 if (RD->isLocalClass()) 5597 Diag(D.getIdentifierLoc(), 5598 diag::err_static_data_member_not_allowed_in_local_class) 5599 << Name << RD->getDeclName(); 5600 5601 // C++98 [class.union]p1: If a union contains a static data member, 5602 // the program is ill-formed. C++11 drops this restriction. 5603 if (RD->isUnion()) 5604 Diag(D.getIdentifierLoc(), 5605 getLangOpts().CPlusPlus11 5606 ? diag::warn_cxx98_compat_static_data_member_in_union 5607 : diag::ext_static_data_member_in_union) << Name; 5608 // We conservatively disallow static data members in anonymous structs. 5609 else if (!RD->getDeclName()) 5610 Diag(D.getIdentifierLoc(), 5611 diag::err_static_data_member_not_allowed_in_anon_struct) 5612 << Name << RD->isUnion(); 5613 } 5614 } 5615 5616 // Match up the template parameter lists with the scope specifier, then 5617 // determine whether we have a template or a template specialization. 5618 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5619 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5620 D.getCXXScopeSpec(), 5621 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5622 ? D.getName().TemplateId 5623 : nullptr, 5624 TemplateParamLists, 5625 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5626 5627 if (TemplateParams) { 5628 if (!TemplateParams->size() && 5629 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5630 // There is an extraneous 'template<>' for this variable. Complain 5631 // about it, but allow the declaration of the variable. 5632 Diag(TemplateParams->getTemplateLoc(), 5633 diag::err_template_variable_noparams) 5634 << II 5635 << SourceRange(TemplateParams->getTemplateLoc(), 5636 TemplateParams->getRAngleLoc()); 5637 TemplateParams = nullptr; 5638 } else { 5639 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5640 // This is an explicit specialization or a partial specialization. 5641 // FIXME: Check that we can declare a specialization here. 5642 IsVariableTemplateSpecialization = true; 5643 IsPartialSpecialization = TemplateParams->size() > 0; 5644 } else { // if (TemplateParams->size() > 0) 5645 // This is a template declaration. 5646 IsVariableTemplate = true; 5647 5648 // Check that we can declare a template here. 5649 if (CheckTemplateDeclScope(S, TemplateParams)) 5650 return nullptr; 5651 5652 // Only C++1y supports variable templates (N3651). 5653 Diag(D.getIdentifierLoc(), 5654 getLangOpts().CPlusPlus14 5655 ? diag::warn_cxx11_compat_variable_template 5656 : diag::ext_variable_template); 5657 } 5658 } 5659 } else { 5660 assert( 5661 (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) && 5662 "should have a 'template<>' for this decl"); 5663 } 5664 5665 if (IsVariableTemplateSpecialization) { 5666 SourceLocation TemplateKWLoc = 5667 TemplateParamLists.size() > 0 5668 ? TemplateParamLists[0]->getTemplateLoc() 5669 : SourceLocation(); 5670 DeclResult Res = ActOnVarTemplateSpecialization( 5671 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5672 IsPartialSpecialization); 5673 if (Res.isInvalid()) 5674 return nullptr; 5675 NewVD = cast<VarDecl>(Res.get()); 5676 AddToScope = false; 5677 } else 5678 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5679 D.getIdentifierLoc(), II, R, TInfo, SC); 5680 5681 // If this is supposed to be a variable template, create it as such. 5682 if (IsVariableTemplate) { 5683 NewTemplate = 5684 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5685 TemplateParams, NewVD); 5686 NewVD->setDescribedVarTemplate(NewTemplate); 5687 } 5688 5689 // If this decl has an auto type in need of deduction, make a note of the 5690 // Decl so we can diagnose uses of it in its own initializer. 5691 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5692 ParsingInitForAutoVars.insert(NewVD); 5693 5694 if (D.isInvalidType() || Invalid) { 5695 NewVD->setInvalidDecl(); 5696 if (NewTemplate) 5697 NewTemplate->setInvalidDecl(); 5698 } 5699 5700 SetNestedNameSpecifier(NewVD, D); 5701 5702 // If we have any template parameter lists that don't directly belong to 5703 // the variable (matching the scope specifier), store them. 5704 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5705 if (TemplateParamLists.size() > VDTemplateParamLists) 5706 NewVD->setTemplateParameterListsInfo( 5707 Context, TemplateParamLists.size() - VDTemplateParamLists, 5708 TemplateParamLists.data()); 5709 5710 if (D.getDeclSpec().isConstexprSpecified()) 5711 NewVD->setConstexpr(true); 5712 } 5713 5714 // Set the lexical context. If the declarator has a C++ scope specifier, the 5715 // lexical context will be different from the semantic context. 5716 NewVD->setLexicalDeclContext(CurContext); 5717 if (NewTemplate) 5718 NewTemplate->setLexicalDeclContext(CurContext); 5719 5720 if (IsLocalExternDecl) 5721 NewVD->setLocalExternDecl(); 5722 5723 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5724 // C++11 [dcl.stc]p4: 5725 // When thread_local is applied to a variable of block scope the 5726 // storage-class-specifier static is implied if it does not appear 5727 // explicitly. 5728 // Core issue: 'static' is not implied if the variable is declared 5729 // 'extern'. 5730 if (NewVD->hasLocalStorage() && 5731 (SCSpec != DeclSpec::SCS_unspecified || 5732 TSCS != DeclSpec::TSCS_thread_local || 5733 !DC->isFunctionOrMethod())) 5734 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5735 diag::err_thread_non_global) 5736 << DeclSpec::getSpecifierName(TSCS); 5737 else if (!Context.getTargetInfo().isTLSSupported()) 5738 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5739 diag::err_thread_unsupported); 5740 else 5741 NewVD->setTSCSpec(TSCS); 5742 } 5743 5744 // C99 6.7.4p3 5745 // An inline definition of a function with external linkage shall 5746 // not contain a definition of a modifiable object with static or 5747 // thread storage duration... 5748 // We only apply this when the function is required to be defined 5749 // elsewhere, i.e. when the function is not 'extern inline'. Note 5750 // that a local variable with thread storage duration still has to 5751 // be marked 'static'. Also note that it's possible to get these 5752 // semantics in C++ using __attribute__((gnu_inline)). 5753 if (SC == SC_Static && S->getFnParent() != nullptr && 5754 !NewVD->getType().isConstQualified()) { 5755 FunctionDecl *CurFD = getCurFunctionDecl(); 5756 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5757 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5758 diag::warn_static_local_in_extern_inline); 5759 MaybeSuggestAddingStaticToDecl(CurFD); 5760 } 5761 } 5762 5763 if (D.getDeclSpec().isModulePrivateSpecified()) { 5764 if (IsVariableTemplateSpecialization) 5765 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5766 << (IsPartialSpecialization ? 1 : 0) 5767 << FixItHint::CreateRemoval( 5768 D.getDeclSpec().getModulePrivateSpecLoc()); 5769 else if (IsExplicitSpecialization) 5770 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5771 << 2 5772 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5773 else if (NewVD->hasLocalStorage()) 5774 Diag(NewVD->getLocation(), diag::err_module_private_local) 5775 << 0 << NewVD->getDeclName() 5776 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5777 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5778 else { 5779 NewVD->setModulePrivate(); 5780 if (NewTemplate) 5781 NewTemplate->setModulePrivate(); 5782 } 5783 } 5784 5785 // Handle attributes prior to checking for duplicates in MergeVarDecl 5786 ProcessDeclAttributes(S, NewVD, D); 5787 5788 if (getLangOpts().CUDA) { 5789 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5790 // storage [duration]." 5791 if (SC == SC_None && S->getFnParent() != nullptr && 5792 (NewVD->hasAttr<CUDASharedAttr>() || 5793 NewVD->hasAttr<CUDAConstantAttr>())) { 5794 NewVD->setStorageClass(SC_Static); 5795 } 5796 } 5797 5798 // Ensure that dllimport globals without explicit storage class are treated as 5799 // extern. The storage class is set above using parsed attributes. Now we can 5800 // check the VarDecl itself. 5801 assert(!NewVD->hasAttr<DLLImportAttr>() || 5802 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5803 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5804 5805 // In auto-retain/release, infer strong retension for variables of 5806 // retainable type. 5807 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5808 NewVD->setInvalidDecl(); 5809 5810 // Handle GNU asm-label extension (encoded as an attribute). 5811 if (Expr *E = (Expr*)D.getAsmLabel()) { 5812 // The parser guarantees this is a string. 5813 StringLiteral *SE = cast<StringLiteral>(E); 5814 StringRef Label = SE->getString(); 5815 if (S->getFnParent() != nullptr) { 5816 switch (SC) { 5817 case SC_None: 5818 case SC_Auto: 5819 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5820 break; 5821 case SC_Register: 5822 // Local Named register 5823 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5824 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5825 break; 5826 case SC_Static: 5827 case SC_Extern: 5828 case SC_PrivateExtern: 5829 case SC_OpenCLWorkGroupLocal: 5830 break; 5831 } 5832 } else if (SC == SC_Register) { 5833 // Global Named register 5834 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5835 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5836 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5837 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5838 NewVD->setInvalidDecl(true); 5839 } 5840 } 5841 5842 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5843 Context, Label, 0)); 5844 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5845 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5846 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5847 if (I != ExtnameUndeclaredIdentifiers.end()) { 5848 NewVD->addAttr(I->second); 5849 ExtnameUndeclaredIdentifiers.erase(I); 5850 } 5851 } 5852 5853 // Diagnose shadowed variables before filtering for scope. 5854 if (D.getCXXScopeSpec().isEmpty()) 5855 CheckShadow(S, NewVD, Previous); 5856 5857 // Don't consider existing declarations that are in a different 5858 // scope and are out-of-semantic-context declarations (if the new 5859 // declaration has linkage). 5860 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5861 D.getCXXScopeSpec().isNotEmpty() || 5862 IsExplicitSpecialization || 5863 IsVariableTemplateSpecialization); 5864 5865 // Check whether the previous declaration is in the same block scope. This 5866 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5867 if (getLangOpts().CPlusPlus && 5868 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5869 NewVD->setPreviousDeclInSameBlockScope( 5870 Previous.isSingleResult() && !Previous.isShadowed() && 5871 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5872 5873 if (!getLangOpts().CPlusPlus) { 5874 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5875 } else { 5876 // If this is an explicit specialization of a static data member, check it. 5877 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5878 CheckMemberSpecialization(NewVD, Previous)) 5879 NewVD->setInvalidDecl(); 5880 5881 // Merge the decl with the existing one if appropriate. 5882 if (!Previous.empty()) { 5883 if (Previous.isSingleResult() && 5884 isa<FieldDecl>(Previous.getFoundDecl()) && 5885 D.getCXXScopeSpec().isSet()) { 5886 // The user tried to define a non-static data member 5887 // out-of-line (C++ [dcl.meaning]p1). 5888 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5889 << D.getCXXScopeSpec().getRange(); 5890 Previous.clear(); 5891 NewVD->setInvalidDecl(); 5892 } 5893 } else if (D.getCXXScopeSpec().isSet()) { 5894 // No previous declaration in the qualifying scope. 5895 Diag(D.getIdentifierLoc(), diag::err_no_member) 5896 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5897 << D.getCXXScopeSpec().getRange(); 5898 NewVD->setInvalidDecl(); 5899 } 5900 5901 if (!IsVariableTemplateSpecialization) 5902 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5903 5904 if (NewTemplate) { 5905 VarTemplateDecl *PrevVarTemplate = 5906 NewVD->getPreviousDecl() 5907 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5908 : nullptr; 5909 5910 // Check the template parameter list of this declaration, possibly 5911 // merging in the template parameter list from the previous variable 5912 // template declaration. 5913 if (CheckTemplateParameterList( 5914 TemplateParams, 5915 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5916 : nullptr, 5917 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5918 DC->isDependentContext()) 5919 ? TPC_ClassTemplateMember 5920 : TPC_VarTemplate)) 5921 NewVD->setInvalidDecl(); 5922 5923 // If we are providing an explicit specialization of a static variable 5924 // template, make a note of that. 5925 if (PrevVarTemplate && 5926 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5927 PrevVarTemplate->setMemberSpecialization(); 5928 } 5929 } 5930 5931 ProcessPragmaWeak(S, NewVD); 5932 5933 // If this is the first declaration of an extern C variable, update 5934 // the map of such variables. 5935 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5936 isIncompleteDeclExternC(*this, NewVD)) 5937 RegisterLocallyScopedExternCDecl(NewVD, S); 5938 5939 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5940 Decl *ManglingContextDecl; 5941 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext( 5942 NewVD->getDeclContext(), ManglingContextDecl)) { 5943 Context.setManglingNumber( 5944 NewVD, MCtx->getManglingNumber( 5945 NewVD, getMSManglingNumber(getLangOpts(), S))); 5946 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5947 } 5948 } 5949 5950 if (D.isRedeclaration() && !Previous.empty()) { 5951 checkDLLAttributeRedeclaration( 5952 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5953 IsExplicitSpecialization); 5954 } 5955 5956 if (NewTemplate) { 5957 if (NewVD->isInvalidDecl()) 5958 NewTemplate->setInvalidDecl(); 5959 ActOnDocumentableDecl(NewTemplate); 5960 return NewTemplate; 5961 } 5962 5963 return NewVD; 5964 } 5965 5966 /// \brief Diagnose variable or built-in function shadowing. Implements 5967 /// -Wshadow. 5968 /// 5969 /// This method is called whenever a VarDecl is added to a "useful" 5970 /// scope. 5971 /// 5972 /// \param S the scope in which the shadowing name is being declared 5973 /// \param R the lookup of the name 5974 /// 5975 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5976 // Return if warning is ignored. 5977 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 5978 return; 5979 5980 // Don't diagnose declarations at file scope. 5981 if (D->hasGlobalStorage()) 5982 return; 5983 5984 DeclContext *NewDC = D->getDeclContext(); 5985 5986 // Only diagnose if we're shadowing an unambiguous field or variable. 5987 if (R.getResultKind() != LookupResult::Found) 5988 return; 5989 5990 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5991 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5992 return; 5993 5994 // Fields are not shadowed by variables in C++ static methods. 5995 if (isa<FieldDecl>(ShadowedDecl)) 5996 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5997 if (MD->isStatic()) 5998 return; 5999 6000 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 6001 if (shadowedVar->isExternC()) { 6002 // For shadowing external vars, make sure that we point to the global 6003 // declaration, not a locally scoped extern declaration. 6004 for (auto I : shadowedVar->redecls()) 6005 if (I->isFileVarDecl()) { 6006 ShadowedDecl = I; 6007 break; 6008 } 6009 } 6010 6011 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 6012 6013 // Only warn about certain kinds of shadowing for class members. 6014 if (NewDC && NewDC->isRecord()) { 6015 // In particular, don't warn about shadowing non-class members. 6016 if (!OldDC->isRecord()) 6017 return; 6018 6019 // TODO: should we warn about static data members shadowing 6020 // static data members from base classes? 6021 6022 // TODO: don't diagnose for inaccessible shadowed members. 6023 // This is hard to do perfectly because we might friend the 6024 // shadowing context, but that's just a false negative. 6025 } 6026 6027 // Determine what kind of declaration we're shadowing. 6028 unsigned Kind; 6029 if (isa<RecordDecl>(OldDC)) { 6030 if (isa<FieldDecl>(ShadowedDecl)) 6031 Kind = 3; // field 6032 else 6033 Kind = 2; // static data member 6034 } else if (OldDC->isFileContext()) 6035 Kind = 1; // global 6036 else 6037 Kind = 0; // local 6038 6039 DeclarationName Name = R.getLookupName(); 6040 6041 // Emit warning and note. 6042 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 6043 return; 6044 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 6045 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 6046 } 6047 6048 /// \brief Check -Wshadow without the advantage of a previous lookup. 6049 void Sema::CheckShadow(Scope *S, VarDecl *D) { 6050 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 6051 return; 6052 6053 LookupResult R(*this, D->getDeclName(), D->getLocation(), 6054 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 6055 LookupName(R, S); 6056 CheckShadow(S, D, R); 6057 } 6058 6059 /// Check for conflict between this global or extern "C" declaration and 6060 /// previous global or extern "C" declarations. This is only used in C++. 6061 template<typename T> 6062 static bool checkGlobalOrExternCConflict( 6063 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 6064 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 6065 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 6066 6067 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 6068 // The common case: this global doesn't conflict with any extern "C" 6069 // declaration. 6070 return false; 6071 } 6072 6073 if (Prev) { 6074 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 6075 // Both the old and new declarations have C language linkage. This is a 6076 // redeclaration. 6077 Previous.clear(); 6078 Previous.addDecl(Prev); 6079 return true; 6080 } 6081 6082 // This is a global, non-extern "C" declaration, and there is a previous 6083 // non-global extern "C" declaration. Diagnose if this is a variable 6084 // declaration. 6085 if (!isa<VarDecl>(ND)) 6086 return false; 6087 } else { 6088 // The declaration is extern "C". Check for any declaration in the 6089 // translation unit which might conflict. 6090 if (IsGlobal) { 6091 // We have already performed the lookup into the translation unit. 6092 IsGlobal = false; 6093 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6094 I != E; ++I) { 6095 if (isa<VarDecl>(*I)) { 6096 Prev = *I; 6097 break; 6098 } 6099 } 6100 } else { 6101 DeclContext::lookup_result R = 6102 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6103 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6104 I != E; ++I) { 6105 if (isa<VarDecl>(*I)) { 6106 Prev = *I; 6107 break; 6108 } 6109 // FIXME: If we have any other entity with this name in global scope, 6110 // the declaration is ill-formed, but that is a defect: it breaks the 6111 // 'stat' hack, for instance. Only variables can have mangled name 6112 // clashes with extern "C" declarations, so only they deserve a 6113 // diagnostic. 6114 } 6115 } 6116 6117 if (!Prev) 6118 return false; 6119 } 6120 6121 // Use the first declaration's location to ensure we point at something which 6122 // is lexically inside an extern "C" linkage-spec. 6123 assert(Prev && "should have found a previous declaration to diagnose"); 6124 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6125 Prev = FD->getFirstDecl(); 6126 else 6127 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6128 6129 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6130 << IsGlobal << ND; 6131 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6132 << IsGlobal; 6133 return false; 6134 } 6135 6136 /// Apply special rules for handling extern "C" declarations. Returns \c true 6137 /// if we have found that this is a redeclaration of some prior entity. 6138 /// 6139 /// Per C++ [dcl.link]p6: 6140 /// Two declarations [for a function or variable] with C language linkage 6141 /// with the same name that appear in different scopes refer to the same 6142 /// [entity]. An entity with C language linkage shall not be declared with 6143 /// the same name as an entity in global scope. 6144 template<typename T> 6145 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6146 LookupResult &Previous) { 6147 if (!S.getLangOpts().CPlusPlus) { 6148 // In C, when declaring a global variable, look for a corresponding 'extern' 6149 // variable declared in function scope. We don't need this in C++, because 6150 // we find local extern decls in the surrounding file-scope DeclContext. 6151 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6152 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6153 Previous.clear(); 6154 Previous.addDecl(Prev); 6155 return true; 6156 } 6157 } 6158 return false; 6159 } 6160 6161 // A declaration in the translation unit can conflict with an extern "C" 6162 // declaration. 6163 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6164 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6165 6166 // An extern "C" declaration can conflict with a declaration in the 6167 // translation unit or can be a redeclaration of an extern "C" declaration 6168 // in another scope. 6169 if (isIncompleteDeclExternC(S,ND)) 6170 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6171 6172 // Neither global nor extern "C": nothing to do. 6173 return false; 6174 } 6175 6176 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6177 // If the decl is already known invalid, don't check it. 6178 if (NewVD->isInvalidDecl()) 6179 return; 6180 6181 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6182 QualType T = TInfo->getType(); 6183 6184 // Defer checking an 'auto' type until its initializer is attached. 6185 if (T->isUndeducedType()) 6186 return; 6187 6188 if (NewVD->hasAttrs()) 6189 CheckAlignasUnderalignment(NewVD); 6190 6191 if (T->isObjCObjectType()) { 6192 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6193 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6194 T = Context.getObjCObjectPointerType(T); 6195 NewVD->setType(T); 6196 } 6197 6198 // Emit an error if an address space was applied to decl with local storage. 6199 // This includes arrays of objects with address space qualifiers, but not 6200 // automatic variables that point to other address spaces. 6201 // ISO/IEC TR 18037 S5.1.2 6202 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6203 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6204 NewVD->setInvalidDecl(); 6205 return; 6206 } 6207 6208 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6209 // __constant address space. 6210 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 6211 && T.getAddressSpace() != LangAS::opencl_constant 6212 && !T->isSamplerT()){ 6213 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 6214 NewVD->setInvalidDecl(); 6215 return; 6216 } 6217 6218 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6219 // scope. 6220 if ((getLangOpts().OpenCLVersion >= 120) 6221 && NewVD->isStaticLocal()) { 6222 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6223 NewVD->setInvalidDecl(); 6224 return; 6225 } 6226 6227 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6228 && !NewVD->hasAttr<BlocksAttr>()) { 6229 if (getLangOpts().getGC() != LangOptions::NonGC) 6230 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6231 else { 6232 assert(!getLangOpts().ObjCAutoRefCount); 6233 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6234 } 6235 } 6236 6237 bool isVM = T->isVariablyModifiedType(); 6238 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6239 NewVD->hasAttr<BlocksAttr>()) 6240 getCurFunction()->setHasBranchProtectedScope(); 6241 6242 if ((isVM && NewVD->hasLinkage()) || 6243 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6244 bool SizeIsNegative; 6245 llvm::APSInt Oversized; 6246 TypeSourceInfo *FixedTInfo = 6247 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6248 SizeIsNegative, Oversized); 6249 if (!FixedTInfo && T->isVariableArrayType()) { 6250 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6251 // FIXME: This won't give the correct result for 6252 // int a[10][n]; 6253 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6254 6255 if (NewVD->isFileVarDecl()) 6256 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6257 << SizeRange; 6258 else if (NewVD->isStaticLocal()) 6259 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6260 << SizeRange; 6261 else 6262 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6263 << SizeRange; 6264 NewVD->setInvalidDecl(); 6265 return; 6266 } 6267 6268 if (!FixedTInfo) { 6269 if (NewVD->isFileVarDecl()) 6270 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6271 else 6272 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6273 NewVD->setInvalidDecl(); 6274 return; 6275 } 6276 6277 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6278 NewVD->setType(FixedTInfo->getType()); 6279 NewVD->setTypeSourceInfo(FixedTInfo); 6280 } 6281 6282 if (T->isVoidType()) { 6283 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6284 // of objects and functions. 6285 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6286 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6287 << T; 6288 NewVD->setInvalidDecl(); 6289 return; 6290 } 6291 } 6292 6293 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6294 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6295 NewVD->setInvalidDecl(); 6296 return; 6297 } 6298 6299 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6300 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6301 NewVD->setInvalidDecl(); 6302 return; 6303 } 6304 6305 if (NewVD->isConstexpr() && !T->isDependentType() && 6306 RequireLiteralType(NewVD->getLocation(), T, 6307 diag::err_constexpr_var_non_literal)) { 6308 NewVD->setInvalidDecl(); 6309 return; 6310 } 6311 } 6312 6313 /// \brief Perform semantic checking on a newly-created variable 6314 /// declaration. 6315 /// 6316 /// This routine performs all of the type-checking required for a 6317 /// variable declaration once it has been built. It is used both to 6318 /// check variables after they have been parsed and their declarators 6319 /// have been translated into a declaration, and to check variables 6320 /// that have been instantiated from a template. 6321 /// 6322 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6323 /// 6324 /// Returns true if the variable declaration is a redeclaration. 6325 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6326 CheckVariableDeclarationType(NewVD); 6327 6328 // If the decl is already known invalid, don't check it. 6329 if (NewVD->isInvalidDecl()) 6330 return false; 6331 6332 // If we did not find anything by this name, look for a non-visible 6333 // extern "C" declaration with the same name. 6334 if (Previous.empty() && 6335 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6336 Previous.setShadowed(); 6337 6338 // Filter out any non-conflicting previous declarations. 6339 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 6340 6341 if (!Previous.empty()) { 6342 MergeVarDecl(NewVD, Previous); 6343 return true; 6344 } 6345 return false; 6346 } 6347 6348 /// \brief Data used with FindOverriddenMethod 6349 struct FindOverriddenMethodData { 6350 Sema *S; 6351 CXXMethodDecl *Method; 6352 }; 6353 6354 /// \brief Member lookup function that determines whether a given C++ 6355 /// method overrides a method in a base class, to be used with 6356 /// CXXRecordDecl::lookupInBases(). 6357 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6358 CXXBasePath &Path, 6359 void *UserData) { 6360 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6361 6362 FindOverriddenMethodData *Data 6363 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6364 6365 DeclarationName Name = Data->Method->getDeclName(); 6366 6367 // FIXME: Do we care about other names here too? 6368 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6369 // We really want to find the base class destructor here. 6370 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6371 CanQualType CT = Data->S->Context.getCanonicalType(T); 6372 6373 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6374 } 6375 6376 for (Path.Decls = BaseRecord->lookup(Name); 6377 !Path.Decls.empty(); 6378 Path.Decls = Path.Decls.slice(1)) { 6379 NamedDecl *D = Path.Decls.front(); 6380 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6381 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6382 return true; 6383 } 6384 } 6385 6386 return false; 6387 } 6388 6389 namespace { 6390 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6391 } 6392 /// \brief Report an error regarding overriding, along with any relevant 6393 /// overriden methods. 6394 /// 6395 /// \param DiagID the primary error to report. 6396 /// \param MD the overriding method. 6397 /// \param OEK which overrides to include as notes. 6398 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6399 OverrideErrorKind OEK = OEK_All) { 6400 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6401 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6402 E = MD->end_overridden_methods(); 6403 I != E; ++I) { 6404 // This check (& the OEK parameter) could be replaced by a predicate, but 6405 // without lambdas that would be overkill. This is still nicer than writing 6406 // out the diag loop 3 times. 6407 if ((OEK == OEK_All) || 6408 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6409 (OEK == OEK_Deleted && (*I)->isDeleted())) 6410 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6411 } 6412 } 6413 6414 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6415 /// and if so, check that it's a valid override and remember it. 6416 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6417 // Look for methods in base classes that this method might override. 6418 CXXBasePaths Paths; 6419 FindOverriddenMethodData Data; 6420 Data.Method = MD; 6421 Data.S = this; 6422 bool hasDeletedOverridenMethods = false; 6423 bool hasNonDeletedOverridenMethods = false; 6424 bool AddedAny = false; 6425 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6426 for (auto *I : Paths.found_decls()) { 6427 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6428 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6429 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6430 !CheckOverridingFunctionAttributes(MD, OldMD) && 6431 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6432 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6433 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6434 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6435 AddedAny = true; 6436 } 6437 } 6438 } 6439 } 6440 6441 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6442 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6443 } 6444 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6445 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6446 } 6447 6448 return AddedAny; 6449 } 6450 6451 namespace { 6452 // Struct for holding all of the extra arguments needed by 6453 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6454 struct ActOnFDArgs { 6455 Scope *S; 6456 Declarator &D; 6457 MultiTemplateParamsArg TemplateParamLists; 6458 bool AddToScope; 6459 }; 6460 } 6461 6462 namespace { 6463 6464 // Callback to only accept typo corrections that have a non-zero edit distance. 6465 // Also only accept corrections that have the same parent decl. 6466 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6467 public: 6468 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6469 CXXRecordDecl *Parent) 6470 : Context(Context), OriginalFD(TypoFD), 6471 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6472 6473 bool ValidateCandidate(const TypoCorrection &candidate) override { 6474 if (candidate.getEditDistance() == 0) 6475 return false; 6476 6477 SmallVector<unsigned, 1> MismatchedParams; 6478 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6479 CDeclEnd = candidate.end(); 6480 CDecl != CDeclEnd; ++CDecl) { 6481 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6482 6483 if (FD && !FD->hasBody() && 6484 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6485 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6486 CXXRecordDecl *Parent = MD->getParent(); 6487 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6488 return true; 6489 } else if (!ExpectedParent) { 6490 return true; 6491 } 6492 } 6493 } 6494 6495 return false; 6496 } 6497 6498 private: 6499 ASTContext &Context; 6500 FunctionDecl *OriginalFD; 6501 CXXRecordDecl *ExpectedParent; 6502 }; 6503 6504 } 6505 6506 /// \brief Generate diagnostics for an invalid function redeclaration. 6507 /// 6508 /// This routine handles generating the diagnostic messages for an invalid 6509 /// function redeclaration, including finding possible similar declarations 6510 /// or performing typo correction if there are no previous declarations with 6511 /// the same name. 6512 /// 6513 /// Returns a NamedDecl iff typo correction was performed and substituting in 6514 /// the new declaration name does not cause new errors. 6515 static NamedDecl *DiagnoseInvalidRedeclaration( 6516 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6517 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6518 DeclarationName Name = NewFD->getDeclName(); 6519 DeclContext *NewDC = NewFD->getDeclContext(); 6520 SmallVector<unsigned, 1> MismatchedParams; 6521 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6522 TypoCorrection Correction; 6523 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6524 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6525 : diag::err_member_decl_does_not_match; 6526 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6527 IsLocalFriend ? Sema::LookupLocalFriendName 6528 : Sema::LookupOrdinaryName, 6529 Sema::ForRedeclaration); 6530 6531 NewFD->setInvalidDecl(); 6532 if (IsLocalFriend) 6533 SemaRef.LookupName(Prev, S); 6534 else 6535 SemaRef.LookupQualifiedName(Prev, NewDC); 6536 assert(!Prev.isAmbiguous() && 6537 "Cannot have an ambiguity in previous-declaration lookup"); 6538 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6539 if (!Prev.empty()) { 6540 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6541 Func != FuncEnd; ++Func) { 6542 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6543 if (FD && 6544 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6545 // Add 1 to the index so that 0 can mean the mismatch didn't 6546 // involve a parameter 6547 unsigned ParamNum = 6548 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6549 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6550 } 6551 } 6552 // If the qualified name lookup yielded nothing, try typo correction 6553 } else if ((Correction = SemaRef.CorrectTypo( 6554 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6555 &ExtraArgs.D.getCXXScopeSpec(), 6556 llvm::make_unique<DifferentNameValidatorCCC>( 6557 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr), 6558 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6559 // Set up everything for the call to ActOnFunctionDeclarator 6560 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6561 ExtraArgs.D.getIdentifierLoc()); 6562 Previous.clear(); 6563 Previous.setLookupName(Correction.getCorrection()); 6564 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6565 CDeclEnd = Correction.end(); 6566 CDecl != CDeclEnd; ++CDecl) { 6567 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6568 if (FD && !FD->hasBody() && 6569 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6570 Previous.addDecl(FD); 6571 } 6572 } 6573 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6574 6575 NamedDecl *Result; 6576 // Retry building the function declaration with the new previous 6577 // declarations, and with errors suppressed. 6578 { 6579 // Trap errors. 6580 Sema::SFINAETrap Trap(SemaRef); 6581 6582 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6583 // pieces need to verify the typo-corrected C++ declaration and hopefully 6584 // eliminate the need for the parameter pack ExtraArgs. 6585 Result = SemaRef.ActOnFunctionDeclarator( 6586 ExtraArgs.S, ExtraArgs.D, 6587 Correction.getCorrectionDecl()->getDeclContext(), 6588 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6589 ExtraArgs.AddToScope); 6590 6591 if (Trap.hasErrorOccurred()) 6592 Result = nullptr; 6593 } 6594 6595 if (Result) { 6596 // Determine which correction we picked. 6597 Decl *Canonical = Result->getCanonicalDecl(); 6598 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6599 I != E; ++I) 6600 if ((*I)->getCanonicalDecl() == Canonical) 6601 Correction.setCorrectionDecl(*I); 6602 6603 SemaRef.diagnoseTypo( 6604 Correction, 6605 SemaRef.PDiag(IsLocalFriend 6606 ? diag::err_no_matching_local_friend_suggest 6607 : diag::err_member_decl_does_not_match_suggest) 6608 << Name << NewDC << IsDefinition); 6609 return Result; 6610 } 6611 6612 // Pretend the typo correction never occurred 6613 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6614 ExtraArgs.D.getIdentifierLoc()); 6615 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6616 Previous.clear(); 6617 Previous.setLookupName(Name); 6618 } 6619 6620 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6621 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6622 6623 bool NewFDisConst = false; 6624 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6625 NewFDisConst = NewMD->isConst(); 6626 6627 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6628 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6629 NearMatch != NearMatchEnd; ++NearMatch) { 6630 FunctionDecl *FD = NearMatch->first; 6631 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6632 bool FDisConst = MD && MD->isConst(); 6633 bool IsMember = MD || !IsLocalFriend; 6634 6635 // FIXME: These notes are poorly worded for the local friend case. 6636 if (unsigned Idx = NearMatch->second) { 6637 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6638 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6639 if (Loc.isInvalid()) Loc = FD->getLocation(); 6640 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6641 : diag::note_local_decl_close_param_match) 6642 << Idx << FDParam->getType() 6643 << NewFD->getParamDecl(Idx - 1)->getType(); 6644 } else if (FDisConst != NewFDisConst) { 6645 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6646 << NewFDisConst << FD->getSourceRange().getEnd(); 6647 } else 6648 SemaRef.Diag(FD->getLocation(), 6649 IsMember ? diag::note_member_def_close_match 6650 : diag::note_local_decl_close_match); 6651 } 6652 return nullptr; 6653 } 6654 6655 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) { 6656 switch (D.getDeclSpec().getStorageClassSpec()) { 6657 default: llvm_unreachable("Unknown storage class!"); 6658 case DeclSpec::SCS_auto: 6659 case DeclSpec::SCS_register: 6660 case DeclSpec::SCS_mutable: 6661 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6662 diag::err_typecheck_sclass_func); 6663 D.setInvalidType(); 6664 break; 6665 case DeclSpec::SCS_unspecified: break; 6666 case DeclSpec::SCS_extern: 6667 if (D.getDeclSpec().isExternInLinkageSpec()) 6668 return SC_None; 6669 return SC_Extern; 6670 case DeclSpec::SCS_static: { 6671 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6672 // C99 6.7.1p5: 6673 // The declaration of an identifier for a function that has 6674 // block scope shall have no explicit storage-class specifier 6675 // other than extern 6676 // See also (C++ [dcl.stc]p4). 6677 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6678 diag::err_static_block_func); 6679 break; 6680 } else 6681 return SC_Static; 6682 } 6683 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6684 } 6685 6686 // No explicit storage class has already been returned 6687 return SC_None; 6688 } 6689 6690 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6691 DeclContext *DC, QualType &R, 6692 TypeSourceInfo *TInfo, 6693 StorageClass SC, 6694 bool &IsVirtualOkay) { 6695 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6696 DeclarationName Name = NameInfo.getName(); 6697 6698 FunctionDecl *NewFD = nullptr; 6699 bool isInline = D.getDeclSpec().isInlineSpecified(); 6700 6701 if (!SemaRef.getLangOpts().CPlusPlus) { 6702 // Determine whether the function was written with a 6703 // prototype. This true when: 6704 // - there is a prototype in the declarator, or 6705 // - the type R of the function is some kind of typedef or other reference 6706 // to a type name (which eventually refers to a function type). 6707 bool HasPrototype = 6708 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6709 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6710 6711 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6712 D.getLocStart(), NameInfo, R, 6713 TInfo, SC, isInline, 6714 HasPrototype, false); 6715 if (D.isInvalidType()) 6716 NewFD->setInvalidDecl(); 6717 6718 return NewFD; 6719 } 6720 6721 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6722 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6723 6724 // Check that the return type is not an abstract class type. 6725 // For record types, this is done by the AbstractClassUsageDiagnoser once 6726 // the class has been completely parsed. 6727 if (!DC->isRecord() && 6728 SemaRef.RequireNonAbstractType( 6729 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6730 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6731 D.setInvalidType(); 6732 6733 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6734 // This is a C++ constructor declaration. 6735 assert(DC->isRecord() && 6736 "Constructors can only be declared in a member context"); 6737 6738 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6739 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6740 D.getLocStart(), NameInfo, 6741 R, TInfo, isExplicit, isInline, 6742 /*isImplicitlyDeclared=*/false, 6743 isConstexpr); 6744 6745 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6746 // This is a C++ destructor declaration. 6747 if (DC->isRecord()) { 6748 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6749 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6750 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6751 SemaRef.Context, Record, 6752 D.getLocStart(), 6753 NameInfo, R, TInfo, isInline, 6754 /*isImplicitlyDeclared=*/false); 6755 6756 // If the class is complete, then we now create the implicit exception 6757 // specification. If the class is incomplete or dependent, we can't do 6758 // it yet. 6759 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6760 Record->getDefinition() && !Record->isBeingDefined() && 6761 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6762 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6763 } 6764 6765 IsVirtualOkay = true; 6766 return NewDD; 6767 6768 } else { 6769 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6770 D.setInvalidType(); 6771 6772 // Create a FunctionDecl to satisfy the function definition parsing 6773 // code path. 6774 return FunctionDecl::Create(SemaRef.Context, DC, 6775 D.getLocStart(), 6776 D.getIdentifierLoc(), Name, R, TInfo, 6777 SC, isInline, 6778 /*hasPrototype=*/true, isConstexpr); 6779 } 6780 6781 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6782 if (!DC->isRecord()) { 6783 SemaRef.Diag(D.getIdentifierLoc(), 6784 diag::err_conv_function_not_member); 6785 return nullptr; 6786 } 6787 6788 SemaRef.CheckConversionDeclarator(D, R, SC); 6789 IsVirtualOkay = true; 6790 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6791 D.getLocStart(), NameInfo, 6792 R, TInfo, isInline, isExplicit, 6793 isConstexpr, SourceLocation()); 6794 6795 } else if (DC->isRecord()) { 6796 // If the name of the function is the same as the name of the record, 6797 // then this must be an invalid constructor that has a return type. 6798 // (The parser checks for a return type and makes the declarator a 6799 // constructor if it has no return type). 6800 if (Name.getAsIdentifierInfo() && 6801 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6802 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6803 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6804 << SourceRange(D.getIdentifierLoc()); 6805 return nullptr; 6806 } 6807 6808 // This is a C++ method declaration. 6809 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6810 cast<CXXRecordDecl>(DC), 6811 D.getLocStart(), NameInfo, R, 6812 TInfo, SC, isInline, 6813 isConstexpr, SourceLocation()); 6814 IsVirtualOkay = !Ret->isStatic(); 6815 return Ret; 6816 } else { 6817 bool isFriend = 6818 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified(); 6819 if (!isFriend && SemaRef.CurContext->isRecord()) 6820 return nullptr; 6821 6822 // Determine whether the function was written with a 6823 // prototype. This true when: 6824 // - we're in C++ (where every function has a prototype), 6825 return FunctionDecl::Create(SemaRef.Context, DC, 6826 D.getLocStart(), 6827 NameInfo, R, TInfo, SC, isInline, 6828 true/*HasPrototype*/, isConstexpr); 6829 } 6830 } 6831 6832 enum OpenCLParamType { 6833 ValidKernelParam, 6834 PtrPtrKernelParam, 6835 PtrKernelParam, 6836 PrivatePtrKernelParam, 6837 InvalidKernelParam, 6838 RecordKernelParam 6839 }; 6840 6841 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6842 if (PT->isPointerType()) { 6843 QualType PointeeType = PT->getPointeeType(); 6844 if (PointeeType->isPointerType()) 6845 return PtrPtrKernelParam; 6846 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6847 : PtrKernelParam; 6848 } 6849 6850 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6851 // be used as builtin types. 6852 6853 if (PT->isImageType()) 6854 return PtrKernelParam; 6855 6856 if (PT->isBooleanType()) 6857 return InvalidKernelParam; 6858 6859 if (PT->isEventT()) 6860 return InvalidKernelParam; 6861 6862 if (PT->isHalfType()) 6863 return InvalidKernelParam; 6864 6865 if (PT->isRecordType()) 6866 return RecordKernelParam; 6867 6868 return ValidKernelParam; 6869 } 6870 6871 static void checkIsValidOpenCLKernelParameter( 6872 Sema &S, 6873 Declarator &D, 6874 ParmVarDecl *Param, 6875 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 6876 QualType PT = Param->getType(); 6877 6878 // Cache the valid types we encounter to avoid rechecking structs that are 6879 // used again 6880 if (ValidTypes.count(PT.getTypePtr())) 6881 return; 6882 6883 switch (getOpenCLKernelParameterType(PT)) { 6884 case PtrPtrKernelParam: 6885 // OpenCL v1.2 s6.9.a: 6886 // A kernel function argument cannot be declared as a 6887 // pointer to a pointer type. 6888 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6889 D.setInvalidType(); 6890 return; 6891 6892 case PrivatePtrKernelParam: 6893 // OpenCL v1.2 s6.9.a: 6894 // A kernel function argument cannot be declared as a 6895 // pointer to the private address space. 6896 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6897 D.setInvalidType(); 6898 return; 6899 6900 // OpenCL v1.2 s6.9.k: 6901 // Arguments to kernel functions in a program cannot be declared with the 6902 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6903 // uintptr_t or a struct and/or union that contain fields declared to be 6904 // one of these built-in scalar types. 6905 6906 case InvalidKernelParam: 6907 // OpenCL v1.2 s6.8 n: 6908 // A kernel function argument cannot be declared 6909 // of event_t type. 6910 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6911 D.setInvalidType(); 6912 return; 6913 6914 case PtrKernelParam: 6915 case ValidKernelParam: 6916 ValidTypes.insert(PT.getTypePtr()); 6917 return; 6918 6919 case RecordKernelParam: 6920 break; 6921 } 6922 6923 // Track nested structs we will inspect 6924 SmallVector<const Decl *, 4> VisitStack; 6925 6926 // Track where we are in the nested structs. Items will migrate from 6927 // VisitStack to HistoryStack as we do the DFS for bad field. 6928 SmallVector<const FieldDecl *, 4> HistoryStack; 6929 HistoryStack.push_back(nullptr); 6930 6931 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6932 VisitStack.push_back(PD); 6933 6934 assert(VisitStack.back() && "First decl null?"); 6935 6936 do { 6937 const Decl *Next = VisitStack.pop_back_val(); 6938 if (!Next) { 6939 assert(!HistoryStack.empty()); 6940 // Found a marker, we have gone up a level 6941 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6942 ValidTypes.insert(Hist->getType().getTypePtr()); 6943 6944 continue; 6945 } 6946 6947 // Adds everything except the original parameter declaration (which is not a 6948 // field itself) to the history stack. 6949 const RecordDecl *RD; 6950 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6951 HistoryStack.push_back(Field); 6952 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6953 } else { 6954 RD = cast<RecordDecl>(Next); 6955 } 6956 6957 // Add a null marker so we know when we've gone back up a level 6958 VisitStack.push_back(nullptr); 6959 6960 for (const auto *FD : RD->fields()) { 6961 QualType QT = FD->getType(); 6962 6963 if (ValidTypes.count(QT.getTypePtr())) 6964 continue; 6965 6966 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6967 if (ParamType == ValidKernelParam) 6968 continue; 6969 6970 if (ParamType == RecordKernelParam) { 6971 VisitStack.push_back(FD); 6972 continue; 6973 } 6974 6975 // OpenCL v1.2 s6.9.p: 6976 // Arguments to kernel functions that are declared to be a struct or union 6977 // do not allow OpenCL objects to be passed as elements of the struct or 6978 // union. 6979 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6980 ParamType == PrivatePtrKernelParam) { 6981 S.Diag(Param->getLocation(), 6982 diag::err_record_with_pointers_kernel_param) 6983 << PT->isUnionType() 6984 << PT; 6985 } else { 6986 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6987 } 6988 6989 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6990 << PD->getDeclName(); 6991 6992 // We have an error, now let's go back up through history and show where 6993 // the offending field came from 6994 for (ArrayRef<const FieldDecl *>::const_iterator 6995 I = HistoryStack.begin() + 1, 6996 E = HistoryStack.end(); 6997 I != E; ++I) { 6998 const FieldDecl *OuterField = *I; 6999 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 7000 << OuterField->getType(); 7001 } 7002 7003 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 7004 << QT->isPointerType() 7005 << QT; 7006 D.setInvalidType(); 7007 return; 7008 } 7009 } while (!VisitStack.empty()); 7010 } 7011 7012 NamedDecl* 7013 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 7014 TypeSourceInfo *TInfo, LookupResult &Previous, 7015 MultiTemplateParamsArg TemplateParamLists, 7016 bool &AddToScope) { 7017 QualType R = TInfo->getType(); 7018 7019 assert(R.getTypePtr()->isFunctionType()); 7020 7021 // TODO: consider using NameInfo for diagnostic. 7022 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 7023 DeclarationName Name = NameInfo.getName(); 7024 StorageClass SC = getFunctionStorageClass(*this, D); 7025 7026 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 7027 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 7028 diag::err_invalid_thread) 7029 << DeclSpec::getSpecifierName(TSCS); 7030 7031 if (D.isFirstDeclarationOfMember()) 7032 adjustMemberFunctionCC(R, D.isStaticMember()); 7033 7034 bool isFriend = false; 7035 FunctionTemplateDecl *FunctionTemplate = nullptr; 7036 bool isExplicitSpecialization = false; 7037 bool isFunctionTemplateSpecialization = false; 7038 7039 bool isDependentClassScopeExplicitSpecialization = false; 7040 bool HasExplicitTemplateArgs = false; 7041 TemplateArgumentListInfo TemplateArgs; 7042 7043 bool isVirtualOkay = false; 7044 7045 DeclContext *OriginalDC = DC; 7046 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 7047 7048 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 7049 isVirtualOkay); 7050 if (!NewFD) return nullptr; 7051 7052 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 7053 NewFD->setTopLevelDeclInObjCContainer(); 7054 7055 // Set the lexical context. If this is a function-scope declaration, or has a 7056 // C++ scope specifier, or is the object of a friend declaration, the lexical 7057 // context will be different from the semantic context. 7058 NewFD->setLexicalDeclContext(CurContext); 7059 7060 if (IsLocalExternDecl) 7061 NewFD->setLocalExternDecl(); 7062 7063 if (getLangOpts().CPlusPlus) { 7064 bool isInline = D.getDeclSpec().isInlineSpecified(); 7065 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 7066 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 7067 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 7068 isFriend = D.getDeclSpec().isFriendSpecified(); 7069 if (isFriend && !isInline && D.isFunctionDefinition()) { 7070 // C++ [class.friend]p5 7071 // A function can be defined in a friend declaration of a 7072 // class . . . . Such a function is implicitly inline. 7073 NewFD->setImplicitlyInline(); 7074 } 7075 7076 // If this is a method defined in an __interface, and is not a constructor 7077 // or an overloaded operator, then set the pure flag (isVirtual will already 7078 // return true). 7079 if (const CXXRecordDecl *Parent = 7080 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 7081 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 7082 NewFD->setPure(true); 7083 } 7084 7085 SetNestedNameSpecifier(NewFD, D); 7086 isExplicitSpecialization = false; 7087 isFunctionTemplateSpecialization = false; 7088 if (D.isInvalidType()) 7089 NewFD->setInvalidDecl(); 7090 7091 // Match up the template parameter lists with the scope specifier, then 7092 // determine whether we have a template or a template specialization. 7093 bool Invalid = false; 7094 if (TemplateParameterList *TemplateParams = 7095 MatchTemplateParametersToScopeSpecifier( 7096 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 7097 D.getCXXScopeSpec(), 7098 D.getName().getKind() == UnqualifiedId::IK_TemplateId 7099 ? D.getName().TemplateId 7100 : nullptr, 7101 TemplateParamLists, isFriend, isExplicitSpecialization, 7102 Invalid)) { 7103 if (TemplateParams->size() > 0) { 7104 // This is a function template 7105 7106 // Check that we can declare a template here. 7107 if (CheckTemplateDeclScope(S, TemplateParams)) 7108 NewFD->setInvalidDecl(); 7109 7110 // A destructor cannot be a template. 7111 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7112 Diag(NewFD->getLocation(), diag::err_destructor_template); 7113 NewFD->setInvalidDecl(); 7114 } 7115 7116 // If we're adding a template to a dependent context, we may need to 7117 // rebuilding some of the types used within the template parameter list, 7118 // now that we know what the current instantiation is. 7119 if (DC->isDependentContext()) { 7120 ContextRAII SavedContext(*this, DC); 7121 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7122 Invalid = true; 7123 } 7124 7125 7126 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7127 NewFD->getLocation(), 7128 Name, TemplateParams, 7129 NewFD); 7130 FunctionTemplate->setLexicalDeclContext(CurContext); 7131 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7132 7133 // For source fidelity, store the other template param lists. 7134 if (TemplateParamLists.size() > 1) { 7135 NewFD->setTemplateParameterListsInfo(Context, 7136 TemplateParamLists.size() - 1, 7137 TemplateParamLists.data()); 7138 } 7139 } else { 7140 // This is a function template specialization. 7141 isFunctionTemplateSpecialization = true; 7142 // For source fidelity, store all the template param lists. 7143 if (TemplateParamLists.size() > 0) 7144 NewFD->setTemplateParameterListsInfo(Context, 7145 TemplateParamLists.size(), 7146 TemplateParamLists.data()); 7147 7148 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7149 if (isFriend) { 7150 // We want to remove the "template<>", found here. 7151 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7152 7153 // If we remove the template<> and the name is not a 7154 // template-id, we're actually silently creating a problem: 7155 // the friend declaration will refer to an untemplated decl, 7156 // and clearly the user wants a template specialization. So 7157 // we need to insert '<>' after the name. 7158 SourceLocation InsertLoc; 7159 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7160 InsertLoc = D.getName().getSourceRange().getEnd(); 7161 InsertLoc = getLocForEndOfToken(InsertLoc); 7162 } 7163 7164 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7165 << Name << RemoveRange 7166 << FixItHint::CreateRemoval(RemoveRange) 7167 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7168 } 7169 } 7170 } 7171 else { 7172 // All template param lists were matched against the scope specifier: 7173 // this is NOT (an explicit specialization of) a template. 7174 if (TemplateParamLists.size() > 0) 7175 // For source fidelity, store all the template param lists. 7176 NewFD->setTemplateParameterListsInfo(Context, 7177 TemplateParamLists.size(), 7178 TemplateParamLists.data()); 7179 } 7180 7181 if (Invalid) { 7182 NewFD->setInvalidDecl(); 7183 if (FunctionTemplate) 7184 FunctionTemplate->setInvalidDecl(); 7185 } 7186 7187 // C++ [dcl.fct.spec]p5: 7188 // The virtual specifier shall only be used in declarations of 7189 // nonstatic class member functions that appear within a 7190 // member-specification of a class declaration; see 10.3. 7191 // 7192 if (isVirtual && !NewFD->isInvalidDecl()) { 7193 if (!isVirtualOkay) { 7194 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7195 diag::err_virtual_non_function); 7196 } else if (!CurContext->isRecord()) { 7197 // 'virtual' was specified outside of the class. 7198 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7199 diag::err_virtual_out_of_class) 7200 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7201 } else if (NewFD->getDescribedFunctionTemplate()) { 7202 // C++ [temp.mem]p3: 7203 // A member function template shall not be virtual. 7204 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7205 diag::err_virtual_member_function_template) 7206 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7207 } else { 7208 // Okay: Add virtual to the method. 7209 NewFD->setVirtualAsWritten(true); 7210 } 7211 7212 if (getLangOpts().CPlusPlus14 && 7213 NewFD->getReturnType()->isUndeducedType()) 7214 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7215 } 7216 7217 if (getLangOpts().CPlusPlus14 && 7218 (NewFD->isDependentContext() || 7219 (isFriend && CurContext->isDependentContext())) && 7220 NewFD->getReturnType()->isUndeducedType()) { 7221 // If the function template is referenced directly (for instance, as a 7222 // member of the current instantiation), pretend it has a dependent type. 7223 // This is not really justified by the standard, but is the only sane 7224 // thing to do. 7225 // FIXME: For a friend function, we have not marked the function as being 7226 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7227 const FunctionProtoType *FPT = 7228 NewFD->getType()->castAs<FunctionProtoType>(); 7229 QualType Result = 7230 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7231 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7232 FPT->getExtProtoInfo())); 7233 } 7234 7235 // C++ [dcl.fct.spec]p3: 7236 // The inline specifier shall not appear on a block scope function 7237 // declaration. 7238 if (isInline && !NewFD->isInvalidDecl()) { 7239 if (CurContext->isFunctionOrMethod()) { 7240 // 'inline' is not allowed on block scope function declaration. 7241 Diag(D.getDeclSpec().getInlineSpecLoc(), 7242 diag::err_inline_declaration_block_scope) << Name 7243 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7244 } 7245 } 7246 7247 // C++ [dcl.fct.spec]p6: 7248 // The explicit specifier shall be used only in the declaration of a 7249 // constructor or conversion function within its class definition; 7250 // see 12.3.1 and 12.3.2. 7251 if (isExplicit && !NewFD->isInvalidDecl()) { 7252 if (!CurContext->isRecord()) { 7253 // 'explicit' was specified outside of the class. 7254 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7255 diag::err_explicit_out_of_class) 7256 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7257 } else if (!isa<CXXConstructorDecl>(NewFD) && 7258 !isa<CXXConversionDecl>(NewFD)) { 7259 // 'explicit' was specified on a function that wasn't a constructor 7260 // or conversion function. 7261 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7262 diag::err_explicit_non_ctor_or_conv_function) 7263 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7264 } 7265 } 7266 7267 if (isConstexpr) { 7268 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7269 // are implicitly inline. 7270 NewFD->setImplicitlyInline(); 7271 7272 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7273 // be either constructors or to return a literal type. Therefore, 7274 // destructors cannot be declared constexpr. 7275 if (isa<CXXDestructorDecl>(NewFD)) 7276 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7277 } 7278 7279 // If __module_private__ was specified, mark the function accordingly. 7280 if (D.getDeclSpec().isModulePrivateSpecified()) { 7281 if (isFunctionTemplateSpecialization) { 7282 SourceLocation ModulePrivateLoc 7283 = D.getDeclSpec().getModulePrivateSpecLoc(); 7284 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7285 << 0 7286 << FixItHint::CreateRemoval(ModulePrivateLoc); 7287 } else { 7288 NewFD->setModulePrivate(); 7289 if (FunctionTemplate) 7290 FunctionTemplate->setModulePrivate(); 7291 } 7292 } 7293 7294 if (isFriend) { 7295 if (FunctionTemplate) { 7296 FunctionTemplate->setObjectOfFriendDecl(); 7297 FunctionTemplate->setAccess(AS_public); 7298 } 7299 NewFD->setObjectOfFriendDecl(); 7300 NewFD->setAccess(AS_public); 7301 } 7302 7303 // If a function is defined as defaulted or deleted, mark it as such now. 7304 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7305 // definition kind to FDK_Definition. 7306 switch (D.getFunctionDefinitionKind()) { 7307 case FDK_Declaration: 7308 case FDK_Definition: 7309 break; 7310 7311 case FDK_Defaulted: 7312 NewFD->setDefaulted(); 7313 break; 7314 7315 case FDK_Deleted: 7316 NewFD->setDeletedAsWritten(); 7317 break; 7318 } 7319 7320 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7321 D.isFunctionDefinition()) { 7322 // C++ [class.mfct]p2: 7323 // A member function may be defined (8.4) in its class definition, in 7324 // which case it is an inline member function (7.1.2) 7325 NewFD->setImplicitlyInline(); 7326 } 7327 7328 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7329 !CurContext->isRecord()) { 7330 // C++ [class.static]p1: 7331 // A data or function member of a class may be declared static 7332 // in a class definition, in which case it is a static member of 7333 // the class. 7334 7335 // Complain about the 'static' specifier if it's on an out-of-line 7336 // member function definition. 7337 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7338 diag::err_static_out_of_line) 7339 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7340 } 7341 7342 // C++11 [except.spec]p15: 7343 // A deallocation function with no exception-specification is treated 7344 // as if it were specified with noexcept(true). 7345 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7346 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7347 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7348 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7349 NewFD->setType(Context.getFunctionType( 7350 FPT->getReturnType(), FPT->getParamTypes(), 7351 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7352 } 7353 7354 // Filter out previous declarations that don't match the scope. 7355 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7356 D.getCXXScopeSpec().isNotEmpty() || 7357 isExplicitSpecialization || 7358 isFunctionTemplateSpecialization); 7359 7360 // Handle GNU asm-label extension (encoded as an attribute). 7361 if (Expr *E = (Expr*) D.getAsmLabel()) { 7362 // The parser guarantees this is a string. 7363 StringLiteral *SE = cast<StringLiteral>(E); 7364 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7365 SE->getString(), 0)); 7366 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7367 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7368 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7369 if (I != ExtnameUndeclaredIdentifiers.end()) { 7370 NewFD->addAttr(I->second); 7371 ExtnameUndeclaredIdentifiers.erase(I); 7372 } 7373 } 7374 7375 // Copy the parameter declarations from the declarator D to the function 7376 // declaration NewFD, if they are available. First scavenge them into Params. 7377 SmallVector<ParmVarDecl*, 16> Params; 7378 if (D.isFunctionDeclarator()) { 7379 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7380 7381 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7382 // function that takes no arguments, not a function that takes a 7383 // single void argument. 7384 // We let through "const void" here because Sema::GetTypeForDeclarator 7385 // already checks for that case. 7386 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7387 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7388 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7389 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7390 Param->setDeclContext(NewFD); 7391 Params.push_back(Param); 7392 7393 if (Param->isInvalidDecl()) 7394 NewFD->setInvalidDecl(); 7395 } 7396 } 7397 7398 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7399 // When we're declaring a function with a typedef, typeof, etc as in the 7400 // following example, we'll need to synthesize (unnamed) 7401 // parameters for use in the declaration. 7402 // 7403 // @code 7404 // typedef void fn(int); 7405 // fn f; 7406 // @endcode 7407 7408 // Synthesize a parameter for each argument type. 7409 for (const auto &AI : FT->param_types()) { 7410 ParmVarDecl *Param = 7411 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7412 Param->setScopeInfo(0, Params.size()); 7413 Params.push_back(Param); 7414 } 7415 } else { 7416 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7417 "Should not need args for typedef of non-prototype fn"); 7418 } 7419 7420 // Finally, we know we have the right number of parameters, install them. 7421 NewFD->setParams(Params); 7422 7423 // Find all anonymous symbols defined during the declaration of this function 7424 // and add to NewFD. This lets us track decls such 'enum Y' in: 7425 // 7426 // void f(enum Y {AA} x) {} 7427 // 7428 // which would otherwise incorrectly end up in the translation unit scope. 7429 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7430 DeclsInPrototypeScope.clear(); 7431 7432 if (D.getDeclSpec().isNoreturnSpecified()) 7433 NewFD->addAttr( 7434 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7435 Context, 0)); 7436 7437 // Functions returning a variably modified type violate C99 6.7.5.2p2 7438 // because all functions have linkage. 7439 if (!NewFD->isInvalidDecl() && 7440 NewFD->getReturnType()->isVariablyModifiedType()) { 7441 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7442 NewFD->setInvalidDecl(); 7443 } 7444 7445 // Apply an implicit SectionAttr if #pragma code_seg is active. 7446 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() && 7447 !NewFD->hasAttr<SectionAttr>()) { 7448 NewFD->addAttr( 7449 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7450 CodeSegStack.CurrentValue->getString(), 7451 CodeSegStack.CurrentPragmaLocation)); 7452 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7453 ASTContext::PSF_Implicit | ASTContext::PSF_Execute | 7454 ASTContext::PSF_Read, 7455 NewFD)) 7456 NewFD->dropAttr<SectionAttr>(); 7457 } 7458 7459 // Handle attributes. 7460 ProcessDeclAttributes(S, NewFD, D); 7461 7462 QualType RetType = NewFD->getReturnType(); 7463 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7464 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7465 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7466 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7467 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7468 // Attach WarnUnusedResult to functions returning types with that attribute. 7469 // Don't apply the attribute to that type's own non-static member functions 7470 // (to avoid warning on things like assignment operators) 7471 if (!MD || MD->getParent() != Ret) 7472 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7473 } 7474 7475 if (getLangOpts().OpenCL) { 7476 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7477 // type declaration will generate a compilation error. 7478 unsigned AddressSpace = RetType.getAddressSpace(); 7479 if (AddressSpace == LangAS::opencl_local || 7480 AddressSpace == LangAS::opencl_global || 7481 AddressSpace == LangAS::opencl_constant) { 7482 Diag(NewFD->getLocation(), 7483 diag::err_opencl_return_value_with_address_space); 7484 NewFD->setInvalidDecl(); 7485 } 7486 } 7487 7488 if (!getLangOpts().CPlusPlus) { 7489 // Perform semantic checking on the function declaration. 7490 bool isExplicitSpecialization=false; 7491 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7492 CheckMain(NewFD, D.getDeclSpec()); 7493 7494 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7495 CheckMSVCRTEntryPoint(NewFD); 7496 7497 if (!NewFD->isInvalidDecl()) 7498 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7499 isExplicitSpecialization)); 7500 else if (!Previous.empty()) 7501 // Recover gracefully from an invalid redeclaration. 7502 D.setRedeclaration(true); 7503 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7504 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7505 "previous declaration set still overloaded"); 7506 7507 // Diagnose no-prototype function declarations with calling conventions that 7508 // don't support variadic calls. Only do this in C and do it after merging 7509 // possibly prototyped redeclarations. 7510 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>(); 7511 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) { 7512 CallingConv CC = FT->getExtInfo().getCC(); 7513 if (!supportsVariadicCall(CC)) { 7514 // Windows system headers sometimes accidentally use stdcall without 7515 // (void) parameters, so we relax this to a warning. 7516 int DiagID = 7517 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr; 7518 Diag(NewFD->getLocation(), DiagID) 7519 << FunctionType::getNameForCallConv(CC); 7520 } 7521 } 7522 } else { 7523 // C++11 [replacement.functions]p3: 7524 // The program's definitions shall not be specified as inline. 7525 // 7526 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7527 // 7528 // Suppress the diagnostic if the function is __attribute__((used)), since 7529 // that forces an external definition to be emitted. 7530 if (D.getDeclSpec().isInlineSpecified() && 7531 NewFD->isReplaceableGlobalAllocationFunction() && 7532 !NewFD->hasAttr<UsedAttr>()) 7533 Diag(D.getDeclSpec().getInlineSpecLoc(), 7534 diag::ext_operator_new_delete_declared_inline) 7535 << NewFD->getDeclName(); 7536 7537 // If the declarator is a template-id, translate the parser's template 7538 // argument list into our AST format. 7539 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7540 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7541 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7542 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7543 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7544 TemplateId->NumArgs); 7545 translateTemplateArguments(TemplateArgsPtr, 7546 TemplateArgs); 7547 7548 HasExplicitTemplateArgs = true; 7549 7550 if (NewFD->isInvalidDecl()) { 7551 HasExplicitTemplateArgs = false; 7552 } else if (FunctionTemplate) { 7553 // Function template with explicit template arguments. 7554 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7555 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7556 7557 HasExplicitTemplateArgs = false; 7558 } else { 7559 assert((isFunctionTemplateSpecialization || 7560 D.getDeclSpec().isFriendSpecified()) && 7561 "should have a 'template<>' for this decl"); 7562 // "friend void foo<>(int);" is an implicit specialization decl. 7563 isFunctionTemplateSpecialization = true; 7564 } 7565 } else if (isFriend && isFunctionTemplateSpecialization) { 7566 // This combination is only possible in a recovery case; the user 7567 // wrote something like: 7568 // template <> friend void foo(int); 7569 // which we're recovering from as if the user had written: 7570 // friend void foo<>(int); 7571 // Go ahead and fake up a template id. 7572 HasExplicitTemplateArgs = true; 7573 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7574 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7575 } 7576 7577 // If it's a friend (and only if it's a friend), it's possible 7578 // that either the specialized function type or the specialized 7579 // template is dependent, and therefore matching will fail. In 7580 // this case, don't check the specialization yet. 7581 bool InstantiationDependent = false; 7582 if (isFunctionTemplateSpecialization && isFriend && 7583 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7584 TemplateSpecializationType::anyDependentTemplateArguments( 7585 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7586 InstantiationDependent))) { 7587 assert(HasExplicitTemplateArgs && 7588 "friend function specialization without template args"); 7589 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7590 Previous)) 7591 NewFD->setInvalidDecl(); 7592 } else if (isFunctionTemplateSpecialization) { 7593 if (CurContext->isDependentContext() && CurContext->isRecord() 7594 && !isFriend) { 7595 isDependentClassScopeExplicitSpecialization = true; 7596 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7597 diag::ext_function_specialization_in_class : 7598 diag::err_function_specialization_in_class) 7599 << NewFD->getDeclName(); 7600 } else if (CheckFunctionTemplateSpecialization(NewFD, 7601 (HasExplicitTemplateArgs ? &TemplateArgs 7602 : nullptr), 7603 Previous)) 7604 NewFD->setInvalidDecl(); 7605 7606 // C++ [dcl.stc]p1: 7607 // A storage-class-specifier shall not be specified in an explicit 7608 // specialization (14.7.3) 7609 FunctionTemplateSpecializationInfo *Info = 7610 NewFD->getTemplateSpecializationInfo(); 7611 if (Info && SC != SC_None) { 7612 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7613 Diag(NewFD->getLocation(), 7614 diag::err_explicit_specialization_inconsistent_storage_class) 7615 << SC 7616 << FixItHint::CreateRemoval( 7617 D.getDeclSpec().getStorageClassSpecLoc()); 7618 7619 else 7620 Diag(NewFD->getLocation(), 7621 diag::ext_explicit_specialization_storage_class) 7622 << FixItHint::CreateRemoval( 7623 D.getDeclSpec().getStorageClassSpecLoc()); 7624 } 7625 7626 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7627 if (CheckMemberSpecialization(NewFD, Previous)) 7628 NewFD->setInvalidDecl(); 7629 } 7630 7631 // Perform semantic checking on the function declaration. 7632 if (!isDependentClassScopeExplicitSpecialization) { 7633 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7634 CheckMain(NewFD, D.getDeclSpec()); 7635 7636 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7637 CheckMSVCRTEntryPoint(NewFD); 7638 7639 if (!NewFD->isInvalidDecl()) 7640 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7641 isExplicitSpecialization)); 7642 else if (!Previous.empty()) 7643 // Recover gracefully from an invalid redeclaration. 7644 D.setRedeclaration(true); 7645 } 7646 7647 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7648 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7649 "previous declaration set still overloaded"); 7650 7651 NamedDecl *PrincipalDecl = (FunctionTemplate 7652 ? cast<NamedDecl>(FunctionTemplate) 7653 : NewFD); 7654 7655 if (isFriend && D.isRedeclaration()) { 7656 AccessSpecifier Access = AS_public; 7657 if (!NewFD->isInvalidDecl()) 7658 Access = NewFD->getPreviousDecl()->getAccess(); 7659 7660 NewFD->setAccess(Access); 7661 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7662 } 7663 7664 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7665 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7666 PrincipalDecl->setNonMemberOperator(); 7667 7668 // If we have a function template, check the template parameter 7669 // list. This will check and merge default template arguments. 7670 if (FunctionTemplate) { 7671 FunctionTemplateDecl *PrevTemplate = 7672 FunctionTemplate->getPreviousDecl(); 7673 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7674 PrevTemplate ? PrevTemplate->getTemplateParameters() 7675 : nullptr, 7676 D.getDeclSpec().isFriendSpecified() 7677 ? (D.isFunctionDefinition() 7678 ? TPC_FriendFunctionTemplateDefinition 7679 : TPC_FriendFunctionTemplate) 7680 : (D.getCXXScopeSpec().isSet() && 7681 DC && DC->isRecord() && 7682 DC->isDependentContext()) 7683 ? TPC_ClassTemplateMember 7684 : TPC_FunctionTemplate); 7685 } 7686 7687 if (NewFD->isInvalidDecl()) { 7688 // Ignore all the rest of this. 7689 } else if (!D.isRedeclaration()) { 7690 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7691 AddToScope }; 7692 // Fake up an access specifier if it's supposed to be a class member. 7693 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7694 NewFD->setAccess(AS_public); 7695 7696 // Qualified decls generally require a previous declaration. 7697 if (D.getCXXScopeSpec().isSet()) { 7698 // ...with the major exception of templated-scope or 7699 // dependent-scope friend declarations. 7700 7701 // TODO: we currently also suppress this check in dependent 7702 // contexts because (1) the parameter depth will be off when 7703 // matching friend templates and (2) we might actually be 7704 // selecting a friend based on a dependent factor. But there 7705 // are situations where these conditions don't apply and we 7706 // can actually do this check immediately. 7707 if (isFriend && 7708 (TemplateParamLists.size() || 7709 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7710 CurContext->isDependentContext())) { 7711 // ignore these 7712 } else { 7713 // The user tried to provide an out-of-line definition for a 7714 // function that is a member of a class or namespace, but there 7715 // was no such member function declared (C++ [class.mfct]p2, 7716 // C++ [namespace.memdef]p2). For example: 7717 // 7718 // class X { 7719 // void f() const; 7720 // }; 7721 // 7722 // void X::f() { } // ill-formed 7723 // 7724 // Complain about this problem, and attempt to suggest close 7725 // matches (e.g., those that differ only in cv-qualifiers and 7726 // whether the parameter types are references). 7727 7728 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7729 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7730 AddToScope = ExtraArgs.AddToScope; 7731 return Result; 7732 } 7733 } 7734 7735 // Unqualified local friend declarations are required to resolve 7736 // to something. 7737 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7738 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7739 *this, Previous, NewFD, ExtraArgs, true, S)) { 7740 AddToScope = ExtraArgs.AddToScope; 7741 return Result; 7742 } 7743 } 7744 7745 } else if (!D.isFunctionDefinition() && 7746 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7747 !isFriend && !isFunctionTemplateSpecialization && 7748 !isExplicitSpecialization) { 7749 // An out-of-line member function declaration must also be a 7750 // definition (C++ [class.mfct]p2). 7751 // Note that this is not the case for explicit specializations of 7752 // function templates or member functions of class templates, per 7753 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7754 // extension for compatibility with old SWIG code which likes to 7755 // generate them. 7756 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7757 << D.getCXXScopeSpec().getRange(); 7758 } 7759 } 7760 7761 ProcessPragmaWeak(S, NewFD); 7762 checkAttributesAfterMerging(*this, *NewFD); 7763 7764 AddKnownFunctionAttributes(NewFD); 7765 7766 if (NewFD->hasAttr<OverloadableAttr>() && 7767 !NewFD->getType()->getAs<FunctionProtoType>()) { 7768 Diag(NewFD->getLocation(), 7769 diag::err_attribute_overloadable_no_prototype) 7770 << NewFD; 7771 7772 // Turn this into a variadic function with no parameters. 7773 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7774 FunctionProtoType::ExtProtoInfo EPI( 7775 Context.getDefaultCallingConvention(true, false)); 7776 EPI.Variadic = true; 7777 EPI.ExtInfo = FT->getExtInfo(); 7778 7779 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7780 NewFD->setType(R); 7781 } 7782 7783 // If there's a #pragma GCC visibility in scope, and this isn't a class 7784 // member, set the visibility of this function. 7785 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7786 AddPushedVisibilityAttribute(NewFD); 7787 7788 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7789 // marking the function. 7790 AddCFAuditedAttribute(NewFD); 7791 7792 // If this is a function definition, check if we have to apply optnone due to 7793 // a pragma. 7794 if(D.isFunctionDefinition()) 7795 AddRangeBasedOptnone(NewFD); 7796 7797 // If this is the first declaration of an extern C variable, update 7798 // the map of such variables. 7799 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7800 isIncompleteDeclExternC(*this, NewFD)) 7801 RegisterLocallyScopedExternCDecl(NewFD, S); 7802 7803 // Set this FunctionDecl's range up to the right paren. 7804 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7805 7806 if (D.isRedeclaration() && !Previous.empty()) { 7807 checkDLLAttributeRedeclaration( 7808 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7809 isExplicitSpecialization || isFunctionTemplateSpecialization); 7810 } 7811 7812 if (getLangOpts().CPlusPlus) { 7813 if (FunctionTemplate) { 7814 if (NewFD->isInvalidDecl()) 7815 FunctionTemplate->setInvalidDecl(); 7816 return FunctionTemplate; 7817 } 7818 } 7819 7820 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7821 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7822 if ((getLangOpts().OpenCLVersion >= 120) 7823 && (SC == SC_Static)) { 7824 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7825 D.setInvalidType(); 7826 } 7827 7828 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7829 if (!NewFD->getReturnType()->isVoidType()) { 7830 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 7831 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 7832 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 7833 : FixItHint()); 7834 D.setInvalidType(); 7835 } 7836 7837 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7838 for (auto Param : NewFD->params()) 7839 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7840 } 7841 7842 MarkUnusedFileScopedDecl(NewFD); 7843 7844 if (getLangOpts().CUDA) 7845 if (IdentifierInfo *II = NewFD->getIdentifier()) 7846 if (!NewFD->isInvalidDecl() && 7847 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7848 if (II->isStr("cudaConfigureCall")) { 7849 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7850 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7851 7852 Context.setcudaConfigureCallDecl(NewFD); 7853 } 7854 } 7855 7856 // Here we have an function template explicit specialization at class scope. 7857 // The actually specialization will be postponed to template instatiation 7858 // time via the ClassScopeFunctionSpecializationDecl node. 7859 if (isDependentClassScopeExplicitSpecialization) { 7860 ClassScopeFunctionSpecializationDecl *NewSpec = 7861 ClassScopeFunctionSpecializationDecl::Create( 7862 Context, CurContext, SourceLocation(), 7863 cast<CXXMethodDecl>(NewFD), 7864 HasExplicitTemplateArgs, TemplateArgs); 7865 CurContext->addDecl(NewSpec); 7866 AddToScope = false; 7867 } 7868 7869 return NewFD; 7870 } 7871 7872 /// \brief Perform semantic checking of a new function declaration. 7873 /// 7874 /// Performs semantic analysis of the new function declaration 7875 /// NewFD. This routine performs all semantic checking that does not 7876 /// require the actual declarator involved in the declaration, and is 7877 /// used both for the declaration of functions as they are parsed 7878 /// (called via ActOnDeclarator) and for the declaration of functions 7879 /// that have been instantiated via C++ template instantiation (called 7880 /// via InstantiateDecl). 7881 /// 7882 /// \param IsExplicitSpecialization whether this new function declaration is 7883 /// an explicit specialization of the previous declaration. 7884 /// 7885 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7886 /// 7887 /// \returns true if the function declaration is a redeclaration. 7888 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7889 LookupResult &Previous, 7890 bool IsExplicitSpecialization) { 7891 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7892 "Variably modified return types are not handled here"); 7893 7894 // Determine whether the type of this function should be merged with 7895 // a previous visible declaration. This never happens for functions in C++, 7896 // and always happens in C if the previous declaration was visible. 7897 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7898 !Previous.isShadowed(); 7899 7900 // Filter out any non-conflicting previous declarations. 7901 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7902 7903 bool Redeclaration = false; 7904 NamedDecl *OldDecl = nullptr; 7905 7906 // Merge or overload the declaration with an existing declaration of 7907 // the same name, if appropriate. 7908 if (!Previous.empty()) { 7909 // Determine whether NewFD is an overload of PrevDecl or 7910 // a declaration that requires merging. If it's an overload, 7911 // there's no more work to do here; we'll just add the new 7912 // function to the scope. 7913 if (!AllowOverloadingOfFunction(Previous, Context)) { 7914 NamedDecl *Candidate = Previous.getFoundDecl(); 7915 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7916 Redeclaration = true; 7917 OldDecl = Candidate; 7918 } 7919 } else { 7920 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7921 /*NewIsUsingDecl*/ false)) { 7922 case Ovl_Match: 7923 Redeclaration = true; 7924 break; 7925 7926 case Ovl_NonFunction: 7927 Redeclaration = true; 7928 break; 7929 7930 case Ovl_Overload: 7931 Redeclaration = false; 7932 break; 7933 } 7934 7935 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7936 // If a function name is overloadable in C, then every function 7937 // with that name must be marked "overloadable". 7938 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7939 << Redeclaration << NewFD; 7940 NamedDecl *OverloadedDecl = nullptr; 7941 if (Redeclaration) 7942 OverloadedDecl = OldDecl; 7943 else if (!Previous.empty()) 7944 OverloadedDecl = Previous.getRepresentativeDecl(); 7945 if (OverloadedDecl) 7946 Diag(OverloadedDecl->getLocation(), 7947 diag::note_attribute_overloadable_prev_overload); 7948 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7949 } 7950 } 7951 } 7952 7953 // Check for a previous extern "C" declaration with this name. 7954 if (!Redeclaration && 7955 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7956 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7957 if (!Previous.empty()) { 7958 // This is an extern "C" declaration with the same name as a previous 7959 // declaration, and thus redeclares that entity... 7960 Redeclaration = true; 7961 OldDecl = Previous.getFoundDecl(); 7962 MergeTypeWithPrevious = false; 7963 7964 // ... except in the presence of __attribute__((overloadable)). 7965 if (OldDecl->hasAttr<OverloadableAttr>()) { 7966 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7967 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7968 << Redeclaration << NewFD; 7969 Diag(Previous.getFoundDecl()->getLocation(), 7970 diag::note_attribute_overloadable_prev_overload); 7971 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7972 } 7973 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7974 Redeclaration = false; 7975 OldDecl = nullptr; 7976 } 7977 } 7978 } 7979 } 7980 7981 // C++11 [dcl.constexpr]p8: 7982 // A constexpr specifier for a non-static member function that is not 7983 // a constructor declares that member function to be const. 7984 // 7985 // This needs to be delayed until we know whether this is an out-of-line 7986 // definition of a static member function. 7987 // 7988 // This rule is not present in C++1y, so we produce a backwards 7989 // compatibility warning whenever it happens in C++11. 7990 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7991 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 7992 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7993 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7994 CXXMethodDecl *OldMD = nullptr; 7995 if (OldDecl) 7996 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction()); 7997 if (!OldMD || !OldMD->isStatic()) { 7998 const FunctionProtoType *FPT = 7999 MD->getType()->castAs<FunctionProtoType>(); 8000 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 8001 EPI.TypeQuals |= Qualifiers::Const; 8002 MD->setType(Context.getFunctionType(FPT->getReturnType(), 8003 FPT->getParamTypes(), EPI)); 8004 8005 // Warn that we did this, if we're not performing template instantiation. 8006 // In that case, we'll have warned already when the template was defined. 8007 if (ActiveTemplateInstantiations.empty()) { 8008 SourceLocation AddConstLoc; 8009 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 8010 .IgnoreParens().getAs<FunctionTypeLoc>()) 8011 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 8012 8013 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 8014 << FixItHint::CreateInsertion(AddConstLoc, " const"); 8015 } 8016 } 8017 } 8018 8019 if (Redeclaration) { 8020 // NewFD and OldDecl represent declarations that need to be 8021 // merged. 8022 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 8023 NewFD->setInvalidDecl(); 8024 return Redeclaration; 8025 } 8026 8027 Previous.clear(); 8028 Previous.addDecl(OldDecl); 8029 8030 if (FunctionTemplateDecl *OldTemplateDecl 8031 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 8032 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 8033 FunctionTemplateDecl *NewTemplateDecl 8034 = NewFD->getDescribedFunctionTemplate(); 8035 assert(NewTemplateDecl && "Template/non-template mismatch"); 8036 if (CXXMethodDecl *Method 8037 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 8038 Method->setAccess(OldTemplateDecl->getAccess()); 8039 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 8040 } 8041 8042 // If this is an explicit specialization of a member that is a function 8043 // template, mark it as a member specialization. 8044 if (IsExplicitSpecialization && 8045 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 8046 NewTemplateDecl->setMemberSpecialization(); 8047 assert(OldTemplateDecl->isMemberSpecialization()); 8048 } 8049 8050 } else { 8051 // This needs to happen first so that 'inline' propagates. 8052 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 8053 8054 if (isa<CXXMethodDecl>(NewFD)) 8055 NewFD->setAccess(OldDecl->getAccess()); 8056 } 8057 } 8058 8059 // Semantic checking for this function declaration (in isolation). 8060 8061 if (getLangOpts().CPlusPlus) { 8062 // C++-specific checks. 8063 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 8064 CheckConstructor(Constructor); 8065 } else if (CXXDestructorDecl *Destructor = 8066 dyn_cast<CXXDestructorDecl>(NewFD)) { 8067 CXXRecordDecl *Record = Destructor->getParent(); 8068 QualType ClassType = Context.getTypeDeclType(Record); 8069 8070 // FIXME: Shouldn't we be able to perform this check even when the class 8071 // type is dependent? Both gcc and edg can handle that. 8072 if (!ClassType->isDependentType()) { 8073 DeclarationName Name 8074 = Context.DeclarationNames.getCXXDestructorName( 8075 Context.getCanonicalType(ClassType)); 8076 if (NewFD->getDeclName() != Name) { 8077 Diag(NewFD->getLocation(), diag::err_destructor_name); 8078 NewFD->setInvalidDecl(); 8079 return Redeclaration; 8080 } 8081 } 8082 } else if (CXXConversionDecl *Conversion 8083 = dyn_cast<CXXConversionDecl>(NewFD)) { 8084 ActOnConversionDeclarator(Conversion); 8085 } 8086 8087 // Find any virtual functions that this function overrides. 8088 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 8089 if (!Method->isFunctionTemplateSpecialization() && 8090 !Method->getDescribedFunctionTemplate() && 8091 Method->isCanonicalDecl()) { 8092 if (AddOverriddenMethods(Method->getParent(), Method)) { 8093 // If the function was marked as "static", we have a problem. 8094 if (NewFD->getStorageClass() == SC_Static) { 8095 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8096 } 8097 } 8098 } 8099 8100 if (Method->isStatic()) 8101 checkThisInStaticMemberFunctionType(Method); 8102 } 8103 8104 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8105 if (NewFD->isOverloadedOperator() && 8106 CheckOverloadedOperatorDeclaration(NewFD)) { 8107 NewFD->setInvalidDecl(); 8108 return Redeclaration; 8109 } 8110 8111 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8112 if (NewFD->getLiteralIdentifier() && 8113 CheckLiteralOperatorDeclaration(NewFD)) { 8114 NewFD->setInvalidDecl(); 8115 return Redeclaration; 8116 } 8117 8118 // In C++, check default arguments now that we have merged decls. Unless 8119 // the lexical context is the class, because in this case this is done 8120 // during delayed parsing anyway. 8121 if (!CurContext->isRecord()) 8122 CheckCXXDefaultArguments(NewFD); 8123 8124 // If this function declares a builtin function, check the type of this 8125 // declaration against the expected type for the builtin. 8126 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8127 ASTContext::GetBuiltinTypeError Error; 8128 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8129 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8130 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8131 // The type of this function differs from the type of the builtin, 8132 // so forget about the builtin entirely. 8133 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 8134 } 8135 } 8136 8137 // If this function is declared as being extern "C", then check to see if 8138 // the function returns a UDT (class, struct, or union type) that is not C 8139 // compatible, and if it does, warn the user. 8140 // But, issue any diagnostic on the first declaration only. 8141 if (Previous.empty() && NewFD->isExternC()) { 8142 QualType R = NewFD->getReturnType(); 8143 if (R->isIncompleteType() && !R->isVoidType()) 8144 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8145 << NewFD << R; 8146 else if (!R.isPODType(Context) && !R->isVoidType() && 8147 !R->isObjCObjectPointerType()) 8148 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8149 } 8150 } 8151 return Redeclaration; 8152 } 8153 8154 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8155 // C++11 [basic.start.main]p3: 8156 // A program that [...] declares main to be inline, static or 8157 // constexpr is ill-formed. 8158 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8159 // appear in a declaration of main. 8160 // static main is not an error under C99, but we should warn about it. 8161 // We accept _Noreturn main as an extension. 8162 if (FD->getStorageClass() == SC_Static) 8163 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8164 ? diag::err_static_main : diag::warn_static_main) 8165 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8166 if (FD->isInlineSpecified()) 8167 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8168 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8169 if (DS.isNoreturnSpecified()) { 8170 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8171 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8172 Diag(NoreturnLoc, diag::ext_noreturn_main); 8173 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8174 << FixItHint::CreateRemoval(NoreturnRange); 8175 } 8176 if (FD->isConstexpr()) { 8177 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8178 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8179 FD->setConstexpr(false); 8180 } 8181 8182 if (getLangOpts().OpenCL) { 8183 Diag(FD->getLocation(), diag::err_opencl_no_main) 8184 << FD->hasAttr<OpenCLKernelAttr>(); 8185 FD->setInvalidDecl(); 8186 return; 8187 } 8188 8189 QualType T = FD->getType(); 8190 assert(T->isFunctionType() && "function decl is not of function type"); 8191 const FunctionType* FT = T->castAs<FunctionType>(); 8192 8193 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8194 // In C with GNU extensions we allow main() to have non-integer return 8195 // type, but we should warn about the extension, and we disable the 8196 // implicit-return-zero rule. 8197 8198 // GCC in C mode accepts qualified 'int'. 8199 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8200 FD->setHasImplicitReturnZero(true); 8201 else { 8202 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8203 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8204 if (RTRange.isValid()) 8205 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8206 << FixItHint::CreateReplacement(RTRange, "int"); 8207 } 8208 } else { 8209 // In C and C++, main magically returns 0 if you fall off the end; 8210 // set the flag which tells us that. 8211 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8212 8213 // All the standards say that main() should return 'int'. 8214 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8215 FD->setHasImplicitReturnZero(true); 8216 else { 8217 // Otherwise, this is just a flat-out error. 8218 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8219 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8220 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8221 : FixItHint()); 8222 FD->setInvalidDecl(true); 8223 } 8224 } 8225 8226 // Treat protoless main() as nullary. 8227 if (isa<FunctionNoProtoType>(FT)) return; 8228 8229 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8230 unsigned nparams = FTP->getNumParams(); 8231 assert(FD->getNumParams() == nparams); 8232 8233 bool HasExtraParameters = (nparams > 3); 8234 8235 // Darwin passes an undocumented fourth argument of type char**. If 8236 // other platforms start sprouting these, the logic below will start 8237 // getting shifty. 8238 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8239 HasExtraParameters = false; 8240 8241 if (HasExtraParameters) { 8242 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8243 FD->setInvalidDecl(true); 8244 nparams = 3; 8245 } 8246 8247 // FIXME: a lot of the following diagnostics would be improved 8248 // if we had some location information about types. 8249 8250 QualType CharPP = 8251 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8252 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8253 8254 for (unsigned i = 0; i < nparams; ++i) { 8255 QualType AT = FTP->getParamType(i); 8256 8257 bool mismatch = true; 8258 8259 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8260 mismatch = false; 8261 else if (Expected[i] == CharPP) { 8262 // As an extension, the following forms are okay: 8263 // char const ** 8264 // char const * const * 8265 // char * const * 8266 8267 QualifierCollector qs; 8268 const PointerType* PT; 8269 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8270 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8271 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8272 Context.CharTy)) { 8273 qs.removeConst(); 8274 mismatch = !qs.empty(); 8275 } 8276 } 8277 8278 if (mismatch) { 8279 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8280 // TODO: suggest replacing given type with expected type 8281 FD->setInvalidDecl(true); 8282 } 8283 } 8284 8285 if (nparams == 1 && !FD->isInvalidDecl()) { 8286 Diag(FD->getLocation(), diag::warn_main_one_arg); 8287 } 8288 8289 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8290 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8291 FD->setInvalidDecl(); 8292 } 8293 } 8294 8295 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8296 QualType T = FD->getType(); 8297 assert(T->isFunctionType() && "function decl is not of function type"); 8298 const FunctionType *FT = T->castAs<FunctionType>(); 8299 8300 // Set an implicit return of 'zero' if the function can return some integral, 8301 // enumeration, pointer or nullptr type. 8302 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8303 FT->getReturnType()->isAnyPointerType() || 8304 FT->getReturnType()->isNullPtrType()) 8305 // DllMain is exempt because a return value of zero means it failed. 8306 if (FD->getName() != "DllMain") 8307 FD->setHasImplicitReturnZero(true); 8308 8309 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8310 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8311 FD->setInvalidDecl(); 8312 } 8313 } 8314 8315 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8316 // FIXME: Need strict checking. In C89, we need to check for 8317 // any assignment, increment, decrement, function-calls, or 8318 // commas outside of a sizeof. In C99, it's the same list, 8319 // except that the aforementioned are allowed in unevaluated 8320 // expressions. Everything else falls under the 8321 // "may accept other forms of constant expressions" exception. 8322 // (We never end up here for C++, so the constant expression 8323 // rules there don't matter.) 8324 const Expr *Culprit; 8325 if (Init->isConstantInitializer(Context, false, &Culprit)) 8326 return false; 8327 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8328 << Culprit->getSourceRange(); 8329 return true; 8330 } 8331 8332 namespace { 8333 // Visits an initialization expression to see if OrigDecl is evaluated in 8334 // its own initialization and throws a warning if it does. 8335 class SelfReferenceChecker 8336 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8337 Sema &S; 8338 Decl *OrigDecl; 8339 bool isRecordType; 8340 bool isPODType; 8341 bool isReferenceType; 8342 8343 bool isInitList; 8344 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8345 public: 8346 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8347 8348 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8349 S(S), OrigDecl(OrigDecl) { 8350 isPODType = false; 8351 isRecordType = false; 8352 isReferenceType = false; 8353 isInitList = false; 8354 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8355 isPODType = VD->getType().isPODType(S.Context); 8356 isRecordType = VD->getType()->isRecordType(); 8357 isReferenceType = VD->getType()->isReferenceType(); 8358 } 8359 } 8360 8361 // For most expressions, just call the visitor. For initializer lists, 8362 // track the index of the field being initialized since fields are 8363 // initialized in order allowing use of previously initialized fields. 8364 void CheckExpr(Expr *E) { 8365 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8366 if (!InitList) { 8367 Visit(E); 8368 return; 8369 } 8370 8371 // Track and increment the index here. 8372 isInitList = true; 8373 InitFieldIndex.push_back(0); 8374 for (auto Child : InitList->children()) { 8375 CheckExpr(cast<Expr>(Child)); 8376 ++InitFieldIndex.back(); 8377 } 8378 InitFieldIndex.pop_back(); 8379 } 8380 8381 // Returns true if MemberExpr is checked and no futher checking is needed. 8382 // Returns false if additional checking is required. 8383 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8384 llvm::SmallVector<FieldDecl*, 4> Fields; 8385 Expr *Base = E; 8386 bool ReferenceField = false; 8387 8388 // Get the field memebers used. 8389 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8390 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8391 if (!FD) 8392 return false; 8393 Fields.push_back(FD); 8394 if (FD->getType()->isReferenceType()) 8395 ReferenceField = true; 8396 Base = ME->getBase()->IgnoreParenImpCasts(); 8397 } 8398 8399 // Keep checking only if the base Decl is the same. 8400 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8401 if (!DRE || DRE->getDecl() != OrigDecl) 8402 return false; 8403 8404 // A reference field can be bound to an unininitialized field. 8405 if (CheckReference && !ReferenceField) 8406 return true; 8407 8408 // Convert FieldDecls to their index number. 8409 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8410 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) { 8411 UsedFieldIndex.push_back((*I)->getFieldIndex()); 8412 } 8413 8414 // See if a warning is needed by checking the first difference in index 8415 // numbers. If field being used has index less than the field being 8416 // initialized, then the use is safe. 8417 for (auto UsedIter = UsedFieldIndex.begin(), 8418 UsedEnd = UsedFieldIndex.end(), 8419 OrigIter = InitFieldIndex.begin(), 8420 OrigEnd = InitFieldIndex.end(); 8421 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8422 if (*UsedIter < *OrigIter) 8423 return true; 8424 if (*UsedIter > *OrigIter) 8425 break; 8426 } 8427 8428 // TODO: Add a different warning which will print the field names. 8429 HandleDeclRefExpr(DRE); 8430 return true; 8431 } 8432 8433 // For most expressions, the cast is directly above the DeclRefExpr. 8434 // For conditional operators, the cast can be outside the conditional 8435 // operator if both expressions are DeclRefExpr's. 8436 void HandleValue(Expr *E) { 8437 E = E->IgnoreParens(); 8438 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8439 HandleDeclRefExpr(DRE); 8440 return; 8441 } 8442 8443 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8444 Visit(CO->getCond()); 8445 HandleValue(CO->getTrueExpr()); 8446 HandleValue(CO->getFalseExpr()); 8447 return; 8448 } 8449 8450 if (BinaryConditionalOperator *BCO = 8451 dyn_cast<BinaryConditionalOperator>(E)) { 8452 Visit(BCO->getCond()); 8453 HandleValue(BCO->getFalseExpr()); 8454 return; 8455 } 8456 8457 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8458 HandleValue(OVE->getSourceExpr()); 8459 return; 8460 } 8461 8462 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8463 if (BO->getOpcode() == BO_Comma) { 8464 Visit(BO->getLHS()); 8465 HandleValue(BO->getRHS()); 8466 return; 8467 } 8468 } 8469 8470 if (isa<MemberExpr>(E)) { 8471 if (isInitList) { 8472 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8473 false /*CheckReference*/)) 8474 return; 8475 } 8476 8477 Expr *Base = E->IgnoreParenImpCasts(); 8478 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8479 // Check for static member variables and don't warn on them. 8480 if (!isa<FieldDecl>(ME->getMemberDecl())) 8481 return; 8482 Base = ME->getBase()->IgnoreParenImpCasts(); 8483 } 8484 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8485 HandleDeclRefExpr(DRE); 8486 return; 8487 } 8488 8489 Visit(E); 8490 } 8491 8492 // Reference types not handled in HandleValue are handled here since all 8493 // uses of references are bad, not just r-value uses. 8494 void VisitDeclRefExpr(DeclRefExpr *E) { 8495 if (isReferenceType) 8496 HandleDeclRefExpr(E); 8497 } 8498 8499 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8500 if (E->getCastKind() == CK_LValueToRValue) { 8501 HandleValue(E->getSubExpr()); 8502 return; 8503 } 8504 8505 Inherited::VisitImplicitCastExpr(E); 8506 } 8507 8508 void VisitMemberExpr(MemberExpr *E) { 8509 if (isInitList) { 8510 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 8511 return; 8512 } 8513 8514 // Don't warn on arrays since they can be treated as pointers. 8515 if (E->getType()->canDecayToPointerType()) return; 8516 8517 // Warn when a non-static method call is followed by non-static member 8518 // field accesses, which is followed by a DeclRefExpr. 8519 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8520 bool Warn = (MD && !MD->isStatic()); 8521 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8522 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8523 if (!isa<FieldDecl>(ME->getMemberDecl())) 8524 Warn = false; 8525 Base = ME->getBase()->IgnoreParenImpCasts(); 8526 } 8527 8528 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8529 if (Warn) 8530 HandleDeclRefExpr(DRE); 8531 return; 8532 } 8533 8534 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8535 // Visit that expression. 8536 Visit(Base); 8537 } 8538 8539 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8540 Expr *Callee = E->getCallee(); 8541 8542 if (isa<UnresolvedLookupExpr>(Callee)) 8543 return Inherited::VisitCXXOperatorCallExpr(E); 8544 8545 Visit(Callee); 8546 for (auto Arg: E->arguments()) 8547 HandleValue(Arg->IgnoreParenImpCasts()); 8548 } 8549 8550 void VisitUnaryOperator(UnaryOperator *E) { 8551 // For POD record types, addresses of its own members are well-defined. 8552 if (E->getOpcode() == UO_AddrOf && isRecordType && 8553 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8554 if (!isPODType) 8555 HandleValue(E->getSubExpr()); 8556 return; 8557 } 8558 8559 if (E->isIncrementDecrementOp()) { 8560 HandleValue(E->getSubExpr()); 8561 return; 8562 } 8563 8564 Inherited::VisitUnaryOperator(E); 8565 } 8566 8567 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8568 8569 void VisitCXXConstructExpr(CXXConstructExpr *E) { 8570 if (E->getConstructor()->isCopyConstructor()) { 8571 Expr *ArgExpr = E->getArg(0); 8572 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 8573 if (ILE->getNumInits() == 1) 8574 ArgExpr = ILE->getInit(0); 8575 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8576 if (ICE->getCastKind() == CK_NoOp) 8577 ArgExpr = ICE->getSubExpr(); 8578 HandleValue(ArgExpr); 8579 return; 8580 } 8581 Inherited::VisitCXXConstructExpr(E); 8582 } 8583 8584 void VisitCallExpr(CallExpr *E) { 8585 // Treat std::move as a use. 8586 if (E->getNumArgs() == 1) { 8587 if (FunctionDecl *FD = E->getDirectCallee()) { 8588 if (FD->isInStdNamespace() && FD->getIdentifier() && 8589 FD->getIdentifier()->isStr("move")) { 8590 HandleValue(E->getArg(0)); 8591 return; 8592 } 8593 } 8594 } 8595 8596 Inherited::VisitCallExpr(E); 8597 } 8598 8599 void VisitBinaryOperator(BinaryOperator *E) { 8600 if (E->isCompoundAssignmentOp()) { 8601 HandleValue(E->getLHS()); 8602 Visit(E->getRHS()); 8603 return; 8604 } 8605 8606 Inherited::VisitBinaryOperator(E); 8607 } 8608 8609 // A custom visitor for BinaryConditionalOperator is needed because the 8610 // regular visitor would check the condition and true expression separately 8611 // but both point to the same place giving duplicate diagnostics. 8612 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 8613 Visit(E->getCond()); 8614 Visit(E->getFalseExpr()); 8615 } 8616 8617 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8618 Decl* ReferenceDecl = DRE->getDecl(); 8619 if (OrigDecl != ReferenceDecl) return; 8620 unsigned diag; 8621 if (isReferenceType) { 8622 diag = diag::warn_uninit_self_reference_in_reference_init; 8623 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8624 diag = diag::warn_static_self_reference_in_init; 8625 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) || 8626 isa<NamespaceDecl>(OrigDecl->getDeclContext()) || 8627 DRE->getDecl()->getType()->isRecordType()) { 8628 diag = diag::warn_uninit_self_reference_in_init; 8629 } else { 8630 // Local variables will be handled by the CFG analysis. 8631 return; 8632 } 8633 8634 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8635 S.PDiag(diag) 8636 << DRE->getNameInfo().getName() 8637 << OrigDecl->getLocation() 8638 << DRE->getSourceRange()); 8639 } 8640 }; 8641 8642 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8643 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8644 bool DirectInit) { 8645 // Parameters arguments are occassionially constructed with itself, 8646 // for instance, in recursive functions. Skip them. 8647 if (isa<ParmVarDecl>(OrigDecl)) 8648 return; 8649 8650 E = E->IgnoreParens(); 8651 8652 // Skip checking T a = a where T is not a record or reference type. 8653 // Doing so is a way to silence uninitialized warnings. 8654 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8655 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8656 if (ICE->getCastKind() == CK_LValueToRValue) 8657 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8658 if (DRE->getDecl() == OrigDecl) 8659 return; 8660 8661 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 8662 } 8663 } 8664 8665 /// AddInitializerToDecl - Adds the initializer Init to the 8666 /// declaration dcl. If DirectInit is true, this is C++ direct 8667 /// initialization rather than copy initialization. 8668 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8669 bool DirectInit, bool TypeMayContainAuto) { 8670 // If there is no declaration, there was an error parsing it. Just ignore 8671 // the initializer. 8672 if (!RealDecl || RealDecl->isInvalidDecl()) { 8673 CorrectDelayedTyposInExpr(Init); 8674 return; 8675 } 8676 8677 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8678 // With declarators parsed the way they are, the parser cannot 8679 // distinguish between a normal initializer and a pure-specifier. 8680 // Thus this grotesque test. 8681 IntegerLiteral *IL; 8682 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8683 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8684 CheckPureMethod(Method, Init->getSourceRange()); 8685 else { 8686 Diag(Method->getLocation(), diag::err_member_function_initialization) 8687 << Method->getDeclName() << Init->getSourceRange(); 8688 Method->setInvalidDecl(); 8689 } 8690 return; 8691 } 8692 8693 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8694 if (!VDecl) { 8695 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8696 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8697 RealDecl->setInvalidDecl(); 8698 return; 8699 } 8700 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8701 8702 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8703 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8704 // Attempt typo correction early so that the type of the init expression can 8705 // be deduced based on the chosen correction:if the original init contains a 8706 // TypoExpr. 8707 ExprResult Res = CorrectDelayedTyposInExpr(Init); 8708 if (!Res.isUsable()) { 8709 RealDecl->setInvalidDecl(); 8710 return; 8711 } 8712 if (Res.get() != Init) { 8713 Init = Res.get(); 8714 if (CXXDirectInit) 8715 CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8716 } 8717 8718 Expr *DeduceInit = Init; 8719 // Initializer could be a C++ direct-initializer. Deduction only works if it 8720 // contains exactly one expression. 8721 if (CXXDirectInit) { 8722 if (CXXDirectInit->getNumExprs() == 0) { 8723 // It isn't possible to write this directly, but it is possible to 8724 // end up in this situation with "auto x(some_pack...);" 8725 Diag(CXXDirectInit->getLocStart(), 8726 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8727 : diag::err_auto_var_init_no_expression) 8728 << VDecl->getDeclName() << VDecl->getType() 8729 << VDecl->getSourceRange(); 8730 RealDecl->setInvalidDecl(); 8731 return; 8732 } else if (CXXDirectInit->getNumExprs() > 1) { 8733 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8734 VDecl->isInitCapture() 8735 ? diag::err_init_capture_multiple_expressions 8736 : diag::err_auto_var_init_multiple_expressions) 8737 << VDecl->getDeclName() << VDecl->getType() 8738 << VDecl->getSourceRange(); 8739 RealDecl->setInvalidDecl(); 8740 return; 8741 } else { 8742 DeduceInit = CXXDirectInit->getExpr(0); 8743 if (isa<InitListExpr>(DeduceInit)) 8744 Diag(CXXDirectInit->getLocStart(), 8745 diag::err_auto_var_init_paren_braces) 8746 << VDecl->getDeclName() << VDecl->getType() 8747 << VDecl->getSourceRange(); 8748 } 8749 } 8750 8751 // Expressions default to 'id' when we're in a debugger. 8752 bool DefaultedToAuto = false; 8753 if (getLangOpts().DebuggerCastResultToId && 8754 Init->getType() == Context.UnknownAnyTy) { 8755 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8756 if (Result.isInvalid()) { 8757 VDecl->setInvalidDecl(); 8758 return; 8759 } 8760 Init = Result.get(); 8761 DefaultedToAuto = true; 8762 } 8763 8764 QualType DeducedType; 8765 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8766 DAR_Failed) 8767 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8768 if (DeducedType.isNull()) { 8769 RealDecl->setInvalidDecl(); 8770 return; 8771 } 8772 VDecl->setType(DeducedType); 8773 assert(VDecl->isLinkageValid()); 8774 8775 // In ARC, infer lifetime. 8776 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8777 VDecl->setInvalidDecl(); 8778 8779 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8780 // 'id' instead of a specific object type prevents most of our usual checks. 8781 // We only want to warn outside of template instantiations, though: 8782 // inside a template, the 'id' could have come from a parameter. 8783 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8784 DeducedType->isObjCIdType()) { 8785 SourceLocation Loc = 8786 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8787 Diag(Loc, diag::warn_auto_var_is_id) 8788 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8789 } 8790 8791 // If this is a redeclaration, check that the type we just deduced matches 8792 // the previously declared type. 8793 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8794 // We never need to merge the type, because we cannot form an incomplete 8795 // array of auto, nor deduce such a type. 8796 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8797 } 8798 8799 // Check the deduced type is valid for a variable declaration. 8800 CheckVariableDeclarationType(VDecl); 8801 if (VDecl->isInvalidDecl()) 8802 return; 8803 8804 // If all looks well, warn if this is a case that will change meaning when 8805 // we implement N3922. 8806 if (DirectInit && !CXXDirectInit && isa<InitListExpr>(Init)) { 8807 Diag(Init->getLocStart(), 8808 diag::warn_auto_var_direct_list_init) 8809 << FixItHint::CreateInsertion(Init->getLocStart(), "="); 8810 } 8811 } 8812 8813 // dllimport cannot be used on variable definitions. 8814 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8815 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8816 VDecl->setInvalidDecl(); 8817 return; 8818 } 8819 8820 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8821 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8822 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8823 VDecl->setInvalidDecl(); 8824 return; 8825 } 8826 8827 if (!VDecl->getType()->isDependentType()) { 8828 // A definition must end up with a complete type, which means it must be 8829 // complete with the restriction that an array type might be completed by 8830 // the initializer; note that later code assumes this restriction. 8831 QualType BaseDeclType = VDecl->getType(); 8832 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8833 BaseDeclType = Array->getElementType(); 8834 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8835 diag::err_typecheck_decl_incomplete_type)) { 8836 RealDecl->setInvalidDecl(); 8837 return; 8838 } 8839 8840 // The variable can not have an abstract class type. 8841 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8842 diag::err_abstract_type_in_decl, 8843 AbstractVariableType)) 8844 VDecl->setInvalidDecl(); 8845 } 8846 8847 const VarDecl *Def; 8848 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8849 Diag(VDecl->getLocation(), diag::err_redefinition) 8850 << VDecl->getDeclName(); 8851 Diag(Def->getLocation(), diag::note_previous_definition); 8852 VDecl->setInvalidDecl(); 8853 return; 8854 } 8855 8856 const VarDecl *PrevInit = nullptr; 8857 if (getLangOpts().CPlusPlus) { 8858 // C++ [class.static.data]p4 8859 // If a static data member is of const integral or const 8860 // enumeration type, its declaration in the class definition can 8861 // specify a constant-initializer which shall be an integral 8862 // constant expression (5.19). In that case, the member can appear 8863 // in integral constant expressions. The member shall still be 8864 // defined in a namespace scope if it is used in the program and the 8865 // namespace scope definition shall not contain an initializer. 8866 // 8867 // We already performed a redefinition check above, but for static 8868 // data members we also need to check whether there was an in-class 8869 // declaration with an initializer. 8870 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8871 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8872 << VDecl->getDeclName(); 8873 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8874 return; 8875 } 8876 8877 if (VDecl->hasLocalStorage()) 8878 getCurFunction()->setHasBranchProtectedScope(); 8879 8880 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8881 VDecl->setInvalidDecl(); 8882 return; 8883 } 8884 } 8885 8886 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8887 // a kernel function cannot be initialized." 8888 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8889 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8890 VDecl->setInvalidDecl(); 8891 return; 8892 } 8893 8894 // Get the decls type and save a reference for later, since 8895 // CheckInitializerTypes may change it. 8896 QualType DclT = VDecl->getType(), SavT = DclT; 8897 8898 // Expressions default to 'id' when we're in a debugger 8899 // and we are assigning it to a variable of Objective-C pointer type. 8900 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8901 Init->getType() == Context.UnknownAnyTy) { 8902 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8903 if (Result.isInvalid()) { 8904 VDecl->setInvalidDecl(); 8905 return; 8906 } 8907 Init = Result.get(); 8908 } 8909 8910 // Perform the initialization. 8911 if (!VDecl->isInvalidDecl()) { 8912 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8913 InitializationKind Kind 8914 = DirectInit ? 8915 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8916 Init->getLocStart(), 8917 Init->getLocEnd()) 8918 : InitializationKind::CreateDirectList( 8919 VDecl->getLocation()) 8920 : InitializationKind::CreateCopy(VDecl->getLocation(), 8921 Init->getLocStart()); 8922 8923 MultiExprArg Args = Init; 8924 if (CXXDirectInit) 8925 Args = MultiExprArg(CXXDirectInit->getExprs(), 8926 CXXDirectInit->getNumExprs()); 8927 8928 // Try to correct any TypoExprs in the initialization arguments. 8929 for (size_t Idx = 0; Idx < Args.size(); ++Idx) { 8930 ExprResult Res = 8931 CorrectDelayedTyposInExpr(Args[Idx], [this, Entity, Kind](Expr *E) { 8932 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E)); 8933 return Init.Failed() ? ExprError() : E; 8934 }); 8935 if (Res.isInvalid()) { 8936 VDecl->setInvalidDecl(); 8937 } else if (Res.get() != Args[Idx]) { 8938 Args[Idx] = Res.get(); 8939 } 8940 } 8941 if (VDecl->isInvalidDecl()) 8942 return; 8943 8944 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8945 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8946 if (Result.isInvalid()) { 8947 VDecl->setInvalidDecl(); 8948 return; 8949 } 8950 8951 Init = Result.getAs<Expr>(); 8952 } 8953 8954 // Check for self-references within variable initializers. 8955 // Variables declared within a function/method body (except for references) 8956 // are handled by a dataflow analysis. 8957 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8958 VDecl->getType()->isReferenceType()) { 8959 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8960 } 8961 8962 // If the type changed, it means we had an incomplete type that was 8963 // completed by the initializer. For example: 8964 // int ary[] = { 1, 3, 5 }; 8965 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8966 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8967 VDecl->setType(DclT); 8968 8969 if (!VDecl->isInvalidDecl()) { 8970 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8971 8972 if (VDecl->hasAttr<BlocksAttr>()) 8973 checkRetainCycles(VDecl, Init); 8974 8975 // It is safe to assign a weak reference into a strong variable. 8976 // Although this code can still have problems: 8977 // id x = self.weakProp; 8978 // id y = self.weakProp; 8979 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8980 // paths through the function. This should be revisited if 8981 // -Wrepeated-use-of-weak is made flow-sensitive. 8982 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 8983 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 8984 Init->getLocStart())) 8985 getCurFunction()->markSafeWeakUse(Init); 8986 } 8987 8988 // The initialization is usually a full-expression. 8989 // 8990 // FIXME: If this is a braced initialization of an aggregate, it is not 8991 // an expression, and each individual field initializer is a separate 8992 // full-expression. For instance, in: 8993 // 8994 // struct Temp { ~Temp(); }; 8995 // struct S { S(Temp); }; 8996 // struct T { S a, b; } t = { Temp(), Temp() } 8997 // 8998 // we should destroy the first Temp before constructing the second. 8999 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 9000 false, 9001 VDecl->isConstexpr()); 9002 if (Result.isInvalid()) { 9003 VDecl->setInvalidDecl(); 9004 return; 9005 } 9006 Init = Result.get(); 9007 9008 // Attach the initializer to the decl. 9009 VDecl->setInit(Init); 9010 9011 if (VDecl->isLocalVarDecl()) { 9012 // C99 6.7.8p4: All the expressions in an initializer for an object that has 9013 // static storage duration shall be constant expressions or string literals. 9014 // C++ does not have this restriction. 9015 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 9016 const Expr *Culprit; 9017 if (VDecl->getStorageClass() == SC_Static) 9018 CheckForConstantInitializer(Init, DclT); 9019 // C89 is stricter than C99 for non-static aggregate types. 9020 // C89 6.5.7p3: All the expressions [...] in an initializer list 9021 // for an object that has aggregate or union type shall be 9022 // constant expressions. 9023 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 9024 isa<InitListExpr>(Init) && 9025 !Init->isConstantInitializer(Context, false, &Culprit)) 9026 Diag(Culprit->getExprLoc(), 9027 diag::ext_aggregate_init_not_constant) 9028 << Culprit->getSourceRange(); 9029 } 9030 } else if (VDecl->isStaticDataMember() && 9031 VDecl->getLexicalDeclContext()->isRecord()) { 9032 // This is an in-class initialization for a static data member, e.g., 9033 // 9034 // struct S { 9035 // static const int value = 17; 9036 // }; 9037 9038 // C++ [class.mem]p4: 9039 // A member-declarator can contain a constant-initializer only 9040 // if it declares a static member (9.4) of const integral or 9041 // const enumeration type, see 9.4.2. 9042 // 9043 // C++11 [class.static.data]p3: 9044 // If a non-volatile const static data member is of integral or 9045 // enumeration type, its declaration in the class definition can 9046 // specify a brace-or-equal-initializer in which every initalizer-clause 9047 // that is an assignment-expression is a constant expression. A static 9048 // data member of literal type can be declared in the class definition 9049 // with the constexpr specifier; if so, its declaration shall specify a 9050 // brace-or-equal-initializer in which every initializer-clause that is 9051 // an assignment-expression is a constant expression. 9052 9053 // Do nothing on dependent types. 9054 if (DclT->isDependentType()) { 9055 9056 // Allow any 'static constexpr' members, whether or not they are of literal 9057 // type. We separately check that every constexpr variable is of literal 9058 // type. 9059 } else if (VDecl->isConstexpr()) { 9060 9061 // Require constness. 9062 } else if (!DclT.isConstQualified()) { 9063 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 9064 << Init->getSourceRange(); 9065 VDecl->setInvalidDecl(); 9066 9067 // We allow integer constant expressions in all cases. 9068 } else if (DclT->isIntegralOrEnumerationType()) { 9069 // Check whether the expression is a constant expression. 9070 SourceLocation Loc; 9071 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 9072 // In C++11, a non-constexpr const static data member with an 9073 // in-class initializer cannot be volatile. 9074 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 9075 else if (Init->isValueDependent()) 9076 ; // Nothing to check. 9077 else if (Init->isIntegerConstantExpr(Context, &Loc)) 9078 ; // Ok, it's an ICE! 9079 else if (Init->isEvaluatable(Context)) { 9080 // If we can constant fold the initializer through heroics, accept it, 9081 // but report this as a use of an extension for -pedantic. 9082 Diag(Loc, diag::ext_in_class_initializer_non_constant) 9083 << Init->getSourceRange(); 9084 } else { 9085 // Otherwise, this is some crazy unknown case. Report the issue at the 9086 // location provided by the isIntegerConstantExpr failed check. 9087 Diag(Loc, diag::err_in_class_initializer_non_constant) 9088 << Init->getSourceRange(); 9089 VDecl->setInvalidDecl(); 9090 } 9091 9092 // We allow foldable floating-point constants as an extension. 9093 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 9094 // In C++98, this is a GNU extension. In C++11, it is not, but we support 9095 // it anyway and provide a fixit to add the 'constexpr'. 9096 if (getLangOpts().CPlusPlus11) { 9097 Diag(VDecl->getLocation(), 9098 diag::ext_in_class_initializer_float_type_cxx11) 9099 << DclT << Init->getSourceRange(); 9100 Diag(VDecl->getLocStart(), 9101 diag::note_in_class_initializer_float_type_cxx11) 9102 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9103 } else { 9104 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 9105 << DclT << Init->getSourceRange(); 9106 9107 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 9108 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 9109 << Init->getSourceRange(); 9110 VDecl->setInvalidDecl(); 9111 } 9112 } 9113 9114 // Suggest adding 'constexpr' in C++11 for literal types. 9115 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 9116 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 9117 << DclT << Init->getSourceRange() 9118 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 9119 VDecl->setConstexpr(true); 9120 9121 } else { 9122 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 9123 << DclT << Init->getSourceRange(); 9124 VDecl->setInvalidDecl(); 9125 } 9126 } else if (VDecl->isFileVarDecl()) { 9127 if (VDecl->getStorageClass() == SC_Extern && 9128 (!getLangOpts().CPlusPlus || 9129 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 9130 VDecl->isExternC())) && 9131 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 9132 Diag(VDecl->getLocation(), diag::warn_extern_init); 9133 9134 // C99 6.7.8p4. All file scoped initializers need to be constant. 9135 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 9136 CheckForConstantInitializer(Init, DclT); 9137 } 9138 9139 // We will represent direct-initialization similarly to copy-initialization: 9140 // int x(1); -as-> int x = 1; 9141 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9142 // 9143 // Clients that want to distinguish between the two forms, can check for 9144 // direct initializer using VarDecl::getInitStyle(). 9145 // A major benefit is that clients that don't particularly care about which 9146 // exactly form was it (like the CodeGen) can handle both cases without 9147 // special case code. 9148 9149 // C++ 8.5p11: 9150 // The form of initialization (using parentheses or '=') is generally 9151 // insignificant, but does matter when the entity being initialized has a 9152 // class type. 9153 if (CXXDirectInit) { 9154 assert(DirectInit && "Call-style initializer must be direct init."); 9155 VDecl->setInitStyle(VarDecl::CallInit); 9156 } else if (DirectInit) { 9157 // This must be list-initialization. No other way is direct-initialization. 9158 VDecl->setInitStyle(VarDecl::ListInit); 9159 } 9160 9161 CheckCompleteVariableDeclaration(VDecl); 9162 } 9163 9164 /// ActOnInitializerError - Given that there was an error parsing an 9165 /// initializer for the given declaration, try to return to some form 9166 /// of sanity. 9167 void Sema::ActOnInitializerError(Decl *D) { 9168 // Our main concern here is re-establishing invariants like "a 9169 // variable's type is either dependent or complete". 9170 if (!D || D->isInvalidDecl()) return; 9171 9172 VarDecl *VD = dyn_cast<VarDecl>(D); 9173 if (!VD) return; 9174 9175 // Auto types are meaningless if we can't make sense of the initializer. 9176 if (ParsingInitForAutoVars.count(D)) { 9177 D->setInvalidDecl(); 9178 return; 9179 } 9180 9181 QualType Ty = VD->getType(); 9182 if (Ty->isDependentType()) return; 9183 9184 // Require a complete type. 9185 if (RequireCompleteType(VD->getLocation(), 9186 Context.getBaseElementType(Ty), 9187 diag::err_typecheck_decl_incomplete_type)) { 9188 VD->setInvalidDecl(); 9189 return; 9190 } 9191 9192 // Require a non-abstract type. 9193 if (RequireNonAbstractType(VD->getLocation(), Ty, 9194 diag::err_abstract_type_in_decl, 9195 AbstractVariableType)) { 9196 VD->setInvalidDecl(); 9197 return; 9198 } 9199 9200 // Don't bother complaining about constructors or destructors, 9201 // though. 9202 } 9203 9204 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9205 bool TypeMayContainAuto) { 9206 // If there is no declaration, there was an error parsing it. Just ignore it. 9207 if (!RealDecl) 9208 return; 9209 9210 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9211 QualType Type = Var->getType(); 9212 9213 // C++11 [dcl.spec.auto]p3 9214 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9215 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9216 << Var->getDeclName() << Type; 9217 Var->setInvalidDecl(); 9218 return; 9219 } 9220 9221 // C++11 [class.static.data]p3: A static data member can be declared with 9222 // the constexpr specifier; if so, its declaration shall specify 9223 // a brace-or-equal-initializer. 9224 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9225 // the definition of a variable [...] or the declaration of a static data 9226 // member. 9227 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9228 if (Var->isStaticDataMember()) 9229 Diag(Var->getLocation(), 9230 diag::err_constexpr_static_mem_var_requires_init) 9231 << Var->getDeclName(); 9232 else 9233 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9234 Var->setInvalidDecl(); 9235 return; 9236 } 9237 9238 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9239 // be initialized. 9240 if (!Var->isInvalidDecl() && 9241 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9242 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9243 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9244 Var->setInvalidDecl(); 9245 return; 9246 } 9247 9248 switch (Var->isThisDeclarationADefinition()) { 9249 case VarDecl::Definition: 9250 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9251 break; 9252 9253 // We have an out-of-line definition of a static data member 9254 // that has an in-class initializer, so we type-check this like 9255 // a declaration. 9256 // 9257 // Fall through 9258 9259 case VarDecl::DeclarationOnly: 9260 // It's only a declaration. 9261 9262 // Block scope. C99 6.7p7: If an identifier for an object is 9263 // declared with no linkage (C99 6.2.2p6), the type for the 9264 // object shall be complete. 9265 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9266 !Var->hasLinkage() && !Var->isInvalidDecl() && 9267 RequireCompleteType(Var->getLocation(), Type, 9268 diag::err_typecheck_decl_incomplete_type)) 9269 Var->setInvalidDecl(); 9270 9271 // Make sure that the type is not abstract. 9272 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9273 RequireNonAbstractType(Var->getLocation(), Type, 9274 diag::err_abstract_type_in_decl, 9275 AbstractVariableType)) 9276 Var->setInvalidDecl(); 9277 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9278 Var->getStorageClass() == SC_PrivateExtern) { 9279 Diag(Var->getLocation(), diag::warn_private_extern); 9280 Diag(Var->getLocation(), diag::note_private_extern); 9281 } 9282 9283 return; 9284 9285 case VarDecl::TentativeDefinition: 9286 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9287 // object that has file scope without an initializer, and without a 9288 // storage-class specifier or with the storage-class specifier "static", 9289 // constitutes a tentative definition. Note: A tentative definition with 9290 // external linkage is valid (C99 6.2.2p5). 9291 if (!Var->isInvalidDecl()) { 9292 if (const IncompleteArrayType *ArrayT 9293 = Context.getAsIncompleteArrayType(Type)) { 9294 if (RequireCompleteType(Var->getLocation(), 9295 ArrayT->getElementType(), 9296 diag::err_illegal_decl_array_incomplete_type)) 9297 Var->setInvalidDecl(); 9298 } else if (Var->getStorageClass() == SC_Static) { 9299 // C99 6.9.2p3: If the declaration of an identifier for an object is 9300 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9301 // declared type shall not be an incomplete type. 9302 // NOTE: code such as the following 9303 // static struct s; 9304 // struct s { int a; }; 9305 // is accepted by gcc. Hence here we issue a warning instead of 9306 // an error and we do not invalidate the static declaration. 9307 // NOTE: to avoid multiple warnings, only check the first declaration. 9308 if (Var->isFirstDecl()) 9309 RequireCompleteType(Var->getLocation(), Type, 9310 diag::ext_typecheck_decl_incomplete_type); 9311 } 9312 } 9313 9314 // Record the tentative definition; we're done. 9315 if (!Var->isInvalidDecl()) 9316 TentativeDefinitions.push_back(Var); 9317 return; 9318 } 9319 9320 // Provide a specific diagnostic for uninitialized variable 9321 // definitions with incomplete array type. 9322 if (Type->isIncompleteArrayType()) { 9323 Diag(Var->getLocation(), 9324 diag::err_typecheck_incomplete_array_needs_initializer); 9325 Var->setInvalidDecl(); 9326 return; 9327 } 9328 9329 // Provide a specific diagnostic for uninitialized variable 9330 // definitions with reference type. 9331 if (Type->isReferenceType()) { 9332 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9333 << Var->getDeclName() 9334 << SourceRange(Var->getLocation(), Var->getLocation()); 9335 Var->setInvalidDecl(); 9336 return; 9337 } 9338 9339 // Do not attempt to type-check the default initializer for a 9340 // variable with dependent type. 9341 if (Type->isDependentType()) 9342 return; 9343 9344 if (Var->isInvalidDecl()) 9345 return; 9346 9347 if (!Var->hasAttr<AliasAttr>()) { 9348 if (RequireCompleteType(Var->getLocation(), 9349 Context.getBaseElementType(Type), 9350 diag::err_typecheck_decl_incomplete_type)) { 9351 Var->setInvalidDecl(); 9352 return; 9353 } 9354 } else { 9355 return; 9356 } 9357 9358 // The variable can not have an abstract class type. 9359 if (RequireNonAbstractType(Var->getLocation(), Type, 9360 diag::err_abstract_type_in_decl, 9361 AbstractVariableType)) { 9362 Var->setInvalidDecl(); 9363 return; 9364 } 9365 9366 // Check for jumps past the implicit initializer. C++0x 9367 // clarifies that this applies to a "variable with automatic 9368 // storage duration", not a "local variable". 9369 // C++11 [stmt.dcl]p3 9370 // A program that jumps from a point where a variable with automatic 9371 // storage duration is not in scope to a point where it is in scope is 9372 // ill-formed unless the variable has scalar type, class type with a 9373 // trivial default constructor and a trivial destructor, a cv-qualified 9374 // version of one of these types, or an array of one of the preceding 9375 // types and is declared without an initializer. 9376 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9377 if (const RecordType *Record 9378 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9379 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9380 // Mark the function for further checking even if the looser rules of 9381 // C++11 do not require such checks, so that we can diagnose 9382 // incompatibilities with C++98. 9383 if (!CXXRecord->isPOD()) 9384 getCurFunction()->setHasBranchProtectedScope(); 9385 } 9386 } 9387 9388 // C++03 [dcl.init]p9: 9389 // If no initializer is specified for an object, and the 9390 // object is of (possibly cv-qualified) non-POD class type (or 9391 // array thereof), the object shall be default-initialized; if 9392 // the object is of const-qualified type, the underlying class 9393 // type shall have a user-declared default 9394 // constructor. Otherwise, if no initializer is specified for 9395 // a non- static object, the object and its subobjects, if 9396 // any, have an indeterminate initial value); if the object 9397 // or any of its subobjects are of const-qualified type, the 9398 // program is ill-formed. 9399 // C++0x [dcl.init]p11: 9400 // If no initializer is specified for an object, the object is 9401 // default-initialized; [...]. 9402 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9403 InitializationKind Kind 9404 = InitializationKind::CreateDefault(Var->getLocation()); 9405 9406 InitializationSequence InitSeq(*this, Entity, Kind, None); 9407 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9408 if (Init.isInvalid()) 9409 Var->setInvalidDecl(); 9410 else if (Init.get()) { 9411 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9412 // This is important for template substitution. 9413 Var->setInitStyle(VarDecl::CallInit); 9414 } 9415 9416 CheckCompleteVariableDeclaration(Var); 9417 } 9418 } 9419 9420 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9421 VarDecl *VD = dyn_cast<VarDecl>(D); 9422 if (!VD) { 9423 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9424 D->setInvalidDecl(); 9425 return; 9426 } 9427 9428 VD->setCXXForRangeDecl(true); 9429 9430 // for-range-declaration cannot be given a storage class specifier. 9431 int Error = -1; 9432 switch (VD->getStorageClass()) { 9433 case SC_None: 9434 break; 9435 case SC_Extern: 9436 Error = 0; 9437 break; 9438 case SC_Static: 9439 Error = 1; 9440 break; 9441 case SC_PrivateExtern: 9442 Error = 2; 9443 break; 9444 case SC_Auto: 9445 Error = 3; 9446 break; 9447 case SC_Register: 9448 Error = 4; 9449 break; 9450 case SC_OpenCLWorkGroupLocal: 9451 llvm_unreachable("Unexpected storage class"); 9452 } 9453 if (Error != -1) { 9454 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9455 << VD->getDeclName() << Error; 9456 D->setInvalidDecl(); 9457 } 9458 } 9459 9460 StmtResult 9461 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9462 IdentifierInfo *Ident, 9463 ParsedAttributes &Attrs, 9464 SourceLocation AttrEnd) { 9465 // C++1y [stmt.iter]p1: 9466 // A range-based for statement of the form 9467 // for ( for-range-identifier : for-range-initializer ) statement 9468 // is equivalent to 9469 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9470 DeclSpec DS(Attrs.getPool().getFactory()); 9471 9472 const char *PrevSpec; 9473 unsigned DiagID; 9474 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 9475 getPrintingPolicy()); 9476 9477 Declarator D(DS, Declarator::ForContext); 9478 D.SetIdentifier(Ident, IdentLoc); 9479 D.takeAttributes(Attrs, AttrEnd); 9480 9481 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 9482 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 9483 EmptyAttrs, IdentLoc); 9484 Decl *Var = ActOnDeclarator(S, D); 9485 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 9486 FinalizeDeclaration(Var); 9487 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 9488 AttrEnd.isValid() ? AttrEnd : IdentLoc); 9489 } 9490 9491 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 9492 if (var->isInvalidDecl()) return; 9493 9494 // In ARC, don't allow jumps past the implicit initialization of a 9495 // local retaining variable. 9496 if (getLangOpts().ObjCAutoRefCount && 9497 var->hasLocalStorage()) { 9498 switch (var->getType().getObjCLifetime()) { 9499 case Qualifiers::OCL_None: 9500 case Qualifiers::OCL_ExplicitNone: 9501 case Qualifiers::OCL_Autoreleasing: 9502 break; 9503 9504 case Qualifiers::OCL_Weak: 9505 case Qualifiers::OCL_Strong: 9506 getCurFunction()->setHasBranchProtectedScope(); 9507 break; 9508 } 9509 } 9510 9511 // Warn about externally-visible variables being defined without a 9512 // prior declaration. We only want to do this for global 9513 // declarations, but we also specifically need to avoid doing it for 9514 // class members because the linkage of an anonymous class can 9515 // change if it's later given a typedef name. 9516 if (var->isThisDeclarationADefinition() && 9517 var->getDeclContext()->getRedeclContext()->isFileContext() && 9518 var->isExternallyVisible() && var->hasLinkage() && 9519 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9520 var->getLocation())) { 9521 // Find a previous declaration that's not a definition. 9522 VarDecl *prev = var->getPreviousDecl(); 9523 while (prev && prev->isThisDeclarationADefinition()) 9524 prev = prev->getPreviousDecl(); 9525 9526 if (!prev) 9527 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9528 } 9529 9530 if (var->getTLSKind() == VarDecl::TLS_Static) { 9531 const Expr *Culprit; 9532 if (var->getType().isDestructedType()) { 9533 // GNU C++98 edits for __thread, [basic.start.term]p3: 9534 // The type of an object with thread storage duration shall not 9535 // have a non-trivial destructor. 9536 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9537 if (getLangOpts().CPlusPlus11) 9538 Diag(var->getLocation(), diag::note_use_thread_local); 9539 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9540 !var->getInit()->isConstantInitializer( 9541 Context, var->getType()->isReferenceType(), &Culprit)) { 9542 // GNU C++98 edits for __thread, [basic.start.init]p4: 9543 // An object of thread storage duration shall not require dynamic 9544 // initialization. 9545 // FIXME: Need strict checking here. 9546 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9547 << Culprit->getSourceRange(); 9548 if (getLangOpts().CPlusPlus11) 9549 Diag(var->getLocation(), diag::note_use_thread_local); 9550 } 9551 9552 } 9553 9554 // Apply section attributes and pragmas to global variables. 9555 bool GlobalStorage = var->hasGlobalStorage(); 9556 if (GlobalStorage && var->isThisDeclarationADefinition() && 9557 ActiveTemplateInstantiations.empty()) { 9558 PragmaStack<StringLiteral *> *Stack = nullptr; 9559 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read; 9560 if (var->getType().isConstQualified()) 9561 Stack = &ConstSegStack; 9562 else if (!var->getInit()) { 9563 Stack = &BSSSegStack; 9564 SectionFlags |= ASTContext::PSF_Write; 9565 } else { 9566 Stack = &DataSegStack; 9567 SectionFlags |= ASTContext::PSF_Write; 9568 } 9569 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) { 9570 var->addAttr(SectionAttr::CreateImplicit( 9571 Context, SectionAttr::Declspec_allocate, 9572 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation)); 9573 } 9574 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9575 if (UnifySection(SA->getName(), SectionFlags, var)) 9576 var->dropAttr<SectionAttr>(); 9577 9578 // Apply the init_seg attribute if this has an initializer. If the 9579 // initializer turns out to not be dynamic, we'll end up ignoring this 9580 // attribute. 9581 if (CurInitSeg && var->getInit()) 9582 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 9583 CurInitSegLoc)); 9584 } 9585 9586 // All the following checks are C++ only. 9587 if (!getLangOpts().CPlusPlus) return; 9588 9589 QualType type = var->getType(); 9590 if (type->isDependentType()) return; 9591 9592 // __block variables might require us to capture a copy-initializer. 9593 if (var->hasAttr<BlocksAttr>()) { 9594 // It's currently invalid to ever have a __block variable with an 9595 // array type; should we diagnose that here? 9596 9597 // Regardless, we don't want to ignore array nesting when 9598 // constructing this copy. 9599 if (type->isStructureOrClassType()) { 9600 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9601 SourceLocation poi = var->getLocation(); 9602 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9603 ExprResult result 9604 = PerformMoveOrCopyInitialization( 9605 InitializedEntity::InitializeBlock(poi, type, false), 9606 var, var->getType(), varRef, /*AllowNRVO=*/true); 9607 if (!result.isInvalid()) { 9608 result = MaybeCreateExprWithCleanups(result); 9609 Expr *init = result.getAs<Expr>(); 9610 Context.setBlockVarCopyInits(var, init); 9611 } 9612 } 9613 } 9614 9615 Expr *Init = var->getInit(); 9616 bool IsGlobal = GlobalStorage && !var->isStaticLocal(); 9617 QualType baseType = Context.getBaseElementType(type); 9618 9619 if (!var->getDeclContext()->isDependentContext() && 9620 Init && !Init->isValueDependent()) { 9621 if (IsGlobal && !var->isConstexpr() && 9622 !getDiagnostics().isIgnored(diag::warn_global_constructor, 9623 var->getLocation())) { 9624 // Warn about globals which don't have a constant initializer. Don't 9625 // warn about globals with a non-trivial destructor because we already 9626 // warned about them. 9627 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9628 if (!(RD && !RD->hasTrivialDestructor()) && 9629 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9630 Diag(var->getLocation(), diag::warn_global_constructor) 9631 << Init->getSourceRange(); 9632 } 9633 9634 if (var->isConstexpr()) { 9635 SmallVector<PartialDiagnosticAt, 8> Notes; 9636 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9637 SourceLocation DiagLoc = var->getLocation(); 9638 // If the note doesn't add any useful information other than a source 9639 // location, fold it into the primary diagnostic. 9640 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9641 diag::note_invalid_subexpr_in_const_expr) { 9642 DiagLoc = Notes[0].first; 9643 Notes.clear(); 9644 } 9645 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9646 << var << Init->getSourceRange(); 9647 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9648 Diag(Notes[I].first, Notes[I].second); 9649 } 9650 } else if (var->isUsableInConstantExpressions(Context)) { 9651 // Check whether the initializer of a const variable of integral or 9652 // enumeration type is an ICE now, since we can't tell whether it was 9653 // initialized by a constant expression if we check later. 9654 var->checkInitIsICE(); 9655 } 9656 } 9657 9658 // Require the destructor. 9659 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9660 FinalizeVarWithDestructor(var, recordType); 9661 } 9662 9663 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9664 /// any semantic actions necessary after any initializer has been attached. 9665 void 9666 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9667 // Note that we are no longer parsing the initializer for this declaration. 9668 ParsingInitForAutoVars.erase(ThisDecl); 9669 9670 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9671 if (!VD) 9672 return; 9673 9674 checkAttributesAfterMerging(*this, *VD); 9675 9676 // Static locals inherit dll attributes from their function. 9677 if (VD->isStaticLocal()) { 9678 if (FunctionDecl *FD = 9679 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 9680 if (Attr *A = getDLLAttr(FD)) { 9681 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 9682 NewAttr->setInherited(true); 9683 VD->addAttr(NewAttr); 9684 } 9685 } 9686 } 9687 9688 // Grab the dllimport or dllexport attribute off of the VarDecl. 9689 const InheritableAttr *DLLAttr = getDLLAttr(VD); 9690 9691 // Imported static data members cannot be defined out-of-line. 9692 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) { 9693 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9694 VD->isThisDeclarationADefinition()) { 9695 // We allow definitions of dllimport class template static data members 9696 // with a warning. 9697 CXXRecordDecl *Context = 9698 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9699 bool IsClassTemplateMember = 9700 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9701 Context->getDescribedClassTemplate(); 9702 9703 Diag(VD->getLocation(), 9704 IsClassTemplateMember 9705 ? diag::warn_attribute_dllimport_static_field_definition 9706 : diag::err_attribute_dllimport_static_field_definition); 9707 Diag(IA->getLocation(), diag::note_attribute); 9708 if (!IsClassTemplateMember) 9709 VD->setInvalidDecl(); 9710 } 9711 } 9712 9713 // dllimport/dllexport variables cannot be thread local, their TLS index 9714 // isn't exported with the variable. 9715 if (DLLAttr && VD->getTLSKind()) { 9716 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD 9717 << DLLAttr; 9718 VD->setInvalidDecl(); 9719 } 9720 9721 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9722 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9723 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9724 VD->dropAttr<UsedAttr>(); 9725 } 9726 } 9727 9728 const DeclContext *DC = VD->getDeclContext(); 9729 // If there's a #pragma GCC visibility in scope, and this isn't a class 9730 // member, set the visibility of this variable. 9731 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9732 AddPushedVisibilityAttribute(VD); 9733 9734 // FIXME: Warn on unused templates. 9735 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9736 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9737 MarkUnusedFileScopedDecl(VD); 9738 9739 // Now we have parsed the initializer and can update the table of magic 9740 // tag values. 9741 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9742 !VD->getType()->isIntegralOrEnumerationType()) 9743 return; 9744 9745 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9746 const Expr *MagicValueExpr = VD->getInit(); 9747 if (!MagicValueExpr) { 9748 continue; 9749 } 9750 llvm::APSInt MagicValueInt; 9751 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9752 Diag(I->getRange().getBegin(), 9753 diag::err_type_tag_for_datatype_not_ice) 9754 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9755 continue; 9756 } 9757 if (MagicValueInt.getActiveBits() > 64) { 9758 Diag(I->getRange().getBegin(), 9759 diag::err_type_tag_for_datatype_too_large) 9760 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9761 continue; 9762 } 9763 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9764 RegisterTypeTagForDatatype(I->getArgumentKind(), 9765 MagicValue, 9766 I->getMatchingCType(), 9767 I->getLayoutCompatible(), 9768 I->getMustBeNull()); 9769 } 9770 } 9771 9772 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9773 ArrayRef<Decl *> Group) { 9774 SmallVector<Decl*, 8> Decls; 9775 9776 if (DS.isTypeSpecOwned()) 9777 Decls.push_back(DS.getRepAsDecl()); 9778 9779 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9780 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9781 if (Decl *D = Group[i]) { 9782 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9783 if (!FirstDeclaratorInGroup) 9784 FirstDeclaratorInGroup = DD; 9785 Decls.push_back(D); 9786 } 9787 9788 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9789 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9790 handleTagNumbering(Tag, S); 9791 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9792 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9793 } 9794 } 9795 9796 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9797 } 9798 9799 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9800 /// group, performing any necessary semantic checking. 9801 Sema::DeclGroupPtrTy 9802 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 9803 bool TypeMayContainAuto) { 9804 // C++0x [dcl.spec.auto]p7: 9805 // If the type deduced for the template parameter U is not the same in each 9806 // deduction, the program is ill-formed. 9807 // FIXME: When initializer-list support is added, a distinction is needed 9808 // between the deduced type U and the deduced type which 'auto' stands for. 9809 // auto a = 0, b = { 1, 2, 3 }; 9810 // is legal because the deduced type U is 'int' in both cases. 9811 if (TypeMayContainAuto && Group.size() > 1) { 9812 QualType Deduced; 9813 CanQualType DeducedCanon; 9814 VarDecl *DeducedDecl = nullptr; 9815 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9816 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9817 AutoType *AT = D->getType()->getContainedAutoType(); 9818 // Don't reissue diagnostics when instantiating a template. 9819 if (AT && D->isInvalidDecl()) 9820 break; 9821 QualType U = AT ? AT->getDeducedType() : QualType(); 9822 if (!U.isNull()) { 9823 CanQualType UCanon = Context.getCanonicalType(U); 9824 if (Deduced.isNull()) { 9825 Deduced = U; 9826 DeducedCanon = UCanon; 9827 DeducedDecl = D; 9828 } else if (DeducedCanon != UCanon) { 9829 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9830 diag::err_auto_different_deductions) 9831 << (AT->isDecltypeAuto() ? 1 : 0) 9832 << Deduced << DeducedDecl->getDeclName() 9833 << U << D->getDeclName() 9834 << DeducedDecl->getInit()->getSourceRange() 9835 << D->getInit()->getSourceRange(); 9836 D->setInvalidDecl(); 9837 break; 9838 } 9839 } 9840 } 9841 } 9842 } 9843 9844 ActOnDocumentableDecls(Group); 9845 9846 return DeclGroupPtrTy::make( 9847 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9848 } 9849 9850 void Sema::ActOnDocumentableDecl(Decl *D) { 9851 ActOnDocumentableDecls(D); 9852 } 9853 9854 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9855 // Don't parse the comment if Doxygen diagnostics are ignored. 9856 if (Group.empty() || !Group[0]) 9857 return; 9858 9859 if (Diags.isIgnored(diag::warn_doc_param_not_found, 9860 Group[0]->getLocation()) && 9861 Diags.isIgnored(diag::warn_unknown_comment_command_name, 9862 Group[0]->getLocation())) 9863 return; 9864 9865 if (Group.size() >= 2) { 9866 // This is a decl group. Normally it will contain only declarations 9867 // produced from declarator list. But in case we have any definitions or 9868 // additional declaration references: 9869 // 'typedef struct S {} S;' 9870 // 'typedef struct S *S;' 9871 // 'struct S *pS;' 9872 // FinalizeDeclaratorGroup adds these as separate declarations. 9873 Decl *MaybeTagDecl = Group[0]; 9874 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9875 Group = Group.slice(1); 9876 } 9877 } 9878 9879 // See if there are any new comments that are not attached to a decl. 9880 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9881 if (!Comments.empty() && 9882 !Comments.back()->isAttached()) { 9883 // There is at least one comment that not attached to a decl. 9884 // Maybe it should be attached to one of these decls? 9885 // 9886 // Note that this way we pick up not only comments that precede the 9887 // declaration, but also comments that *follow* the declaration -- thanks to 9888 // the lookahead in the lexer: we've consumed the semicolon and looked 9889 // ahead through comments. 9890 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9891 Context.getCommentForDecl(Group[i], &PP); 9892 } 9893 } 9894 9895 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9896 /// to introduce parameters into function prototype scope. 9897 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9898 const DeclSpec &DS = D.getDeclSpec(); 9899 9900 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9901 9902 // C++03 [dcl.stc]p2 also permits 'auto'. 9903 StorageClass SC = SC_None; 9904 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9905 SC = SC_Register; 9906 } else if (getLangOpts().CPlusPlus && 9907 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9908 SC = SC_Auto; 9909 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9910 Diag(DS.getStorageClassSpecLoc(), 9911 diag::err_invalid_storage_class_in_func_decl); 9912 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9913 } 9914 9915 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9916 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9917 << DeclSpec::getSpecifierName(TSCS); 9918 if (DS.isConstexprSpecified()) 9919 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9920 << 0; 9921 9922 DiagnoseFunctionSpecifiers(DS); 9923 9924 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9925 QualType parmDeclType = TInfo->getType(); 9926 9927 if (getLangOpts().CPlusPlus) { 9928 // Check that there are no default arguments inside the type of this 9929 // parameter. 9930 CheckExtraCXXDefaultArguments(D); 9931 9932 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9933 if (D.getCXXScopeSpec().isSet()) { 9934 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9935 << D.getCXXScopeSpec().getRange(); 9936 D.getCXXScopeSpec().clear(); 9937 } 9938 } 9939 9940 // Ensure we have a valid name 9941 IdentifierInfo *II = nullptr; 9942 if (D.hasName()) { 9943 II = D.getIdentifier(); 9944 if (!II) { 9945 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9946 << GetNameForDeclarator(D).getName(); 9947 D.setInvalidType(true); 9948 } 9949 } 9950 9951 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9952 if (II) { 9953 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9954 ForRedeclaration); 9955 LookupName(R, S); 9956 if (R.isSingleResult()) { 9957 NamedDecl *PrevDecl = R.getFoundDecl(); 9958 if (PrevDecl->isTemplateParameter()) { 9959 // Maybe we will complain about the shadowed template parameter. 9960 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9961 // Just pretend that we didn't see the previous declaration. 9962 PrevDecl = nullptr; 9963 } else if (S->isDeclScope(PrevDecl)) { 9964 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9965 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9966 9967 // Recover by removing the name 9968 II = nullptr; 9969 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 9970 D.setInvalidType(true); 9971 } 9972 } 9973 } 9974 9975 // Temporarily put parameter variables in the translation unit, not 9976 // the enclosing context. This prevents them from accidentally 9977 // looking like class members in C++. 9978 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9979 D.getLocStart(), 9980 D.getIdentifierLoc(), II, 9981 parmDeclType, TInfo, 9982 SC); 9983 9984 if (D.isInvalidType()) 9985 New->setInvalidDecl(); 9986 9987 assert(S->isFunctionPrototypeScope()); 9988 assert(S->getFunctionPrototypeDepth() >= 1); 9989 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9990 S->getNextFunctionPrototypeIndex()); 9991 9992 // Add the parameter declaration into this scope. 9993 S->AddDecl(New); 9994 if (II) 9995 IdResolver.AddDecl(New); 9996 9997 ProcessDeclAttributes(S, New, D); 9998 9999 if (D.getDeclSpec().isModulePrivateSpecified()) 10000 Diag(New->getLocation(), diag::err_module_private_local) 10001 << 1 << New->getDeclName() 10002 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10003 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10004 10005 if (New->hasAttr<BlocksAttr>()) { 10006 Diag(New->getLocation(), diag::err_block_on_nonlocal); 10007 } 10008 return New; 10009 } 10010 10011 /// \brief Synthesizes a variable for a parameter arising from a 10012 /// typedef. 10013 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 10014 SourceLocation Loc, 10015 QualType T) { 10016 /* FIXME: setting StartLoc == Loc. 10017 Would it be worth to modify callers so as to provide proper source 10018 location for the unnamed parameters, embedding the parameter's type? */ 10019 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 10020 T, Context.getTrivialTypeSourceInfo(T, Loc), 10021 SC_None, nullptr); 10022 Param->setImplicit(); 10023 return Param; 10024 } 10025 10026 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 10027 ParmVarDecl * const *ParamEnd) { 10028 // Don't diagnose unused-parameter errors in template instantiations; we 10029 // will already have done so in the template itself. 10030 if (!ActiveTemplateInstantiations.empty()) 10031 return; 10032 10033 for (; Param != ParamEnd; ++Param) { 10034 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 10035 !(*Param)->hasAttr<UnusedAttr>()) { 10036 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 10037 << (*Param)->getDeclName(); 10038 } 10039 } 10040 } 10041 10042 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 10043 ParmVarDecl * const *ParamEnd, 10044 QualType ReturnTy, 10045 NamedDecl *D) { 10046 if (LangOpts.NumLargeByValueCopy == 0) // No check. 10047 return; 10048 10049 // Warn if the return value is pass-by-value and larger than the specified 10050 // threshold. 10051 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 10052 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 10053 if (Size > LangOpts.NumLargeByValueCopy) 10054 Diag(D->getLocation(), diag::warn_return_value_size) 10055 << D->getDeclName() << Size; 10056 } 10057 10058 // Warn if any parameter is pass-by-value and larger than the specified 10059 // threshold. 10060 for (; Param != ParamEnd; ++Param) { 10061 QualType T = (*Param)->getType(); 10062 if (T->isDependentType() || !T.isPODType(Context)) 10063 continue; 10064 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 10065 if (Size > LangOpts.NumLargeByValueCopy) 10066 Diag((*Param)->getLocation(), diag::warn_parameter_size) 10067 << (*Param)->getDeclName() << Size; 10068 } 10069 } 10070 10071 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 10072 SourceLocation NameLoc, IdentifierInfo *Name, 10073 QualType T, TypeSourceInfo *TSInfo, 10074 StorageClass SC) { 10075 // In ARC, infer a lifetime qualifier for appropriate parameter types. 10076 if (getLangOpts().ObjCAutoRefCount && 10077 T.getObjCLifetime() == Qualifiers::OCL_None && 10078 T->isObjCLifetimeType()) { 10079 10080 Qualifiers::ObjCLifetime lifetime; 10081 10082 // Special cases for arrays: 10083 // - if it's const, use __unsafe_unretained 10084 // - otherwise, it's an error 10085 if (T->isArrayType()) { 10086 if (!T.isConstQualified()) { 10087 DelayedDiagnostics.add( 10088 sema::DelayedDiagnostic::makeForbiddenType( 10089 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 10090 } 10091 lifetime = Qualifiers::OCL_ExplicitNone; 10092 } else { 10093 lifetime = T->getObjCARCImplicitLifetime(); 10094 } 10095 T = Context.getLifetimeQualifiedType(T, lifetime); 10096 } 10097 10098 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 10099 Context.getAdjustedParameterType(T), 10100 TSInfo, SC, nullptr); 10101 10102 // Parameters can not be abstract class types. 10103 // For record types, this is done by the AbstractClassUsageDiagnoser once 10104 // the class has been completely parsed. 10105 if (!CurContext->isRecord() && 10106 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 10107 AbstractParamType)) 10108 New->setInvalidDecl(); 10109 10110 // Parameter declarators cannot be interface types. All ObjC objects are 10111 // passed by reference. 10112 if (T->isObjCObjectType()) { 10113 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 10114 Diag(NameLoc, 10115 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 10116 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 10117 T = Context.getObjCObjectPointerType(T); 10118 New->setType(T); 10119 } 10120 10121 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 10122 // duration shall not be qualified by an address-space qualifier." 10123 // Since all parameters have automatic store duration, they can not have 10124 // an address space. 10125 if (T.getAddressSpace() != 0) { 10126 // OpenCL allows function arguments declared to be an array of a type 10127 // to be qualified with an address space. 10128 if (!(getLangOpts().OpenCL && T->isArrayType())) { 10129 Diag(NameLoc, diag::err_arg_with_address_space); 10130 New->setInvalidDecl(); 10131 } 10132 } 10133 10134 return New; 10135 } 10136 10137 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 10138 SourceLocation LocAfterDecls) { 10139 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 10140 10141 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 10142 // for a K&R function. 10143 if (!FTI.hasPrototype) { 10144 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10145 --i; 10146 if (FTI.Params[i].Param == nullptr) { 10147 SmallString<256> Code; 10148 llvm::raw_svector_ostream(Code) 10149 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10150 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10151 << FTI.Params[i].Ident 10152 << FixItHint::CreateInsertion(LocAfterDecls, Code); 10153 10154 // Implicitly declare the argument as type 'int' for lack of a better 10155 // type. 10156 AttributeFactory attrs; 10157 DeclSpec DS(attrs); 10158 const char* PrevSpec; // unused 10159 unsigned DiagID; // unused 10160 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10161 DiagID, Context.getPrintingPolicy()); 10162 // Use the identifier location for the type source range. 10163 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10164 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10165 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10166 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10167 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10168 } 10169 } 10170 } 10171 } 10172 10173 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 10174 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10175 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10176 Scope *ParentScope = FnBodyScope->getParent(); 10177 10178 D.setFunctionDefinitionKind(FDK_Definition); 10179 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 10180 return ActOnStartOfFunctionDef(FnBodyScope, DP); 10181 } 10182 10183 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10184 Consumer.HandleInlineMethodDefinition(D); 10185 } 10186 10187 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10188 const FunctionDecl*& PossibleZeroParamPrototype) { 10189 // Don't warn about invalid declarations. 10190 if (FD->isInvalidDecl()) 10191 return false; 10192 10193 // Or declarations that aren't global. 10194 if (!FD->isGlobal()) 10195 return false; 10196 10197 // Don't warn about C++ member functions. 10198 if (isa<CXXMethodDecl>(FD)) 10199 return false; 10200 10201 // Don't warn about 'main'. 10202 if (FD->isMain()) 10203 return false; 10204 10205 // Don't warn about inline functions. 10206 if (FD->isInlined()) 10207 return false; 10208 10209 // Don't warn about function templates. 10210 if (FD->getDescribedFunctionTemplate()) 10211 return false; 10212 10213 // Don't warn about function template specializations. 10214 if (FD->isFunctionTemplateSpecialization()) 10215 return false; 10216 10217 // Don't warn for OpenCL kernels. 10218 if (FD->hasAttr<OpenCLKernelAttr>()) 10219 return false; 10220 10221 // Don't warn on explicitly deleted functions. 10222 if (FD->isDeleted()) 10223 return false; 10224 10225 bool MissingPrototype = true; 10226 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10227 Prev; Prev = Prev->getPreviousDecl()) { 10228 // Ignore any declarations that occur in function or method 10229 // scope, because they aren't visible from the header. 10230 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10231 continue; 10232 10233 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10234 if (FD->getNumParams() == 0) 10235 PossibleZeroParamPrototype = Prev; 10236 break; 10237 } 10238 10239 return MissingPrototype; 10240 } 10241 10242 void 10243 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10244 const FunctionDecl *EffectiveDefinition) { 10245 // Don't complain if we're in GNU89 mode and the previous definition 10246 // was an extern inline function. 10247 const FunctionDecl *Definition = EffectiveDefinition; 10248 if (!Definition) 10249 if (!FD->isDefined(Definition)) 10250 return; 10251 10252 if (canRedefineFunction(Definition, getLangOpts())) 10253 return; 10254 10255 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10256 Definition->getStorageClass() == SC_Extern) 10257 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10258 << FD->getDeclName() << getLangOpts().CPlusPlus; 10259 else 10260 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10261 10262 Diag(Definition->getLocation(), diag::note_previous_definition); 10263 FD->setInvalidDecl(); 10264 } 10265 10266 10267 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10268 Sema &S) { 10269 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10270 10271 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10272 LSI->CallOperator = CallOperator; 10273 LSI->Lambda = LambdaClass; 10274 LSI->ReturnType = CallOperator->getReturnType(); 10275 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10276 10277 if (LCD == LCD_None) 10278 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10279 else if (LCD == LCD_ByCopy) 10280 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10281 else if (LCD == LCD_ByRef) 10282 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10283 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10284 10285 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10286 LSI->Mutable = !CallOperator->isConst(); 10287 10288 // Add the captures to the LSI so they can be noted as already 10289 // captured within tryCaptureVar. 10290 auto I = LambdaClass->field_begin(); 10291 for (const auto &C : LambdaClass->captures()) { 10292 if (C.capturesVariable()) { 10293 VarDecl *VD = C.getCapturedVar(); 10294 if (VD->isInitCapture()) 10295 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10296 QualType CaptureType = VD->getType(); 10297 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10298 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10299 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(), 10300 /*EllipsisLoc*/C.isPackExpansion() 10301 ? C.getEllipsisLoc() : SourceLocation(), 10302 CaptureType, /*Expr*/ nullptr); 10303 10304 } else if (C.capturesThis()) { 10305 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10306 S.getCurrentThisType(), /*Expr*/ nullptr); 10307 } else { 10308 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10309 } 10310 ++I; 10311 } 10312 } 10313 10314 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 10315 // Clear the last template instantiation error context. 10316 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10317 10318 if (!D) 10319 return D; 10320 FunctionDecl *FD = nullptr; 10321 10322 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10323 FD = FunTmpl->getTemplatedDecl(); 10324 else 10325 FD = cast<FunctionDecl>(D); 10326 // If we are instantiating a generic lambda call operator, push 10327 // a LambdaScopeInfo onto the function stack. But use the information 10328 // that's already been calculated (ActOnLambdaExpr) to prime the current 10329 // LambdaScopeInfo. 10330 // When the template operator is being specialized, the LambdaScopeInfo, 10331 // has to be properly restored so that tryCaptureVariable doesn't try 10332 // and capture any new variables. In addition when calculating potential 10333 // captures during transformation of nested lambdas, it is necessary to 10334 // have the LSI properly restored. 10335 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10336 assert(ActiveTemplateInstantiations.size() && 10337 "There should be an active template instantiation on the stack " 10338 "when instantiating a generic lambda!"); 10339 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10340 } 10341 else 10342 // Enter a new function scope 10343 PushFunctionScope(); 10344 10345 // See if this is a redefinition. 10346 if (!FD->isLateTemplateParsed()) 10347 CheckForFunctionRedefinition(FD); 10348 10349 // Builtin functions cannot be defined. 10350 if (unsigned BuiltinID = FD->getBuiltinID()) { 10351 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10352 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10353 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10354 FD->setInvalidDecl(); 10355 } 10356 } 10357 10358 // The return type of a function definition must be complete 10359 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10360 QualType ResultType = FD->getReturnType(); 10361 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10362 !FD->isInvalidDecl() && 10363 RequireCompleteType(FD->getLocation(), ResultType, 10364 diag::err_func_def_incomplete_result)) 10365 FD->setInvalidDecl(); 10366 10367 if (FnBodyScope) 10368 PushDeclContext(FnBodyScope, FD); 10369 10370 // Check the validity of our function parameters 10371 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10372 /*CheckParameterNames=*/true); 10373 10374 // Introduce our parameters into the function scope 10375 for (auto Param : FD->params()) { 10376 Param->setOwningFunction(FD); 10377 10378 // If this has an identifier, add it to the scope stack. 10379 if (Param->getIdentifier() && FnBodyScope) { 10380 CheckShadow(FnBodyScope, Param); 10381 10382 PushOnScopeChains(Param, FnBodyScope); 10383 } 10384 } 10385 10386 // If we had any tags defined in the function prototype, 10387 // introduce them into the function scope. 10388 if (FnBodyScope) { 10389 for (ArrayRef<NamedDecl *>::iterator 10390 I = FD->getDeclsInPrototypeScope().begin(), 10391 E = FD->getDeclsInPrototypeScope().end(); 10392 I != E; ++I) { 10393 NamedDecl *D = *I; 10394 10395 // Some of these decls (like enums) may have been pinned to the 10396 // translation unit for lack of a real context earlier. If so, remove 10397 // from the translation unit and reattach to the current context. 10398 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 10399 // Is the decl actually in the context? 10400 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 10401 if (DI == D) { 10402 Context.getTranslationUnitDecl()->removeDecl(D); 10403 break; 10404 } 10405 } 10406 // Either way, reassign the lexical decl context to our FunctionDecl. 10407 D->setLexicalDeclContext(CurContext); 10408 } 10409 10410 // If the decl has a non-null name, make accessible in the current scope. 10411 if (!D->getName().empty()) 10412 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 10413 10414 // Similarly, dive into enums and fish their constants out, making them 10415 // accessible in this scope. 10416 if (auto *ED = dyn_cast<EnumDecl>(D)) { 10417 for (auto *EI : ED->enumerators()) 10418 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 10419 } 10420 } 10421 } 10422 10423 // Ensure that the function's exception specification is instantiated. 10424 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 10425 ResolveExceptionSpec(D->getLocation(), FPT); 10426 10427 // dllimport cannot be applied to non-inline function definitions. 10428 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 10429 !FD->isTemplateInstantiation()) { 10430 assert(!FD->hasAttr<DLLExportAttr>()); 10431 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 10432 FD->setInvalidDecl(); 10433 return D; 10434 } 10435 // We want to attach documentation to original Decl (which might be 10436 // a function template). 10437 ActOnDocumentableDecl(D); 10438 if (getCurLexicalContext()->isObjCContainer() && 10439 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 10440 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 10441 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 10442 10443 return D; 10444 } 10445 10446 /// \brief Given the set of return statements within a function body, 10447 /// compute the variables that are subject to the named return value 10448 /// optimization. 10449 /// 10450 /// Each of the variables that is subject to the named return value 10451 /// optimization will be marked as NRVO variables in the AST, and any 10452 /// return statement that has a marked NRVO variable as its NRVO candidate can 10453 /// use the named return value optimization. 10454 /// 10455 /// This function applies a very simplistic algorithm for NRVO: if every return 10456 /// statement in the scope of a variable has the same NRVO candidate, that 10457 /// candidate is an NRVO variable. 10458 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 10459 ReturnStmt **Returns = Scope->Returns.data(); 10460 10461 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 10462 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 10463 if (!NRVOCandidate->isNRVOVariable()) 10464 Returns[I]->setNRVOCandidate(nullptr); 10465 } 10466 } 10467 } 10468 10469 bool Sema::canDelayFunctionBody(const Declarator &D) { 10470 // We can't delay parsing the body of a constexpr function template (yet). 10471 if (D.getDeclSpec().isConstexprSpecified()) 10472 return false; 10473 10474 // We can't delay parsing the body of a function template with a deduced 10475 // return type (yet). 10476 if (D.getDeclSpec().containsPlaceholderType()) { 10477 // If the placeholder introduces a non-deduced trailing return type, 10478 // we can still delay parsing it. 10479 if (D.getNumTypeObjects()) { 10480 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 10481 if (Outer.Kind == DeclaratorChunk::Function && 10482 Outer.Fun.hasTrailingReturnType()) { 10483 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 10484 return Ty.isNull() || !Ty->isUndeducedType(); 10485 } 10486 } 10487 return false; 10488 } 10489 10490 return true; 10491 } 10492 10493 bool Sema::canSkipFunctionBody(Decl *D) { 10494 // We cannot skip the body of a function (or function template) which is 10495 // constexpr, since we may need to evaluate its body in order to parse the 10496 // rest of the file. 10497 // We cannot skip the body of a function with an undeduced return type, 10498 // because any callers of that function need to know the type. 10499 if (const FunctionDecl *FD = D->getAsFunction()) 10500 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 10501 return false; 10502 return Consumer.shouldSkipFunctionBody(D); 10503 } 10504 10505 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 10506 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 10507 FD->setHasSkippedBody(); 10508 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10509 MD->setHasSkippedBody(); 10510 return ActOnFinishFunctionBody(Decl, nullptr); 10511 } 10512 10513 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10514 return ActOnFinishFunctionBody(D, BodyArg, false); 10515 } 10516 10517 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10518 bool IsInstantiation) { 10519 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10520 10521 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10522 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10523 10524 if (FD) { 10525 FD->setBody(Body); 10526 10527 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body && 10528 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10529 // If the function has a deduced result type but contains no 'return' 10530 // statements, the result type as written must be exactly 'auto', and 10531 // the deduced result type is 'void'. 10532 if (!FD->getReturnType()->getAs<AutoType>()) { 10533 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10534 << FD->getReturnType(); 10535 FD->setInvalidDecl(); 10536 } else { 10537 // Substitute 'void' for the 'auto' in the type. 10538 TypeLoc ResultType = getReturnTypeLoc(FD); 10539 Context.adjustDeducedFunctionResultType( 10540 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10541 } 10542 } 10543 10544 // The only way to be included in UndefinedButUsed is if there is an 10545 // ODR use before the definition. Avoid the expensive map lookup if this 10546 // is the first declaration. 10547 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 10548 if (!FD->isExternallyVisible()) 10549 UndefinedButUsed.erase(FD); 10550 else if (FD->isInlined() && 10551 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10552 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 10553 UndefinedButUsed.erase(FD); 10554 } 10555 10556 // If the function implicitly returns zero (like 'main') or is naked, 10557 // don't complain about missing return statements. 10558 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 10559 WP.disableCheckFallThrough(); 10560 10561 // MSVC permits the use of pure specifier (=0) on function definition, 10562 // defined at class scope, warn about this non-standard construct. 10563 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10564 Diag(FD->getLocation(), diag::ext_pure_function_definition); 10565 10566 if (!FD->isInvalidDecl()) { 10567 // Don't diagnose unused parameters of defaulted or deleted functions. 10568 if (!FD->isDeleted() && !FD->isDefaulted()) 10569 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10570 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10571 FD->getReturnType(), FD); 10572 10573 // If this is a structor, we need a vtable. 10574 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10575 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10576 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD)) 10577 MarkVTableUsed(FD->getLocation(), Destructor->getParent()); 10578 10579 // Try to apply the named return value optimization. We have to check 10580 // if we can do this here because lambdas keep return statements around 10581 // to deduce an implicit return type. 10582 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10583 !FD->isDependentContext()) 10584 computeNRVO(Body, getCurFunction()); 10585 } 10586 10587 // GNU warning -Wmissing-prototypes: 10588 // Warn if a global function is defined without a previous 10589 // prototype declaration. This warning is issued even if the 10590 // definition itself provides a prototype. The aim is to detect 10591 // global functions that fail to be declared in header files. 10592 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 10593 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 10594 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 10595 10596 if (PossibleZeroParamPrototype) { 10597 // We found a declaration that is not a prototype, 10598 // but that could be a zero-parameter prototype 10599 if (TypeSourceInfo *TI = 10600 PossibleZeroParamPrototype->getTypeSourceInfo()) { 10601 TypeLoc TL = TI->getTypeLoc(); 10602 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 10603 Diag(PossibleZeroParamPrototype->getLocation(), 10604 diag::note_declaration_not_a_prototype) 10605 << PossibleZeroParamPrototype 10606 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 10607 } 10608 } 10609 } 10610 10611 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 10612 const CXXMethodDecl *KeyFunction; 10613 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) && 10614 MD->isVirtual() && 10615 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) && 10616 MD == KeyFunction->getCanonicalDecl()) { 10617 // Update the key-function state if necessary for this ABI. 10618 if (FD->isInlined() && 10619 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 10620 Context.setNonKeyFunction(MD); 10621 10622 // If the newly-chosen key function is already defined, then we 10623 // need to mark the vtable as used retroactively. 10624 KeyFunction = Context.getCurrentKeyFunction(MD->getParent()); 10625 const FunctionDecl *Definition; 10626 if (KeyFunction && KeyFunction->isDefined(Definition)) 10627 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true); 10628 } else { 10629 // We just defined they key function; mark the vtable as used. 10630 MarkVTableUsed(FD->getLocation(), MD->getParent(), true); 10631 } 10632 } 10633 } 10634 10635 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10636 "Function parsing confused"); 10637 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10638 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10639 MD->setBody(Body); 10640 if (!MD->isInvalidDecl()) { 10641 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10642 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10643 MD->getReturnType(), MD); 10644 10645 if (Body) 10646 computeNRVO(Body, getCurFunction()); 10647 } 10648 if (getCurFunction()->ObjCShouldCallSuper) { 10649 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10650 << MD->getSelector().getAsString(); 10651 getCurFunction()->ObjCShouldCallSuper = false; 10652 } 10653 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10654 const ObjCMethodDecl *InitMethod = nullptr; 10655 bool isDesignated = 10656 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10657 assert(isDesignated && InitMethod); 10658 (void)isDesignated; 10659 10660 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10661 auto IFace = MD->getClassInterface(); 10662 if (!IFace) 10663 return false; 10664 auto SuperD = IFace->getSuperClass(); 10665 if (!SuperD) 10666 return false; 10667 return SuperD->getIdentifier() == 10668 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10669 }; 10670 // Don't issue this warning for unavailable inits or direct subclasses 10671 // of NSObject. 10672 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10673 Diag(MD->getLocation(), 10674 diag::warn_objc_designated_init_missing_super_call); 10675 Diag(InitMethod->getLocation(), 10676 diag::note_objc_designated_init_marked_here); 10677 } 10678 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10679 } 10680 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10681 // Don't issue this warning for unavaialable inits. 10682 if (!MD->isUnavailable()) 10683 Diag(MD->getLocation(), 10684 diag::warn_objc_secondary_init_missing_init_call); 10685 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10686 } 10687 } else { 10688 return nullptr; 10689 } 10690 10691 assert(!getCurFunction()->ObjCShouldCallSuper && 10692 "This should only be set for ObjC methods, which should have been " 10693 "handled in the block above."); 10694 10695 // Verify and clean out per-function state. 10696 if (Body && (!FD || !FD->isDefaulted())) { 10697 // C++ constructors that have function-try-blocks can't have return 10698 // statements in the handlers of that block. (C++ [except.handle]p14) 10699 // Verify this. 10700 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10701 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10702 10703 // Verify that gotos and switch cases don't jump into scopes illegally. 10704 if (getCurFunction()->NeedsScopeChecking() && 10705 !PP.isCodeCompletionEnabled()) 10706 DiagnoseInvalidJumps(Body); 10707 10708 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10709 if (!Destructor->getParent()->isDependentType()) 10710 CheckDestructor(Destructor); 10711 10712 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10713 Destructor->getParent()); 10714 } 10715 10716 // If any errors have occurred, clear out any temporaries that may have 10717 // been leftover. This ensures that these temporaries won't be picked up for 10718 // deletion in some later function. 10719 if (getDiagnostics().hasErrorOccurred() || 10720 getDiagnostics().getSuppressAllDiagnostics()) { 10721 DiscardCleanupsInEvaluationContext(); 10722 } 10723 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10724 !isa<FunctionTemplateDecl>(dcl)) { 10725 // Since the body is valid, issue any analysis-based warnings that are 10726 // enabled. 10727 ActivePolicy = &WP; 10728 } 10729 10730 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10731 (!CheckConstexprFunctionDecl(FD) || 10732 !CheckConstexprFunctionBody(FD, Body))) 10733 FD->setInvalidDecl(); 10734 10735 if (FD && FD->hasAttr<NakedAttr>()) { 10736 for (const Stmt *S : Body->children()) { 10737 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 10738 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 10739 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 10740 FD->setInvalidDecl(); 10741 break; 10742 } 10743 } 10744 } 10745 10746 assert(ExprCleanupObjects.size() == 10747 ExprEvalContexts.back().NumCleanupObjects && 10748 "Leftover temporaries in function"); 10749 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10750 assert(MaybeODRUseExprs.empty() && 10751 "Leftover expressions for odr-use checking"); 10752 } 10753 10754 if (!IsInstantiation) 10755 PopDeclContext(); 10756 10757 PopFunctionScopeInfo(ActivePolicy, dcl); 10758 // If any errors have occurred, clear out any temporaries that may have 10759 // been leftover. This ensures that these temporaries won't be picked up for 10760 // deletion in some later function. 10761 if (getDiagnostics().hasErrorOccurred()) { 10762 DiscardCleanupsInEvaluationContext(); 10763 } 10764 10765 return dcl; 10766 } 10767 10768 10769 /// When we finish delayed parsing of an attribute, we must attach it to the 10770 /// relevant Decl. 10771 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10772 ParsedAttributes &Attrs) { 10773 // Always attach attributes to the underlying decl. 10774 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10775 D = TD->getTemplatedDecl(); 10776 ProcessDeclAttributeList(S, D, Attrs.getList()); 10777 10778 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10779 if (Method->isStatic()) 10780 checkThisInStaticMemberFunctionAttributes(Method); 10781 } 10782 10783 10784 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10785 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10786 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10787 IdentifierInfo &II, Scope *S) { 10788 // Before we produce a declaration for an implicitly defined 10789 // function, see whether there was a locally-scoped declaration of 10790 // this name as a function or variable. If so, use that 10791 // (non-visible) declaration, and complain about it. 10792 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10793 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10794 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10795 return ExternCPrev; 10796 } 10797 10798 // Extension in C99. Legal in C90, but warn about it. 10799 unsigned diag_id; 10800 if (II.getName().startswith("__builtin_")) 10801 diag_id = diag::warn_builtin_unknown; 10802 else if (getLangOpts().C99) 10803 diag_id = diag::ext_implicit_function_decl; 10804 else 10805 diag_id = diag::warn_implicit_function_decl; 10806 Diag(Loc, diag_id) << &II; 10807 10808 // Because typo correction is expensive, only do it if the implicit 10809 // function declaration is going to be treated as an error. 10810 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10811 TypoCorrection Corrected; 10812 if (S && 10813 (Corrected = CorrectTypo( 10814 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr, 10815 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError))) 10816 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10817 /*ErrorRecovery*/false); 10818 } 10819 10820 // Set a Declarator for the implicit definition: int foo(); 10821 const char *Dummy; 10822 AttributeFactory attrFactory; 10823 DeclSpec DS(attrFactory); 10824 unsigned DiagID; 10825 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10826 Context.getPrintingPolicy()); 10827 (void)Error; // Silence warning. 10828 assert(!Error && "Error setting up implicit decl!"); 10829 SourceLocation NoLoc; 10830 Declarator D(DS, Declarator::BlockContext); 10831 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10832 /*IsAmbiguous=*/false, 10833 /*LParenLoc=*/NoLoc, 10834 /*Params=*/nullptr, 10835 /*NumParams=*/0, 10836 /*EllipsisLoc=*/NoLoc, 10837 /*RParenLoc=*/NoLoc, 10838 /*TypeQuals=*/0, 10839 /*RefQualifierIsLvalueRef=*/true, 10840 /*RefQualifierLoc=*/NoLoc, 10841 /*ConstQualifierLoc=*/NoLoc, 10842 /*VolatileQualifierLoc=*/NoLoc, 10843 /*RestrictQualifierLoc=*/NoLoc, 10844 /*MutableLoc=*/NoLoc, 10845 EST_None, 10846 /*ESpecLoc=*/NoLoc, 10847 /*Exceptions=*/nullptr, 10848 /*ExceptionRanges=*/nullptr, 10849 /*NumExceptions=*/0, 10850 /*NoexceptExpr=*/nullptr, 10851 /*ExceptionSpecTokens=*/nullptr, 10852 Loc, Loc, D), 10853 DS.getAttributes(), 10854 SourceLocation()); 10855 D.SetIdentifier(&II, Loc); 10856 10857 // Insert this function into translation-unit scope. 10858 10859 DeclContext *PrevDC = CurContext; 10860 CurContext = Context.getTranslationUnitDecl(); 10861 10862 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10863 FD->setImplicit(); 10864 10865 CurContext = PrevDC; 10866 10867 AddKnownFunctionAttributes(FD); 10868 10869 return FD; 10870 } 10871 10872 /// \brief Adds any function attributes that we know a priori based on 10873 /// the declaration of this function. 10874 /// 10875 /// These attributes can apply both to implicitly-declared builtins 10876 /// (like __builtin___printf_chk) or to library-declared functions 10877 /// like NSLog or printf. 10878 /// 10879 /// We need to check for duplicate attributes both here and where user-written 10880 /// attributes are applied to declarations. 10881 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10882 if (FD->isInvalidDecl()) 10883 return; 10884 10885 // If this is a built-in function, map its builtin attributes to 10886 // actual attributes. 10887 if (unsigned BuiltinID = FD->getBuiltinID()) { 10888 // Handle printf-formatting attributes. 10889 unsigned FormatIdx; 10890 bool HasVAListArg; 10891 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10892 if (!FD->hasAttr<FormatAttr>()) { 10893 const char *fmt = "printf"; 10894 unsigned int NumParams = FD->getNumParams(); 10895 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10896 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10897 fmt = "NSString"; 10898 FD->addAttr(FormatAttr::CreateImplicit(Context, 10899 &Context.Idents.get(fmt), 10900 FormatIdx+1, 10901 HasVAListArg ? 0 : FormatIdx+2, 10902 FD->getLocation())); 10903 } 10904 } 10905 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10906 HasVAListArg)) { 10907 if (!FD->hasAttr<FormatAttr>()) 10908 FD->addAttr(FormatAttr::CreateImplicit(Context, 10909 &Context.Idents.get("scanf"), 10910 FormatIdx+1, 10911 HasVAListArg ? 0 : FormatIdx+2, 10912 FD->getLocation())); 10913 } 10914 10915 // Mark const if we don't care about errno and that is the only 10916 // thing preventing the function from being const. This allows 10917 // IRgen to use LLVM intrinsics for such functions. 10918 if (!getLangOpts().MathErrno && 10919 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10920 if (!FD->hasAttr<ConstAttr>()) 10921 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10922 } 10923 10924 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10925 !FD->hasAttr<ReturnsTwiceAttr>()) 10926 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10927 FD->getLocation())); 10928 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10929 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10930 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10931 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10932 } 10933 10934 IdentifierInfo *Name = FD->getIdentifier(); 10935 if (!Name) 10936 return; 10937 if ((!getLangOpts().CPlusPlus && 10938 FD->getDeclContext()->isTranslationUnit()) || 10939 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10940 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10941 LinkageSpecDecl::lang_c)) { 10942 // Okay: this could be a libc/libm/Objective-C function we know 10943 // about. 10944 } else 10945 return; 10946 10947 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10948 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10949 // target-specific builtins, perhaps? 10950 if (!FD->hasAttr<FormatAttr>()) 10951 FD->addAttr(FormatAttr::CreateImplicit(Context, 10952 &Context.Idents.get("printf"), 2, 10953 Name->isStr("vasprintf") ? 0 : 3, 10954 FD->getLocation())); 10955 } 10956 10957 if (Name->isStr("__CFStringMakeConstantString")) { 10958 // We already have a __builtin___CFStringMakeConstantString, 10959 // but builds that use -fno-constant-cfstrings don't go through that. 10960 if (!FD->hasAttr<FormatArgAttr>()) 10961 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10962 FD->getLocation())); 10963 } 10964 } 10965 10966 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10967 TypeSourceInfo *TInfo) { 10968 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10969 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10970 10971 if (!TInfo) { 10972 assert(D.isInvalidType() && "no declarator info for valid type"); 10973 TInfo = Context.getTrivialTypeSourceInfo(T); 10974 } 10975 10976 // Scope manipulation handled by caller. 10977 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10978 D.getLocStart(), 10979 D.getIdentifierLoc(), 10980 D.getIdentifier(), 10981 TInfo); 10982 10983 // Bail out immediately if we have an invalid declaration. 10984 if (D.isInvalidType()) { 10985 NewTD->setInvalidDecl(); 10986 return NewTD; 10987 } 10988 10989 if (D.getDeclSpec().isModulePrivateSpecified()) { 10990 if (CurContext->isFunctionOrMethod()) 10991 Diag(NewTD->getLocation(), diag::err_module_private_local) 10992 << 2 << NewTD->getDeclName() 10993 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10994 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10995 else 10996 NewTD->setModulePrivate(); 10997 } 10998 10999 // C++ [dcl.typedef]p8: 11000 // If the typedef declaration defines an unnamed class (or 11001 // enum), the first typedef-name declared by the declaration 11002 // to be that class type (or enum type) is used to denote the 11003 // class type (or enum type) for linkage purposes only. 11004 // We need to check whether the type was declared in the declaration. 11005 switch (D.getDeclSpec().getTypeSpecType()) { 11006 case TST_enum: 11007 case TST_struct: 11008 case TST_interface: 11009 case TST_union: 11010 case TST_class: { 11011 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 11012 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD); 11013 break; 11014 } 11015 11016 default: 11017 break; 11018 } 11019 11020 return NewTD; 11021 } 11022 11023 11024 /// \brief Check that this is a valid underlying type for an enum declaration. 11025 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 11026 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 11027 QualType T = TI->getType(); 11028 11029 if (T->isDependentType()) 11030 return false; 11031 11032 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 11033 if (BT->isInteger()) 11034 return false; 11035 11036 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 11037 return true; 11038 } 11039 11040 /// Check whether this is a valid redeclaration of a previous enumeration. 11041 /// \return true if the redeclaration was invalid. 11042 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 11043 QualType EnumUnderlyingTy, 11044 const EnumDecl *Prev) { 11045 bool IsFixed = !EnumUnderlyingTy.isNull(); 11046 11047 if (IsScoped != Prev->isScoped()) { 11048 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 11049 << Prev->isScoped(); 11050 Diag(Prev->getLocation(), diag::note_previous_declaration); 11051 return true; 11052 } 11053 11054 if (IsFixed && Prev->isFixed()) { 11055 if (!EnumUnderlyingTy->isDependentType() && 11056 !Prev->getIntegerType()->isDependentType() && 11057 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 11058 Prev->getIntegerType())) { 11059 // TODO: Highlight the underlying type of the redeclaration. 11060 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 11061 << EnumUnderlyingTy << Prev->getIntegerType(); 11062 Diag(Prev->getLocation(), diag::note_previous_declaration) 11063 << Prev->getIntegerTypeRange(); 11064 return true; 11065 } 11066 } else if (IsFixed != Prev->isFixed()) { 11067 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 11068 << Prev->isFixed(); 11069 Diag(Prev->getLocation(), diag::note_previous_declaration); 11070 return true; 11071 } 11072 11073 return false; 11074 } 11075 11076 /// \brief Get diagnostic %select index for tag kind for 11077 /// redeclaration diagnostic message. 11078 /// WARNING: Indexes apply to particular diagnostics only! 11079 /// 11080 /// \returns diagnostic %select index. 11081 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 11082 switch (Tag) { 11083 case TTK_Struct: return 0; 11084 case TTK_Interface: return 1; 11085 case TTK_Class: return 2; 11086 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 11087 } 11088 } 11089 11090 /// \brief Determine if tag kind is a class-key compatible with 11091 /// class for redeclaration (class, struct, or __interface). 11092 /// 11093 /// \returns true iff the tag kind is compatible. 11094 static bool isClassCompatTagKind(TagTypeKind Tag) 11095 { 11096 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 11097 } 11098 11099 /// \brief Determine whether a tag with a given kind is acceptable 11100 /// as a redeclaration of the given tag declaration. 11101 /// 11102 /// \returns true if the new tag kind is acceptable, false otherwise. 11103 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 11104 TagTypeKind NewTag, bool isDefinition, 11105 SourceLocation NewTagLoc, 11106 const IdentifierInfo &Name) { 11107 // C++ [dcl.type.elab]p3: 11108 // The class-key or enum keyword present in the 11109 // elaborated-type-specifier shall agree in kind with the 11110 // declaration to which the name in the elaborated-type-specifier 11111 // refers. This rule also applies to the form of 11112 // elaborated-type-specifier that declares a class-name or 11113 // friend class since it can be construed as referring to the 11114 // definition of the class. Thus, in any 11115 // elaborated-type-specifier, the enum keyword shall be used to 11116 // refer to an enumeration (7.2), the union class-key shall be 11117 // used to refer to a union (clause 9), and either the class or 11118 // struct class-key shall be used to refer to a class (clause 9) 11119 // declared using the class or struct class-key. 11120 TagTypeKind OldTag = Previous->getTagKind(); 11121 if (!isDefinition || !isClassCompatTagKind(NewTag)) 11122 if (OldTag == NewTag) 11123 return true; 11124 11125 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 11126 // Warn about the struct/class tag mismatch. 11127 bool isTemplate = false; 11128 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 11129 isTemplate = Record->getDescribedClassTemplate(); 11130 11131 if (!ActiveTemplateInstantiations.empty()) { 11132 // In a template instantiation, do not offer fix-its for tag mismatches 11133 // since they usually mess up the template instead of fixing the problem. 11134 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11135 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11136 << getRedeclDiagFromTagKind(OldTag); 11137 return true; 11138 } 11139 11140 if (isDefinition) { 11141 // On definitions, check previous tags and issue a fix-it for each 11142 // one that doesn't match the current tag. 11143 if (Previous->getDefinition()) { 11144 // Don't suggest fix-its for redefinitions. 11145 return true; 11146 } 11147 11148 bool previousMismatch = false; 11149 for (auto I : Previous->redecls()) { 11150 if (I->getTagKind() != NewTag) { 11151 if (!previousMismatch) { 11152 previousMismatch = true; 11153 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11154 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11155 << getRedeclDiagFromTagKind(I->getTagKind()); 11156 } 11157 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11158 << getRedeclDiagFromTagKind(NewTag) 11159 << FixItHint::CreateReplacement(I->getInnerLocStart(), 11160 TypeWithKeyword::getTagTypeKindName(NewTag)); 11161 } 11162 } 11163 return true; 11164 } 11165 11166 // Check for a previous definition. If current tag and definition 11167 // are same type, do nothing. If no definition, but disagree with 11168 // with previous tag type, give a warning, but no fix-it. 11169 const TagDecl *Redecl = Previous->getDefinition() ? 11170 Previous->getDefinition() : Previous; 11171 if (Redecl->getTagKind() == NewTag) { 11172 return true; 11173 } 11174 11175 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11176 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11177 << getRedeclDiagFromTagKind(OldTag); 11178 Diag(Redecl->getLocation(), diag::note_previous_use); 11179 11180 // If there is a previous definition, suggest a fix-it. 11181 if (Previous->getDefinition()) { 11182 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11183 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11184 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11185 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11186 } 11187 11188 return true; 11189 } 11190 return false; 11191 } 11192 11193 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11194 /// from an outer enclosing namespace or file scope inside a friend declaration. 11195 /// This should provide the commented out code in the following snippet: 11196 /// namespace N { 11197 /// struct X; 11198 /// namespace M { 11199 /// struct Y { friend struct /*N::*/ X; }; 11200 /// } 11201 /// } 11202 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11203 SourceLocation NameLoc) { 11204 // While the decl is in a namespace, do repeated lookup of that name and see 11205 // if we get the same namespace back. If we do not, continue until 11206 // translation unit scope, at which point we have a fully qualified NNS. 11207 SmallVector<IdentifierInfo *, 4> Namespaces; 11208 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11209 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11210 // This tag should be declared in a namespace, which can only be enclosed by 11211 // other namespaces. Bail if there's an anonymous namespace in the chain. 11212 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11213 if (!Namespace || Namespace->isAnonymousNamespace()) 11214 return FixItHint(); 11215 IdentifierInfo *II = Namespace->getIdentifier(); 11216 Namespaces.push_back(II); 11217 NamedDecl *Lookup = SemaRef.LookupSingleName( 11218 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11219 if (Lookup == Namespace) 11220 break; 11221 } 11222 11223 // Once we have all the namespaces, reverse them to go outermost first, and 11224 // build an NNS. 11225 SmallString<64> Insertion; 11226 llvm::raw_svector_ostream OS(Insertion); 11227 if (DC->isTranslationUnit()) 11228 OS << "::"; 11229 std::reverse(Namespaces.begin(), Namespaces.end()); 11230 for (auto *II : Namespaces) 11231 OS << II->getName() << "::"; 11232 OS.flush(); 11233 return FixItHint::CreateInsertion(NameLoc, Insertion); 11234 } 11235 11236 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 11237 /// former case, Name will be non-null. In the later case, Name will be null. 11238 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11239 /// reference/declaration/definition of a tag. 11240 /// 11241 /// IsTypeSpecifier is true if this is a type-specifier (or 11242 /// trailing-type-specifier) other than one in an alias-declaration. 11243 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11244 SourceLocation KWLoc, CXXScopeSpec &SS, 11245 IdentifierInfo *Name, SourceLocation NameLoc, 11246 AttributeList *Attr, AccessSpecifier AS, 11247 SourceLocation ModulePrivateLoc, 11248 MultiTemplateParamsArg TemplateParameterLists, 11249 bool &OwnedDecl, bool &IsDependent, 11250 SourceLocation ScopedEnumKWLoc, 11251 bool ScopedEnumUsesClassTag, 11252 TypeResult UnderlyingType, 11253 bool IsTypeSpecifier) { 11254 // If this is not a definition, it must have a name. 11255 IdentifierInfo *OrigName = Name; 11256 assert((Name != nullptr || TUK == TUK_Definition) && 11257 "Nameless record must be a definition!"); 11258 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11259 11260 OwnedDecl = false; 11261 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11262 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11263 11264 // FIXME: Check explicit specializations more carefully. 11265 bool isExplicitSpecialization = false; 11266 bool Invalid = false; 11267 11268 // We only need to do this matching if we have template parameters 11269 // or a scope specifier, which also conveniently avoids this work 11270 // for non-C++ cases. 11271 if (TemplateParameterLists.size() > 0 || 11272 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11273 if (TemplateParameterList *TemplateParams = 11274 MatchTemplateParametersToScopeSpecifier( 11275 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11276 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11277 if (Kind == TTK_Enum) { 11278 Diag(KWLoc, diag::err_enum_template); 11279 return nullptr; 11280 } 11281 11282 if (TemplateParams->size() > 0) { 11283 // This is a declaration or definition of a class template (which may 11284 // be a member of another template). 11285 11286 if (Invalid) 11287 return nullptr; 11288 11289 OwnedDecl = false; 11290 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11291 SS, Name, NameLoc, Attr, 11292 TemplateParams, AS, 11293 ModulePrivateLoc, 11294 /*FriendLoc*/SourceLocation(), 11295 TemplateParameterLists.size()-1, 11296 TemplateParameterLists.data()); 11297 return Result.get(); 11298 } else { 11299 // The "template<>" header is extraneous. 11300 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11301 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11302 isExplicitSpecialization = true; 11303 } 11304 } 11305 } 11306 11307 // Figure out the underlying type if this a enum declaration. We need to do 11308 // this early, because it's needed to detect if this is an incompatible 11309 // redeclaration. 11310 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 11311 11312 if (Kind == TTK_Enum) { 11313 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 11314 // No underlying type explicitly specified, or we failed to parse the 11315 // type, default to int. 11316 EnumUnderlying = Context.IntTy.getTypePtr(); 11317 else if (UnderlyingType.get()) { 11318 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 11319 // integral type; any cv-qualification is ignored. 11320 TypeSourceInfo *TI = nullptr; 11321 GetTypeFromParser(UnderlyingType.get(), &TI); 11322 EnumUnderlying = TI; 11323 11324 if (CheckEnumUnderlyingType(TI)) 11325 // Recover by falling back to int. 11326 EnumUnderlying = Context.IntTy.getTypePtr(); 11327 11328 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 11329 UPPC_FixedUnderlyingType)) 11330 EnumUnderlying = Context.IntTy.getTypePtr(); 11331 11332 } else if (getLangOpts().MSVCCompat) 11333 // Microsoft enums are always of int type. 11334 EnumUnderlying = Context.IntTy.getTypePtr(); 11335 } 11336 11337 DeclContext *SearchDC = CurContext; 11338 DeclContext *DC = CurContext; 11339 bool isStdBadAlloc = false; 11340 11341 RedeclarationKind Redecl = ForRedeclaration; 11342 if (TUK == TUK_Friend || TUK == TUK_Reference) 11343 Redecl = NotForRedeclaration; 11344 11345 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 11346 if (Name && SS.isNotEmpty()) { 11347 // We have a nested-name tag ('struct foo::bar'). 11348 11349 // Check for invalid 'foo::'. 11350 if (SS.isInvalid()) { 11351 Name = nullptr; 11352 goto CreateNewDecl; 11353 } 11354 11355 // If this is a friend or a reference to a class in a dependent 11356 // context, don't try to make a decl for it. 11357 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11358 DC = computeDeclContext(SS, false); 11359 if (!DC) { 11360 IsDependent = true; 11361 return nullptr; 11362 } 11363 } else { 11364 DC = computeDeclContext(SS, true); 11365 if (!DC) { 11366 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 11367 << SS.getRange(); 11368 return nullptr; 11369 } 11370 } 11371 11372 if (RequireCompleteDeclContext(SS, DC)) 11373 return nullptr; 11374 11375 SearchDC = DC; 11376 // Look-up name inside 'foo::'. 11377 LookupQualifiedName(Previous, DC); 11378 11379 if (Previous.isAmbiguous()) 11380 return nullptr; 11381 11382 if (Previous.empty()) { 11383 // Name lookup did not find anything. However, if the 11384 // nested-name-specifier refers to the current instantiation, 11385 // and that current instantiation has any dependent base 11386 // classes, we might find something at instantiation time: treat 11387 // this as a dependent elaborated-type-specifier. 11388 // But this only makes any sense for reference-like lookups. 11389 if (Previous.wasNotFoundInCurrentInstantiation() && 11390 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11391 IsDependent = true; 11392 return nullptr; 11393 } 11394 11395 // A tag 'foo::bar' must already exist. 11396 Diag(NameLoc, diag::err_not_tag_in_scope) 11397 << Kind << Name << DC << SS.getRange(); 11398 Name = nullptr; 11399 Invalid = true; 11400 goto CreateNewDecl; 11401 } 11402 } else if (Name) { 11403 // If this is a named struct, check to see if there was a previous forward 11404 // declaration or definition. 11405 // FIXME: We're looking into outer scopes here, even when we 11406 // shouldn't be. Doing so can result in ambiguities that we 11407 // shouldn't be diagnosing. 11408 LookupName(Previous, S); 11409 11410 // When declaring or defining a tag, ignore ambiguities introduced 11411 // by types using'ed into this scope. 11412 if (Previous.isAmbiguous() && 11413 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 11414 LookupResult::Filter F = Previous.makeFilter(); 11415 while (F.hasNext()) { 11416 NamedDecl *ND = F.next(); 11417 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 11418 F.erase(); 11419 } 11420 F.done(); 11421 } 11422 11423 // C++11 [namespace.memdef]p3: 11424 // If the name in a friend declaration is neither qualified nor 11425 // a template-id and the declaration is a function or an 11426 // elaborated-type-specifier, the lookup to determine whether 11427 // the entity has been previously declared shall not consider 11428 // any scopes outside the innermost enclosing namespace. 11429 // 11430 // MSVC doesn't implement the above rule for types, so a friend tag 11431 // declaration may be a redeclaration of a type declared in an enclosing 11432 // scope. They do implement this rule for friend functions. 11433 // 11434 // Does it matter that this should be by scope instead of by 11435 // semantic context? 11436 if (!Previous.empty() && TUK == TUK_Friend) { 11437 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 11438 LookupResult::Filter F = Previous.makeFilter(); 11439 bool FriendSawTagOutsideEnclosingNamespace = false; 11440 while (F.hasNext()) { 11441 NamedDecl *ND = F.next(); 11442 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11443 if (DC->isFileContext() && 11444 !EnclosingNS->Encloses(ND->getDeclContext())) { 11445 if (getLangOpts().MSVCCompat) 11446 FriendSawTagOutsideEnclosingNamespace = true; 11447 else 11448 F.erase(); 11449 } 11450 } 11451 F.done(); 11452 11453 // Diagnose this MSVC extension in the easy case where lookup would have 11454 // unambiguously found something outside the enclosing namespace. 11455 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 11456 NamedDecl *ND = Previous.getFoundDecl(); 11457 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 11458 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 11459 } 11460 } 11461 11462 // Note: there used to be some attempt at recovery here. 11463 if (Previous.isAmbiguous()) 11464 return nullptr; 11465 11466 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 11467 // FIXME: This makes sure that we ignore the contexts associated 11468 // with C structs, unions, and enums when looking for a matching 11469 // tag declaration or definition. See the similar lookup tweak 11470 // in Sema::LookupName; is there a better way to deal with this? 11471 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 11472 SearchDC = SearchDC->getParent(); 11473 } 11474 } 11475 11476 if (Previous.isSingleResult() && 11477 Previous.getFoundDecl()->isTemplateParameter()) { 11478 // Maybe we will complain about the shadowed template parameter. 11479 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 11480 // Just pretend that we didn't see the previous declaration. 11481 Previous.clear(); 11482 } 11483 11484 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 11485 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 11486 // This is a declaration of or a reference to "std::bad_alloc". 11487 isStdBadAlloc = true; 11488 11489 if (Previous.empty() && StdBadAlloc) { 11490 // std::bad_alloc has been implicitly declared (but made invisible to 11491 // name lookup). Fill in this implicit declaration as the previous 11492 // declaration, so that the declarations get chained appropriately. 11493 Previous.addDecl(getStdBadAlloc()); 11494 } 11495 } 11496 11497 // If we didn't find a previous declaration, and this is a reference 11498 // (or friend reference), move to the correct scope. In C++, we 11499 // also need to do a redeclaration lookup there, just in case 11500 // there's a shadow friend decl. 11501 if (Name && Previous.empty() && 11502 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11503 if (Invalid) goto CreateNewDecl; 11504 assert(SS.isEmpty()); 11505 11506 if (TUK == TUK_Reference) { 11507 // C++ [basic.scope.pdecl]p5: 11508 // -- for an elaborated-type-specifier of the form 11509 // 11510 // class-key identifier 11511 // 11512 // if the elaborated-type-specifier is used in the 11513 // decl-specifier-seq or parameter-declaration-clause of a 11514 // function defined in namespace scope, the identifier is 11515 // declared as a class-name in the namespace that contains 11516 // the declaration; otherwise, except as a friend 11517 // declaration, the identifier is declared in the smallest 11518 // non-class, non-function-prototype scope that contains the 11519 // declaration. 11520 // 11521 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 11522 // C structs and unions. 11523 // 11524 // It is an error in C++ to declare (rather than define) an enum 11525 // type, including via an elaborated type specifier. We'll 11526 // diagnose that later; for now, declare the enum in the same 11527 // scope as we would have picked for any other tag type. 11528 // 11529 // GNU C also supports this behavior as part of its incomplete 11530 // enum types extension, while GNU C++ does not. 11531 // 11532 // Find the context where we'll be declaring the tag. 11533 // FIXME: We would like to maintain the current DeclContext as the 11534 // lexical context, 11535 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 11536 SearchDC = SearchDC->getParent(); 11537 11538 // Find the scope where we'll be declaring the tag. 11539 while (S->isClassScope() || 11540 (getLangOpts().CPlusPlus && 11541 S->isFunctionPrototypeScope()) || 11542 ((S->getFlags() & Scope::DeclScope) == 0) || 11543 (S->getEntity() && S->getEntity()->isTransparentContext())) 11544 S = S->getParent(); 11545 } else { 11546 assert(TUK == TUK_Friend); 11547 // C++ [namespace.memdef]p3: 11548 // If a friend declaration in a non-local class first declares a 11549 // class or function, the friend class or function is a member of 11550 // the innermost enclosing namespace. 11551 SearchDC = SearchDC->getEnclosingNamespaceContext(); 11552 } 11553 11554 // In C++, we need to do a redeclaration lookup to properly 11555 // diagnose some problems. 11556 if (getLangOpts().CPlusPlus) { 11557 Previous.setRedeclarationKind(ForRedeclaration); 11558 LookupQualifiedName(Previous, SearchDC); 11559 } 11560 } 11561 11562 if (!Previous.empty()) { 11563 NamedDecl *PrevDecl = Previous.getFoundDecl(); 11564 NamedDecl *DirectPrevDecl = 11565 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 11566 11567 // It's okay to have a tag decl in the same scope as a typedef 11568 // which hides a tag decl in the same scope. Finding this 11569 // insanity with a redeclaration lookup can only actually happen 11570 // in C++. 11571 // 11572 // This is also okay for elaborated-type-specifiers, which is 11573 // technically forbidden by the current standard but which is 11574 // okay according to the likely resolution of an open issue; 11575 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 11576 if (getLangOpts().CPlusPlus) { 11577 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11578 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 11579 TagDecl *Tag = TT->getDecl(); 11580 if (Tag->getDeclName() == Name && 11581 Tag->getDeclContext()->getRedeclContext() 11582 ->Equals(TD->getDeclContext()->getRedeclContext())) { 11583 PrevDecl = Tag; 11584 Previous.clear(); 11585 Previous.addDecl(Tag); 11586 Previous.resolveKind(); 11587 } 11588 } 11589 } 11590 } 11591 11592 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 11593 // If this is a use of a previous tag, or if the tag is already declared 11594 // in the same scope (so that the definition/declaration completes or 11595 // rementions the tag), reuse the decl. 11596 if (TUK == TUK_Reference || TUK == TUK_Friend || 11597 isDeclInScope(DirectPrevDecl, SearchDC, S, 11598 SS.isNotEmpty() || isExplicitSpecialization)) { 11599 // Make sure that this wasn't declared as an enum and now used as a 11600 // struct or something similar. 11601 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 11602 TUK == TUK_Definition, KWLoc, 11603 *Name)) { 11604 bool SafeToContinue 11605 = (PrevTagDecl->getTagKind() != TTK_Enum && 11606 Kind != TTK_Enum); 11607 if (SafeToContinue) 11608 Diag(KWLoc, diag::err_use_with_wrong_tag) 11609 << Name 11610 << FixItHint::CreateReplacement(SourceRange(KWLoc), 11611 PrevTagDecl->getKindName()); 11612 else 11613 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 11614 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 11615 11616 if (SafeToContinue) 11617 Kind = PrevTagDecl->getTagKind(); 11618 else { 11619 // Recover by making this an anonymous redefinition. 11620 Name = nullptr; 11621 Previous.clear(); 11622 Invalid = true; 11623 } 11624 } 11625 11626 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 11627 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 11628 11629 // If this is an elaborated-type-specifier for a scoped enumeration, 11630 // the 'class' keyword is not necessary and not permitted. 11631 if (TUK == TUK_Reference || TUK == TUK_Friend) { 11632 if (ScopedEnum) 11633 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 11634 << PrevEnum->isScoped() 11635 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 11636 return PrevTagDecl; 11637 } 11638 11639 QualType EnumUnderlyingTy; 11640 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11641 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 11642 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 11643 EnumUnderlyingTy = QualType(T, 0); 11644 11645 // All conflicts with previous declarations are recovered by 11646 // returning the previous declaration, unless this is a definition, 11647 // in which case we want the caller to bail out. 11648 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11649 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11650 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11651 } 11652 11653 // C++11 [class.mem]p1: 11654 // A member shall not be declared twice in the member-specification, 11655 // except that a nested class or member class template can be declared 11656 // and then later defined. 11657 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11658 S->isDeclScope(PrevDecl)) { 11659 Diag(NameLoc, diag::ext_member_redeclared); 11660 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11661 } 11662 11663 if (!Invalid) { 11664 // If this is a use, just return the declaration we found, unless 11665 // we have attributes. 11666 11667 // FIXME: In the future, return a variant or some other clue 11668 // for the consumer of this Decl to know it doesn't own it. 11669 // For our current ASTs this shouldn't be a problem, but will 11670 // need to be changed with DeclGroups. 11671 if (!Attr && 11672 ((TUK == TUK_Reference && 11673 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11674 || TUK == TUK_Friend)) 11675 return PrevTagDecl; 11676 11677 // Diagnose attempts to redefine a tag. 11678 if (TUK == TUK_Definition) { 11679 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 11680 // If we're defining a specialization and the previous definition 11681 // is from an implicit instantiation, don't emit an error 11682 // here; we'll catch this in the general case below. 11683 bool IsExplicitSpecializationAfterInstantiation = false; 11684 if (isExplicitSpecialization) { 11685 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11686 IsExplicitSpecializationAfterInstantiation = 11687 RD->getTemplateSpecializationKind() != 11688 TSK_ExplicitSpecialization; 11689 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11690 IsExplicitSpecializationAfterInstantiation = 11691 ED->getTemplateSpecializationKind() != 11692 TSK_ExplicitSpecialization; 11693 } 11694 11695 if (!IsExplicitSpecializationAfterInstantiation) { 11696 // A redeclaration in function prototype scope in C isn't 11697 // visible elsewhere, so merely issue a warning. 11698 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11699 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11700 else 11701 Diag(NameLoc, diag::err_redefinition) << Name; 11702 Diag(Def->getLocation(), diag::note_previous_definition); 11703 // If this is a redefinition, recover by making this 11704 // struct be anonymous, which will make any later 11705 // references get the previous definition. 11706 Name = nullptr; 11707 Previous.clear(); 11708 Invalid = true; 11709 } 11710 } else { 11711 // If the type is currently being defined, complain 11712 // about a nested redefinition. 11713 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl(); 11714 if (TD->isBeingDefined()) { 11715 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11716 Diag(PrevTagDecl->getLocation(), 11717 diag::note_previous_definition); 11718 Name = nullptr; 11719 Previous.clear(); 11720 Invalid = true; 11721 } 11722 } 11723 11724 // Okay, this is definition of a previously declared or referenced 11725 // tag. We're going to create a new Decl for it. 11726 } 11727 11728 // Okay, we're going to make a redeclaration. If this is some kind 11729 // of reference, make sure we build the redeclaration in the same DC 11730 // as the original, and ignore the current access specifier. 11731 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11732 SearchDC = PrevTagDecl->getDeclContext(); 11733 AS = AS_none; 11734 } 11735 } 11736 // If we get here we have (another) forward declaration or we 11737 // have a definition. Just create a new decl. 11738 11739 } else { 11740 // If we get here, this is a definition of a new tag type in a nested 11741 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11742 // new decl/type. We set PrevDecl to NULL so that the entities 11743 // have distinct types. 11744 Previous.clear(); 11745 } 11746 // If we get here, we're going to create a new Decl. If PrevDecl 11747 // is non-NULL, it's a definition of the tag declared by 11748 // PrevDecl. If it's NULL, we have a new definition. 11749 11750 11751 // Otherwise, PrevDecl is not a tag, but was found with tag 11752 // lookup. This is only actually possible in C++, where a few 11753 // things like templates still live in the tag namespace. 11754 } else { 11755 // Use a better diagnostic if an elaborated-type-specifier 11756 // found the wrong kind of type on the first 11757 // (non-redeclaration) lookup. 11758 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11759 !Previous.isForRedeclaration()) { 11760 unsigned Kind = 0; 11761 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11762 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11763 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11764 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11765 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11766 Invalid = true; 11767 11768 // Otherwise, only diagnose if the declaration is in scope. 11769 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11770 SS.isNotEmpty() || isExplicitSpecialization)) { 11771 // do nothing 11772 11773 // Diagnose implicit declarations introduced by elaborated types. 11774 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11775 unsigned Kind = 0; 11776 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11777 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11778 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11779 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11780 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11781 Invalid = true; 11782 11783 // Otherwise it's a declaration. Call out a particularly common 11784 // case here. 11785 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11786 unsigned Kind = 0; 11787 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11788 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11789 << Name << Kind << TND->getUnderlyingType(); 11790 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11791 Invalid = true; 11792 11793 // Otherwise, diagnose. 11794 } else { 11795 // The tag name clashes with something else in the target scope, 11796 // issue an error and recover by making this tag be anonymous. 11797 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11798 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11799 Name = nullptr; 11800 Invalid = true; 11801 } 11802 11803 // The existing declaration isn't relevant to us; we're in a 11804 // new scope, so clear out the previous declaration. 11805 Previous.clear(); 11806 } 11807 } 11808 11809 CreateNewDecl: 11810 11811 TagDecl *PrevDecl = nullptr; 11812 if (Previous.isSingleResult()) 11813 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11814 11815 // If there is an identifier, use the location of the identifier as the 11816 // location of the decl, otherwise use the location of the struct/union 11817 // keyword. 11818 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11819 11820 // Otherwise, create a new declaration. If there is a previous 11821 // declaration of the same entity, the two will be linked via 11822 // PrevDecl. 11823 TagDecl *New; 11824 11825 bool IsForwardReference = false; 11826 if (Kind == TTK_Enum) { 11827 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11828 // enum X { A, B, C } D; D should chain to X. 11829 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11830 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11831 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11832 // If this is an undefined enum, warn. 11833 if (TUK != TUK_Definition && !Invalid) { 11834 TagDecl *Def; 11835 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11836 cast<EnumDecl>(New)->isFixed()) { 11837 // C++0x: 7.2p2: opaque-enum-declaration. 11838 // Conflicts are diagnosed above. Do nothing. 11839 } 11840 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11841 Diag(Loc, diag::ext_forward_ref_enum_def) 11842 << New; 11843 Diag(Def->getLocation(), diag::note_previous_definition); 11844 } else { 11845 unsigned DiagID = diag::ext_forward_ref_enum; 11846 if (getLangOpts().MSVCCompat) 11847 DiagID = diag::ext_ms_forward_ref_enum; 11848 else if (getLangOpts().CPlusPlus) 11849 DiagID = diag::err_forward_ref_enum; 11850 Diag(Loc, DiagID); 11851 11852 // If this is a forward-declared reference to an enumeration, make a 11853 // note of it; we won't actually be introducing the declaration into 11854 // the declaration context. 11855 if (TUK == TUK_Reference) 11856 IsForwardReference = true; 11857 } 11858 } 11859 11860 if (EnumUnderlying) { 11861 EnumDecl *ED = cast<EnumDecl>(New); 11862 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11863 ED->setIntegerTypeSourceInfo(TI); 11864 else 11865 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11866 ED->setPromotionType(ED->getIntegerType()); 11867 } 11868 11869 } else { 11870 // struct/union/class 11871 11872 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11873 // struct X { int A; } D; D should chain to X. 11874 if (getLangOpts().CPlusPlus) { 11875 // FIXME: Look for a way to use RecordDecl for simple structs. 11876 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11877 cast_or_null<CXXRecordDecl>(PrevDecl)); 11878 11879 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11880 StdBadAlloc = cast<CXXRecordDecl>(New); 11881 } else 11882 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11883 cast_or_null<RecordDecl>(PrevDecl)); 11884 } 11885 11886 // C++11 [dcl.type]p3: 11887 // A type-specifier-seq shall not define a class or enumeration [...]. 11888 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11889 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11890 << Context.getTagDeclType(New); 11891 Invalid = true; 11892 } 11893 11894 // Maybe add qualifier info. 11895 if (SS.isNotEmpty()) { 11896 if (SS.isSet()) { 11897 // If this is either a declaration or a definition, check the 11898 // nested-name-specifier against the current context. We don't do this 11899 // for explicit specializations, because they have similar checking 11900 // (with more specific diagnostics) in the call to 11901 // CheckMemberSpecialization, below. 11902 if (!isExplicitSpecialization && 11903 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11904 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc)) 11905 Invalid = true; 11906 11907 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11908 if (TemplateParameterLists.size() > 0) { 11909 New->setTemplateParameterListsInfo(Context, 11910 TemplateParameterLists.size(), 11911 TemplateParameterLists.data()); 11912 } 11913 } 11914 else 11915 Invalid = true; 11916 } 11917 11918 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11919 // Add alignment attributes if necessary; these attributes are checked when 11920 // the ASTContext lays out the structure. 11921 // 11922 // It is important for implementing the correct semantics that this 11923 // happen here (in act on tag decl). The #pragma pack stack is 11924 // maintained as a result of parser callbacks which can occur at 11925 // many points during the parsing of a struct declaration (because 11926 // the #pragma tokens are effectively skipped over during the 11927 // parsing of the struct). 11928 if (TUK == TUK_Definition) { 11929 AddAlignmentAttributesForRecord(RD); 11930 AddMsStructLayoutForRecord(RD); 11931 } 11932 } 11933 11934 if (ModulePrivateLoc.isValid()) { 11935 if (isExplicitSpecialization) 11936 Diag(New->getLocation(), diag::err_module_private_specialization) 11937 << 2 11938 << FixItHint::CreateRemoval(ModulePrivateLoc); 11939 // __module_private__ does not apply to local classes. However, we only 11940 // diagnose this as an error when the declaration specifiers are 11941 // freestanding. Here, we just ignore the __module_private__. 11942 else if (!SearchDC->isFunctionOrMethod()) 11943 New->setModulePrivate(); 11944 } 11945 11946 // If this is a specialization of a member class (of a class template), 11947 // check the specialization. 11948 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11949 Invalid = true; 11950 11951 // If we're declaring or defining a tag in function prototype scope in C, 11952 // note that this type can only be used within the function and add it to 11953 // the list of decls to inject into the function definition scope. 11954 if ((Name || Kind == TTK_Enum) && 11955 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11956 if (getLangOpts().CPlusPlus) { 11957 // C++ [dcl.fct]p6: 11958 // Types shall not be defined in return or parameter types. 11959 if (TUK == TUK_Definition && !IsTypeSpecifier) { 11960 Diag(Loc, diag::err_type_defined_in_param_type) 11961 << Name; 11962 Invalid = true; 11963 } 11964 } else { 11965 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11966 } 11967 DeclsInPrototypeScope.push_back(New); 11968 } 11969 11970 if (Invalid) 11971 New->setInvalidDecl(); 11972 11973 if (Attr) 11974 ProcessDeclAttributeList(S, New, Attr); 11975 11976 // Set the lexical context. If the tag has a C++ scope specifier, the 11977 // lexical context will be different from the semantic context. 11978 New->setLexicalDeclContext(CurContext); 11979 11980 // Mark this as a friend decl if applicable. 11981 // In Microsoft mode, a friend declaration also acts as a forward 11982 // declaration so we always pass true to setObjectOfFriendDecl to make 11983 // the tag name visible. 11984 if (TUK == TUK_Friend) 11985 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 11986 11987 // Set the access specifier. 11988 if (!Invalid && SearchDC->isRecord()) 11989 SetMemberAccessSpecifier(New, PrevDecl, AS); 11990 11991 if (TUK == TUK_Definition) 11992 New->startDefinition(); 11993 11994 // If this has an identifier, add it to the scope stack. 11995 if (TUK == TUK_Friend) { 11996 // We might be replacing an existing declaration in the lookup tables; 11997 // if so, borrow its access specifier. 11998 if (PrevDecl) 11999 New->setAccess(PrevDecl->getAccess()); 12000 12001 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 12002 DC->makeDeclVisibleInContext(New); 12003 if (Name) // can be null along some error paths 12004 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 12005 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 12006 } else if (Name) { 12007 S = getNonFieldDeclScope(S); 12008 PushOnScopeChains(New, S, !IsForwardReference); 12009 if (IsForwardReference) 12010 SearchDC->makeDeclVisibleInContext(New); 12011 12012 } else { 12013 CurContext->addDecl(New); 12014 } 12015 12016 // If this is the C FILE type, notify the AST context. 12017 if (IdentifierInfo *II = New->getIdentifier()) 12018 if (!New->isInvalidDecl() && 12019 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 12020 II->isStr("FILE")) 12021 Context.setFILEDecl(New); 12022 12023 if (PrevDecl) 12024 mergeDeclAttributes(New, PrevDecl); 12025 12026 // If there's a #pragma GCC visibility in scope, set the visibility of this 12027 // record. 12028 AddPushedVisibilityAttribute(New); 12029 12030 OwnedDecl = true; 12031 // In C++, don't return an invalid declaration. We can't recover well from 12032 // the cases where we make the type anonymous. 12033 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 12034 } 12035 12036 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 12037 AdjustDeclIfTemplate(TagD); 12038 TagDecl *Tag = cast<TagDecl>(TagD); 12039 12040 // Enter the tag context. 12041 PushDeclContext(S, Tag); 12042 12043 ActOnDocumentableDecl(TagD); 12044 12045 // If there's a #pragma GCC visibility in scope, set the visibility of this 12046 // record. 12047 AddPushedVisibilityAttribute(Tag); 12048 } 12049 12050 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 12051 assert(isa<ObjCContainerDecl>(IDecl) && 12052 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 12053 DeclContext *OCD = cast<DeclContext>(IDecl); 12054 assert(getContainingDC(OCD) == CurContext && 12055 "The next DeclContext should be lexically contained in the current one."); 12056 CurContext = OCD; 12057 return IDecl; 12058 } 12059 12060 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 12061 SourceLocation FinalLoc, 12062 bool IsFinalSpelledSealed, 12063 SourceLocation LBraceLoc) { 12064 AdjustDeclIfTemplate(TagD); 12065 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 12066 12067 FieldCollector->StartClass(); 12068 12069 if (!Record->getIdentifier()) 12070 return; 12071 12072 if (FinalLoc.isValid()) 12073 Record->addAttr(new (Context) 12074 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 12075 12076 // C++ [class]p2: 12077 // [...] The class-name is also inserted into the scope of the 12078 // class itself; this is known as the injected-class-name. For 12079 // purposes of access checking, the injected-class-name is treated 12080 // as if it were a public member name. 12081 CXXRecordDecl *InjectedClassName 12082 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 12083 Record->getLocStart(), Record->getLocation(), 12084 Record->getIdentifier(), 12085 /*PrevDecl=*/nullptr, 12086 /*DelayTypeCreation=*/true); 12087 Context.getTypeDeclType(InjectedClassName, Record); 12088 InjectedClassName->setImplicit(); 12089 InjectedClassName->setAccess(AS_public); 12090 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 12091 InjectedClassName->setDescribedClassTemplate(Template); 12092 PushOnScopeChains(InjectedClassName, S); 12093 assert(InjectedClassName->isInjectedClassName() && 12094 "Broken injected-class-name"); 12095 } 12096 12097 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 12098 SourceLocation RBraceLoc) { 12099 AdjustDeclIfTemplate(TagD); 12100 TagDecl *Tag = cast<TagDecl>(TagD); 12101 Tag->setRBraceLoc(RBraceLoc); 12102 12103 // Make sure we "complete" the definition even it is invalid. 12104 if (Tag->isBeingDefined()) { 12105 assert(Tag->isInvalidDecl() && "We should already have completed it"); 12106 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12107 RD->completeDefinition(); 12108 } 12109 12110 if (isa<CXXRecordDecl>(Tag)) 12111 FieldCollector->FinishClass(); 12112 12113 // Exit this scope of this tag's definition. 12114 PopDeclContext(); 12115 12116 if (getCurLexicalContext()->isObjCContainer() && 12117 Tag->getDeclContext()->isFileContext()) 12118 Tag->setTopLevelDeclInObjCContainer(); 12119 12120 // Notify the consumer that we've defined a tag. 12121 if (!Tag->isInvalidDecl()) 12122 Consumer.HandleTagDeclDefinition(Tag); 12123 } 12124 12125 void Sema::ActOnObjCContainerFinishDefinition() { 12126 // Exit this scope of this interface definition. 12127 PopDeclContext(); 12128 } 12129 12130 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 12131 assert(DC == CurContext && "Mismatch of container contexts"); 12132 OriginalLexicalContext = DC; 12133 ActOnObjCContainerFinishDefinition(); 12134 } 12135 12136 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 12137 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 12138 OriginalLexicalContext = nullptr; 12139 } 12140 12141 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 12142 AdjustDeclIfTemplate(TagD); 12143 TagDecl *Tag = cast<TagDecl>(TagD); 12144 Tag->setInvalidDecl(); 12145 12146 // Make sure we "complete" the definition even it is invalid. 12147 if (Tag->isBeingDefined()) { 12148 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12149 RD->completeDefinition(); 12150 } 12151 12152 // We're undoing ActOnTagStartDefinition here, not 12153 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 12154 // the FieldCollector. 12155 12156 PopDeclContext(); 12157 } 12158 12159 // Note that FieldName may be null for anonymous bitfields. 12160 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 12161 IdentifierInfo *FieldName, 12162 QualType FieldTy, bool IsMsStruct, 12163 Expr *BitWidth, bool *ZeroWidth) { 12164 // Default to true; that shouldn't confuse checks for emptiness 12165 if (ZeroWidth) 12166 *ZeroWidth = true; 12167 12168 // C99 6.7.2.1p4 - verify the field type. 12169 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 12170 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 12171 // Handle incomplete types with specific error. 12172 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12173 return ExprError(); 12174 if (FieldName) 12175 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12176 << FieldName << FieldTy << BitWidth->getSourceRange(); 12177 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12178 << FieldTy << BitWidth->getSourceRange(); 12179 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12180 UPPC_BitFieldWidth)) 12181 return ExprError(); 12182 12183 // If the bit-width is type- or value-dependent, don't try to check 12184 // it now. 12185 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12186 return BitWidth; 12187 12188 llvm::APSInt Value; 12189 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12190 if (ICE.isInvalid()) 12191 return ICE; 12192 BitWidth = ICE.get(); 12193 12194 if (Value != 0 && ZeroWidth) 12195 *ZeroWidth = false; 12196 12197 // Zero-width bitfield is ok for anonymous field. 12198 if (Value == 0 && FieldName) 12199 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12200 12201 if (Value.isSigned() && Value.isNegative()) { 12202 if (FieldName) 12203 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12204 << FieldName << Value.toString(10); 12205 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12206 << Value.toString(10); 12207 } 12208 12209 if (!FieldTy->isDependentType()) { 12210 uint64_t TypeSize = Context.getTypeSize(FieldTy); 12211 if (Value.getZExtValue() > TypeSize) { 12212 if (!getLangOpts().CPlusPlus || IsMsStruct || 12213 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12214 if (FieldName) 12215 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 12216 << FieldName << (unsigned)Value.getZExtValue() 12217 << (unsigned)TypeSize; 12218 12219 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 12220 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12221 } 12222 12223 if (FieldName) 12224 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 12225 << FieldName << (unsigned)Value.getZExtValue() 12226 << (unsigned)TypeSize; 12227 else 12228 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 12229 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12230 } 12231 } 12232 12233 return BitWidth; 12234 } 12235 12236 /// ActOnField - Each field of a C struct/union is passed into this in order 12237 /// to create a FieldDecl object for it. 12238 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 12239 Declarator &D, Expr *BitfieldWidth) { 12240 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 12241 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 12242 /*InitStyle=*/ICIS_NoInit, AS_public); 12243 return Res; 12244 } 12245 12246 /// HandleField - Analyze a field of a C struct or a C++ data member. 12247 /// 12248 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 12249 SourceLocation DeclStart, 12250 Declarator &D, Expr *BitWidth, 12251 InClassInitStyle InitStyle, 12252 AccessSpecifier AS) { 12253 IdentifierInfo *II = D.getIdentifier(); 12254 SourceLocation Loc = DeclStart; 12255 if (II) Loc = D.getIdentifierLoc(); 12256 12257 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12258 QualType T = TInfo->getType(); 12259 if (getLangOpts().CPlusPlus) { 12260 CheckExtraCXXDefaultArguments(D); 12261 12262 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12263 UPPC_DataMemberType)) { 12264 D.setInvalidType(); 12265 T = Context.IntTy; 12266 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12267 } 12268 } 12269 12270 // TR 18037 does not allow fields to be declared with address spaces. 12271 if (T.getQualifiers().hasAddressSpace()) { 12272 Diag(Loc, diag::err_field_with_address_space); 12273 D.setInvalidType(); 12274 } 12275 12276 // OpenCL 1.2 spec, s6.9 r: 12277 // The event type cannot be used to declare a structure or union field. 12278 if (LangOpts.OpenCL && T->isEventT()) { 12279 Diag(Loc, diag::err_event_t_struct_field); 12280 D.setInvalidType(); 12281 } 12282 12283 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12284 12285 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12286 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12287 diag::err_invalid_thread) 12288 << DeclSpec::getSpecifierName(TSCS); 12289 12290 // Check to see if this name was declared as a member previously 12291 NamedDecl *PrevDecl = nullptr; 12292 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12293 LookupName(Previous, S); 12294 switch (Previous.getResultKind()) { 12295 case LookupResult::Found: 12296 case LookupResult::FoundUnresolvedValue: 12297 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12298 break; 12299 12300 case LookupResult::FoundOverloaded: 12301 PrevDecl = Previous.getRepresentativeDecl(); 12302 break; 12303 12304 case LookupResult::NotFound: 12305 case LookupResult::NotFoundInCurrentInstantiation: 12306 case LookupResult::Ambiguous: 12307 break; 12308 } 12309 Previous.suppressDiagnostics(); 12310 12311 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12312 // Maybe we will complain about the shadowed template parameter. 12313 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12314 // Just pretend that we didn't see the previous declaration. 12315 PrevDecl = nullptr; 12316 } 12317 12318 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12319 PrevDecl = nullptr; 12320 12321 bool Mutable 12322 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 12323 SourceLocation TSSL = D.getLocStart(); 12324 FieldDecl *NewFD 12325 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 12326 TSSL, AS, PrevDecl, &D); 12327 12328 if (NewFD->isInvalidDecl()) 12329 Record->setInvalidDecl(); 12330 12331 if (D.getDeclSpec().isModulePrivateSpecified()) 12332 NewFD->setModulePrivate(); 12333 12334 if (NewFD->isInvalidDecl() && PrevDecl) { 12335 // Don't introduce NewFD into scope; there's already something 12336 // with the same name in the same scope. 12337 } else if (II) { 12338 PushOnScopeChains(NewFD, S); 12339 } else 12340 Record->addDecl(NewFD); 12341 12342 return NewFD; 12343 } 12344 12345 /// \brief Build a new FieldDecl and check its well-formedness. 12346 /// 12347 /// This routine builds a new FieldDecl given the fields name, type, 12348 /// record, etc. \p PrevDecl should refer to any previous declaration 12349 /// with the same name and in the same scope as the field to be 12350 /// created. 12351 /// 12352 /// \returns a new FieldDecl. 12353 /// 12354 /// \todo The Declarator argument is a hack. It will be removed once 12355 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 12356 TypeSourceInfo *TInfo, 12357 RecordDecl *Record, SourceLocation Loc, 12358 bool Mutable, Expr *BitWidth, 12359 InClassInitStyle InitStyle, 12360 SourceLocation TSSL, 12361 AccessSpecifier AS, NamedDecl *PrevDecl, 12362 Declarator *D) { 12363 IdentifierInfo *II = Name.getAsIdentifierInfo(); 12364 bool InvalidDecl = false; 12365 if (D) InvalidDecl = D->isInvalidType(); 12366 12367 // If we receive a broken type, recover by assuming 'int' and 12368 // marking this declaration as invalid. 12369 if (T.isNull()) { 12370 InvalidDecl = true; 12371 T = Context.IntTy; 12372 } 12373 12374 QualType EltTy = Context.getBaseElementType(T); 12375 if (!EltTy->isDependentType()) { 12376 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 12377 // Fields of incomplete type force their record to be invalid. 12378 Record->setInvalidDecl(); 12379 InvalidDecl = true; 12380 } else { 12381 NamedDecl *Def; 12382 EltTy->isIncompleteType(&Def); 12383 if (Def && Def->isInvalidDecl()) { 12384 Record->setInvalidDecl(); 12385 InvalidDecl = true; 12386 } 12387 } 12388 } 12389 12390 // OpenCL v1.2 s6.9.c: bitfields are not supported. 12391 if (BitWidth && getLangOpts().OpenCL) { 12392 Diag(Loc, diag::err_opencl_bitfields); 12393 InvalidDecl = true; 12394 } 12395 12396 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12397 // than a variably modified type. 12398 if (!InvalidDecl && T->isVariablyModifiedType()) { 12399 bool SizeIsNegative; 12400 llvm::APSInt Oversized; 12401 12402 TypeSourceInfo *FixedTInfo = 12403 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 12404 SizeIsNegative, 12405 Oversized); 12406 if (FixedTInfo) { 12407 Diag(Loc, diag::warn_illegal_constant_array_size); 12408 TInfo = FixedTInfo; 12409 T = FixedTInfo->getType(); 12410 } else { 12411 if (SizeIsNegative) 12412 Diag(Loc, diag::err_typecheck_negative_array_size); 12413 else if (Oversized.getBoolValue()) 12414 Diag(Loc, diag::err_array_too_large) 12415 << Oversized.toString(10); 12416 else 12417 Diag(Loc, diag::err_typecheck_field_variable_size); 12418 InvalidDecl = true; 12419 } 12420 } 12421 12422 // Fields can not have abstract class types 12423 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 12424 diag::err_abstract_type_in_decl, 12425 AbstractFieldType)) 12426 InvalidDecl = true; 12427 12428 bool ZeroWidth = false; 12429 // If this is declared as a bit-field, check the bit-field. 12430 if (!InvalidDecl && BitWidth) { 12431 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 12432 &ZeroWidth).get(); 12433 if (!BitWidth) { 12434 InvalidDecl = true; 12435 BitWidth = nullptr; 12436 ZeroWidth = false; 12437 } 12438 } 12439 12440 // Check that 'mutable' is consistent with the type of the declaration. 12441 if (!InvalidDecl && Mutable) { 12442 unsigned DiagID = 0; 12443 if (T->isReferenceType()) 12444 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference 12445 : diag::err_mutable_reference; 12446 else if (T.isConstQualified()) 12447 DiagID = diag::err_mutable_const; 12448 12449 if (DiagID) { 12450 SourceLocation ErrLoc = Loc; 12451 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 12452 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 12453 Diag(ErrLoc, DiagID); 12454 if (DiagID != diag::ext_mutable_reference) { 12455 Mutable = false; 12456 InvalidDecl = true; 12457 } 12458 } 12459 } 12460 12461 // C++11 [class.union]p8 (DR1460): 12462 // At most one variant member of a union may have a 12463 // brace-or-equal-initializer. 12464 if (InitStyle != ICIS_NoInit) 12465 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 12466 12467 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 12468 BitWidth, Mutable, InitStyle); 12469 if (InvalidDecl) 12470 NewFD->setInvalidDecl(); 12471 12472 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 12473 Diag(Loc, diag::err_duplicate_member) << II; 12474 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12475 NewFD->setInvalidDecl(); 12476 } 12477 12478 if (!InvalidDecl && getLangOpts().CPlusPlus) { 12479 if (Record->isUnion()) { 12480 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12481 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12482 if (RDecl->getDefinition()) { 12483 // C++ [class.union]p1: An object of a class with a non-trivial 12484 // constructor, a non-trivial copy constructor, a non-trivial 12485 // destructor, or a non-trivial copy assignment operator 12486 // cannot be a member of a union, nor can an array of such 12487 // objects. 12488 if (CheckNontrivialField(NewFD)) 12489 NewFD->setInvalidDecl(); 12490 } 12491 } 12492 12493 // C++ [class.union]p1: If a union contains a member of reference type, 12494 // the program is ill-formed, except when compiling with MSVC extensions 12495 // enabled. 12496 if (EltTy->isReferenceType()) { 12497 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 12498 diag::ext_union_member_of_reference_type : 12499 diag::err_union_member_of_reference_type) 12500 << NewFD->getDeclName() << EltTy; 12501 if (!getLangOpts().MicrosoftExt) 12502 NewFD->setInvalidDecl(); 12503 } 12504 } 12505 } 12506 12507 // FIXME: We need to pass in the attributes given an AST 12508 // representation, not a parser representation. 12509 if (D) { 12510 // FIXME: The current scope is almost... but not entirely... correct here. 12511 ProcessDeclAttributes(getCurScope(), NewFD, *D); 12512 12513 if (NewFD->hasAttrs()) 12514 CheckAlignasUnderalignment(NewFD); 12515 } 12516 12517 // In auto-retain/release, infer strong retension for fields of 12518 // retainable type. 12519 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 12520 NewFD->setInvalidDecl(); 12521 12522 if (T.isObjCGCWeak()) 12523 Diag(Loc, diag::warn_attribute_weak_on_field); 12524 12525 NewFD->setAccess(AS); 12526 return NewFD; 12527 } 12528 12529 bool Sema::CheckNontrivialField(FieldDecl *FD) { 12530 assert(FD); 12531 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 12532 12533 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 12534 return false; 12535 12536 QualType EltTy = Context.getBaseElementType(FD->getType()); 12537 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12538 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12539 if (RDecl->getDefinition()) { 12540 // We check for copy constructors before constructors 12541 // because otherwise we'll never get complaints about 12542 // copy constructors. 12543 12544 CXXSpecialMember member = CXXInvalid; 12545 // We're required to check for any non-trivial constructors. Since the 12546 // implicit default constructor is suppressed if there are any 12547 // user-declared constructors, we just need to check that there is a 12548 // trivial default constructor and a trivial copy constructor. (We don't 12549 // worry about move constructors here, since this is a C++98 check.) 12550 if (RDecl->hasNonTrivialCopyConstructor()) 12551 member = CXXCopyConstructor; 12552 else if (!RDecl->hasTrivialDefaultConstructor()) 12553 member = CXXDefaultConstructor; 12554 else if (RDecl->hasNonTrivialCopyAssignment()) 12555 member = CXXCopyAssignment; 12556 else if (RDecl->hasNonTrivialDestructor()) 12557 member = CXXDestructor; 12558 12559 if (member != CXXInvalid) { 12560 if (!getLangOpts().CPlusPlus11 && 12561 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 12562 // Objective-C++ ARC: it is an error to have a non-trivial field of 12563 // a union. However, system headers in Objective-C programs 12564 // occasionally have Objective-C lifetime objects within unions, 12565 // and rather than cause the program to fail, we make those 12566 // members unavailable. 12567 SourceLocation Loc = FD->getLocation(); 12568 if (getSourceManager().isInSystemHeader(Loc)) { 12569 if (!FD->hasAttr<UnavailableAttr>()) 12570 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12571 "this system field has retaining ownership", 12572 Loc)); 12573 return false; 12574 } 12575 } 12576 12577 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 12578 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 12579 diag::err_illegal_union_or_anon_struct_member) 12580 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 12581 DiagnoseNontrivial(RDecl, member); 12582 return !getLangOpts().CPlusPlus11; 12583 } 12584 } 12585 } 12586 12587 return false; 12588 } 12589 12590 /// TranslateIvarVisibility - Translate visibility from a token ID to an 12591 /// AST enum value. 12592 static ObjCIvarDecl::AccessControl 12593 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 12594 switch (ivarVisibility) { 12595 default: llvm_unreachable("Unknown visitibility kind"); 12596 case tok::objc_private: return ObjCIvarDecl::Private; 12597 case tok::objc_public: return ObjCIvarDecl::Public; 12598 case tok::objc_protected: return ObjCIvarDecl::Protected; 12599 case tok::objc_package: return ObjCIvarDecl::Package; 12600 } 12601 } 12602 12603 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 12604 /// in order to create an IvarDecl object for it. 12605 Decl *Sema::ActOnIvar(Scope *S, 12606 SourceLocation DeclStart, 12607 Declarator &D, Expr *BitfieldWidth, 12608 tok::ObjCKeywordKind Visibility) { 12609 12610 IdentifierInfo *II = D.getIdentifier(); 12611 Expr *BitWidth = (Expr*)BitfieldWidth; 12612 SourceLocation Loc = DeclStart; 12613 if (II) Loc = D.getIdentifierLoc(); 12614 12615 // FIXME: Unnamed fields can be handled in various different ways, for 12616 // example, unnamed unions inject all members into the struct namespace! 12617 12618 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12619 QualType T = TInfo->getType(); 12620 12621 if (BitWidth) { 12622 // 6.7.2.1p3, 6.7.2.1p4 12623 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 12624 if (!BitWidth) 12625 D.setInvalidType(); 12626 } else { 12627 // Not a bitfield. 12628 12629 // validate II. 12630 12631 } 12632 if (T->isReferenceType()) { 12633 Diag(Loc, diag::err_ivar_reference_type); 12634 D.setInvalidType(); 12635 } 12636 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12637 // than a variably modified type. 12638 else if (T->isVariablyModifiedType()) { 12639 Diag(Loc, diag::err_typecheck_ivar_variable_size); 12640 D.setInvalidType(); 12641 } 12642 12643 // Get the visibility (access control) for this ivar. 12644 ObjCIvarDecl::AccessControl ac = 12645 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 12646 : ObjCIvarDecl::None; 12647 // Must set ivar's DeclContext to its enclosing interface. 12648 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 12649 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 12650 return nullptr; 12651 ObjCContainerDecl *EnclosingContext; 12652 if (ObjCImplementationDecl *IMPDecl = 12653 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12654 if (LangOpts.ObjCRuntime.isFragile()) { 12655 // Case of ivar declared in an implementation. Context is that of its class. 12656 EnclosingContext = IMPDecl->getClassInterface(); 12657 assert(EnclosingContext && "Implementation has no class interface!"); 12658 } 12659 else 12660 EnclosingContext = EnclosingDecl; 12661 } else { 12662 if (ObjCCategoryDecl *CDecl = 12663 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12664 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12665 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12666 return nullptr; 12667 } 12668 } 12669 EnclosingContext = EnclosingDecl; 12670 } 12671 12672 // Construct the decl. 12673 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12674 DeclStart, Loc, II, T, 12675 TInfo, ac, (Expr *)BitfieldWidth); 12676 12677 if (II) { 12678 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12679 ForRedeclaration); 12680 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12681 && !isa<TagDecl>(PrevDecl)) { 12682 Diag(Loc, diag::err_duplicate_member) << II; 12683 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12684 NewID->setInvalidDecl(); 12685 } 12686 } 12687 12688 // Process attributes attached to the ivar. 12689 ProcessDeclAttributes(S, NewID, D); 12690 12691 if (D.isInvalidType()) 12692 NewID->setInvalidDecl(); 12693 12694 // In ARC, infer 'retaining' for ivars of retainable type. 12695 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12696 NewID->setInvalidDecl(); 12697 12698 if (D.getDeclSpec().isModulePrivateSpecified()) 12699 NewID->setModulePrivate(); 12700 12701 if (II) { 12702 // FIXME: When interfaces are DeclContexts, we'll need to add 12703 // these to the interface. 12704 S->AddDecl(NewID); 12705 IdResolver.AddDecl(NewID); 12706 } 12707 12708 if (LangOpts.ObjCRuntime.isNonFragile() && 12709 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12710 Diag(Loc, diag::warn_ivars_in_interface); 12711 12712 return NewID; 12713 } 12714 12715 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12716 /// class and class extensions. For every class \@interface and class 12717 /// extension \@interface, if the last ivar is a bitfield of any type, 12718 /// then add an implicit `char :0` ivar to the end of that interface. 12719 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12720 SmallVectorImpl<Decl *> &AllIvarDecls) { 12721 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12722 return; 12723 12724 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12725 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12726 12727 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12728 return; 12729 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12730 if (!ID) { 12731 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12732 if (!CD->IsClassExtension()) 12733 return; 12734 } 12735 // No need to add this to end of @implementation. 12736 else 12737 return; 12738 } 12739 // All conditions are met. Add a new bitfield to the tail end of ivars. 12740 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12741 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12742 12743 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12744 DeclLoc, DeclLoc, nullptr, 12745 Context.CharTy, 12746 Context.getTrivialTypeSourceInfo(Context.CharTy, 12747 DeclLoc), 12748 ObjCIvarDecl::Private, BW, 12749 true); 12750 AllIvarDecls.push_back(Ivar); 12751 } 12752 12753 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12754 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12755 SourceLocation RBrac, AttributeList *Attr) { 12756 assert(EnclosingDecl && "missing record or interface decl"); 12757 12758 // If this is an Objective-C @implementation or category and we have 12759 // new fields here we should reset the layout of the interface since 12760 // it will now change. 12761 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12762 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12763 switch (DC->getKind()) { 12764 default: break; 12765 case Decl::ObjCCategory: 12766 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12767 break; 12768 case Decl::ObjCImplementation: 12769 Context. 12770 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12771 break; 12772 } 12773 } 12774 12775 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12776 12777 // Start counting up the number of named members; make sure to include 12778 // members of anonymous structs and unions in the total. 12779 unsigned NumNamedMembers = 0; 12780 if (Record) { 12781 for (const auto *I : Record->decls()) { 12782 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12783 if (IFD->getDeclName()) 12784 ++NumNamedMembers; 12785 } 12786 } 12787 12788 // Verify that all the fields are okay. 12789 SmallVector<FieldDecl*, 32> RecFields; 12790 12791 bool ARCErrReported = false; 12792 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12793 i != end; ++i) { 12794 FieldDecl *FD = cast<FieldDecl>(*i); 12795 12796 // Get the type for the field. 12797 const Type *FDTy = FD->getType().getTypePtr(); 12798 12799 if (!FD->isAnonymousStructOrUnion()) { 12800 // Remember all fields written by the user. 12801 RecFields.push_back(FD); 12802 } 12803 12804 // If the field is already invalid for some reason, don't emit more 12805 // diagnostics about it. 12806 if (FD->isInvalidDecl()) { 12807 EnclosingDecl->setInvalidDecl(); 12808 continue; 12809 } 12810 12811 // C99 6.7.2.1p2: 12812 // A structure or union shall not contain a member with 12813 // incomplete or function type (hence, a structure shall not 12814 // contain an instance of itself, but may contain a pointer to 12815 // an instance of itself), except that the last member of a 12816 // structure with more than one named member may have incomplete 12817 // array type; such a structure (and any union containing, 12818 // possibly recursively, a member that is such a structure) 12819 // shall not be a member of a structure or an element of an 12820 // array. 12821 if (FDTy->isFunctionType()) { 12822 // Field declared as a function. 12823 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12824 << FD->getDeclName(); 12825 FD->setInvalidDecl(); 12826 EnclosingDecl->setInvalidDecl(); 12827 continue; 12828 } else if (FDTy->isIncompleteArrayType() && Record && 12829 ((i + 1 == Fields.end() && !Record->isUnion()) || 12830 ((getLangOpts().MicrosoftExt || 12831 getLangOpts().CPlusPlus) && 12832 (i + 1 == Fields.end() || Record->isUnion())))) { 12833 // Flexible array member. 12834 // Microsoft and g++ is more permissive regarding flexible array. 12835 // It will accept flexible array in union and also 12836 // as the sole element of a struct/class. 12837 unsigned DiagID = 0; 12838 if (Record->isUnion()) 12839 DiagID = getLangOpts().MicrosoftExt 12840 ? diag::ext_flexible_array_union_ms 12841 : getLangOpts().CPlusPlus 12842 ? diag::ext_flexible_array_union_gnu 12843 : diag::err_flexible_array_union; 12844 else if (Fields.size() == 1) 12845 DiagID = getLangOpts().MicrosoftExt 12846 ? diag::ext_flexible_array_empty_aggregate_ms 12847 : getLangOpts().CPlusPlus 12848 ? diag::ext_flexible_array_empty_aggregate_gnu 12849 : NumNamedMembers < 1 12850 ? diag::err_flexible_array_empty_aggregate 12851 : 0; 12852 12853 if (DiagID) 12854 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12855 << Record->getTagKind(); 12856 // While the layout of types that contain virtual bases is not specified 12857 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12858 // virtual bases after the derived members. This would make a flexible 12859 // array member declared at the end of an object not adjacent to the end 12860 // of the type. 12861 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12862 if (RD->getNumVBases() != 0) 12863 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12864 << FD->getDeclName() << Record->getTagKind(); 12865 if (!getLangOpts().C99) 12866 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12867 << FD->getDeclName() << Record->getTagKind(); 12868 12869 // If the element type has a non-trivial destructor, we would not 12870 // implicitly destroy the elements, so disallow it for now. 12871 // 12872 // FIXME: GCC allows this. We should probably either implicitly delete 12873 // the destructor of the containing class, or just allow this. 12874 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12875 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12876 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12877 << FD->getDeclName() << FD->getType(); 12878 FD->setInvalidDecl(); 12879 EnclosingDecl->setInvalidDecl(); 12880 continue; 12881 } 12882 // Okay, we have a legal flexible array member at the end of the struct. 12883 Record->setHasFlexibleArrayMember(true); 12884 } else if (!FDTy->isDependentType() && 12885 RequireCompleteType(FD->getLocation(), FD->getType(), 12886 diag::err_field_incomplete)) { 12887 // Incomplete type 12888 FD->setInvalidDecl(); 12889 EnclosingDecl->setInvalidDecl(); 12890 continue; 12891 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12892 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 12893 // A type which contains a flexible array member is considered to be a 12894 // flexible array member. 12895 Record->setHasFlexibleArrayMember(true); 12896 if (!Record->isUnion()) { 12897 // If this is a struct/class and this is not the last element, reject 12898 // it. Note that GCC supports variable sized arrays in the middle of 12899 // structures. 12900 if (i + 1 != Fields.end()) 12901 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12902 << FD->getDeclName() << FD->getType(); 12903 else { 12904 // We support flexible arrays at the end of structs in 12905 // other structs as an extension. 12906 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12907 << FD->getDeclName(); 12908 } 12909 } 12910 } 12911 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12912 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12913 diag::err_abstract_type_in_decl, 12914 AbstractIvarType)) { 12915 // Ivars can not have abstract class types 12916 FD->setInvalidDecl(); 12917 } 12918 if (Record && FDTTy->getDecl()->hasObjectMember()) 12919 Record->setHasObjectMember(true); 12920 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12921 Record->setHasVolatileMember(true); 12922 } else if (FDTy->isObjCObjectType()) { 12923 /// A field cannot be an Objective-c object 12924 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12925 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12926 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12927 FD->setType(T); 12928 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12929 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12930 // It's an error in ARC if a field has lifetime. 12931 // We don't want to report this in a system header, though, 12932 // so we just make the field unavailable. 12933 // FIXME: that's really not sufficient; we need to make the type 12934 // itself invalid to, say, initialize or copy. 12935 QualType T = FD->getType(); 12936 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12937 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12938 SourceLocation loc = FD->getLocation(); 12939 if (getSourceManager().isInSystemHeader(loc)) { 12940 if (!FD->hasAttr<UnavailableAttr>()) { 12941 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12942 "this system field has retaining ownership", 12943 loc)); 12944 } 12945 } else { 12946 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12947 << T->isBlockPointerType() << Record->getTagKind(); 12948 } 12949 ARCErrReported = true; 12950 } 12951 } else if (getLangOpts().ObjC1 && 12952 getLangOpts().getGC() != LangOptions::NonGC && 12953 Record && !Record->hasObjectMember()) { 12954 if (FD->getType()->isObjCObjectPointerType() || 12955 FD->getType().isObjCGCStrong()) 12956 Record->setHasObjectMember(true); 12957 else if (Context.getAsArrayType(FD->getType())) { 12958 QualType BaseType = Context.getBaseElementType(FD->getType()); 12959 if (BaseType->isRecordType() && 12960 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12961 Record->setHasObjectMember(true); 12962 else if (BaseType->isObjCObjectPointerType() || 12963 BaseType.isObjCGCStrong()) 12964 Record->setHasObjectMember(true); 12965 } 12966 } 12967 if (Record && FD->getType().isVolatileQualified()) 12968 Record->setHasVolatileMember(true); 12969 // Keep track of the number of named members. 12970 if (FD->getIdentifier()) 12971 ++NumNamedMembers; 12972 } 12973 12974 // Okay, we successfully defined 'Record'. 12975 if (Record) { 12976 bool Completed = false; 12977 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12978 if (!CXXRecord->isInvalidDecl()) { 12979 // Set access bits correctly on the directly-declared conversions. 12980 for (CXXRecordDecl::conversion_iterator 12981 I = CXXRecord->conversion_begin(), 12982 E = CXXRecord->conversion_end(); I != E; ++I) 12983 I.setAccess((*I)->getAccess()); 12984 12985 if (!CXXRecord->isDependentType()) { 12986 if (CXXRecord->hasUserDeclaredDestructor()) { 12987 // Adjust user-defined destructor exception spec. 12988 if (getLangOpts().CPlusPlus11) 12989 AdjustDestructorExceptionSpec(CXXRecord, 12990 CXXRecord->getDestructor()); 12991 } 12992 12993 // Add any implicitly-declared members to this class. 12994 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12995 12996 // If we have virtual base classes, we may end up finding multiple 12997 // final overriders for a given virtual function. Check for this 12998 // problem now. 12999 if (CXXRecord->getNumVBases()) { 13000 CXXFinalOverriderMap FinalOverriders; 13001 CXXRecord->getFinalOverriders(FinalOverriders); 13002 13003 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 13004 MEnd = FinalOverriders.end(); 13005 M != MEnd; ++M) { 13006 for (OverridingMethods::iterator SO = M->second.begin(), 13007 SOEnd = M->second.end(); 13008 SO != SOEnd; ++SO) { 13009 assert(SO->second.size() > 0 && 13010 "Virtual function without overridding functions?"); 13011 if (SO->second.size() == 1) 13012 continue; 13013 13014 // C++ [class.virtual]p2: 13015 // In a derived class, if a virtual member function of a base 13016 // class subobject has more than one final overrider the 13017 // program is ill-formed. 13018 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 13019 << (const NamedDecl *)M->first << Record; 13020 Diag(M->first->getLocation(), 13021 diag::note_overridden_virtual_function); 13022 for (OverridingMethods::overriding_iterator 13023 OM = SO->second.begin(), 13024 OMEnd = SO->second.end(); 13025 OM != OMEnd; ++OM) 13026 Diag(OM->Method->getLocation(), diag::note_final_overrider) 13027 << (const NamedDecl *)M->first << OM->Method->getParent(); 13028 13029 Record->setInvalidDecl(); 13030 } 13031 } 13032 CXXRecord->completeDefinition(&FinalOverriders); 13033 Completed = true; 13034 } 13035 } 13036 } 13037 } 13038 13039 if (!Completed) 13040 Record->completeDefinition(); 13041 13042 if (Record->hasAttrs()) { 13043 CheckAlignasUnderalignment(Record); 13044 13045 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 13046 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 13047 IA->getRange(), IA->getBestCase(), 13048 IA->getSemanticSpelling()); 13049 } 13050 13051 // Check if the structure/union declaration is a type that can have zero 13052 // size in C. For C this is a language extension, for C++ it may cause 13053 // compatibility problems. 13054 bool CheckForZeroSize; 13055 if (!getLangOpts().CPlusPlus) { 13056 CheckForZeroSize = true; 13057 } else { 13058 // For C++ filter out types that cannot be referenced in C code. 13059 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 13060 CheckForZeroSize = 13061 CXXRecord->getLexicalDeclContext()->isExternCContext() && 13062 !CXXRecord->isDependentType() && 13063 CXXRecord->isCLike(); 13064 } 13065 if (CheckForZeroSize) { 13066 bool ZeroSize = true; 13067 bool IsEmpty = true; 13068 unsigned NonBitFields = 0; 13069 for (RecordDecl::field_iterator I = Record->field_begin(), 13070 E = Record->field_end(); 13071 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 13072 IsEmpty = false; 13073 if (I->isUnnamedBitfield()) { 13074 if (I->getBitWidthValue(Context) > 0) 13075 ZeroSize = false; 13076 } else { 13077 ++NonBitFields; 13078 QualType FieldType = I->getType(); 13079 if (FieldType->isIncompleteType() || 13080 !Context.getTypeSizeInChars(FieldType).isZero()) 13081 ZeroSize = false; 13082 } 13083 } 13084 13085 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 13086 // allowed in C++, but warn if its declaration is inside 13087 // extern "C" block. 13088 if (ZeroSize) { 13089 Diag(RecLoc, getLangOpts().CPlusPlus ? 13090 diag::warn_zero_size_struct_union_in_extern_c : 13091 diag::warn_zero_size_struct_union_compat) 13092 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 13093 } 13094 13095 // Structs without named members are extension in C (C99 6.7.2.1p7), 13096 // but are accepted by GCC. 13097 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 13098 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 13099 diag::ext_no_named_members_in_struct_union) 13100 << Record->isUnion(); 13101 } 13102 } 13103 } else { 13104 ObjCIvarDecl **ClsFields = 13105 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 13106 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 13107 ID->setEndOfDefinitionLoc(RBrac); 13108 // Add ivar's to class's DeclContext. 13109 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13110 ClsFields[i]->setLexicalDeclContext(ID); 13111 ID->addDecl(ClsFields[i]); 13112 } 13113 // Must enforce the rule that ivars in the base classes may not be 13114 // duplicates. 13115 if (ID->getSuperClass()) 13116 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 13117 } else if (ObjCImplementationDecl *IMPDecl = 13118 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 13119 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 13120 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 13121 // Ivar declared in @implementation never belongs to the implementation. 13122 // Only it is in implementation's lexical context. 13123 ClsFields[I]->setLexicalDeclContext(IMPDecl); 13124 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 13125 IMPDecl->setIvarLBraceLoc(LBrac); 13126 IMPDecl->setIvarRBraceLoc(RBrac); 13127 } else if (ObjCCategoryDecl *CDecl = 13128 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 13129 // case of ivars in class extension; all other cases have been 13130 // reported as errors elsewhere. 13131 // FIXME. Class extension does not have a LocEnd field. 13132 // CDecl->setLocEnd(RBrac); 13133 // Add ivar's to class extension's DeclContext. 13134 // Diagnose redeclaration of private ivars. 13135 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 13136 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 13137 if (IDecl) { 13138 if (const ObjCIvarDecl *ClsIvar = 13139 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 13140 Diag(ClsFields[i]->getLocation(), 13141 diag::err_duplicate_ivar_declaration); 13142 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 13143 continue; 13144 } 13145 for (const auto *Ext : IDecl->known_extensions()) { 13146 if (const ObjCIvarDecl *ClsExtIvar 13147 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 13148 Diag(ClsFields[i]->getLocation(), 13149 diag::err_duplicate_ivar_declaration); 13150 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 13151 continue; 13152 } 13153 } 13154 } 13155 ClsFields[i]->setLexicalDeclContext(CDecl); 13156 CDecl->addDecl(ClsFields[i]); 13157 } 13158 CDecl->setIvarLBraceLoc(LBrac); 13159 CDecl->setIvarRBraceLoc(RBrac); 13160 } 13161 } 13162 13163 if (Attr) 13164 ProcessDeclAttributeList(S, Record, Attr); 13165 } 13166 13167 /// \brief Determine whether the given integral value is representable within 13168 /// the given type T. 13169 static bool isRepresentableIntegerValue(ASTContext &Context, 13170 llvm::APSInt &Value, 13171 QualType T) { 13172 assert(T->isIntegralType(Context) && "Integral type required!"); 13173 unsigned BitWidth = Context.getIntWidth(T); 13174 13175 if (Value.isUnsigned() || Value.isNonNegative()) { 13176 if (T->isSignedIntegerOrEnumerationType()) 13177 --BitWidth; 13178 return Value.getActiveBits() <= BitWidth; 13179 } 13180 return Value.getMinSignedBits() <= BitWidth; 13181 } 13182 13183 // \brief Given an integral type, return the next larger integral type 13184 // (or a NULL type of no such type exists). 13185 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13186 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13187 // enum checking below. 13188 assert(T->isIntegralType(Context) && "Integral type required!"); 13189 const unsigned NumTypes = 4; 13190 QualType SignedIntegralTypes[NumTypes] = { 13191 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13192 }; 13193 QualType UnsignedIntegralTypes[NumTypes] = { 13194 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13195 Context.UnsignedLongLongTy 13196 }; 13197 13198 unsigned BitWidth = Context.getTypeSize(T); 13199 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13200 : UnsignedIntegralTypes; 13201 for (unsigned I = 0; I != NumTypes; ++I) 13202 if (Context.getTypeSize(Types[I]) > BitWidth) 13203 return Types[I]; 13204 13205 return QualType(); 13206 } 13207 13208 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13209 EnumConstantDecl *LastEnumConst, 13210 SourceLocation IdLoc, 13211 IdentifierInfo *Id, 13212 Expr *Val) { 13213 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13214 llvm::APSInt EnumVal(IntWidth); 13215 QualType EltTy; 13216 13217 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13218 Val = nullptr; 13219 13220 if (Val) 13221 Val = DefaultLvalueConversion(Val).get(); 13222 13223 if (Val) { 13224 if (Enum->isDependentType() || Val->isTypeDependent()) 13225 EltTy = Context.DependentTy; 13226 else { 13227 SourceLocation ExpLoc; 13228 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 13229 !getLangOpts().MSVCCompat) { 13230 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 13231 // constant-expression in the enumerator-definition shall be a converted 13232 // constant expression of the underlying type. 13233 EltTy = Enum->getIntegerType(); 13234 ExprResult Converted = 13235 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 13236 CCEK_Enumerator); 13237 if (Converted.isInvalid()) 13238 Val = nullptr; 13239 else 13240 Val = Converted.get(); 13241 } else if (!Val->isValueDependent() && 13242 !(Val = VerifyIntegerConstantExpression(Val, 13243 &EnumVal).get())) { 13244 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 13245 } else { 13246 if (Enum->isFixed()) { 13247 EltTy = Enum->getIntegerType(); 13248 13249 // In Obj-C and Microsoft mode, require the enumeration value to be 13250 // representable in the underlying type of the enumeration. In C++11, 13251 // we perform a non-narrowing conversion as part of converted constant 13252 // expression checking. 13253 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13254 if (getLangOpts().MSVCCompat) { 13255 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 13256 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13257 } else 13258 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 13259 } else 13260 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13261 } else if (getLangOpts().CPlusPlus) { 13262 // C++11 [dcl.enum]p5: 13263 // If the underlying type is not fixed, the type of each enumerator 13264 // is the type of its initializing value: 13265 // - If an initializer is specified for an enumerator, the 13266 // initializing value has the same type as the expression. 13267 EltTy = Val->getType(); 13268 } else { 13269 // C99 6.7.2.2p2: 13270 // The expression that defines the value of an enumeration constant 13271 // shall be an integer constant expression that has a value 13272 // representable as an int. 13273 13274 // Complain if the value is not representable in an int. 13275 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 13276 Diag(IdLoc, diag::ext_enum_value_not_int) 13277 << EnumVal.toString(10) << Val->getSourceRange() 13278 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 13279 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 13280 // Force the type of the expression to 'int'. 13281 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 13282 } 13283 EltTy = Val->getType(); 13284 } 13285 } 13286 } 13287 } 13288 13289 if (!Val) { 13290 if (Enum->isDependentType()) 13291 EltTy = Context.DependentTy; 13292 else if (!LastEnumConst) { 13293 // C++0x [dcl.enum]p5: 13294 // If the underlying type is not fixed, the type of each enumerator 13295 // is the type of its initializing value: 13296 // - If no initializer is specified for the first enumerator, the 13297 // initializing value has an unspecified integral type. 13298 // 13299 // GCC uses 'int' for its unspecified integral type, as does 13300 // C99 6.7.2.2p3. 13301 if (Enum->isFixed()) { 13302 EltTy = Enum->getIntegerType(); 13303 } 13304 else { 13305 EltTy = Context.IntTy; 13306 } 13307 } else { 13308 // Assign the last value + 1. 13309 EnumVal = LastEnumConst->getInitVal(); 13310 ++EnumVal; 13311 EltTy = LastEnumConst->getType(); 13312 13313 // Check for overflow on increment. 13314 if (EnumVal < LastEnumConst->getInitVal()) { 13315 // C++0x [dcl.enum]p5: 13316 // If the underlying type is not fixed, the type of each enumerator 13317 // is the type of its initializing value: 13318 // 13319 // - Otherwise the type of the initializing value is the same as 13320 // the type of the initializing value of the preceding enumerator 13321 // unless the incremented value is not representable in that type, 13322 // in which case the type is an unspecified integral type 13323 // sufficient to contain the incremented value. If no such type 13324 // exists, the program is ill-formed. 13325 QualType T = getNextLargerIntegralType(Context, EltTy); 13326 if (T.isNull() || Enum->isFixed()) { 13327 // There is no integral type larger enough to represent this 13328 // value. Complain, then allow the value to wrap around. 13329 EnumVal = LastEnumConst->getInitVal(); 13330 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 13331 ++EnumVal; 13332 if (Enum->isFixed()) 13333 // When the underlying type is fixed, this is ill-formed. 13334 Diag(IdLoc, diag::err_enumerator_wrapped) 13335 << EnumVal.toString(10) 13336 << EltTy; 13337 else 13338 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 13339 << EnumVal.toString(10); 13340 } else { 13341 EltTy = T; 13342 } 13343 13344 // Retrieve the last enumerator's value, extent that type to the 13345 // type that is supposed to be large enough to represent the incremented 13346 // value, then increment. 13347 EnumVal = LastEnumConst->getInitVal(); 13348 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13349 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 13350 ++EnumVal; 13351 13352 // If we're not in C++, diagnose the overflow of enumerator values, 13353 // which in C99 means that the enumerator value is not representable in 13354 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 13355 // permits enumerator values that are representable in some larger 13356 // integral type. 13357 if (!getLangOpts().CPlusPlus && !T.isNull()) 13358 Diag(IdLoc, diag::warn_enum_value_overflow); 13359 } else if (!getLangOpts().CPlusPlus && 13360 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13361 // Enforce C99 6.7.2.2p2 even when we compute the next value. 13362 Diag(IdLoc, diag::ext_enum_value_not_int) 13363 << EnumVal.toString(10) << 1; 13364 } 13365 } 13366 } 13367 13368 if (!EltTy->isDependentType()) { 13369 // Make the enumerator value match the signedness and size of the 13370 // enumerator's type. 13371 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 13372 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13373 } 13374 13375 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 13376 Val, EnumVal); 13377 } 13378 13379 13380 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 13381 SourceLocation IdLoc, IdentifierInfo *Id, 13382 AttributeList *Attr, 13383 SourceLocation EqualLoc, Expr *Val) { 13384 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 13385 EnumConstantDecl *LastEnumConst = 13386 cast_or_null<EnumConstantDecl>(lastEnumConst); 13387 13388 // The scope passed in may not be a decl scope. Zip up the scope tree until 13389 // we find one that is. 13390 S = getNonFieldDeclScope(S); 13391 13392 // Verify that there isn't already something declared with this name in this 13393 // scope. 13394 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 13395 ForRedeclaration); 13396 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13397 // Maybe we will complain about the shadowed template parameter. 13398 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 13399 // Just pretend that we didn't see the previous declaration. 13400 PrevDecl = nullptr; 13401 } 13402 13403 if (PrevDecl) { 13404 // When in C++, we may get a TagDecl with the same name; in this case the 13405 // enum constant will 'hide' the tag. 13406 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 13407 "Received TagDecl when not in C++!"); 13408 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 13409 if (isa<EnumConstantDecl>(PrevDecl)) 13410 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 13411 else 13412 Diag(IdLoc, diag::err_redefinition) << Id; 13413 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13414 return nullptr; 13415 } 13416 } 13417 13418 // C++ [class.mem]p15: 13419 // If T is the name of a class, then each of the following shall have a name 13420 // different from T: 13421 // - every enumerator of every member of class T that is an unscoped 13422 // enumerated type 13423 if (CXXRecordDecl *Record 13424 = dyn_cast<CXXRecordDecl>( 13425 TheEnumDecl->getDeclContext()->getRedeclContext())) 13426 if (!TheEnumDecl->isScoped() && 13427 Record->getIdentifier() && Record->getIdentifier() == Id) 13428 Diag(IdLoc, diag::err_member_name_of_class) << Id; 13429 13430 EnumConstantDecl *New = 13431 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 13432 13433 if (New) { 13434 // Process attributes. 13435 if (Attr) ProcessDeclAttributeList(S, New, Attr); 13436 13437 // Register this decl in the current scope stack. 13438 New->setAccess(TheEnumDecl->getAccess()); 13439 PushOnScopeChains(New, S); 13440 } 13441 13442 ActOnDocumentableDecl(New); 13443 13444 return New; 13445 } 13446 13447 // Returns true when the enum initial expression does not trigger the 13448 // duplicate enum warning. A few common cases are exempted as follows: 13449 // Element2 = Element1 13450 // Element2 = Element1 + 1 13451 // Element2 = Element1 - 1 13452 // Where Element2 and Element1 are from the same enum. 13453 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 13454 Expr *InitExpr = ECD->getInitExpr(); 13455 if (!InitExpr) 13456 return true; 13457 InitExpr = InitExpr->IgnoreImpCasts(); 13458 13459 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 13460 if (!BO->isAdditiveOp()) 13461 return true; 13462 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 13463 if (!IL) 13464 return true; 13465 if (IL->getValue() != 1) 13466 return true; 13467 13468 InitExpr = BO->getLHS(); 13469 } 13470 13471 // This checks if the elements are from the same enum. 13472 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 13473 if (!DRE) 13474 return true; 13475 13476 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 13477 if (!EnumConstant) 13478 return true; 13479 13480 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 13481 Enum) 13482 return true; 13483 13484 return false; 13485 } 13486 13487 struct DupKey { 13488 int64_t val; 13489 bool isTombstoneOrEmptyKey; 13490 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 13491 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 13492 }; 13493 13494 static DupKey GetDupKey(const llvm::APSInt& Val) { 13495 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 13496 false); 13497 } 13498 13499 struct DenseMapInfoDupKey { 13500 static DupKey getEmptyKey() { return DupKey(0, true); } 13501 static DupKey getTombstoneKey() { return DupKey(1, true); } 13502 static unsigned getHashValue(const DupKey Key) { 13503 return (unsigned)(Key.val * 37); 13504 } 13505 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 13506 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 13507 LHS.val == RHS.val; 13508 } 13509 }; 13510 13511 // Emits a warning when an element is implicitly set a value that 13512 // a previous element has already been set to. 13513 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 13514 EnumDecl *Enum, 13515 QualType EnumType) { 13516 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 13517 return; 13518 // Avoid anonymous enums 13519 if (!Enum->getIdentifier()) 13520 return; 13521 13522 // Only check for small enums. 13523 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 13524 return; 13525 13526 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 13527 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 13528 13529 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 13530 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 13531 ValueToVectorMap; 13532 13533 DuplicatesVector DupVector; 13534 ValueToVectorMap EnumMap; 13535 13536 // Populate the EnumMap with all values represented by enum constants without 13537 // an initialier. 13538 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13539 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13540 13541 // Null EnumConstantDecl means a previous diagnostic has been emitted for 13542 // this constant. Skip this enum since it may be ill-formed. 13543 if (!ECD) { 13544 return; 13545 } 13546 13547 if (ECD->getInitExpr()) 13548 continue; 13549 13550 DupKey Key = GetDupKey(ECD->getInitVal()); 13551 DeclOrVector &Entry = EnumMap[Key]; 13552 13553 // First time encountering this value. 13554 if (Entry.isNull()) 13555 Entry = ECD; 13556 } 13557 13558 // Create vectors for any values that has duplicates. 13559 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13560 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 13561 if (!ValidDuplicateEnum(ECD, Enum)) 13562 continue; 13563 13564 DupKey Key = GetDupKey(ECD->getInitVal()); 13565 13566 DeclOrVector& Entry = EnumMap[Key]; 13567 if (Entry.isNull()) 13568 continue; 13569 13570 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 13571 // Ensure constants are different. 13572 if (D == ECD) 13573 continue; 13574 13575 // Create new vector and push values onto it. 13576 ECDVector *Vec = new ECDVector(); 13577 Vec->push_back(D); 13578 Vec->push_back(ECD); 13579 13580 // Update entry to point to the duplicates vector. 13581 Entry = Vec; 13582 13583 // Store the vector somewhere we can consult later for quick emission of 13584 // diagnostics. 13585 DupVector.push_back(Vec); 13586 continue; 13587 } 13588 13589 ECDVector *Vec = Entry.get<ECDVector*>(); 13590 // Make sure constants are not added more than once. 13591 if (*Vec->begin() == ECD) 13592 continue; 13593 13594 Vec->push_back(ECD); 13595 } 13596 13597 // Emit diagnostics. 13598 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 13599 DupVectorEnd = DupVector.end(); 13600 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 13601 ECDVector *Vec = *DupVectorIter; 13602 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 13603 13604 // Emit warning for one enum constant. 13605 ECDVector::iterator I = Vec->begin(); 13606 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 13607 << (*I)->getName() << (*I)->getInitVal().toString(10) 13608 << (*I)->getSourceRange(); 13609 ++I; 13610 13611 // Emit one note for each of the remaining enum constants with 13612 // the same value. 13613 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 13614 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 13615 << (*I)->getName() << (*I)->getInitVal().toString(10) 13616 << (*I)->getSourceRange(); 13617 delete Vec; 13618 } 13619 } 13620 13621 bool 13622 Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, 13623 bool AllowMask) const { 13624 FlagEnumAttr *FEAttr = ED->getAttr<FlagEnumAttr>(); 13625 assert(FEAttr && "looking for value in non-flag enum"); 13626 13627 llvm::APInt FlagMask = ~FEAttr->getFlagBits(); 13628 unsigned Width = FlagMask.getBitWidth(); 13629 13630 // We will try a zero-extended value for the regular check first. 13631 llvm::APInt ExtVal = Val.zextOrSelf(Width); 13632 13633 // A value is in a flag enum if either its bits are a subset of the enum's 13634 // flag bits (the first condition) or we are allowing masks and the same is 13635 // true of its complement (the second condition). When masks are allowed, we 13636 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value. 13637 // 13638 // While it's true that any value could be used as a mask, the assumption is 13639 // that a mask will have all of the insignificant bits set. Anything else is 13640 // likely a logic error. 13641 if (!(FlagMask & ExtVal)) 13642 return true; 13643 13644 if (AllowMask) { 13645 // Try a one-extended value instead. This can happen if the enum is wider 13646 // than the constant used, in C with extensions to allow for wider enums. 13647 // The mask will still have the correct behaviour, so we give the user the 13648 // benefit of the doubt. 13649 // 13650 // FIXME: This heuristic can cause weird results if the enum was extended 13651 // to a larger type and is signed, because then bit-masks of smaller types 13652 // that get extended will fall out of range (e.g. ~0x1u). We currently don't 13653 // detect that case and will get a false positive for it. In most cases, 13654 // though, it can be fixed by making it a signed type (e.g. ~0x1), so it may 13655 // be fine just to accept this as a warning. 13656 ExtVal |= llvm::APInt::getHighBitsSet(Width, Width - Val.getBitWidth()); 13657 if (!(FlagMask & ~ExtVal)) 13658 return true; 13659 } 13660 13661 return false; 13662 } 13663 13664 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 13665 SourceLocation RBraceLoc, Decl *EnumDeclX, 13666 ArrayRef<Decl *> Elements, 13667 Scope *S, AttributeList *Attr) { 13668 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 13669 QualType EnumType = Context.getTypeDeclType(Enum); 13670 13671 if (Attr) 13672 ProcessDeclAttributeList(S, Enum, Attr); 13673 13674 if (Enum->isDependentType()) { 13675 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13676 EnumConstantDecl *ECD = 13677 cast_or_null<EnumConstantDecl>(Elements[i]); 13678 if (!ECD) continue; 13679 13680 ECD->setType(EnumType); 13681 } 13682 13683 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 13684 return; 13685 } 13686 13687 // TODO: If the result value doesn't fit in an int, it must be a long or long 13688 // long value. ISO C does not support this, but GCC does as an extension, 13689 // emit a warning. 13690 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13691 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 13692 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 13693 13694 // Verify that all the values are okay, compute the size of the values, and 13695 // reverse the list. 13696 unsigned NumNegativeBits = 0; 13697 unsigned NumPositiveBits = 0; 13698 13699 // Keep track of whether all elements have type int. 13700 bool AllElementsInt = true; 13701 13702 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13703 EnumConstantDecl *ECD = 13704 cast_or_null<EnumConstantDecl>(Elements[i]); 13705 if (!ECD) continue; // Already issued a diagnostic. 13706 13707 const llvm::APSInt &InitVal = ECD->getInitVal(); 13708 13709 // Keep track of the size of positive and negative values. 13710 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13711 NumPositiveBits = std::max(NumPositiveBits, 13712 (unsigned)InitVal.getActiveBits()); 13713 else 13714 NumNegativeBits = std::max(NumNegativeBits, 13715 (unsigned)InitVal.getMinSignedBits()); 13716 13717 // Keep track of whether every enum element has type int (very commmon). 13718 if (AllElementsInt) 13719 AllElementsInt = ECD->getType() == Context.IntTy; 13720 } 13721 13722 // Figure out the type that should be used for this enum. 13723 QualType BestType; 13724 unsigned BestWidth; 13725 13726 // C++0x N3000 [conv.prom]p3: 13727 // An rvalue of an unscoped enumeration type whose underlying 13728 // type is not fixed can be converted to an rvalue of the first 13729 // of the following types that can represent all the values of 13730 // the enumeration: int, unsigned int, long int, unsigned long 13731 // int, long long int, or unsigned long long int. 13732 // C99 6.4.4.3p2: 13733 // An identifier declared as an enumeration constant has type int. 13734 // The C99 rule is modified by a gcc extension 13735 QualType BestPromotionType; 13736 13737 bool Packed = Enum->hasAttr<PackedAttr>(); 13738 // -fshort-enums is the equivalent to specifying the packed attribute on all 13739 // enum definitions. 13740 if (LangOpts.ShortEnums) 13741 Packed = true; 13742 13743 if (Enum->isFixed()) { 13744 BestType = Enum->getIntegerType(); 13745 if (BestType->isPromotableIntegerType()) 13746 BestPromotionType = Context.getPromotedIntegerType(BestType); 13747 else 13748 BestPromotionType = BestType; 13749 13750 BestWidth = Context.getIntWidth(BestType); 13751 } 13752 else if (NumNegativeBits) { 13753 // If there is a negative value, figure out the smallest integer type (of 13754 // int/long/longlong) that fits. 13755 // If it's packed, check also if it fits a char or a short. 13756 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13757 BestType = Context.SignedCharTy; 13758 BestWidth = CharWidth; 13759 } else if (Packed && NumNegativeBits <= ShortWidth && 13760 NumPositiveBits < ShortWidth) { 13761 BestType = Context.ShortTy; 13762 BestWidth = ShortWidth; 13763 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13764 BestType = Context.IntTy; 13765 BestWidth = IntWidth; 13766 } else { 13767 BestWidth = Context.getTargetInfo().getLongWidth(); 13768 13769 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13770 BestType = Context.LongTy; 13771 } else { 13772 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13773 13774 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13775 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13776 BestType = Context.LongLongTy; 13777 } 13778 } 13779 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13780 } else { 13781 // If there is no negative value, figure out the smallest type that fits 13782 // all of the enumerator values. 13783 // If it's packed, check also if it fits a char or a short. 13784 if (Packed && NumPositiveBits <= CharWidth) { 13785 BestType = Context.UnsignedCharTy; 13786 BestPromotionType = Context.IntTy; 13787 BestWidth = CharWidth; 13788 } else if (Packed && NumPositiveBits <= ShortWidth) { 13789 BestType = Context.UnsignedShortTy; 13790 BestPromotionType = Context.IntTy; 13791 BestWidth = ShortWidth; 13792 } else if (NumPositiveBits <= IntWidth) { 13793 BestType = Context.UnsignedIntTy; 13794 BestWidth = IntWidth; 13795 BestPromotionType 13796 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13797 ? Context.UnsignedIntTy : Context.IntTy; 13798 } else if (NumPositiveBits <= 13799 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13800 BestType = Context.UnsignedLongTy; 13801 BestPromotionType 13802 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13803 ? Context.UnsignedLongTy : Context.LongTy; 13804 } else { 13805 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13806 assert(NumPositiveBits <= BestWidth && 13807 "How could an initializer get larger than ULL?"); 13808 BestType = Context.UnsignedLongLongTy; 13809 BestPromotionType 13810 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13811 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13812 } 13813 } 13814 13815 FlagEnumAttr *FEAttr = Enum->getAttr<FlagEnumAttr>(); 13816 if (FEAttr) 13817 FEAttr->getFlagBits() = llvm::APInt(BestWidth, 0); 13818 13819 // Loop over all of the enumerator constants, changing their types to match 13820 // the type of the enum if needed. If we have a flag type, we also prepare the 13821 // FlagBits cache. 13822 for (auto *D : Elements) { 13823 auto *ECD = cast_or_null<EnumConstantDecl>(D); 13824 if (!ECD) continue; // Already issued a diagnostic. 13825 13826 // Standard C says the enumerators have int type, but we allow, as an 13827 // extension, the enumerators to be larger than int size. If each 13828 // enumerator value fits in an int, type it as an int, otherwise type it the 13829 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13830 // that X has type 'int', not 'unsigned'. 13831 13832 // Determine whether the value fits into an int. 13833 llvm::APSInt InitVal = ECD->getInitVal(); 13834 13835 // If it fits into an integer type, force it. Otherwise force it to match 13836 // the enum decl type. 13837 QualType NewTy; 13838 unsigned NewWidth; 13839 bool NewSign; 13840 if (!getLangOpts().CPlusPlus && 13841 !Enum->isFixed() && 13842 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13843 NewTy = Context.IntTy; 13844 NewWidth = IntWidth; 13845 NewSign = true; 13846 } else if (ECD->getType() == BestType) { 13847 // Already the right type! 13848 if (getLangOpts().CPlusPlus) 13849 // C++ [dcl.enum]p4: Following the closing brace of an 13850 // enum-specifier, each enumerator has the type of its 13851 // enumeration. 13852 ECD->setType(EnumType); 13853 goto flagbits; 13854 } else { 13855 NewTy = BestType; 13856 NewWidth = BestWidth; 13857 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13858 } 13859 13860 // Adjust the APSInt value. 13861 InitVal = InitVal.extOrTrunc(NewWidth); 13862 InitVal.setIsSigned(NewSign); 13863 ECD->setInitVal(InitVal); 13864 13865 // Adjust the Expr initializer and type. 13866 if (ECD->getInitExpr() && 13867 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13868 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13869 CK_IntegralCast, 13870 ECD->getInitExpr(), 13871 /*base paths*/ nullptr, 13872 VK_RValue)); 13873 if (getLangOpts().CPlusPlus) 13874 // C++ [dcl.enum]p4: Following the closing brace of an 13875 // enum-specifier, each enumerator has the type of its 13876 // enumeration. 13877 ECD->setType(EnumType); 13878 else 13879 ECD->setType(NewTy); 13880 13881 flagbits: 13882 // Check to see if we have a constant with exactly one bit set. Note that x 13883 // & (x - 1) will be nonzero if and only if x has more than one bit set. 13884 if (FEAttr) { 13885 llvm::APInt ExtVal = InitVal.zextOrSelf(BestWidth); 13886 if (ExtVal != 0 && !(ExtVal & (ExtVal - 1))) { 13887 FEAttr->getFlagBits() |= ExtVal; 13888 } 13889 } 13890 } 13891 13892 if (FEAttr) { 13893 for (Decl *D : Elements) { 13894 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D); 13895 if (!ECD) continue; // Already issued a diagnostic. 13896 13897 llvm::APSInt InitVal = ECD->getInitVal(); 13898 if (InitVal != 0 && !IsValueInFlagEnum(Enum, InitVal, true)) 13899 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range) 13900 << ECD << Enum; 13901 } 13902 } 13903 13904 13905 13906 Enum->completeDefinition(BestType, BestPromotionType, 13907 NumPositiveBits, NumNegativeBits); 13908 13909 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13910 13911 // Now that the enum type is defined, ensure it's not been underaligned. 13912 if (Enum->hasAttrs()) 13913 CheckAlignasUnderalignment(Enum); 13914 } 13915 13916 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13917 SourceLocation StartLoc, 13918 SourceLocation EndLoc) { 13919 StringLiteral *AsmString = cast<StringLiteral>(expr); 13920 13921 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13922 AsmString, StartLoc, 13923 EndLoc); 13924 CurContext->addDecl(New); 13925 return New; 13926 } 13927 13928 static void checkModuleImportContext(Sema &S, Module *M, 13929 SourceLocation ImportLoc, 13930 DeclContext *DC) { 13931 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13932 switch (LSD->getLanguage()) { 13933 case LinkageSpecDecl::lang_c: 13934 if (!M->IsExternC) { 13935 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13936 << M->getFullModuleName(); 13937 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13938 return; 13939 } 13940 break; 13941 case LinkageSpecDecl::lang_cxx: 13942 break; 13943 } 13944 DC = LSD->getParent(); 13945 } 13946 13947 while (isa<LinkageSpecDecl>(DC)) 13948 DC = DC->getParent(); 13949 if (!isa<TranslationUnitDecl>(DC)) { 13950 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13951 << M->getFullModuleName() << DC; 13952 S.Diag(cast<Decl>(DC)->getLocStart(), 13953 diag::note_module_import_not_at_top_level) 13954 << DC; 13955 } 13956 } 13957 13958 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13959 SourceLocation ImportLoc, 13960 ModuleIdPath Path) { 13961 Module *Mod = 13962 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 13963 /*IsIncludeDirective=*/false); 13964 if (!Mod) 13965 return true; 13966 13967 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13968 13969 // FIXME: we should support importing a submodule within a different submodule 13970 // of the same top-level module. Until we do, make it an error rather than 13971 // silently ignoring the import. 13972 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 13973 Diag(ImportLoc, diag::err_module_self_import) 13974 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 13975 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule) 13976 Diag(ImportLoc, diag::err_module_import_in_implementation) 13977 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule; 13978 13979 SmallVector<SourceLocation, 2> IdentifierLocs; 13980 Module *ModCheck = Mod; 13981 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13982 // If we've run out of module parents, just drop the remaining identifiers. 13983 // We need the length to be consistent. 13984 if (!ModCheck) 13985 break; 13986 ModCheck = ModCheck->Parent; 13987 13988 IdentifierLocs.push_back(Path[I].second); 13989 } 13990 13991 ImportDecl *Import = ImportDecl::Create(Context, 13992 Context.getTranslationUnitDecl(), 13993 AtLoc.isValid()? AtLoc : ImportLoc, 13994 Mod, IdentifierLocs); 13995 Context.getTranslationUnitDecl()->addDecl(Import); 13996 return Import; 13997 } 13998 13999 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 14000 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 14001 14002 // FIXME: Should we synthesize an ImportDecl here? 14003 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 14004 /*Complain=*/true); 14005 } 14006 14007 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 14008 Module *Mod) { 14009 // Bail if we're not allowed to implicitly import a module here. 14010 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 14011 return; 14012 14013 // Create the implicit import declaration. 14014 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 14015 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 14016 Loc, Mod, Loc); 14017 TU->addDecl(ImportD); 14018 Consumer.HandleImplicitImportDecl(ImportD); 14019 14020 // Make the module visible. 14021 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 14022 /*Complain=*/false); 14023 } 14024 14025 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 14026 IdentifierInfo* AliasName, 14027 SourceLocation PragmaLoc, 14028 SourceLocation NameLoc, 14029 SourceLocation AliasNameLoc) { 14030 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 14031 LookupOrdinaryName); 14032 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 14033 AliasName->getName(), 0); 14034 14035 if (PrevDecl) 14036 PrevDecl->addAttr(Attr); 14037 else 14038 (void)ExtnameUndeclaredIdentifiers.insert( 14039 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 14040 } 14041 14042 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 14043 SourceLocation PragmaLoc, 14044 SourceLocation NameLoc) { 14045 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 14046 14047 if (PrevDecl) { 14048 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 14049 } else { 14050 (void)WeakUndeclaredIdentifiers.insert( 14051 std::pair<IdentifierInfo*,WeakInfo> 14052 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 14053 } 14054 } 14055 14056 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 14057 IdentifierInfo* AliasName, 14058 SourceLocation PragmaLoc, 14059 SourceLocation NameLoc, 14060 SourceLocation AliasNameLoc) { 14061 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 14062 LookupOrdinaryName); 14063 WeakInfo W = WeakInfo(Name, NameLoc); 14064 14065 if (PrevDecl) { 14066 if (!PrevDecl->hasAttr<AliasAttr>()) 14067 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 14068 DeclApplyPragmaWeak(TUScope, ND, W); 14069 } else { 14070 (void)WeakUndeclaredIdentifiers.insert( 14071 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 14072 } 14073 } 14074 14075 Decl *Sema::getObjCDeclContext() const { 14076 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 14077 } 14078 14079 AvailabilityResult Sema::getCurContextAvailability() const { 14080 const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext()); 14081 if (!D) 14082 return AR_Available; 14083 14084 // If we are within an Objective-C method, we should consult 14085 // both the availability of the method as well as the 14086 // enclosing class. If the class is (say) deprecated, 14087 // the entire method is considered deprecated from the 14088 // purpose of checking if the current context is deprecated. 14089 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 14090 AvailabilityResult R = MD->getAvailability(); 14091 if (R != AR_Available) 14092 return R; 14093 D = MD->getClassInterface(); 14094 } 14095 // If we are within an Objective-c @implementation, it 14096 // gets the same availability context as the @interface. 14097 else if (const ObjCImplementationDecl *ID = 14098 dyn_cast<ObjCImplementationDecl>(D)) { 14099 D = ID->getClassInterface(); 14100 } 14101 // Recover from user error. 14102 return D ? D->getAvailability() : AR_Available; 14103 } 14104