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 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, 132 const IdentifierInfo &II, 133 SourceLocation NameLoc) { 134 // Find the first parent class template context, if any. 135 // FIXME: Perform the lookup in all enclosing class templates. 136 const CXXRecordDecl *RD = nullptr; 137 for (DeclContext *DC = S.CurContext; DC; DC = DC->getParent()) { 138 RD = dyn_cast<CXXRecordDecl>(DC); 139 if (RD && RD->getDescribedClassTemplate()) 140 break; 141 } 142 if (!RD) 143 return ParsedType(); 144 145 // Look for type decls in dependent base classes that have known primary 146 // templates. 147 bool FoundTypeDecl = false; 148 for (const auto &Base : RD->bases()) { 149 auto *TST = Base.getType()->getAs<TemplateSpecializationType>(); 150 if (!TST || !TST->isDependentType()) 151 continue; 152 auto *TD = TST->getTemplateName().getAsTemplateDecl(); 153 if (!TD) 154 continue; 155 auto *BasePrimaryTemplate = 156 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl()); 157 if (!BasePrimaryTemplate) 158 continue; 159 // FIXME: Allow lookup into non-dependent bases of dependent bases, possibly 160 // by calling or integrating with the main LookupQualifiedName mechanism. 161 for (NamedDecl *ND : BasePrimaryTemplate->lookup(&II)) { 162 if (FoundTypeDecl) 163 return ParsedType(); 164 FoundTypeDecl = isa<TypeDecl>(ND); 165 if (!FoundTypeDecl) 166 return ParsedType(); 167 } 168 } 169 if (!FoundTypeDecl) 170 return ParsedType(); 171 172 // We found some types in dependent base classes. Recover as if the user 173 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the 174 // lookup during template instantiation. 175 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II; 176 177 ASTContext &Context = S.Context; 178 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false, 179 cast<Type>(Context.getRecordType(RD))); 180 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II); 181 182 CXXScopeSpec SS; 183 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 184 185 TypeLocBuilder Builder; 186 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 187 DepTL.setNameLoc(NameLoc); 188 DepTL.setElaboratedKeywordLoc(SourceLocation()); 189 DepTL.setQualifierLoc(SS.getWithLocInContext(Context)); 190 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 191 } 192 193 /// \brief If the identifier refers to a type name within this scope, 194 /// return the declaration of that type. 195 /// 196 /// This routine performs ordinary name lookup of the identifier II 197 /// within the given scope, with optional C++ scope specifier SS, to 198 /// determine whether the name refers to a type. If so, returns an 199 /// opaque pointer (actually a QualType) corresponding to that 200 /// type. Otherwise, returns NULL. 201 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, 202 Scope *S, CXXScopeSpec *SS, 203 bool isClassName, bool HasTrailingDot, 204 ParsedType ObjectTypePtr, 205 bool IsCtorOrDtorName, 206 bool WantNontrivialTypeSourceInfo, 207 IdentifierInfo **CorrectedII) { 208 // Determine where we will perform name lookup. 209 DeclContext *LookupCtx = nullptr; 210 if (ObjectTypePtr) { 211 QualType ObjectType = ObjectTypePtr.get(); 212 if (ObjectType->isRecordType()) 213 LookupCtx = computeDeclContext(ObjectType); 214 } else if (SS && SS->isNotEmpty()) { 215 LookupCtx = computeDeclContext(*SS, false); 216 217 if (!LookupCtx) { 218 if (isDependentScopeSpecifier(*SS)) { 219 // C++ [temp.res]p3: 220 // A qualified-id that refers to a type and in which the 221 // nested-name-specifier depends on a template-parameter (14.6.2) 222 // shall be prefixed by the keyword typename to indicate that the 223 // qualified-id denotes a type, forming an 224 // elaborated-type-specifier (7.1.5.3). 225 // 226 // We therefore do not perform any name lookup if the result would 227 // refer to a member of an unknown specialization. 228 if (!isClassName && !IsCtorOrDtorName) 229 return ParsedType(); 230 231 // We know from the grammar that this name refers to a type, 232 // so build a dependent node to describe the type. 233 if (WantNontrivialTypeSourceInfo) 234 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get(); 235 236 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context); 237 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc, 238 II, NameLoc); 239 return ParsedType::make(T); 240 } 241 242 return ParsedType(); 243 } 244 245 if (!LookupCtx->isDependentContext() && 246 RequireCompleteDeclContext(*SS, LookupCtx)) 247 return ParsedType(); 248 } 249 250 // FIXME: LookupNestedNameSpecifierName isn't the right kind of 251 // lookup for class-names. 252 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName : 253 LookupOrdinaryName; 254 LookupResult Result(*this, &II, NameLoc, Kind); 255 if (LookupCtx) { 256 // Perform "qualified" name lookup into the declaration context we 257 // computed, which is either the type of the base of a member access 258 // expression or the declaration context associated with a prior 259 // nested-name-specifier. 260 LookupQualifiedName(Result, LookupCtx); 261 262 if (ObjectTypePtr && Result.empty()) { 263 // C++ [basic.lookup.classref]p3: 264 // If the unqualified-id is ~type-name, the type-name is looked up 265 // in the context of the entire postfix-expression. If the type T of 266 // the object expression is of a class type C, the type-name is also 267 // looked up in the scope of class C. At least one of the lookups shall 268 // find a name that refers to (possibly cv-qualified) T. 269 LookupName(Result, S); 270 } 271 } else { 272 // Perform unqualified name lookup. 273 LookupName(Result, S); 274 275 // For unqualified lookup in a class template in MSVC mode, look into 276 // dependent base classes where the primary class template is known. 277 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) { 278 if (ParsedType TypeInBase = 279 recoverFromTypeInKnownDependentBase(*this, II, NameLoc)) 280 return TypeInBase; 281 } 282 } 283 284 NamedDecl *IIDecl = nullptr; 285 switch (Result.getResultKind()) { 286 case LookupResult::NotFound: 287 case LookupResult::NotFoundInCurrentInstantiation: 288 if (CorrectedII) { 289 TypeNameValidatorCCC Validator(true, isClassName); 290 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), 291 Kind, S, SS, Validator, 292 CTK_ErrorRecovery); 293 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo(); 294 TemplateTy Template; 295 bool MemberOfUnknownSpecialization; 296 UnqualifiedId TemplateName; 297 TemplateName.setIdentifier(NewII, NameLoc); 298 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier(); 299 CXXScopeSpec NewSS, *NewSSPtr = SS; 300 if (SS && NNS) { 301 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 302 NewSSPtr = &NewSS; 303 } 304 if (Correction && (NNS || NewII != &II) && 305 // Ignore a correction to a template type as the to-be-corrected 306 // identifier is not a template (typo correction for template names 307 // is handled elsewhere). 308 !(getLangOpts().CPlusPlus && NewSSPtr && 309 isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(), 310 false, Template, MemberOfUnknownSpecialization))) { 311 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr, 312 isClassName, HasTrailingDot, ObjectTypePtr, 313 IsCtorOrDtorName, 314 WantNontrivialTypeSourceInfo); 315 if (Ty) { 316 diagnoseTypo(Correction, 317 PDiag(diag::err_unknown_type_or_class_name_suggest) 318 << Result.getLookupName() << isClassName); 319 if (SS && NNS) 320 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc)); 321 *CorrectedII = NewII; 322 return Ty; 323 } 324 } 325 } 326 // If typo correction failed or was not performed, fall through 327 case LookupResult::FoundOverloaded: 328 case LookupResult::FoundUnresolvedValue: 329 Result.suppressDiagnostics(); 330 return ParsedType(); 331 332 case LookupResult::Ambiguous: 333 // Recover from type-hiding ambiguities by hiding the type. We'll 334 // do the lookup again when looking for an object, and we can 335 // diagnose the error then. If we don't do this, then the error 336 // about hiding the type will be immediately followed by an error 337 // that only makes sense if the identifier was treated like a type. 338 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) { 339 Result.suppressDiagnostics(); 340 return ParsedType(); 341 } 342 343 // Look to see if we have a type anywhere in the list of results. 344 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end(); 345 Res != ResEnd; ++Res) { 346 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) { 347 if (!IIDecl || 348 (*Res)->getLocation().getRawEncoding() < 349 IIDecl->getLocation().getRawEncoding()) 350 IIDecl = *Res; 351 } 352 } 353 354 if (!IIDecl) { 355 // None of the entities we found is a type, so there is no way 356 // to even assume that the result is a type. In this case, don't 357 // complain about the ambiguity. The parser will either try to 358 // perform this lookup again (e.g., as an object name), which 359 // will produce the ambiguity, or will complain that it expected 360 // a type name. 361 Result.suppressDiagnostics(); 362 return ParsedType(); 363 } 364 365 // We found a type within the ambiguous lookup; diagnose the 366 // ambiguity and then return that type. This might be the right 367 // answer, or it might not be, but it suppresses any attempt to 368 // perform the name lookup again. 369 break; 370 371 case LookupResult::Found: 372 IIDecl = Result.getFoundDecl(); 373 break; 374 } 375 376 assert(IIDecl && "Didn't find decl"); 377 378 QualType T; 379 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) { 380 DiagnoseUseOfDecl(IIDecl, NameLoc); 381 382 T = Context.getTypeDeclType(TD); 383 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false); 384 385 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a 386 // constructor or destructor name (in such a case, the scope specifier 387 // will be attached to the enclosing Expr or Decl node). 388 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) { 389 if (WantNontrivialTypeSourceInfo) { 390 // Construct a type with type-source information. 391 TypeLocBuilder Builder; 392 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 393 394 T = getElaboratedType(ETK_None, *SS, T); 395 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 396 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 397 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context)); 398 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 399 } else { 400 T = getElaboratedType(ETK_None, *SS, T); 401 } 402 } 403 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) { 404 (void)DiagnoseUseOfDecl(IDecl, NameLoc); 405 if (!HasTrailingDot) 406 T = Context.getObjCInterfaceType(IDecl); 407 } 408 409 if (T.isNull()) { 410 // If it's not plausibly a type, suppress diagnostics. 411 Result.suppressDiagnostics(); 412 return ParsedType(); 413 } 414 return ParsedType::make(T); 415 } 416 417 // Builds a fake NNS for the given decl context. 418 static NestedNameSpecifier * 419 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) { 420 for (;; DC = DC->getLookupParent()) { 421 DC = DC->getPrimaryContext(); 422 auto *ND = dyn_cast<NamespaceDecl>(DC); 423 if (ND && !ND->isInline() && !ND->isAnonymousNamespace()) 424 return NestedNameSpecifier::Create(Context, nullptr, ND); 425 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) 426 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(), 427 RD->getTypeForDecl()); 428 else if (isa<TranslationUnitDecl>(DC)) 429 return NestedNameSpecifier::GlobalSpecifier(Context); 430 } 431 llvm_unreachable("something isn't in TU scope?"); 432 } 433 434 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II, 435 SourceLocation NameLoc) { 436 // Accepting an undeclared identifier as a default argument for a template 437 // type parameter is a Microsoft extension. 438 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II; 439 440 // Build a fake DependentNameType that will perform lookup into CurContext at 441 // instantiation time. The name specifier isn't dependent, so template 442 // instantiation won't transform it. It will retry the lookup, however. 443 NestedNameSpecifier *NNS = 444 synthesizeCurrentNestedNameSpecifier(Context, CurContext); 445 QualType T = Context.getDependentNameType(ETK_None, NNS, &II); 446 447 // Build type location information. We synthesized the qualifier, so we have 448 // to build a fake NestedNameSpecifierLoc. 449 NestedNameSpecifierLocBuilder NNSLocBuilder; 450 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc)); 451 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context); 452 453 TypeLocBuilder Builder; 454 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T); 455 DepTL.setNameLoc(NameLoc); 456 DepTL.setElaboratedKeywordLoc(SourceLocation()); 457 DepTL.setQualifierLoc(QualifierLoc); 458 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 459 } 460 461 /// isTagName() - This method is called *for error recovery purposes only* 462 /// to determine if the specified name is a valid tag name ("struct foo"). If 463 /// so, this returns the TST for the tag corresponding to it (TST_enum, 464 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose 465 /// cases in C where the user forgot to specify the tag. 466 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) { 467 // Do a tag name lookup in this scope. 468 LookupResult R(*this, &II, SourceLocation(), LookupTagName); 469 LookupName(R, S, false); 470 R.suppressDiagnostics(); 471 if (R.getResultKind() == LookupResult::Found) 472 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) { 473 switch (TD->getTagKind()) { 474 case TTK_Struct: return DeclSpec::TST_struct; 475 case TTK_Interface: return DeclSpec::TST_interface; 476 case TTK_Union: return DeclSpec::TST_union; 477 case TTK_Class: return DeclSpec::TST_class; 478 case TTK_Enum: return DeclSpec::TST_enum; 479 } 480 } 481 482 return DeclSpec::TST_unspecified; 483 } 484 485 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope, 486 /// if a CXXScopeSpec's type is equal to the type of one of the base classes 487 /// then downgrade the missing typename error to a warning. 488 /// This is needed for MSVC compatibility; Example: 489 /// @code 490 /// template<class T> class A { 491 /// public: 492 /// typedef int TYPE; 493 /// }; 494 /// template<class T> class B : public A<T> { 495 /// public: 496 /// A<T>::TYPE a; // no typename required because A<T> is a base class. 497 /// }; 498 /// @endcode 499 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) { 500 if (CurContext->isRecord()) { 501 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super) 502 return true; 503 504 const Type *Ty = SS->getScopeRep()->getAsType(); 505 506 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext); 507 for (const auto &Base : RD->bases()) 508 if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType())) 509 return true; 510 return S->isFunctionPrototypeScope(); 511 } 512 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope(); 513 } 514 515 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II, 516 SourceLocation IILoc, 517 Scope *S, 518 CXXScopeSpec *SS, 519 ParsedType &SuggestedType, 520 bool AllowClassTemplates) { 521 // We don't have anything to suggest (yet). 522 SuggestedType = ParsedType(); 523 524 // There may have been a typo in the name of the type. Look up typo 525 // results, in case we have something that we can suggest. 526 TypeNameValidatorCCC Validator(false, false, AllowClassTemplates); 527 if (TypoCorrection Corrected = CorrectTypo(DeclarationNameInfo(II, IILoc), 528 LookupOrdinaryName, S, SS, 529 Validator, CTK_ErrorRecovery)) { 530 if (Corrected.isKeyword()) { 531 // We corrected to a keyword. 532 diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II); 533 II = Corrected.getCorrectionAsIdentifierInfo(); 534 } else { 535 // We found a similarly-named type or interface; suggest that. 536 if (!SS || !SS->isSet()) { 537 diagnoseTypo(Corrected, 538 PDiag(diag::err_unknown_typename_suggest) << II); 539 } else if (DeclContext *DC = computeDeclContext(*SS, false)) { 540 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 541 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 542 II->getName().equals(CorrectedStr); 543 diagnoseTypo(Corrected, 544 PDiag(diag::err_unknown_nested_typename_suggest) 545 << II << DC << DroppedSpecifier << SS->getRange()); 546 } else { 547 llvm_unreachable("could not have corrected a typo here"); 548 } 549 550 CXXScopeSpec tmpSS; 551 if (Corrected.getCorrectionSpecifier()) 552 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(), 553 SourceRange(IILoc)); 554 SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), 555 IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false, 556 false, ParsedType(), 557 /*IsCtorOrDtorName=*/false, 558 /*NonTrivialTypeSourceInfo=*/true); 559 } 560 return; 561 } 562 563 if (getLangOpts().CPlusPlus) { 564 // See if II is a class template that the user forgot to pass arguments to. 565 UnqualifiedId Name; 566 Name.setIdentifier(II, IILoc); 567 CXXScopeSpec EmptySS; 568 TemplateTy TemplateResult; 569 bool MemberOfUnknownSpecialization; 570 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false, 571 Name, ParsedType(), true, TemplateResult, 572 MemberOfUnknownSpecialization) == TNK_Type_template) { 573 TemplateName TplName = TemplateResult.get(); 574 Diag(IILoc, diag::err_template_missing_args) << TplName; 575 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) { 576 Diag(TplDecl->getLocation(), diag::note_template_decl_here) 577 << TplDecl->getTemplateParameters()->getSourceRange(); 578 } 579 return; 580 } 581 } 582 583 // FIXME: Should we move the logic that tries to recover from a missing tag 584 // (struct, union, enum) from Parser::ParseImplicitInt here, instead? 585 586 if (!SS || (!SS->isSet() && !SS->isInvalid())) 587 Diag(IILoc, diag::err_unknown_typename) << II; 588 else if (DeclContext *DC = computeDeclContext(*SS, false)) 589 Diag(IILoc, diag::err_typename_nested_not_found) 590 << II << DC << SS->getRange(); 591 else if (isDependentScopeSpecifier(*SS)) { 592 unsigned DiagID = diag::err_typename_missing; 593 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S)) 594 DiagID = diag::ext_typename_missing; 595 596 Diag(SS->getRange().getBegin(), DiagID) 597 << SS->getScopeRep() << II->getName() 598 << SourceRange(SS->getRange().getBegin(), IILoc) 599 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename "); 600 SuggestedType = ActOnTypenameType(S, SourceLocation(), 601 *SS, *II, IILoc).get(); 602 } else { 603 assert(SS && SS->isInvalid() && 604 "Invalid scope specifier has already been diagnosed"); 605 } 606 } 607 608 /// \brief Determine whether the given result set contains either a type name 609 /// or 610 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) { 611 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus && 612 NextToken.is(tok::less); 613 614 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) { 615 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I)) 616 return true; 617 618 if (CheckTemplate && isa<TemplateDecl>(*I)) 619 return true; 620 } 621 622 return false; 623 } 624 625 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, 626 Scope *S, CXXScopeSpec &SS, 627 IdentifierInfo *&Name, 628 SourceLocation NameLoc) { 629 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName); 630 SemaRef.LookupParsedName(R, S, &SS); 631 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) { 632 StringRef FixItTagName; 633 switch (Tag->getTagKind()) { 634 case TTK_Class: 635 FixItTagName = "class "; 636 break; 637 638 case TTK_Enum: 639 FixItTagName = "enum "; 640 break; 641 642 case TTK_Struct: 643 FixItTagName = "struct "; 644 break; 645 646 case TTK_Interface: 647 FixItTagName = "__interface "; 648 break; 649 650 case TTK_Union: 651 FixItTagName = "union "; 652 break; 653 } 654 655 StringRef TagName = FixItTagName.drop_back(); 656 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag) 657 << Name << TagName << SemaRef.getLangOpts().CPlusPlus 658 << FixItHint::CreateInsertion(NameLoc, FixItTagName); 659 660 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end(); 661 I != IEnd; ++I) 662 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type) 663 << Name << TagName; 664 665 // Replace lookup results with just the tag decl. 666 Result.clear(Sema::LookupTagName); 667 SemaRef.LookupParsedName(Result, S, &SS); 668 return true; 669 } 670 671 return false; 672 } 673 674 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier. 675 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS, 676 QualType T, SourceLocation NameLoc) { 677 ASTContext &Context = S.Context; 678 679 TypeLocBuilder Builder; 680 Builder.pushTypeSpec(T).setNameLoc(NameLoc); 681 682 T = S.getElaboratedType(ETK_None, SS, T); 683 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T); 684 ElabTL.setElaboratedKeywordLoc(SourceLocation()); 685 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context)); 686 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T)); 687 } 688 689 Sema::NameClassification Sema::ClassifyName(Scope *S, 690 CXXScopeSpec &SS, 691 IdentifierInfo *&Name, 692 SourceLocation NameLoc, 693 const Token &NextToken, 694 bool IsAddressOfOperand, 695 CorrectionCandidateCallback *CCC) { 696 DeclarationNameInfo NameInfo(Name, NameLoc); 697 ObjCMethodDecl *CurMethod = getCurMethodDecl(); 698 699 if (NextToken.is(tok::coloncolon)) { 700 BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(), 701 QualType(), false, SS, nullptr, false); 702 } 703 704 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 705 NestedNameSpecifier *NNS = SS.getScopeRep(); 706 if (NNS && NNS->getKind() == NestedNameSpecifier::Super) 707 LookupInSuper(Result, NNS->getAsRecordDecl()); 708 else 709 LookupParsedName(Result, S, &SS, !CurMethod); 710 711 // For unqualified lookup in a class template in MSVC mode, look into 712 // dependent base classes where the primary class template is known. 713 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) { 714 if (ParsedType TypeInBase = 715 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc)) 716 return TypeInBase; 717 } 718 719 // Perform lookup for Objective-C instance variables (including automatically 720 // synthesized instance variables), if we're in an Objective-C method. 721 // FIXME: This lookup really, really needs to be folded in to the normal 722 // unqualified lookup mechanism. 723 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) { 724 ExprResult E = LookupInObjCMethod(Result, S, Name, true); 725 if (E.get() || E.isInvalid()) 726 return E; 727 } 728 729 bool SecondTry = false; 730 bool IsFilteredTemplateName = false; 731 732 Corrected: 733 switch (Result.getResultKind()) { 734 case LookupResult::NotFound: 735 // If an unqualified-id is followed by a '(', then we have a function 736 // call. 737 if (!SS.isSet() && NextToken.is(tok::l_paren)) { 738 // In C++, this is an ADL-only call. 739 // FIXME: Reference? 740 if (getLangOpts().CPlusPlus) 741 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true); 742 743 // C90 6.3.2.2: 744 // If the expression that precedes the parenthesized argument list in a 745 // function call consists solely of an identifier, and if no 746 // declaration is visible for this identifier, the identifier is 747 // implicitly declared exactly as if, in the innermost block containing 748 // the function call, the declaration 749 // 750 // extern int identifier (); 751 // 752 // appeared. 753 // 754 // We also allow this in C99 as an extension. 755 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) { 756 Result.addDecl(D); 757 Result.resolveKind(); 758 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false); 759 } 760 } 761 762 // In C, we first see whether there is a tag type by the same name, in 763 // which case it's likely that the user just forget to write "enum", 764 // "struct", or "union". 765 if (!getLangOpts().CPlusPlus && !SecondTry && 766 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 767 break; 768 } 769 770 // Perform typo correction to determine if there is another name that is 771 // close to this name. 772 if (!SecondTry && CCC) { 773 SecondTry = true; 774 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), 775 Result.getLookupKind(), S, 776 &SS, *CCC, 777 CTK_ErrorRecovery)) { 778 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest; 779 unsigned QualifiedDiag = diag::err_no_member_suggest; 780 781 NamedDecl *FirstDecl = Corrected.getCorrectionDecl(); 782 NamedDecl *UnderlyingFirstDecl 783 = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr; 784 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 785 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) { 786 UnqualifiedDiag = diag::err_no_template_suggest; 787 QualifiedDiag = diag::err_no_member_template_suggest; 788 } else if (UnderlyingFirstDecl && 789 (isa<TypeDecl>(UnderlyingFirstDecl) || 790 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) || 791 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) { 792 UnqualifiedDiag = diag::err_unknown_typename_suggest; 793 QualifiedDiag = diag::err_unknown_nested_typename_suggest; 794 } 795 796 if (SS.isEmpty()) { 797 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name); 798 } else {// FIXME: is this even reachable? Test it. 799 std::string CorrectedStr(Corrected.getAsString(getLangOpts())); 800 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() && 801 Name->getName().equals(CorrectedStr); 802 diagnoseTypo(Corrected, PDiag(QualifiedDiag) 803 << Name << computeDeclContext(SS, false) 804 << DroppedSpecifier << SS.getRange()); 805 } 806 807 // Update the name, so that the caller has the new name. 808 Name = Corrected.getCorrectionAsIdentifierInfo(); 809 810 // Typo correction corrected to a keyword. 811 if (Corrected.isKeyword()) 812 return Name; 813 814 // Also update the LookupResult... 815 // FIXME: This should probably go away at some point 816 Result.clear(); 817 Result.setLookupName(Corrected.getCorrection()); 818 if (FirstDecl) 819 Result.addDecl(FirstDecl); 820 821 // If we found an Objective-C instance variable, let 822 // LookupInObjCMethod build the appropriate expression to 823 // reference the ivar. 824 // FIXME: This is a gross hack. 825 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) { 826 Result.clear(); 827 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier())); 828 return E; 829 } 830 831 goto Corrected; 832 } 833 } 834 835 // We failed to correct; just fall through and let the parser deal with it. 836 Result.suppressDiagnostics(); 837 return NameClassification::Unknown(); 838 839 case LookupResult::NotFoundInCurrentInstantiation: { 840 // We performed name lookup into the current instantiation, and there were 841 // dependent bases, so we treat this result the same way as any other 842 // dependent nested-name-specifier. 843 844 // C++ [temp.res]p2: 845 // A name used in a template declaration or definition and that is 846 // dependent on a template-parameter is assumed not to name a type 847 // unless the applicable name lookup finds a type name or the name is 848 // qualified by the keyword typename. 849 // 850 // FIXME: If the next token is '<', we might want to ask the parser to 851 // perform some heroics to see if we actually have a 852 // template-argument-list, which would indicate a missing 'template' 853 // keyword here. 854 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(), 855 NameInfo, IsAddressOfOperand, 856 /*TemplateArgs=*/nullptr); 857 } 858 859 case LookupResult::Found: 860 case LookupResult::FoundOverloaded: 861 case LookupResult::FoundUnresolvedValue: 862 break; 863 864 case LookupResult::Ambiguous: 865 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 866 hasAnyAcceptableTemplateNames(Result)) { 867 // C++ [temp.local]p3: 868 // A lookup that finds an injected-class-name (10.2) can result in an 869 // ambiguity in certain cases (for example, if it is found in more than 870 // one base class). If all of the injected-class-names that are found 871 // refer to specializations of the same class template, and if the name 872 // is followed by a template-argument-list, the reference refers to the 873 // class template itself and not a specialization thereof, and is not 874 // ambiguous. 875 // 876 // This filtering can make an ambiguous result into an unambiguous one, 877 // so try again after filtering out template names. 878 FilterAcceptableTemplateNames(Result); 879 if (!Result.isAmbiguous()) { 880 IsFilteredTemplateName = true; 881 break; 882 } 883 } 884 885 // Diagnose the ambiguity and return an error. 886 return NameClassification::Error(); 887 } 888 889 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) && 890 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) { 891 // C++ [temp.names]p3: 892 // After name lookup (3.4) finds that a name is a template-name or that 893 // an operator-function-id or a literal- operator-id refers to a set of 894 // overloaded functions any member of which is a function template if 895 // this is followed by a <, the < is always taken as the delimiter of a 896 // template-argument-list and never as the less-than operator. 897 if (!IsFilteredTemplateName) 898 FilterAcceptableTemplateNames(Result); 899 900 if (!Result.empty()) { 901 bool IsFunctionTemplate; 902 bool IsVarTemplate; 903 TemplateName Template; 904 if (Result.end() - Result.begin() > 1) { 905 IsFunctionTemplate = true; 906 Template = Context.getOverloadedTemplateName(Result.begin(), 907 Result.end()); 908 } else { 909 TemplateDecl *TD 910 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl()); 911 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD); 912 IsVarTemplate = isa<VarTemplateDecl>(TD); 913 914 if (SS.isSet() && !SS.isInvalid()) 915 Template = Context.getQualifiedTemplateName(SS.getScopeRep(), 916 /*TemplateKeyword=*/false, 917 TD); 918 else 919 Template = TemplateName(TD); 920 } 921 922 if (IsFunctionTemplate) { 923 // Function templates always go through overload resolution, at which 924 // point we'll perform the various checks (e.g., accessibility) we need 925 // to based on which function we selected. 926 Result.suppressDiagnostics(); 927 928 return NameClassification::FunctionTemplate(Template); 929 } 930 931 return IsVarTemplate ? NameClassification::VarTemplate(Template) 932 : NameClassification::TypeTemplate(Template); 933 } 934 } 935 936 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl(); 937 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) { 938 DiagnoseUseOfDecl(Type, NameLoc); 939 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); 940 QualType T = Context.getTypeDeclType(Type); 941 if (SS.isNotEmpty()) 942 return buildNestedType(*this, SS, T, NameLoc); 943 return ParsedType::make(T); 944 } 945 946 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl); 947 if (!Class) { 948 // FIXME: It's unfortunate that we don't have a Type node for handling this. 949 if (ObjCCompatibleAliasDecl *Alias = 950 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl)) 951 Class = Alias->getClassInterface(); 952 } 953 954 if (Class) { 955 DiagnoseUseOfDecl(Class, NameLoc); 956 957 if (NextToken.is(tok::period)) { 958 // Interface. <something> is parsed as a property reference expression. 959 // Just return "unknown" as a fall-through for now. 960 Result.suppressDiagnostics(); 961 return NameClassification::Unknown(); 962 } 963 964 QualType T = Context.getObjCInterfaceType(Class); 965 return ParsedType::make(T); 966 } 967 968 // We can have a type template here if we're classifying a template argument. 969 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl)) 970 return NameClassification::TypeTemplate( 971 TemplateName(cast<TemplateDecl>(FirstDecl))); 972 973 // Check for a tag type hidden by a non-type decl in a few cases where it 974 // seems likely a type is wanted instead of the non-type that was found. 975 bool NextIsOp = NextToken.is(tok::amp) || NextToken.is(tok::star); 976 if ((NextToken.is(tok::identifier) || 977 (NextIsOp && 978 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) && 979 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) { 980 TypeDecl *Type = Result.getAsSingle<TypeDecl>(); 981 DiagnoseUseOfDecl(Type, NameLoc); 982 QualType T = Context.getTypeDeclType(Type); 983 if (SS.isNotEmpty()) 984 return buildNestedType(*this, SS, T, NameLoc); 985 return ParsedType::make(T); 986 } 987 988 if (FirstDecl->isCXXClassMember()) 989 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result, 990 nullptr); 991 992 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren)); 993 return BuildDeclarationNameExpr(SS, Result, ADL); 994 } 995 996 // Determines the context to return to after temporarily entering a 997 // context. This depends in an unnecessarily complicated way on the 998 // exact ordering of callbacks from the parser. 999 DeclContext *Sema::getContainingDC(DeclContext *DC) { 1000 1001 // Functions defined inline within classes aren't parsed until we've 1002 // finished parsing the top-level class, so the top-level class is 1003 // the context we'll need to return to. 1004 // A Lambda call operator whose parent is a class must not be treated 1005 // as an inline member function. A Lambda can be used legally 1006 // either as an in-class member initializer or a default argument. These 1007 // are parsed once the class has been marked complete and so the containing 1008 // context would be the nested class (when the lambda is defined in one); 1009 // If the class is not complete, then the lambda is being used in an 1010 // ill-formed fashion (such as to specify the width of a bit-field, or 1011 // in an array-bound) - in which case we still want to return the 1012 // lexically containing DC (which could be a nested class). 1013 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) { 1014 DC = DC->getLexicalParent(); 1015 1016 // A function not defined within a class will always return to its 1017 // lexical context. 1018 if (!isa<CXXRecordDecl>(DC)) 1019 return DC; 1020 1021 // A C++ inline method/friend is parsed *after* the topmost class 1022 // it was declared in is fully parsed ("complete"); the topmost 1023 // class is the context we need to return to. 1024 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent())) 1025 DC = RD; 1026 1027 // Return the declaration context of the topmost class the inline method is 1028 // declared in. 1029 return DC; 1030 } 1031 1032 return DC->getLexicalParent(); 1033 } 1034 1035 void Sema::PushDeclContext(Scope *S, DeclContext *DC) { 1036 assert(getContainingDC(DC) == CurContext && 1037 "The next DeclContext should be lexically contained in the current one."); 1038 CurContext = DC; 1039 S->setEntity(DC); 1040 } 1041 1042 void Sema::PopDeclContext() { 1043 assert(CurContext && "DeclContext imbalance!"); 1044 1045 CurContext = getContainingDC(CurContext); 1046 assert(CurContext && "Popped translation unit!"); 1047 } 1048 1049 /// EnterDeclaratorContext - Used when we must lookup names in the context 1050 /// of a declarator's nested name specifier. 1051 /// 1052 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) { 1053 // C++0x [basic.lookup.unqual]p13: 1054 // A name used in the definition of a static data member of class 1055 // X (after the qualified-id of the static member) is looked up as 1056 // if the name was used in a member function of X. 1057 // C++0x [basic.lookup.unqual]p14: 1058 // If a variable member of a namespace is defined outside of the 1059 // scope of its namespace then any name used in the definition of 1060 // the variable member (after the declarator-id) is looked up as 1061 // if the definition of the variable member occurred in its 1062 // namespace. 1063 // Both of these imply that we should push a scope whose context 1064 // is the semantic context of the declaration. We can't use 1065 // PushDeclContext here because that context is not necessarily 1066 // lexically contained in the current context. Fortunately, 1067 // the containing scope should have the appropriate information. 1068 1069 assert(!S->getEntity() && "scope already has entity"); 1070 1071 #ifndef NDEBUG 1072 Scope *Ancestor = S->getParent(); 1073 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1074 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch"); 1075 #endif 1076 1077 CurContext = DC; 1078 S->setEntity(DC); 1079 } 1080 1081 void Sema::ExitDeclaratorContext(Scope *S) { 1082 assert(S->getEntity() == CurContext && "Context imbalance!"); 1083 1084 // Switch back to the lexical context. The safety of this is 1085 // enforced by an assert in EnterDeclaratorContext. 1086 Scope *Ancestor = S->getParent(); 1087 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent(); 1088 CurContext = Ancestor->getEntity(); 1089 1090 // We don't need to do anything with the scope, which is going to 1091 // disappear. 1092 } 1093 1094 1095 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) { 1096 // We assume that the caller has already called 1097 // ActOnReenterTemplateScope so getTemplatedDecl() works. 1098 FunctionDecl *FD = D->getAsFunction(); 1099 if (!FD) 1100 return; 1101 1102 // Same implementation as PushDeclContext, but enters the context 1103 // from the lexical parent, rather than the top-level class. 1104 assert(CurContext == FD->getLexicalParent() && 1105 "The next DeclContext should be lexically contained in the current one."); 1106 CurContext = FD; 1107 S->setEntity(CurContext); 1108 1109 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) { 1110 ParmVarDecl *Param = FD->getParamDecl(P); 1111 // If the parameter has an identifier, then add it to the scope 1112 if (Param->getIdentifier()) { 1113 S->AddDecl(Param); 1114 IdResolver.AddDecl(Param); 1115 } 1116 } 1117 } 1118 1119 1120 void Sema::ActOnExitFunctionContext() { 1121 // Same implementation as PopDeclContext, but returns to the lexical parent, 1122 // rather than the top-level class. 1123 assert(CurContext && "DeclContext imbalance!"); 1124 CurContext = CurContext->getLexicalParent(); 1125 assert(CurContext && "Popped translation unit!"); 1126 } 1127 1128 1129 /// \brief Determine whether we allow overloading of the function 1130 /// PrevDecl with another declaration. 1131 /// 1132 /// This routine determines whether overloading is possible, not 1133 /// whether some new function is actually an overload. It will return 1134 /// true in C++ (where we can always provide overloads) or, as an 1135 /// extension, in C when the previous function is already an 1136 /// overloaded function declaration or has the "overloadable" 1137 /// attribute. 1138 static bool AllowOverloadingOfFunction(LookupResult &Previous, 1139 ASTContext &Context) { 1140 if (Context.getLangOpts().CPlusPlus) 1141 return true; 1142 1143 if (Previous.getResultKind() == LookupResult::FoundOverloaded) 1144 return true; 1145 1146 return (Previous.getResultKind() == LookupResult::Found 1147 && Previous.getFoundDecl()->hasAttr<OverloadableAttr>()); 1148 } 1149 1150 /// Add this decl to the scope shadowed decl chains. 1151 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) { 1152 // Move up the scope chain until we find the nearest enclosing 1153 // non-transparent context. The declaration will be introduced into this 1154 // scope. 1155 while (S->getEntity() && S->getEntity()->isTransparentContext()) 1156 S = S->getParent(); 1157 1158 // Add scoped declarations into their context, so that they can be 1159 // found later. Declarations without a context won't be inserted 1160 // into any context. 1161 if (AddToContext) 1162 CurContext->addDecl(D); 1163 1164 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they 1165 // are function-local declarations. 1166 if (getLangOpts().CPlusPlus && D->isOutOfLine() && 1167 !D->getDeclContext()->getRedeclContext()->Equals( 1168 D->getLexicalDeclContext()->getRedeclContext()) && 1169 !D->getLexicalDeclContext()->isFunctionOrMethod()) 1170 return; 1171 1172 // Template instantiations should also not be pushed into scope. 1173 if (isa<FunctionDecl>(D) && 1174 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization()) 1175 return; 1176 1177 // If this replaces anything in the current scope, 1178 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()), 1179 IEnd = IdResolver.end(); 1180 for (; I != IEnd; ++I) { 1181 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) { 1182 S->RemoveDecl(*I); 1183 IdResolver.RemoveDecl(*I); 1184 1185 // Should only need to replace one decl. 1186 break; 1187 } 1188 } 1189 1190 S->AddDecl(D); 1191 1192 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) { 1193 // Implicitly-generated labels may end up getting generated in an order that 1194 // isn't strictly lexical, which breaks name lookup. Be careful to insert 1195 // the label at the appropriate place in the identifier chain. 1196 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) { 1197 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext(); 1198 if (IDC == CurContext) { 1199 if (!S->isDeclScope(*I)) 1200 continue; 1201 } else if (IDC->Encloses(CurContext)) 1202 break; 1203 } 1204 1205 IdResolver.InsertDeclAfter(I, D); 1206 } else { 1207 IdResolver.AddDecl(D); 1208 } 1209 } 1210 1211 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) { 1212 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope) 1213 TUScope->AddDecl(D); 1214 } 1215 1216 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S, 1217 bool AllowInlineNamespace) { 1218 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace); 1219 } 1220 1221 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) { 1222 DeclContext *TargetDC = DC->getPrimaryContext(); 1223 do { 1224 if (DeclContext *ScopeDC = S->getEntity()) 1225 if (ScopeDC->getPrimaryContext() == TargetDC) 1226 return S; 1227 } while ((S = S->getParent())); 1228 1229 return nullptr; 1230 } 1231 1232 static bool isOutOfScopePreviousDeclaration(NamedDecl *, 1233 DeclContext*, 1234 ASTContext&); 1235 1236 /// Filters out lookup results that don't fall within the given scope 1237 /// as determined by isDeclInScope. 1238 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 1239 bool ConsiderLinkage, 1240 bool AllowInlineNamespace) { 1241 LookupResult::Filter F = R.makeFilter(); 1242 while (F.hasNext()) { 1243 NamedDecl *D = F.next(); 1244 1245 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace)) 1246 continue; 1247 1248 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context)) 1249 continue; 1250 1251 F.erase(); 1252 } 1253 1254 F.done(); 1255 } 1256 1257 static bool isUsingDecl(NamedDecl *D) { 1258 return isa<UsingShadowDecl>(D) || 1259 isa<UnresolvedUsingTypenameDecl>(D) || 1260 isa<UnresolvedUsingValueDecl>(D); 1261 } 1262 1263 /// Removes using shadow declarations from the lookup results. 1264 static void RemoveUsingDecls(LookupResult &R) { 1265 LookupResult::Filter F = R.makeFilter(); 1266 while (F.hasNext()) 1267 if (isUsingDecl(F.next())) 1268 F.erase(); 1269 1270 F.done(); 1271 } 1272 1273 /// \brief Check for this common pattern: 1274 /// @code 1275 /// class S { 1276 /// S(const S&); // DO NOT IMPLEMENT 1277 /// void operator=(const S&); // DO NOT IMPLEMENT 1278 /// }; 1279 /// @endcode 1280 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) { 1281 // FIXME: Should check for private access too but access is set after we get 1282 // the decl here. 1283 if (D->doesThisDeclarationHaveABody()) 1284 return false; 1285 1286 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D)) 1287 return CD->isCopyConstructor(); 1288 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) 1289 return Method->isCopyAssignmentOperator(); 1290 return false; 1291 } 1292 1293 // We need this to handle 1294 // 1295 // typedef struct { 1296 // void *foo() { return 0; } 1297 // } A; 1298 // 1299 // When we see foo we don't know if after the typedef we will get 'A' or '*A' 1300 // for example. If 'A', foo will have external linkage. If we have '*A', 1301 // foo will have no linkage. Since we can't know until we get to the end 1302 // of the typedef, this function finds out if D might have non-external linkage. 1303 // Callers should verify at the end of the TU if it D has external linkage or 1304 // not. 1305 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) { 1306 const DeclContext *DC = D->getDeclContext(); 1307 while (!DC->isTranslationUnit()) { 1308 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){ 1309 if (!RD->hasNameForLinkage()) 1310 return true; 1311 } 1312 DC = DC->getParent(); 1313 } 1314 1315 return !D->isExternallyVisible(); 1316 } 1317 1318 // FIXME: This needs to be refactored; some other isInMainFile users want 1319 // these semantics. 1320 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) { 1321 if (S.TUKind != TU_Complete) 1322 return false; 1323 return S.SourceMgr.isInMainFile(Loc); 1324 } 1325 1326 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const { 1327 assert(D); 1328 1329 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>()) 1330 return false; 1331 1332 // Ignore all entities declared within templates, and out-of-line definitions 1333 // of members of class templates. 1334 if (D->getDeclContext()->isDependentContext() || 1335 D->getLexicalDeclContext()->isDependentContext()) 1336 return false; 1337 1338 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1339 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1340 return false; 1341 1342 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 1343 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD)) 1344 return false; 1345 } else { 1346 // 'static inline' functions are defined in headers; don't warn. 1347 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation())) 1348 return false; 1349 } 1350 1351 if (FD->doesThisDeclarationHaveABody() && 1352 Context.DeclMustBeEmitted(FD)) 1353 return false; 1354 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1355 // Constants and utility variables are defined in headers with internal 1356 // linkage; don't warn. (Unlike functions, there isn't a convenient marker 1357 // like "inline".) 1358 if (!isMainFileLoc(*this, VD->getLocation())) 1359 return false; 1360 1361 if (Context.DeclMustBeEmitted(VD)) 1362 return false; 1363 1364 if (VD->isStaticDataMember() && 1365 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 1366 return false; 1367 } else { 1368 return false; 1369 } 1370 1371 // Only warn for unused decls internal to the translation unit. 1372 // FIXME: This seems like a bogus check; it suppresses -Wunused-function 1373 // for inline functions defined in the main source file, for instance. 1374 return mightHaveNonExternalLinkage(D); 1375 } 1376 1377 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) { 1378 if (!D) 1379 return; 1380 1381 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1382 const FunctionDecl *First = FD->getFirstDecl(); 1383 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1384 return; // First should already be in the vector. 1385 } 1386 1387 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1388 const VarDecl *First = VD->getFirstDecl(); 1389 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First)) 1390 return; // First should already be in the vector. 1391 } 1392 1393 if (ShouldWarnIfUnusedFileScopedDecl(D)) 1394 UnusedFileScopedDecls.push_back(D); 1395 } 1396 1397 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) { 1398 if (D->isInvalidDecl()) 1399 return false; 1400 1401 if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() || 1402 D->hasAttr<ObjCPreciseLifetimeAttr>()) 1403 return false; 1404 1405 if (isa<LabelDecl>(D)) 1406 return true; 1407 1408 // Except for labels, we only care about unused decls that are local to 1409 // functions. 1410 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod(); 1411 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext())) 1412 // For dependent types, the diagnostic is deferred. 1413 WithinFunction = 1414 WithinFunction || (R->isLocalClass() && !R->isDependentType()); 1415 if (!WithinFunction) 1416 return false; 1417 1418 if (isa<TypedefNameDecl>(D)) 1419 return true; 1420 1421 // White-list anything that isn't a local variable. 1422 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) 1423 return false; 1424 1425 // Types of valid local variables should be complete, so this should succeed. 1426 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1427 1428 // White-list anything with an __attribute__((unused)) type. 1429 QualType Ty = VD->getType(); 1430 1431 // Only look at the outermost level of typedef. 1432 if (const TypedefType *TT = Ty->getAs<TypedefType>()) { 1433 if (TT->getDecl()->hasAttr<UnusedAttr>()) 1434 return false; 1435 } 1436 1437 // If we failed to complete the type for some reason, or if the type is 1438 // dependent, don't diagnose the variable. 1439 if (Ty->isIncompleteType() || Ty->isDependentType()) 1440 return false; 1441 1442 if (const TagType *TT = Ty->getAs<TagType>()) { 1443 const TagDecl *Tag = TT->getDecl(); 1444 if (Tag->hasAttr<UnusedAttr>()) 1445 return false; 1446 1447 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) { 1448 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>()) 1449 return false; 1450 1451 if (const Expr *Init = VD->getInit()) { 1452 if (const ExprWithCleanups *Cleanups = 1453 dyn_cast<ExprWithCleanups>(Init)) 1454 Init = Cleanups->getSubExpr(); 1455 const CXXConstructExpr *Construct = 1456 dyn_cast<CXXConstructExpr>(Init); 1457 if (Construct && !Construct->isElidable()) { 1458 CXXConstructorDecl *CD = Construct->getConstructor(); 1459 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>()) 1460 return false; 1461 } 1462 } 1463 } 1464 } 1465 1466 // TODO: __attribute__((unused)) templates? 1467 } 1468 1469 return true; 1470 } 1471 1472 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, 1473 FixItHint &Hint) { 1474 if (isa<LabelDecl>(D)) { 1475 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(), 1476 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true); 1477 if (AfterColon.isInvalid()) 1478 return; 1479 Hint = FixItHint::CreateRemoval(CharSourceRange:: 1480 getCharRange(D->getLocStart(), AfterColon)); 1481 } 1482 return; 1483 } 1484 1485 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) { 1486 if (D->getTypeForDecl()->isDependentType()) 1487 return; 1488 1489 for (auto *TmpD : D->decls()) { 1490 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD)) 1491 DiagnoseUnusedDecl(T); 1492 else if(const auto *R = dyn_cast<RecordDecl>(TmpD)) 1493 DiagnoseUnusedNestedTypedefs(R); 1494 } 1495 } 1496 1497 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used 1498 /// unless they are marked attr(unused). 1499 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) { 1500 if (!ShouldDiagnoseUnusedDecl(D)) 1501 return; 1502 1503 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) { 1504 // typedefs can be referenced later on, so the diagnostics are emitted 1505 // at end-of-translation-unit. 1506 UnusedLocalTypedefNameCandidates.insert(TD); 1507 return; 1508 } 1509 1510 FixItHint Hint; 1511 GenerateFixForUnusedDecl(D, Context, Hint); 1512 1513 unsigned DiagID; 1514 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable()) 1515 DiagID = diag::warn_unused_exception_param; 1516 else if (isa<LabelDecl>(D)) 1517 DiagID = diag::warn_unused_label; 1518 else 1519 DiagID = diag::warn_unused_variable; 1520 1521 Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint; 1522 } 1523 1524 static void CheckPoppedLabel(LabelDecl *L, Sema &S) { 1525 // Verify that we have no forward references left. If so, there was a goto 1526 // or address of a label taken, but no definition of it. Label fwd 1527 // definitions are indicated with a null substmt which is also not a resolved 1528 // MS inline assembly label name. 1529 bool Diagnose = false; 1530 if (L->isMSAsmLabel()) 1531 Diagnose = !L->isResolvedMSAsmLabel(); 1532 else 1533 Diagnose = L->getStmt() == nullptr; 1534 if (Diagnose) 1535 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName(); 1536 } 1537 1538 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) { 1539 S->mergeNRVOIntoParent(); 1540 1541 if (S->decl_empty()) return; 1542 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && 1543 "Scope shouldn't contain decls!"); 1544 1545 for (auto *TmpD : S->decls()) { 1546 assert(TmpD && "This decl didn't get pushed??"); 1547 1548 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?"); 1549 NamedDecl *D = cast<NamedDecl>(TmpD); 1550 1551 if (!D->getDeclName()) continue; 1552 1553 // Diagnose unused variables in this scope. 1554 if (!S->hasUnrecoverableErrorOccurred()) { 1555 DiagnoseUnusedDecl(D); 1556 if (const auto *RD = dyn_cast<RecordDecl>(D)) 1557 DiagnoseUnusedNestedTypedefs(RD); 1558 } 1559 1560 // If this was a forward reference to a label, verify it was defined. 1561 if (LabelDecl *LD = dyn_cast<LabelDecl>(D)) 1562 CheckPoppedLabel(LD, *this); 1563 1564 // Remove this name from our lexical scope. 1565 IdResolver.RemoveDecl(D); 1566 } 1567 } 1568 1569 /// \brief Look for an Objective-C class in the translation unit. 1570 /// 1571 /// \param Id The name of the Objective-C class we're looking for. If 1572 /// typo-correction fixes this name, the Id will be updated 1573 /// to the fixed name. 1574 /// 1575 /// \param IdLoc The location of the name in the translation unit. 1576 /// 1577 /// \param DoTypoCorrection If true, this routine will attempt typo correction 1578 /// if there is no class with the given name. 1579 /// 1580 /// \returns The declaration of the named Objective-C class, or NULL if the 1581 /// class could not be found. 1582 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id, 1583 SourceLocation IdLoc, 1584 bool DoTypoCorrection) { 1585 // The third "scope" argument is 0 since we aren't enabling lazy built-in 1586 // creation from this context. 1587 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName); 1588 1589 if (!IDecl && DoTypoCorrection) { 1590 // Perform typo correction at the given location, but only if we 1591 // find an Objective-C class name. 1592 DeclFilterCCC<ObjCInterfaceDecl> Validator; 1593 if (TypoCorrection C = CorrectTypo(DeclarationNameInfo(Id, IdLoc), 1594 LookupOrdinaryName, TUScope, nullptr, 1595 Validator, CTK_ErrorRecovery)) { 1596 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id); 1597 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>(); 1598 Id = IDecl->getIdentifier(); 1599 } 1600 } 1601 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl); 1602 // This routine must always return a class definition, if any. 1603 if (Def && Def->getDefinition()) 1604 Def = Def->getDefinition(); 1605 return Def; 1606 } 1607 1608 /// getNonFieldDeclScope - Retrieves the innermost scope, starting 1609 /// from S, where a non-field would be declared. This routine copes 1610 /// with the difference between C and C++ scoping rules in structs and 1611 /// unions. For example, the following code is well-formed in C but 1612 /// ill-formed in C++: 1613 /// @code 1614 /// struct S6 { 1615 /// enum { BAR } e; 1616 /// }; 1617 /// 1618 /// void test_S6() { 1619 /// struct S6 a; 1620 /// a.e = BAR; 1621 /// } 1622 /// @endcode 1623 /// For the declaration of BAR, this routine will return a different 1624 /// scope. The scope S will be the scope of the unnamed enumeration 1625 /// within S6. In C++, this routine will return the scope associated 1626 /// with S6, because the enumeration's scope is a transparent 1627 /// context but structures can contain non-field names. In C, this 1628 /// routine will return the translation unit scope, since the 1629 /// enumeration's scope is a transparent context and structures cannot 1630 /// contain non-field names. 1631 Scope *Sema::getNonFieldDeclScope(Scope *S) { 1632 while (((S->getFlags() & Scope::DeclScope) == 0) || 1633 (S->getEntity() && S->getEntity()->isTransparentContext()) || 1634 (S->isClassScope() && !getLangOpts().CPlusPlus)) 1635 S = S->getParent(); 1636 return S; 1637 } 1638 1639 /// \brief Looks up the declaration of "struct objc_super" and 1640 /// saves it for later use in building builtin declaration of 1641 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such 1642 /// pre-existing declaration exists no action takes place. 1643 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S, 1644 IdentifierInfo *II) { 1645 if (!II->isStr("objc_msgSendSuper")) 1646 return; 1647 ASTContext &Context = ThisSema.Context; 1648 1649 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"), 1650 SourceLocation(), Sema::LookupTagName); 1651 ThisSema.LookupName(Result, S); 1652 if (Result.getResultKind() == LookupResult::Found) 1653 if (const TagDecl *TD = Result.getAsSingle<TagDecl>()) 1654 Context.setObjCSuperType(Context.getTagDeclType(TD)); 1655 } 1656 1657 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) { 1658 switch (Error) { 1659 case ASTContext::GE_None: 1660 return ""; 1661 case ASTContext::GE_Missing_stdio: 1662 return "stdio.h"; 1663 case ASTContext::GE_Missing_setjmp: 1664 return "setjmp.h"; 1665 case ASTContext::GE_Missing_ucontext: 1666 return "ucontext.h"; 1667 } 1668 llvm_unreachable("unhandled error kind"); 1669 } 1670 1671 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at 1672 /// file scope. lazily create a decl for it. ForRedeclaration is true 1673 /// if we're creating this built-in in anticipation of redeclaring the 1674 /// built-in. 1675 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 1676 Scope *S, bool ForRedeclaration, 1677 SourceLocation Loc) { 1678 LookupPredefedObjCSuperType(*this, S, II); 1679 1680 ASTContext::GetBuiltinTypeError Error; 1681 QualType R = Context.GetBuiltinType(ID, Error); 1682 if (Error) { 1683 if (ForRedeclaration) 1684 Diag(Loc, diag::warn_implicit_decl_requires_sysheader) 1685 << getHeaderName(Error) 1686 << Context.BuiltinInfo.GetName(ID); 1687 return nullptr; 1688 } 1689 1690 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) { 1691 Diag(Loc, diag::ext_implicit_lib_function_decl) 1692 << Context.BuiltinInfo.GetName(ID) 1693 << R; 1694 if (Context.BuiltinInfo.getHeaderName(ID) && 1695 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc)) 1696 Diag(Loc, diag::note_include_header_or_declare) 1697 << Context.BuiltinInfo.getHeaderName(ID) 1698 << Context.BuiltinInfo.GetName(ID); 1699 } 1700 1701 DeclContext *Parent = Context.getTranslationUnitDecl(); 1702 if (getLangOpts().CPlusPlus) { 1703 LinkageSpecDecl *CLinkageDecl = 1704 LinkageSpecDecl::Create(Context, Parent, Loc, Loc, 1705 LinkageSpecDecl::lang_c, false); 1706 CLinkageDecl->setImplicit(); 1707 Parent->addDecl(CLinkageDecl); 1708 Parent = CLinkageDecl; 1709 } 1710 1711 FunctionDecl *New = FunctionDecl::Create(Context, 1712 Parent, 1713 Loc, Loc, II, R, /*TInfo=*/nullptr, 1714 SC_Extern, 1715 false, 1716 /*hasPrototype=*/true); 1717 New->setImplicit(); 1718 1719 // Create Decl objects for each parameter, adding them to the 1720 // FunctionDecl. 1721 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) { 1722 SmallVector<ParmVarDecl*, 16> Params; 1723 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) { 1724 ParmVarDecl *parm = 1725 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(), 1726 nullptr, FT->getParamType(i), /*TInfo=*/nullptr, 1727 SC_None, nullptr); 1728 parm->setScopeInfo(0, i); 1729 Params.push_back(parm); 1730 } 1731 New->setParams(Params); 1732 } 1733 1734 AddKnownFunctionAttributes(New); 1735 RegisterLocallyScopedExternCDecl(New, S); 1736 1737 // TUScope is the translation-unit scope to insert this function into. 1738 // FIXME: This is hideous. We need to teach PushOnScopeChains to 1739 // relate Scopes to DeclContexts, and probably eliminate CurContext 1740 // entirely, but we're not there yet. 1741 DeclContext *SavedContext = CurContext; 1742 CurContext = Parent; 1743 PushOnScopeChains(New, TUScope); 1744 CurContext = SavedContext; 1745 return New; 1746 } 1747 1748 /// \brief Filter out any previous declarations that the given declaration 1749 /// should not consider because they are not permitted to conflict, e.g., 1750 /// because they come from hidden sub-modules and do not refer to the same 1751 /// entity. 1752 static void filterNonConflictingPreviousDecls(ASTContext &context, 1753 NamedDecl *decl, 1754 LookupResult &previous){ 1755 // This is only interesting when modules are enabled. 1756 if (!context.getLangOpts().Modules) 1757 return; 1758 1759 // Empty sets are uninteresting. 1760 if (previous.empty()) 1761 return; 1762 1763 LookupResult::Filter filter = previous.makeFilter(); 1764 while (filter.hasNext()) { 1765 NamedDecl *old = filter.next(); 1766 1767 // Non-hidden declarations are never ignored. 1768 if (!old->isHidden()) 1769 continue; 1770 1771 if (!old->isExternallyVisible()) 1772 filter.erase(); 1773 } 1774 1775 filter.done(); 1776 } 1777 1778 /// Typedef declarations don't have linkage, but they still denote the same 1779 /// entity if their types are the same. 1780 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's 1781 /// isSameEntity. 1782 static void filterNonConflictingPreviousTypedefDecls(ASTContext &Context, 1783 TypedefNameDecl *Decl, 1784 LookupResult &Previous) { 1785 // This is only interesting when modules are enabled. 1786 if (!Context.getLangOpts().Modules) 1787 return; 1788 1789 // Empty sets are uninteresting. 1790 if (Previous.empty()) 1791 return; 1792 1793 LookupResult::Filter Filter = Previous.makeFilter(); 1794 while (Filter.hasNext()) { 1795 NamedDecl *Old = Filter.next(); 1796 1797 // Non-hidden declarations are never ignored. 1798 if (!Old->isHidden()) 1799 continue; 1800 1801 // Declarations of the same entity are not ignored, even if they have 1802 // different linkages. 1803 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) 1804 if (Context.hasSameType(OldTD->getUnderlyingType(), 1805 Decl->getUnderlyingType())) 1806 continue; 1807 1808 if (!Old->isExternallyVisible()) 1809 Filter.erase(); 1810 } 1811 1812 Filter.done(); 1813 } 1814 1815 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) { 1816 QualType OldType; 1817 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old)) 1818 OldType = OldTypedef->getUnderlyingType(); 1819 else 1820 OldType = Context.getTypeDeclType(Old); 1821 QualType NewType = New->getUnderlyingType(); 1822 1823 if (NewType->isVariablyModifiedType()) { 1824 // Must not redefine a typedef with a variably-modified type. 1825 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1826 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef) 1827 << Kind << NewType; 1828 if (Old->getLocation().isValid()) 1829 Diag(Old->getLocation(), diag::note_previous_definition); 1830 New->setInvalidDecl(); 1831 return true; 1832 } 1833 1834 if (OldType != NewType && 1835 !OldType->isDependentType() && 1836 !NewType->isDependentType() && 1837 !Context.hasSameType(OldType, NewType)) { 1838 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0; 1839 Diag(New->getLocation(), diag::err_redefinition_different_typedef) 1840 << Kind << NewType << OldType; 1841 if (Old->getLocation().isValid()) 1842 Diag(Old->getLocation(), diag::note_previous_definition); 1843 New->setInvalidDecl(); 1844 return true; 1845 } 1846 return false; 1847 } 1848 1849 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the 1850 /// same name and scope as a previous declaration 'Old'. Figure out 1851 /// how to resolve this situation, merging decls or emitting 1852 /// diagnostics as appropriate. If there was an error, set New to be invalid. 1853 /// 1854 void Sema::MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls) { 1855 // If the new decl is known invalid already, don't bother doing any 1856 // merging checks. 1857 if (New->isInvalidDecl()) return; 1858 1859 // Allow multiple definitions for ObjC built-in typedefs. 1860 // FIXME: Verify the underlying types are equivalent! 1861 if (getLangOpts().ObjC1) { 1862 const IdentifierInfo *TypeID = New->getIdentifier(); 1863 switch (TypeID->getLength()) { 1864 default: break; 1865 case 2: 1866 { 1867 if (!TypeID->isStr("id")) 1868 break; 1869 QualType T = New->getUnderlyingType(); 1870 if (!T->isPointerType()) 1871 break; 1872 if (!T->isVoidPointerType()) { 1873 QualType PT = T->getAs<PointerType>()->getPointeeType(); 1874 if (!PT->isStructureType()) 1875 break; 1876 } 1877 Context.setObjCIdRedefinitionType(T); 1878 // Install the built-in type for 'id', ignoring the current definition. 1879 New->setTypeForDecl(Context.getObjCIdType().getTypePtr()); 1880 return; 1881 } 1882 case 5: 1883 if (!TypeID->isStr("Class")) 1884 break; 1885 Context.setObjCClassRedefinitionType(New->getUnderlyingType()); 1886 // Install the built-in type for 'Class', ignoring the current definition. 1887 New->setTypeForDecl(Context.getObjCClassType().getTypePtr()); 1888 return; 1889 case 3: 1890 if (!TypeID->isStr("SEL")) 1891 break; 1892 Context.setObjCSelRedefinitionType(New->getUnderlyingType()); 1893 // Install the built-in type for 'SEL', ignoring the current definition. 1894 New->setTypeForDecl(Context.getObjCSelType().getTypePtr()); 1895 return; 1896 } 1897 // Fall through - the typedef name was not a builtin type. 1898 } 1899 1900 // Verify the old decl was also a type. 1901 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>(); 1902 if (!Old) { 1903 Diag(New->getLocation(), diag::err_redefinition_different_kind) 1904 << New->getDeclName(); 1905 1906 NamedDecl *OldD = OldDecls.getRepresentativeDecl(); 1907 if (OldD->getLocation().isValid()) 1908 Diag(OldD->getLocation(), diag::note_previous_definition); 1909 1910 return New->setInvalidDecl(); 1911 } 1912 1913 // If the old declaration is invalid, just give up here. 1914 if (Old->isInvalidDecl()) 1915 return New->setInvalidDecl(); 1916 1917 // If the typedef types are not identical, reject them in all languages and 1918 // with any extensions enabled. 1919 if (isIncompatibleTypedef(Old, New)) 1920 return; 1921 1922 // The types match. Link up the redeclaration chain and merge attributes if 1923 // the old declaration was a typedef. 1924 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) { 1925 New->setPreviousDecl(Typedef); 1926 mergeDeclAttributes(New, Old); 1927 } 1928 1929 if (getLangOpts().MicrosoftExt) 1930 return; 1931 1932 if (getLangOpts().CPlusPlus) { 1933 // C++ [dcl.typedef]p2: 1934 // In a given non-class scope, a typedef specifier can be used to 1935 // redefine the name of any type declared in that scope to refer 1936 // to the type to which it already refers. 1937 if (!isa<CXXRecordDecl>(CurContext)) 1938 return; 1939 1940 // C++0x [dcl.typedef]p4: 1941 // In a given class scope, a typedef specifier can be used to redefine 1942 // any class-name declared in that scope that is not also a typedef-name 1943 // to refer to the type to which it already refers. 1944 // 1945 // This wording came in via DR424, which was a correction to the 1946 // wording in DR56, which accidentally banned code like: 1947 // 1948 // struct S { 1949 // typedef struct A { } A; 1950 // }; 1951 // 1952 // in the C++03 standard. We implement the C++0x semantics, which 1953 // allow the above but disallow 1954 // 1955 // struct S { 1956 // typedef int I; 1957 // typedef int I; 1958 // }; 1959 // 1960 // since that was the intent of DR56. 1961 if (!isa<TypedefNameDecl>(Old)) 1962 return; 1963 1964 Diag(New->getLocation(), diag::err_redefinition) 1965 << New->getDeclName(); 1966 Diag(Old->getLocation(), diag::note_previous_definition); 1967 return New->setInvalidDecl(); 1968 } 1969 1970 // Modules always permit redefinition of typedefs, as does C11. 1971 if (getLangOpts().Modules || getLangOpts().C11) 1972 return; 1973 1974 // If we have a redefinition of a typedef in C, emit a warning. This warning 1975 // is normally mapped to an error, but can be controlled with 1976 // -Wtypedef-redefinition. If either the original or the redefinition is 1977 // in a system header, don't emit this for compatibility with GCC. 1978 if (getDiagnostics().getSuppressSystemWarnings() && 1979 (Context.getSourceManager().isInSystemHeader(Old->getLocation()) || 1980 Context.getSourceManager().isInSystemHeader(New->getLocation()))) 1981 return; 1982 1983 Diag(New->getLocation(), diag::ext_redefinition_of_typedef) 1984 << New->getDeclName(); 1985 Diag(Old->getLocation(), diag::note_previous_definition); 1986 return; 1987 } 1988 1989 /// DeclhasAttr - returns true if decl Declaration already has the target 1990 /// attribute. 1991 static bool DeclHasAttr(const Decl *D, const Attr *A) { 1992 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A); 1993 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A); 1994 for (const auto *i : D->attrs()) 1995 if (i->getKind() == A->getKind()) { 1996 if (Ann) { 1997 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation()) 1998 return true; 1999 continue; 2000 } 2001 // FIXME: Don't hardcode this check 2002 if (OA && isa<OwnershipAttr>(i)) 2003 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind(); 2004 return true; 2005 } 2006 2007 return false; 2008 } 2009 2010 static bool isAttributeTargetADefinition(Decl *D) { 2011 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 2012 return VD->isThisDeclarationADefinition(); 2013 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 2014 return TD->isCompleteDefinition() || TD->isBeingDefined(); 2015 return true; 2016 } 2017 2018 /// Merge alignment attributes from \p Old to \p New, taking into account the 2019 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute. 2020 /// 2021 /// \return \c true if any attributes were added to \p New. 2022 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) { 2023 // Look for alignas attributes on Old, and pick out whichever attribute 2024 // specifies the strictest alignment requirement. 2025 AlignedAttr *OldAlignasAttr = nullptr; 2026 AlignedAttr *OldStrictestAlignAttr = nullptr; 2027 unsigned OldAlign = 0; 2028 for (auto *I : Old->specific_attrs<AlignedAttr>()) { 2029 // FIXME: We have no way of representing inherited dependent alignments 2030 // in a case like: 2031 // template<int A, int B> struct alignas(A) X; 2032 // template<int A, int B> struct alignas(B) X {}; 2033 // For now, we just ignore any alignas attributes which are not on the 2034 // definition in such a case. 2035 if (I->isAlignmentDependent()) 2036 return false; 2037 2038 if (I->isAlignas()) 2039 OldAlignasAttr = I; 2040 2041 unsigned Align = I->getAlignment(S.Context); 2042 if (Align > OldAlign) { 2043 OldAlign = Align; 2044 OldStrictestAlignAttr = I; 2045 } 2046 } 2047 2048 // Look for alignas attributes on New. 2049 AlignedAttr *NewAlignasAttr = nullptr; 2050 unsigned NewAlign = 0; 2051 for (auto *I : New->specific_attrs<AlignedAttr>()) { 2052 if (I->isAlignmentDependent()) 2053 return false; 2054 2055 if (I->isAlignas()) 2056 NewAlignasAttr = I; 2057 2058 unsigned Align = I->getAlignment(S.Context); 2059 if (Align > NewAlign) 2060 NewAlign = Align; 2061 } 2062 2063 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) { 2064 // Both declarations have 'alignas' attributes. We require them to match. 2065 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but 2066 // fall short. (If two declarations both have alignas, they must both match 2067 // every definition, and so must match each other if there is a definition.) 2068 2069 // If either declaration only contains 'alignas(0)' specifiers, then it 2070 // specifies the natural alignment for the type. 2071 if (OldAlign == 0 || NewAlign == 0) { 2072 QualType Ty; 2073 if (ValueDecl *VD = dyn_cast<ValueDecl>(New)) 2074 Ty = VD->getType(); 2075 else 2076 Ty = S.Context.getTagDeclType(cast<TagDecl>(New)); 2077 2078 if (OldAlign == 0) 2079 OldAlign = S.Context.getTypeAlign(Ty); 2080 if (NewAlign == 0) 2081 NewAlign = S.Context.getTypeAlign(Ty); 2082 } 2083 2084 if (OldAlign != NewAlign) { 2085 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch) 2086 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity() 2087 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity(); 2088 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration); 2089 } 2090 } 2091 2092 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) { 2093 // C++11 [dcl.align]p6: 2094 // if any declaration of an entity has an alignment-specifier, 2095 // every defining declaration of that entity shall specify an 2096 // equivalent alignment. 2097 // C11 6.7.5/7: 2098 // If the definition of an object does not have an alignment 2099 // specifier, any other declaration of that object shall also 2100 // have no alignment specifier. 2101 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition) 2102 << OldAlignasAttr; 2103 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration) 2104 << OldAlignasAttr; 2105 } 2106 2107 bool AnyAdded = false; 2108 2109 // Ensure we have an attribute representing the strictest alignment. 2110 if (OldAlign > NewAlign) { 2111 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context); 2112 Clone->setInherited(true); 2113 New->addAttr(Clone); 2114 AnyAdded = true; 2115 } 2116 2117 // Ensure we have an alignas attribute if the old declaration had one. 2118 if (OldAlignasAttr && !NewAlignasAttr && 2119 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) { 2120 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context); 2121 Clone->setInherited(true); 2122 New->addAttr(Clone); 2123 AnyAdded = true; 2124 } 2125 2126 return AnyAdded; 2127 } 2128 2129 static bool mergeDeclAttribute(Sema &S, NamedDecl *D, 2130 const InheritableAttr *Attr, bool Override) { 2131 InheritableAttr *NewAttr = nullptr; 2132 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex(); 2133 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr)) 2134 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(), 2135 AA->getIntroduced(), AA->getDeprecated(), 2136 AA->getObsoleted(), AA->getUnavailable(), 2137 AA->getMessage(), Override, 2138 AttrSpellingListIndex); 2139 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr)) 2140 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2141 AttrSpellingListIndex); 2142 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr)) 2143 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(), 2144 AttrSpellingListIndex); 2145 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr)) 2146 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(), 2147 AttrSpellingListIndex); 2148 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr)) 2149 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(), 2150 AttrSpellingListIndex); 2151 else if (const auto *FA = dyn_cast<FormatAttr>(Attr)) 2152 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(), 2153 FA->getFormatIdx(), FA->getFirstArg(), 2154 AttrSpellingListIndex); 2155 else if (const auto *SA = dyn_cast<SectionAttr>(Attr)) 2156 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(), 2157 AttrSpellingListIndex); 2158 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr)) 2159 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(), 2160 AttrSpellingListIndex, 2161 IA->getSemanticSpelling()); 2162 else if (isa<AlignedAttr>(Attr)) 2163 // AlignedAttrs are handled separately, because we need to handle all 2164 // such attributes on a declaration at the same time. 2165 NewAttr = nullptr; 2166 else if (isa<DeprecatedAttr>(Attr) && Override) 2167 NewAttr = nullptr; 2168 else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr)) 2169 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context)); 2170 2171 if (NewAttr) { 2172 NewAttr->setInherited(true); 2173 D->addAttr(NewAttr); 2174 return true; 2175 } 2176 2177 return false; 2178 } 2179 2180 static const Decl *getDefinition(const Decl *D) { 2181 if (const TagDecl *TD = dyn_cast<TagDecl>(D)) 2182 return TD->getDefinition(); 2183 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 2184 const VarDecl *Def = VD->getDefinition(); 2185 if (Def) 2186 return Def; 2187 return VD->getActingDefinition(); 2188 } 2189 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2190 const FunctionDecl* Def; 2191 if (FD->isDefined(Def)) 2192 return Def; 2193 } 2194 return nullptr; 2195 } 2196 2197 static bool hasAttribute(const Decl *D, attr::Kind Kind) { 2198 for (const auto *Attribute : D->attrs()) 2199 if (Attribute->getKind() == Kind) 2200 return true; 2201 return false; 2202 } 2203 2204 /// checkNewAttributesAfterDef - If we already have a definition, check that 2205 /// there are no new attributes in this declaration. 2206 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) { 2207 if (!New->hasAttrs()) 2208 return; 2209 2210 const Decl *Def = getDefinition(Old); 2211 if (!Def || Def == New) 2212 return; 2213 2214 AttrVec &NewAttributes = New->getAttrs(); 2215 for (unsigned I = 0, E = NewAttributes.size(); I != E;) { 2216 const Attr *NewAttribute = NewAttributes[I]; 2217 2218 if (isa<AliasAttr>(NewAttribute)) { 2219 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) 2220 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def)); 2221 else { 2222 VarDecl *VD = cast<VarDecl>(New); 2223 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() == 2224 VarDecl::TentativeDefinition 2225 ? diag::err_alias_after_tentative 2226 : diag::err_redefinition; 2227 S.Diag(VD->getLocation(), Diag) << VD->getDeclName(); 2228 S.Diag(Def->getLocation(), diag::note_previous_definition); 2229 VD->setInvalidDecl(); 2230 } 2231 ++I; 2232 continue; 2233 } 2234 2235 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) { 2236 // Tentative definitions are only interesting for the alias check above. 2237 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) { 2238 ++I; 2239 continue; 2240 } 2241 } 2242 2243 if (hasAttribute(Def, NewAttribute->getKind())) { 2244 ++I; 2245 continue; // regular attr merging will take care of validating this. 2246 } 2247 2248 if (isa<C11NoReturnAttr>(NewAttribute)) { 2249 // C's _Noreturn is allowed to be added to a function after it is defined. 2250 ++I; 2251 continue; 2252 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) { 2253 if (AA->isAlignas()) { 2254 // C++11 [dcl.align]p6: 2255 // if any declaration of an entity has an alignment-specifier, 2256 // every defining declaration of that entity shall specify an 2257 // equivalent alignment. 2258 // C11 6.7.5/7: 2259 // If the definition of an object does not have an alignment 2260 // specifier, any other declaration of that object shall also 2261 // have no alignment specifier. 2262 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition) 2263 << AA; 2264 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration) 2265 << AA; 2266 NewAttributes.erase(NewAttributes.begin() + I); 2267 --E; 2268 continue; 2269 } 2270 } 2271 2272 S.Diag(NewAttribute->getLocation(), 2273 diag::warn_attribute_precede_definition); 2274 S.Diag(Def->getLocation(), diag::note_previous_definition); 2275 NewAttributes.erase(NewAttributes.begin() + I); 2276 --E; 2277 } 2278 } 2279 2280 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one. 2281 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old, 2282 AvailabilityMergeKind AMK) { 2283 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) { 2284 UsedAttr *NewAttr = OldAttr->clone(Context); 2285 NewAttr->setInherited(true); 2286 New->addAttr(NewAttr); 2287 } 2288 2289 if (!Old->hasAttrs() && !New->hasAttrs()) 2290 return; 2291 2292 // attributes declared post-definition are currently ignored 2293 checkNewAttributesAfterDef(*this, New, Old); 2294 2295 if (!Old->hasAttrs()) 2296 return; 2297 2298 bool foundAny = New->hasAttrs(); 2299 2300 // Ensure that any moving of objects within the allocated map is done before 2301 // we process them. 2302 if (!foundAny) New->setAttrs(AttrVec()); 2303 2304 for (auto *I : Old->specific_attrs<InheritableAttr>()) { 2305 bool Override = false; 2306 // Ignore deprecated/unavailable/availability attributes if requested. 2307 if (isa<DeprecatedAttr>(I) || 2308 isa<UnavailableAttr>(I) || 2309 isa<AvailabilityAttr>(I)) { 2310 switch (AMK) { 2311 case AMK_None: 2312 continue; 2313 2314 case AMK_Redeclaration: 2315 break; 2316 2317 case AMK_Override: 2318 Override = true; 2319 break; 2320 } 2321 } 2322 2323 // Already handled. 2324 if (isa<UsedAttr>(I)) 2325 continue; 2326 2327 if (mergeDeclAttribute(*this, New, I, Override)) 2328 foundAny = true; 2329 } 2330 2331 if (mergeAlignedAttrs(*this, New, Old)) 2332 foundAny = true; 2333 2334 if (!foundAny) New->dropAttrs(); 2335 } 2336 2337 /// mergeParamDeclAttributes - Copy attributes from the old parameter 2338 /// to the new one. 2339 static void mergeParamDeclAttributes(ParmVarDecl *newDecl, 2340 const ParmVarDecl *oldDecl, 2341 Sema &S) { 2342 // C++11 [dcl.attr.depend]p2: 2343 // The first declaration of a function shall specify the 2344 // carries_dependency attribute for its declarator-id if any declaration 2345 // of the function specifies the carries_dependency attribute. 2346 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>(); 2347 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) { 2348 S.Diag(CDA->getLocation(), 2349 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/; 2350 // Find the first declaration of the parameter. 2351 // FIXME: Should we build redeclaration chains for function parameters? 2352 const FunctionDecl *FirstFD = 2353 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl(); 2354 const ParmVarDecl *FirstVD = 2355 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex()); 2356 S.Diag(FirstVD->getLocation(), 2357 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/; 2358 } 2359 2360 if (!oldDecl->hasAttrs()) 2361 return; 2362 2363 bool foundAny = newDecl->hasAttrs(); 2364 2365 // Ensure that any moving of objects within the allocated map is 2366 // done before we process them. 2367 if (!foundAny) newDecl->setAttrs(AttrVec()); 2368 2369 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) { 2370 if (!DeclHasAttr(newDecl, I)) { 2371 InheritableAttr *newAttr = 2372 cast<InheritableParamAttr>(I->clone(S.Context)); 2373 newAttr->setInherited(true); 2374 newDecl->addAttr(newAttr); 2375 foundAny = true; 2376 } 2377 } 2378 2379 if (!foundAny) newDecl->dropAttrs(); 2380 } 2381 2382 namespace { 2383 2384 /// Used in MergeFunctionDecl to keep track of function parameters in 2385 /// C. 2386 struct GNUCompatibleParamWarning { 2387 ParmVarDecl *OldParm; 2388 ParmVarDecl *NewParm; 2389 QualType PromotedType; 2390 }; 2391 2392 } 2393 2394 /// getSpecialMember - get the special member enum for a method. 2395 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) { 2396 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 2397 if (Ctor->isDefaultConstructor()) 2398 return Sema::CXXDefaultConstructor; 2399 2400 if (Ctor->isCopyConstructor()) 2401 return Sema::CXXCopyConstructor; 2402 2403 if (Ctor->isMoveConstructor()) 2404 return Sema::CXXMoveConstructor; 2405 } else if (isa<CXXDestructorDecl>(MD)) { 2406 return Sema::CXXDestructor; 2407 } else if (MD->isCopyAssignmentOperator()) { 2408 return Sema::CXXCopyAssignment; 2409 } else if (MD->isMoveAssignmentOperator()) { 2410 return Sema::CXXMoveAssignment; 2411 } 2412 2413 return Sema::CXXInvalid; 2414 } 2415 2416 // Determine whether the previous declaration was a definition, implicit 2417 // declaration, or a declaration. 2418 template <typename T> 2419 static std::pair<diag::kind, SourceLocation> 2420 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) { 2421 diag::kind PrevDiag; 2422 SourceLocation OldLocation = Old->getLocation(); 2423 if (Old->isThisDeclarationADefinition()) 2424 PrevDiag = diag::note_previous_definition; 2425 else if (Old->isImplicit()) { 2426 PrevDiag = diag::note_previous_implicit_declaration; 2427 if (OldLocation.isInvalid()) 2428 OldLocation = New->getLocation(); 2429 } else 2430 PrevDiag = diag::note_previous_declaration; 2431 return std::make_pair(PrevDiag, OldLocation); 2432 } 2433 2434 /// canRedefineFunction - checks if a function can be redefined. Currently, 2435 /// only extern inline functions can be redefined, and even then only in 2436 /// GNU89 mode. 2437 static bool canRedefineFunction(const FunctionDecl *FD, 2438 const LangOptions& LangOpts) { 2439 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) && 2440 !LangOpts.CPlusPlus && 2441 FD->isInlineSpecified() && 2442 FD->getStorageClass() == SC_Extern); 2443 } 2444 2445 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const { 2446 const AttributedType *AT = T->getAs<AttributedType>(); 2447 while (AT && !AT->isCallingConv()) 2448 AT = AT->getModifiedType()->getAs<AttributedType>(); 2449 return AT; 2450 } 2451 2452 template <typename T> 2453 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) { 2454 const DeclContext *DC = Old->getDeclContext(); 2455 if (DC->isRecord()) 2456 return false; 2457 2458 LanguageLinkage OldLinkage = Old->getLanguageLinkage(); 2459 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext()) 2460 return true; 2461 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext()) 2462 return true; 2463 return false; 2464 } 2465 2466 /// MergeFunctionDecl - We just parsed a function 'New' from 2467 /// declarator D which has the same name and scope as a previous 2468 /// declaration 'Old'. Figure out how to resolve this situation, 2469 /// merging decls or emitting diagnostics as appropriate. 2470 /// 2471 /// In C++, New and Old must be declarations that are not 2472 /// overloaded. Use IsOverload to determine whether New and Old are 2473 /// overloaded, and to select the Old declaration that New should be 2474 /// merged with. 2475 /// 2476 /// Returns true if there was an error, false otherwise. 2477 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD, 2478 Scope *S, bool MergeTypeWithOld) { 2479 // Verify the old decl was also a function. 2480 FunctionDecl *Old = OldD->getAsFunction(); 2481 if (!Old) { 2482 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) { 2483 if (New->getFriendObjectKind()) { 2484 Diag(New->getLocation(), diag::err_using_decl_friend); 2485 Diag(Shadow->getTargetDecl()->getLocation(), 2486 diag::note_using_decl_target); 2487 Diag(Shadow->getUsingDecl()->getLocation(), 2488 diag::note_using_decl) << 0; 2489 return true; 2490 } 2491 2492 // C++11 [namespace.udecl]p14: 2493 // If a function declaration in namespace scope or block scope has the 2494 // same name and the same parameter-type-list as a function introduced 2495 // by a using-declaration, and the declarations do not declare the same 2496 // function, the program is ill-formed. 2497 2498 // Check whether the two declarations might declare the same function. 2499 Old = dyn_cast<FunctionDecl>(Shadow->getTargetDecl()); 2500 if (Old && 2501 !Old->getDeclContext()->getRedeclContext()->Equals( 2502 New->getDeclContext()->getRedeclContext()) && 2503 !(Old->isExternC() && New->isExternC())) 2504 Old = nullptr; 2505 2506 if (!Old) { 2507 Diag(New->getLocation(), diag::err_using_decl_conflict_reverse); 2508 Diag(Shadow->getTargetDecl()->getLocation(), 2509 diag::note_using_decl_target); 2510 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl) << 0; 2511 return true; 2512 } 2513 OldD = Old; 2514 } else { 2515 Diag(New->getLocation(), diag::err_redefinition_different_kind) 2516 << New->getDeclName(); 2517 Diag(OldD->getLocation(), diag::note_previous_definition); 2518 return true; 2519 } 2520 } 2521 2522 // If the old declaration is invalid, just give up here. 2523 if (Old->isInvalidDecl()) 2524 return true; 2525 2526 diag::kind PrevDiag; 2527 SourceLocation OldLocation; 2528 std::tie(PrevDiag, OldLocation) = 2529 getNoteDiagForInvalidRedeclaration(Old, New); 2530 2531 // Don't complain about this if we're in GNU89 mode and the old function 2532 // is an extern inline function. 2533 // Don't complain about specializations. They are not supposed to have 2534 // storage classes. 2535 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) && 2536 New->getStorageClass() == SC_Static && 2537 Old->hasExternalFormalLinkage() && 2538 !New->getTemplateSpecializationInfo() && 2539 !canRedefineFunction(Old, getLangOpts())) { 2540 if (getLangOpts().MicrosoftExt) { 2541 Diag(New->getLocation(), diag::ext_static_non_static) << New; 2542 Diag(OldLocation, PrevDiag); 2543 } else { 2544 Diag(New->getLocation(), diag::err_static_non_static) << New; 2545 Diag(OldLocation, PrevDiag); 2546 return true; 2547 } 2548 } 2549 2550 2551 // If a function is first declared with a calling convention, but is later 2552 // declared or defined without one, all following decls assume the calling 2553 // convention of the first. 2554 // 2555 // It's OK if a function is first declared without a calling convention, 2556 // but is later declared or defined with the default calling convention. 2557 // 2558 // To test if either decl has an explicit calling convention, we look for 2559 // AttributedType sugar nodes on the type as written. If they are missing or 2560 // were canonicalized away, we assume the calling convention was implicit. 2561 // 2562 // Note also that we DO NOT return at this point, because we still have 2563 // other tests to run. 2564 QualType OldQType = Context.getCanonicalType(Old->getType()); 2565 QualType NewQType = Context.getCanonicalType(New->getType()); 2566 const FunctionType *OldType = cast<FunctionType>(OldQType); 2567 const FunctionType *NewType = cast<FunctionType>(NewQType); 2568 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo(); 2569 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 2570 bool RequiresAdjustment = false; 2571 2572 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) { 2573 FunctionDecl *First = Old->getFirstDecl(); 2574 const FunctionType *FT = 2575 First->getType().getCanonicalType()->castAs<FunctionType>(); 2576 FunctionType::ExtInfo FI = FT->getExtInfo(); 2577 bool NewCCExplicit = getCallingConvAttributedType(New->getType()); 2578 if (!NewCCExplicit) { 2579 // Inherit the CC from the previous declaration if it was specified 2580 // there but not here. 2581 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC()); 2582 RequiresAdjustment = true; 2583 } else { 2584 // Calling conventions aren't compatible, so complain. 2585 bool FirstCCExplicit = getCallingConvAttributedType(First->getType()); 2586 Diag(New->getLocation(), diag::err_cconv_change) 2587 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()) 2588 << !FirstCCExplicit 2589 << (!FirstCCExplicit ? "" : 2590 FunctionType::getNameForCallConv(FI.getCC())); 2591 2592 // Put the note on the first decl, since it is the one that matters. 2593 Diag(First->getLocation(), diag::note_previous_declaration); 2594 return true; 2595 } 2596 } 2597 2598 // FIXME: diagnose the other way around? 2599 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) { 2600 NewTypeInfo = NewTypeInfo.withNoReturn(true); 2601 RequiresAdjustment = true; 2602 } 2603 2604 // Merge regparm attribute. 2605 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() || 2606 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) { 2607 if (NewTypeInfo.getHasRegParm()) { 2608 Diag(New->getLocation(), diag::err_regparm_mismatch) 2609 << NewType->getRegParmType() 2610 << OldType->getRegParmType(); 2611 Diag(OldLocation, diag::note_previous_declaration); 2612 return true; 2613 } 2614 2615 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm()); 2616 RequiresAdjustment = true; 2617 } 2618 2619 // Merge ns_returns_retained attribute. 2620 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) { 2621 if (NewTypeInfo.getProducesResult()) { 2622 Diag(New->getLocation(), diag::err_returns_retained_mismatch); 2623 Diag(OldLocation, diag::note_previous_declaration); 2624 return true; 2625 } 2626 2627 NewTypeInfo = NewTypeInfo.withProducesResult(true); 2628 RequiresAdjustment = true; 2629 } 2630 2631 if (RequiresAdjustment) { 2632 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>(); 2633 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo); 2634 New->setType(QualType(AdjustedType, 0)); 2635 NewQType = Context.getCanonicalType(New->getType()); 2636 NewType = cast<FunctionType>(NewQType); 2637 } 2638 2639 // If this redeclaration makes the function inline, we may need to add it to 2640 // UndefinedButUsed. 2641 if (!Old->isInlined() && New->isInlined() && 2642 !New->hasAttr<GNUInlineAttr>() && 2643 (getLangOpts().CPlusPlus || !getLangOpts().GNUInline) && 2644 Old->isUsed(false) && 2645 !Old->isDefined() && !New->isThisDeclarationADefinition()) 2646 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(), 2647 SourceLocation())); 2648 2649 // If this redeclaration makes it newly gnu_inline, we don't want to warn 2650 // about it. 2651 if (New->hasAttr<GNUInlineAttr>() && 2652 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) { 2653 UndefinedButUsed.erase(Old->getCanonicalDecl()); 2654 } 2655 2656 if (getLangOpts().CPlusPlus) { 2657 // (C++98 13.1p2): 2658 // Certain function declarations cannot be overloaded: 2659 // -- Function declarations that differ only in the return type 2660 // cannot be overloaded. 2661 2662 // Go back to the type source info to compare the declared return types, 2663 // per C++1y [dcl.type.auto]p13: 2664 // Redeclarations or specializations of a function or function template 2665 // with a declared return type that uses a placeholder type shall also 2666 // use that placeholder, not a deduced type. 2667 QualType OldDeclaredReturnType = 2668 (Old->getTypeSourceInfo() 2669 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2670 : OldType)->getReturnType(); 2671 QualType NewDeclaredReturnType = 2672 (New->getTypeSourceInfo() 2673 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>() 2674 : NewType)->getReturnType(); 2675 QualType ResQT; 2676 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) && 2677 !((NewQType->isDependentType() || OldQType->isDependentType()) && 2678 New->isLocalExternDecl())) { 2679 if (NewDeclaredReturnType->isObjCObjectPointerType() && 2680 OldDeclaredReturnType->isObjCObjectPointerType()) 2681 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType); 2682 if (ResQT.isNull()) { 2683 if (New->isCXXClassMember() && New->isOutOfLine()) 2684 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type) 2685 << New << New->getReturnTypeSourceRange(); 2686 else 2687 Diag(New->getLocation(), diag::err_ovl_diff_return_type) 2688 << New->getReturnTypeSourceRange(); 2689 Diag(OldLocation, PrevDiag) << Old << Old->getType() 2690 << Old->getReturnTypeSourceRange(); 2691 return true; 2692 } 2693 else 2694 NewQType = ResQT; 2695 } 2696 2697 QualType OldReturnType = OldType->getReturnType(); 2698 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType(); 2699 if (OldReturnType != NewReturnType) { 2700 // If this function has a deduced return type and has already been 2701 // defined, copy the deduced value from the old declaration. 2702 AutoType *OldAT = Old->getReturnType()->getContainedAutoType(); 2703 if (OldAT && OldAT->isDeduced()) { 2704 New->setType( 2705 SubstAutoType(New->getType(), 2706 OldAT->isDependentType() ? Context.DependentTy 2707 : OldAT->getDeducedType())); 2708 NewQType = Context.getCanonicalType( 2709 SubstAutoType(NewQType, 2710 OldAT->isDependentType() ? Context.DependentTy 2711 : OldAT->getDeducedType())); 2712 } 2713 } 2714 2715 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 2716 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 2717 if (OldMethod && NewMethod) { 2718 // Preserve triviality. 2719 NewMethod->setTrivial(OldMethod->isTrivial()); 2720 2721 // MSVC allows explicit template specialization at class scope: 2722 // 2 CXXMethodDecls referring to the same function will be injected. 2723 // We don't want a redeclaration error. 2724 bool IsClassScopeExplicitSpecialization = 2725 OldMethod->isFunctionTemplateSpecialization() && 2726 NewMethod->isFunctionTemplateSpecialization(); 2727 bool isFriend = NewMethod->getFriendObjectKind(); 2728 2729 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() && 2730 !IsClassScopeExplicitSpecialization) { 2731 // -- Member function declarations with the same name and the 2732 // same parameter types cannot be overloaded if any of them 2733 // is a static member function declaration. 2734 if (OldMethod->isStatic() != NewMethod->isStatic()) { 2735 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member); 2736 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2737 return true; 2738 } 2739 2740 // C++ [class.mem]p1: 2741 // [...] A member shall not be declared twice in the 2742 // member-specification, except that a nested class or member 2743 // class template can be declared and then later defined. 2744 if (ActiveTemplateInstantiations.empty()) { 2745 unsigned NewDiag; 2746 if (isa<CXXConstructorDecl>(OldMethod)) 2747 NewDiag = diag::err_constructor_redeclared; 2748 else if (isa<CXXDestructorDecl>(NewMethod)) 2749 NewDiag = diag::err_destructor_redeclared; 2750 else if (isa<CXXConversionDecl>(NewMethod)) 2751 NewDiag = diag::err_conv_function_redeclared; 2752 else 2753 NewDiag = diag::err_member_redeclared; 2754 2755 Diag(New->getLocation(), NewDiag); 2756 } else { 2757 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation) 2758 << New << New->getType(); 2759 } 2760 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2761 2762 // Complain if this is an explicit declaration of a special 2763 // member that was initially declared implicitly. 2764 // 2765 // As an exception, it's okay to befriend such methods in order 2766 // to permit the implicit constructor/destructor/operator calls. 2767 } else if (OldMethod->isImplicit()) { 2768 if (isFriend) { 2769 NewMethod->setImplicit(); 2770 } else { 2771 Diag(NewMethod->getLocation(), 2772 diag::err_definition_of_implicitly_declared_member) 2773 << New << getSpecialMember(OldMethod); 2774 return true; 2775 } 2776 } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) { 2777 Diag(NewMethod->getLocation(), 2778 diag::err_definition_of_explicitly_defaulted_member) 2779 << getSpecialMember(OldMethod); 2780 return true; 2781 } 2782 } 2783 2784 // C++11 [dcl.attr.noreturn]p1: 2785 // The first declaration of a function shall specify the noreturn 2786 // attribute if any declaration of that function specifies the noreturn 2787 // attribute. 2788 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>(); 2789 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) { 2790 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl); 2791 Diag(Old->getFirstDecl()->getLocation(), 2792 diag::note_noreturn_missing_first_decl); 2793 } 2794 2795 // C++11 [dcl.attr.depend]p2: 2796 // The first declaration of a function shall specify the 2797 // carries_dependency attribute for its declarator-id if any declaration 2798 // of the function specifies the carries_dependency attribute. 2799 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>(); 2800 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) { 2801 Diag(CDA->getLocation(), 2802 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/; 2803 Diag(Old->getFirstDecl()->getLocation(), 2804 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/; 2805 } 2806 2807 // (C++98 8.3.5p3): 2808 // All declarations for a function shall agree exactly in both the 2809 // return type and the parameter-type-list. 2810 // We also want to respect all the extended bits except noreturn. 2811 2812 // noreturn should now match unless the old type info didn't have it. 2813 QualType OldQTypeForComparison = OldQType; 2814 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) { 2815 assert(OldQType == QualType(OldType, 0)); 2816 const FunctionType *OldTypeForComparison 2817 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true)); 2818 OldQTypeForComparison = QualType(OldTypeForComparison, 0); 2819 assert(OldQTypeForComparison.isCanonical()); 2820 } 2821 2822 if (haveIncompatibleLanguageLinkages(Old, New)) { 2823 // As a special case, retain the language linkage from previous 2824 // declarations of a friend function as an extension. 2825 // 2826 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC 2827 // and is useful because there's otherwise no way to specify language 2828 // linkage within class scope. 2829 // 2830 // Check cautiously as the friend object kind isn't yet complete. 2831 if (New->getFriendObjectKind() != Decl::FOK_None) { 2832 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New; 2833 Diag(OldLocation, PrevDiag); 2834 } else { 2835 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 2836 Diag(OldLocation, PrevDiag); 2837 return true; 2838 } 2839 } 2840 2841 if (OldQTypeForComparison == NewQType) 2842 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2843 2844 if ((NewQType->isDependentType() || OldQType->isDependentType()) && 2845 New->isLocalExternDecl()) { 2846 // It's OK if we couldn't merge types for a local function declaraton 2847 // if either the old or new type is dependent. We'll merge the types 2848 // when we instantiate the function. 2849 return false; 2850 } 2851 2852 // Fall through for conflicting redeclarations and redefinitions. 2853 } 2854 2855 // C: Function types need to be compatible, not identical. This handles 2856 // duplicate function decls like "void f(int); void f(enum X);" properly. 2857 if (!getLangOpts().CPlusPlus && 2858 Context.typesAreCompatible(OldQType, NewQType)) { 2859 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>(); 2860 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>(); 2861 const FunctionProtoType *OldProto = nullptr; 2862 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) && 2863 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) { 2864 // The old declaration provided a function prototype, but the 2865 // new declaration does not. Merge in the prototype. 2866 assert(!OldProto->hasExceptionSpec() && "Exception spec in C"); 2867 SmallVector<QualType, 16> ParamTypes(OldProto->param_types()); 2868 NewQType = 2869 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes, 2870 OldProto->getExtProtoInfo()); 2871 New->setType(NewQType); 2872 New->setHasInheritedPrototype(); 2873 2874 // Synthesize parameters with the same types. 2875 SmallVector<ParmVarDecl*, 16> Params; 2876 for (const auto &ParamType : OldProto->param_types()) { 2877 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(), 2878 SourceLocation(), nullptr, 2879 ParamType, /*TInfo=*/nullptr, 2880 SC_None, nullptr); 2881 Param->setScopeInfo(0, Params.size()); 2882 Param->setImplicit(); 2883 Params.push_back(Param); 2884 } 2885 2886 New->setParams(Params); 2887 } 2888 2889 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2890 } 2891 2892 // GNU C permits a K&R definition to follow a prototype declaration 2893 // if the declared types of the parameters in the K&R definition 2894 // match the types in the prototype declaration, even when the 2895 // promoted types of the parameters from the K&R definition differ 2896 // from the types in the prototype. GCC then keeps the types from 2897 // the prototype. 2898 // 2899 // If a variadic prototype is followed by a non-variadic K&R definition, 2900 // the K&R definition becomes variadic. This is sort of an edge case, but 2901 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and 2902 // C99 6.9.1p8. 2903 if (!getLangOpts().CPlusPlus && 2904 Old->hasPrototype() && !New->hasPrototype() && 2905 New->getType()->getAs<FunctionProtoType>() && 2906 Old->getNumParams() == New->getNumParams()) { 2907 SmallVector<QualType, 16> ArgTypes; 2908 SmallVector<GNUCompatibleParamWarning, 16> Warnings; 2909 const FunctionProtoType *OldProto 2910 = Old->getType()->getAs<FunctionProtoType>(); 2911 const FunctionProtoType *NewProto 2912 = New->getType()->getAs<FunctionProtoType>(); 2913 2914 // Determine whether this is the GNU C extension. 2915 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(), 2916 NewProto->getReturnType()); 2917 bool LooseCompatible = !MergedReturn.isNull(); 2918 for (unsigned Idx = 0, End = Old->getNumParams(); 2919 LooseCompatible && Idx != End; ++Idx) { 2920 ParmVarDecl *OldParm = Old->getParamDecl(Idx); 2921 ParmVarDecl *NewParm = New->getParamDecl(Idx); 2922 if (Context.typesAreCompatible(OldParm->getType(), 2923 NewProto->getParamType(Idx))) { 2924 ArgTypes.push_back(NewParm->getType()); 2925 } else if (Context.typesAreCompatible(OldParm->getType(), 2926 NewParm->getType(), 2927 /*CompareUnqualified=*/true)) { 2928 GNUCompatibleParamWarning Warn = { OldParm, NewParm, 2929 NewProto->getParamType(Idx) }; 2930 Warnings.push_back(Warn); 2931 ArgTypes.push_back(NewParm->getType()); 2932 } else 2933 LooseCompatible = false; 2934 } 2935 2936 if (LooseCompatible) { 2937 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) { 2938 Diag(Warnings[Warn].NewParm->getLocation(), 2939 diag::ext_param_promoted_not_compatible_with_prototype) 2940 << Warnings[Warn].PromotedType 2941 << Warnings[Warn].OldParm->getType(); 2942 if (Warnings[Warn].OldParm->getLocation().isValid()) 2943 Diag(Warnings[Warn].OldParm->getLocation(), 2944 diag::note_previous_declaration); 2945 } 2946 2947 if (MergeTypeWithOld) 2948 New->setType(Context.getFunctionType(MergedReturn, ArgTypes, 2949 OldProto->getExtProtoInfo())); 2950 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld); 2951 } 2952 2953 // Fall through to diagnose conflicting types. 2954 } 2955 2956 // A function that has already been declared has been redeclared or 2957 // defined with a different type; show an appropriate diagnostic. 2958 2959 // If the previous declaration was an implicitly-generated builtin 2960 // declaration, then at the very least we should use a specialized note. 2961 unsigned BuiltinID; 2962 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) { 2963 // If it's actually a library-defined builtin function like 'malloc' 2964 // or 'printf', just warn about the incompatible redeclaration. 2965 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) { 2966 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New; 2967 Diag(OldLocation, diag::note_previous_builtin_declaration) 2968 << Old << Old->getType(); 2969 2970 // If this is a global redeclaration, just forget hereafter 2971 // about the "builtin-ness" of the function. 2972 // 2973 // Doing this for local extern declarations is problematic. If 2974 // the builtin declaration remains visible, a second invalid 2975 // local declaration will produce a hard error; if it doesn't 2976 // remain visible, a single bogus local redeclaration (which is 2977 // actually only a warning) could break all the downstream code. 2978 if (!New->getLexicalDeclContext()->isFunctionOrMethod()) 2979 New->getIdentifier()->setBuiltinID(Builtin::NotBuiltin); 2980 2981 return false; 2982 } 2983 2984 PrevDiag = diag::note_previous_builtin_declaration; 2985 } 2986 2987 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName(); 2988 Diag(OldLocation, PrevDiag) << Old << Old->getType(); 2989 return true; 2990 } 2991 2992 /// \brief Completes the merge of two function declarations that are 2993 /// known to be compatible. 2994 /// 2995 /// This routine handles the merging of attributes and other 2996 /// properties of function declarations from the old declaration to 2997 /// the new declaration, once we know that New is in fact a 2998 /// redeclaration of Old. 2999 /// 3000 /// \returns false 3001 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 3002 Scope *S, bool MergeTypeWithOld) { 3003 // Merge the attributes 3004 mergeDeclAttributes(New, Old); 3005 3006 // Merge "pure" flag. 3007 if (Old->isPure()) 3008 New->setPure(); 3009 3010 // Merge "used" flag. 3011 if (Old->getMostRecentDecl()->isUsed(false)) 3012 New->setIsUsed(); 3013 3014 // Merge attributes from the parameters. These can mismatch with K&R 3015 // declarations. 3016 if (New->getNumParams() == Old->getNumParams()) 3017 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) 3018 mergeParamDeclAttributes(New->getParamDecl(i), Old->getParamDecl(i), 3019 *this); 3020 3021 if (getLangOpts().CPlusPlus) 3022 return MergeCXXFunctionDecl(New, Old, S); 3023 3024 // Merge the function types so the we get the composite types for the return 3025 // and argument types. Per C11 6.2.7/4, only update the type if the old decl 3026 // was visible. 3027 QualType Merged = Context.mergeTypes(Old->getType(), New->getType()); 3028 if (!Merged.isNull() && MergeTypeWithOld) 3029 New->setType(Merged); 3030 3031 return false; 3032 } 3033 3034 3035 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod, 3036 ObjCMethodDecl *oldMethod) { 3037 3038 // Merge the attributes, including deprecated/unavailable 3039 AvailabilityMergeKind MergeKind = 3040 isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration 3041 : AMK_Override; 3042 mergeDeclAttributes(newMethod, oldMethod, MergeKind); 3043 3044 // Merge attributes from the parameters. 3045 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(), 3046 oe = oldMethod->param_end(); 3047 for (ObjCMethodDecl::param_iterator 3048 ni = newMethod->param_begin(), ne = newMethod->param_end(); 3049 ni != ne && oi != oe; ++ni, ++oi) 3050 mergeParamDeclAttributes(*ni, *oi, *this); 3051 3052 CheckObjCMethodOverride(newMethod, oldMethod); 3053 } 3054 3055 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and 3056 /// scope as a previous declaration 'Old'. Figure out how to merge their types, 3057 /// emitting diagnostics as appropriate. 3058 /// 3059 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back 3060 /// to here in AddInitializerToDecl. We can't check them before the initializer 3061 /// is attached. 3062 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old, 3063 bool MergeTypeWithOld) { 3064 if (New->isInvalidDecl() || Old->isInvalidDecl()) 3065 return; 3066 3067 QualType MergedT; 3068 if (getLangOpts().CPlusPlus) { 3069 if (New->getType()->isUndeducedType()) { 3070 // We don't know what the new type is until the initializer is attached. 3071 return; 3072 } else if (Context.hasSameType(New->getType(), Old->getType())) { 3073 // These could still be something that needs exception specs checked. 3074 return MergeVarDeclExceptionSpecs(New, Old); 3075 } 3076 // C++ [basic.link]p10: 3077 // [...] the types specified by all declarations referring to a given 3078 // object or function shall be identical, except that declarations for an 3079 // array object can specify array types that differ by the presence or 3080 // absence of a major array bound (8.3.4). 3081 else if (Old->getType()->isIncompleteArrayType() && 3082 New->getType()->isArrayType()) { 3083 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3084 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3085 if (Context.hasSameType(OldArray->getElementType(), 3086 NewArray->getElementType())) 3087 MergedT = New->getType(); 3088 } else if (Old->getType()->isArrayType() && 3089 New->getType()->isIncompleteArrayType()) { 3090 const ArrayType *OldArray = Context.getAsArrayType(Old->getType()); 3091 const ArrayType *NewArray = Context.getAsArrayType(New->getType()); 3092 if (Context.hasSameType(OldArray->getElementType(), 3093 NewArray->getElementType())) 3094 MergedT = Old->getType(); 3095 } else if (New->getType()->isObjCObjectPointerType() && 3096 Old->getType()->isObjCObjectPointerType()) { 3097 MergedT = Context.mergeObjCGCQualifiers(New->getType(), 3098 Old->getType()); 3099 } 3100 } else { 3101 // C 6.2.7p2: 3102 // All declarations that refer to the same object or function shall have 3103 // compatible type. 3104 MergedT = Context.mergeTypes(New->getType(), Old->getType()); 3105 } 3106 if (MergedT.isNull()) { 3107 // It's OK if we couldn't merge types if either type is dependent, for a 3108 // block-scope variable. In other cases (static data members of class 3109 // templates, variable templates, ...), we require the types to be 3110 // equivalent. 3111 // FIXME: The C++ standard doesn't say anything about this. 3112 if ((New->getType()->isDependentType() || 3113 Old->getType()->isDependentType()) && New->isLocalVarDecl()) { 3114 // If the old type was dependent, we can't merge with it, so the new type 3115 // becomes dependent for now. We'll reproduce the original type when we 3116 // instantiate the TypeSourceInfo for the variable. 3117 if (!New->getType()->isDependentType() && MergeTypeWithOld) 3118 New->setType(Context.DependentTy); 3119 return; 3120 } 3121 3122 // FIXME: Even if this merging succeeds, some other non-visible declaration 3123 // of this variable might have an incompatible type. For instance: 3124 // 3125 // extern int arr[]; 3126 // void f() { extern int arr[2]; } 3127 // void g() { extern int arr[3]; } 3128 // 3129 // Neither C nor C++ requires a diagnostic for this, but we should still try 3130 // to diagnose it. 3131 Diag(New->getLocation(), diag::err_redefinition_different_type) 3132 << New->getDeclName() << New->getType() << Old->getType(); 3133 Diag(Old->getLocation(), diag::note_previous_definition); 3134 return New->setInvalidDecl(); 3135 } 3136 3137 // Don't actually update the type on the new declaration if the old 3138 // declaration was an extern declaration in a different scope. 3139 if (MergeTypeWithOld) 3140 New->setType(MergedT); 3141 } 3142 3143 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, 3144 LookupResult &Previous) { 3145 // C11 6.2.7p4: 3146 // For an identifier with internal or external linkage declared 3147 // in a scope in which a prior declaration of that identifier is 3148 // visible, if the prior declaration specifies internal or 3149 // external linkage, the type of the identifier at the later 3150 // declaration becomes the composite type. 3151 // 3152 // If the variable isn't visible, we do not merge with its type. 3153 if (Previous.isShadowed()) 3154 return false; 3155 3156 if (S.getLangOpts().CPlusPlus) { 3157 // C++11 [dcl.array]p3: 3158 // If there is a preceding declaration of the entity in the same 3159 // scope in which the bound was specified, an omitted array bound 3160 // is taken to be the same as in that earlier declaration. 3161 return NewVD->isPreviousDeclInSameBlockScope() || 3162 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() && 3163 !NewVD->getLexicalDeclContext()->isFunctionOrMethod()); 3164 } else { 3165 // If the old declaration was function-local, don't merge with its 3166 // type unless we're in the same function. 3167 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() || 3168 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext(); 3169 } 3170 } 3171 3172 /// MergeVarDecl - We just parsed a variable 'New' which has the same name 3173 /// and scope as a previous declaration 'Old'. Figure out how to resolve this 3174 /// situation, merging decls or emitting diagnostics as appropriate. 3175 /// 3176 /// Tentative definition rules (C99 6.9.2p2) are checked by 3177 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative 3178 /// definitions here, since the initializer hasn't been attached. 3179 /// 3180 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) { 3181 // If the new decl is already invalid, don't do any other checking. 3182 if (New->isInvalidDecl()) 3183 return; 3184 3185 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate(); 3186 3187 // Verify the old decl was also a variable or variable template. 3188 VarDecl *Old = nullptr; 3189 VarTemplateDecl *OldTemplate = nullptr; 3190 if (Previous.isSingleResult()) { 3191 if (NewTemplate) { 3192 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl()); 3193 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr; 3194 } else 3195 Old = dyn_cast<VarDecl>(Previous.getFoundDecl()); 3196 } 3197 if (!Old) { 3198 Diag(New->getLocation(), diag::err_redefinition_different_kind) 3199 << New->getDeclName(); 3200 Diag(Previous.getRepresentativeDecl()->getLocation(), 3201 diag::note_previous_definition); 3202 return New->setInvalidDecl(); 3203 } 3204 3205 if (!shouldLinkPossiblyHiddenDecl(Old, New)) 3206 return; 3207 3208 // Ensure the template parameters are compatible. 3209 if (NewTemplate && 3210 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 3211 OldTemplate->getTemplateParameters(), 3212 /*Complain=*/true, TPL_TemplateMatch)) 3213 return; 3214 3215 // C++ [class.mem]p1: 3216 // A member shall not be declared twice in the member-specification [...] 3217 // 3218 // Here, we need only consider static data members. 3219 if (Old->isStaticDataMember() && !New->isOutOfLine()) { 3220 Diag(New->getLocation(), diag::err_duplicate_member) 3221 << New->getIdentifier(); 3222 Diag(Old->getLocation(), diag::note_previous_declaration); 3223 New->setInvalidDecl(); 3224 } 3225 3226 mergeDeclAttributes(New, Old); 3227 // Warn if an already-declared variable is made a weak_import in a subsequent 3228 // declaration 3229 if (New->hasAttr<WeakImportAttr>() && 3230 Old->getStorageClass() == SC_None && 3231 !Old->hasAttr<WeakImportAttr>()) { 3232 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName(); 3233 Diag(Old->getLocation(), diag::note_previous_definition); 3234 // Remove weak_import attribute on new declaration. 3235 New->dropAttr<WeakImportAttr>(); 3236 } 3237 3238 // Merge the types. 3239 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous)); 3240 3241 if (New->isInvalidDecl()) 3242 return; 3243 3244 diag::kind PrevDiag; 3245 SourceLocation OldLocation; 3246 std::tie(PrevDiag, OldLocation) = 3247 getNoteDiagForInvalidRedeclaration(Old, New); 3248 3249 // [dcl.stc]p8: Check if we have a non-static decl followed by a static. 3250 if (New->getStorageClass() == SC_Static && 3251 !New->isStaticDataMember() && 3252 Old->hasExternalFormalLinkage()) { 3253 if (getLangOpts().MicrosoftExt) { 3254 Diag(New->getLocation(), diag::ext_static_non_static) 3255 << New->getDeclName(); 3256 Diag(OldLocation, PrevDiag); 3257 } else { 3258 Diag(New->getLocation(), diag::err_static_non_static) 3259 << New->getDeclName(); 3260 Diag(OldLocation, PrevDiag); 3261 return New->setInvalidDecl(); 3262 } 3263 } 3264 // C99 6.2.2p4: 3265 // For an identifier declared with the storage-class specifier 3266 // extern in a scope in which a prior declaration of that 3267 // identifier is visible,23) if the prior declaration specifies 3268 // internal or external linkage, the linkage of the identifier at 3269 // the later declaration is the same as the linkage specified at 3270 // the prior declaration. If no prior declaration is visible, or 3271 // if the prior declaration specifies no linkage, then the 3272 // identifier has external linkage. 3273 if (New->hasExternalStorage() && Old->hasLinkage()) 3274 /* Okay */; 3275 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static && 3276 !New->isStaticDataMember() && 3277 Old->getCanonicalDecl()->getStorageClass() == SC_Static) { 3278 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName(); 3279 Diag(OldLocation, PrevDiag); 3280 return New->setInvalidDecl(); 3281 } 3282 3283 // Check if extern is followed by non-extern and vice-versa. 3284 if (New->hasExternalStorage() && 3285 !Old->hasLinkage() && Old->isLocalVarDecl()) { 3286 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName(); 3287 Diag(OldLocation, PrevDiag); 3288 return New->setInvalidDecl(); 3289 } 3290 if (Old->hasLinkage() && New->isLocalVarDecl() && 3291 !New->hasExternalStorage()) { 3292 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName(); 3293 Diag(OldLocation, PrevDiag); 3294 return New->setInvalidDecl(); 3295 } 3296 3297 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup. 3298 3299 // FIXME: The test for external storage here seems wrong? We still 3300 // need to check for mismatches. 3301 if (!New->hasExternalStorage() && !New->isFileVarDecl() && 3302 // Don't complain about out-of-line definitions of static members. 3303 !(Old->getLexicalDeclContext()->isRecord() && 3304 !New->getLexicalDeclContext()->isRecord())) { 3305 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName(); 3306 Diag(OldLocation, PrevDiag); 3307 return New->setInvalidDecl(); 3308 } 3309 3310 if (New->getTLSKind() != Old->getTLSKind()) { 3311 if (!Old->getTLSKind()) { 3312 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName(); 3313 Diag(OldLocation, PrevDiag); 3314 } else if (!New->getTLSKind()) { 3315 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName(); 3316 Diag(OldLocation, PrevDiag); 3317 } else { 3318 // Do not allow redeclaration to change the variable between requiring 3319 // static and dynamic initialization. 3320 // FIXME: GCC allows this, but uses the TLS keyword on the first 3321 // declaration to determine the kind. Do we need to be compatible here? 3322 Diag(New->getLocation(), diag::err_thread_thread_different_kind) 3323 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic); 3324 Diag(OldLocation, PrevDiag); 3325 } 3326 } 3327 3328 // C++ doesn't have tentative definitions, so go right ahead and check here. 3329 const VarDecl *Def; 3330 if (getLangOpts().CPlusPlus && 3331 New->isThisDeclarationADefinition() == VarDecl::Definition && 3332 (Def = Old->getDefinition())) { 3333 Diag(New->getLocation(), diag::err_redefinition) << New; 3334 Diag(Def->getLocation(), diag::note_previous_definition); 3335 New->setInvalidDecl(); 3336 return; 3337 } 3338 3339 if (haveIncompatibleLanguageLinkages(Old, New)) { 3340 Diag(New->getLocation(), diag::err_different_language_linkage) << New; 3341 Diag(OldLocation, PrevDiag); 3342 New->setInvalidDecl(); 3343 return; 3344 } 3345 3346 // Merge "used" flag. 3347 if (Old->getMostRecentDecl()->isUsed(false)) 3348 New->setIsUsed(); 3349 3350 // Keep a chain of previous declarations. 3351 New->setPreviousDecl(Old); 3352 if (NewTemplate) 3353 NewTemplate->setPreviousDecl(OldTemplate); 3354 3355 // Inherit access appropriately. 3356 New->setAccess(Old->getAccess()); 3357 if (NewTemplate) 3358 NewTemplate->setAccess(New->getAccess()); 3359 } 3360 3361 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3362 /// no declarator (e.g. "struct foo;") is parsed. 3363 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3364 DeclSpec &DS) { 3365 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg()); 3366 } 3367 3368 static void HandleTagNumbering(Sema &S, const TagDecl *Tag, Scope *TagScope) { 3369 if (!S.Context.getLangOpts().CPlusPlus) 3370 return; 3371 3372 if (isa<CXXRecordDecl>(Tag->getParent())) { 3373 // If this tag is the direct child of a class, number it if 3374 // it is anonymous. 3375 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl()) 3376 return; 3377 MangleNumberingContext &MCtx = 3378 S.Context.getManglingNumberContext(Tag->getParent()); 3379 S.Context.setManglingNumber( 3380 Tag, MCtx.getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3381 return; 3382 } 3383 3384 // If this tag isn't a direct child of a class, number it if it is local. 3385 Decl *ManglingContextDecl; 3386 if (MangleNumberingContext *MCtx = 3387 S.getCurrentMangleNumberContext(Tag->getDeclContext(), 3388 ManglingContextDecl)) { 3389 S.Context.setManglingNumber( 3390 Tag, 3391 MCtx->getManglingNumber(Tag, TagScope->getMSLocalManglingNumber())); 3392 } 3393 } 3394 3395 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with 3396 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template 3397 /// parameters to cope with template friend declarations. 3398 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 3399 DeclSpec &DS, 3400 MultiTemplateParamsArg TemplateParams, 3401 bool IsExplicitInstantiation) { 3402 Decl *TagD = nullptr; 3403 TagDecl *Tag = nullptr; 3404 if (DS.getTypeSpecType() == DeclSpec::TST_class || 3405 DS.getTypeSpecType() == DeclSpec::TST_struct || 3406 DS.getTypeSpecType() == DeclSpec::TST_interface || 3407 DS.getTypeSpecType() == DeclSpec::TST_union || 3408 DS.getTypeSpecType() == DeclSpec::TST_enum) { 3409 TagD = DS.getRepAsDecl(); 3410 3411 if (!TagD) // We probably had an error 3412 return nullptr; 3413 3414 // Note that the above type specs guarantee that the 3415 // type rep is a Decl, whereas in many of the others 3416 // it's a Type. 3417 if (isa<TagDecl>(TagD)) 3418 Tag = cast<TagDecl>(TagD); 3419 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD)) 3420 Tag = CTD->getTemplatedDecl(); 3421 } 3422 3423 if (Tag) { 3424 HandleTagNumbering(*this, Tag, S); 3425 Tag->setFreeStanding(); 3426 if (Tag->isInvalidDecl()) 3427 return Tag; 3428 } 3429 3430 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 3431 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 3432 // or incomplete types shall not be restrict-qualified." 3433 if (TypeQuals & DeclSpec::TQ_restrict) 3434 Diag(DS.getRestrictSpecLoc(), 3435 diag::err_typecheck_invalid_restrict_not_pointer_noarg) 3436 << DS.getSourceRange(); 3437 } 3438 3439 if (DS.isConstexprSpecified()) { 3440 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations 3441 // and definitions of functions and variables. 3442 if (Tag) 3443 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag) 3444 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3445 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3446 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3447 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4); 3448 else 3449 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators); 3450 // Don't emit warnings after this error. 3451 return TagD; 3452 } 3453 3454 DiagnoseFunctionSpecifiers(DS); 3455 3456 if (DS.isFriendSpecified()) { 3457 // If we're dealing with a decl but not a TagDecl, assume that 3458 // whatever routines created it handled the friendship aspect. 3459 if (TagD && !Tag) 3460 return nullptr; 3461 return ActOnFriendTypeDecl(S, DS, TemplateParams); 3462 } 3463 3464 CXXScopeSpec &SS = DS.getTypeSpecScope(); 3465 bool IsExplicitSpecialization = 3466 !TemplateParams.empty() && TemplateParams.back()->size() == 0; 3467 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() && 3468 !IsExplicitInstantiation && !IsExplicitSpecialization) { 3469 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a 3470 // nested-name-specifier unless it is an explicit instantiation 3471 // or an explicit specialization. 3472 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either. 3473 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier) 3474 << (DS.getTypeSpecType() == DeclSpec::TST_class ? 0 : 3475 DS.getTypeSpecType() == DeclSpec::TST_struct ? 1 : 3476 DS.getTypeSpecType() == DeclSpec::TST_interface ? 2 : 3477 DS.getTypeSpecType() == DeclSpec::TST_union ? 3 : 4) 3478 << SS.getRange(); 3479 return nullptr; 3480 } 3481 3482 // Track whether this decl-specifier declares anything. 3483 bool DeclaresAnything = true; 3484 3485 // Handle anonymous struct definitions. 3486 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) { 3487 if (!Record->getDeclName() && Record->isCompleteDefinition() && 3488 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) { 3489 if (getLangOpts().CPlusPlus || 3490 Record->getDeclContext()->isRecord()) 3491 return BuildAnonymousStructOrUnion(S, DS, AS, Record, Context.getPrintingPolicy()); 3492 3493 DeclaresAnything = false; 3494 } 3495 } 3496 3497 // C11 6.7.2.1p2: 3498 // A struct-declaration that does not declare an anonymous structure or 3499 // anonymous union shall contain a struct-declarator-list. 3500 // 3501 // This rule also existed in C89 and C99; the grammar for struct-declaration 3502 // did not permit a struct-declaration without a struct-declarator-list. 3503 if (!getLangOpts().CPlusPlus && CurContext->isRecord() && 3504 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) { 3505 // Check for Microsoft C extension: anonymous struct/union member. 3506 // Handle 2 kinds of anonymous struct/union: 3507 // struct STRUCT; 3508 // union UNION; 3509 // and 3510 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct. 3511 // UNION_TYPE; <- where UNION_TYPE is a typedef union. 3512 if ((Tag && Tag->getDeclName()) || 3513 DS.getTypeSpecType() == DeclSpec::TST_typename) { 3514 RecordDecl *Record = nullptr; 3515 if (Tag) 3516 Record = dyn_cast<RecordDecl>(Tag); 3517 else if (const RecordType *RT = 3518 DS.getRepAsType().get()->getAsStructureType()) 3519 Record = RT->getDecl(); 3520 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType()) 3521 Record = UT->getDecl(); 3522 3523 if (Record && getLangOpts().MicrosoftExt) { 3524 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record) 3525 << Record->isUnion() << DS.getSourceRange(); 3526 return BuildMicrosoftCAnonymousStruct(S, DS, Record); 3527 } 3528 3529 DeclaresAnything = false; 3530 } 3531 } 3532 3533 // Skip all the checks below if we have a type error. 3534 if (DS.getTypeSpecType() == DeclSpec::TST_error || 3535 (TagD && TagD->isInvalidDecl())) 3536 return TagD; 3537 3538 if (getLangOpts().CPlusPlus && 3539 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) 3540 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag)) 3541 if (Enum->enumerator_begin() == Enum->enumerator_end() && 3542 !Enum->getIdentifier() && !Enum->isInvalidDecl()) 3543 DeclaresAnything = false; 3544 3545 if (!DS.isMissingDeclaratorOk()) { 3546 // Customize diagnostic for a typedef missing a name. 3547 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef) 3548 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name) 3549 << DS.getSourceRange(); 3550 else 3551 DeclaresAnything = false; 3552 } 3553 3554 if (DS.isModulePrivateSpecified() && 3555 Tag && Tag->getDeclContext()->isFunctionOrMethod()) 3556 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class) 3557 << Tag->getTagKind() 3558 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc()); 3559 3560 ActOnDocumentableDecl(TagD); 3561 3562 // C 6.7/2: 3563 // A declaration [...] shall declare at least a declarator [...], a tag, 3564 // or the members of an enumeration. 3565 // C++ [dcl.dcl]p3: 3566 // [If there are no declarators], and except for the declaration of an 3567 // unnamed bit-field, the decl-specifier-seq shall introduce one or more 3568 // names into the program, or shall redeclare a name introduced by a 3569 // previous declaration. 3570 if (!DeclaresAnything) { 3571 // In C, we allow this as a (popular) extension / bug. Don't bother 3572 // producing further diagnostics for redundant qualifiers after this. 3573 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange(); 3574 return TagD; 3575 } 3576 3577 // C++ [dcl.stc]p1: 3578 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the 3579 // init-declarator-list of the declaration shall not be empty. 3580 // C++ [dcl.fct.spec]p1: 3581 // If a cv-qualifier appears in a decl-specifier-seq, the 3582 // init-declarator-list of the declaration shall not be empty. 3583 // 3584 // Spurious qualifiers here appear to be valid in C. 3585 unsigned DiagID = diag::warn_standalone_specifier; 3586 if (getLangOpts().CPlusPlus) 3587 DiagID = diag::ext_standalone_specifier; 3588 3589 // Note that a linkage-specification sets a storage class, but 3590 // 'extern "C" struct foo;' is actually valid and not theoretically 3591 // useless. 3592 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 3593 if (SCS == DeclSpec::SCS_mutable) 3594 // Since mutable is not a viable storage class specifier in C, there is 3595 // no reason to treat it as an extension. Instead, diagnose as an error. 3596 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember); 3597 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef) 3598 Diag(DS.getStorageClassSpecLoc(), DiagID) 3599 << DeclSpec::getSpecifierName(SCS); 3600 } 3601 3602 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 3603 Diag(DS.getThreadStorageClassSpecLoc(), DiagID) 3604 << DeclSpec::getSpecifierName(TSCS); 3605 if (DS.getTypeQualifiers()) { 3606 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3607 Diag(DS.getConstSpecLoc(), DiagID) << "const"; 3608 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3609 Diag(DS.getConstSpecLoc(), DiagID) << "volatile"; 3610 // Restrict is covered above. 3611 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3612 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic"; 3613 } 3614 3615 // Warn about ignored type attributes, for example: 3616 // __attribute__((aligned)) struct A; 3617 // Attributes should be placed after tag to apply to type declaration. 3618 if (!DS.getAttributes().empty()) { 3619 DeclSpec::TST TypeSpecType = DS.getTypeSpecType(); 3620 if (TypeSpecType == DeclSpec::TST_class || 3621 TypeSpecType == DeclSpec::TST_struct || 3622 TypeSpecType == DeclSpec::TST_interface || 3623 TypeSpecType == DeclSpec::TST_union || 3624 TypeSpecType == DeclSpec::TST_enum) { 3625 AttributeList* attrs = DS.getAttributes().getList(); 3626 while (attrs) { 3627 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored) 3628 << attrs->getName() 3629 << (TypeSpecType == DeclSpec::TST_class ? 0 : 3630 TypeSpecType == DeclSpec::TST_struct ? 1 : 3631 TypeSpecType == DeclSpec::TST_union ? 2 : 3632 TypeSpecType == DeclSpec::TST_interface ? 3 : 4); 3633 attrs = attrs->getNext(); 3634 } 3635 } 3636 } 3637 3638 return TagD; 3639 } 3640 3641 /// We are trying to inject an anonymous member into the given scope; 3642 /// check if there's an existing declaration that can't be overloaded. 3643 /// 3644 /// \return true if this is a forbidden redeclaration 3645 static bool CheckAnonMemberRedeclaration(Sema &SemaRef, 3646 Scope *S, 3647 DeclContext *Owner, 3648 DeclarationName Name, 3649 SourceLocation NameLoc, 3650 unsigned diagnostic) { 3651 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName, 3652 Sema::ForRedeclaration); 3653 if (!SemaRef.LookupName(R, S)) return false; 3654 3655 if (R.getAsSingle<TagDecl>()) 3656 return false; 3657 3658 // Pick a representative declaration. 3659 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl(); 3660 assert(PrevDecl && "Expected a non-null Decl"); 3661 3662 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S)) 3663 return false; 3664 3665 SemaRef.Diag(NameLoc, diagnostic) << Name; 3666 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 3667 3668 return true; 3669 } 3670 3671 /// InjectAnonymousStructOrUnionMembers - Inject the members of the 3672 /// anonymous struct or union AnonRecord into the owning context Owner 3673 /// and scope S. This routine will be invoked just after we realize 3674 /// that an unnamed union or struct is actually an anonymous union or 3675 /// struct, e.g., 3676 /// 3677 /// @code 3678 /// union { 3679 /// int i; 3680 /// float f; 3681 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and 3682 /// // f into the surrounding scope.x 3683 /// @endcode 3684 /// 3685 /// This routine is recursive, injecting the names of nested anonymous 3686 /// structs/unions into the owning context and scope as well. 3687 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, 3688 DeclContext *Owner, 3689 RecordDecl *AnonRecord, 3690 AccessSpecifier AS, 3691 SmallVectorImpl<NamedDecl *> &Chaining, 3692 bool MSAnonStruct) { 3693 unsigned diagKind 3694 = AnonRecord->isUnion() ? diag::err_anonymous_union_member_redecl 3695 : diag::err_anonymous_struct_member_redecl; 3696 3697 bool Invalid = false; 3698 3699 // Look every FieldDecl and IndirectFieldDecl with a name. 3700 for (auto *D : AnonRecord->decls()) { 3701 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) && 3702 cast<NamedDecl>(D)->getDeclName()) { 3703 ValueDecl *VD = cast<ValueDecl>(D); 3704 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(), 3705 VD->getLocation(), diagKind)) { 3706 // C++ [class.union]p2: 3707 // The names of the members of an anonymous union shall be 3708 // distinct from the names of any other entity in the 3709 // scope in which the anonymous union is declared. 3710 Invalid = true; 3711 } else { 3712 // C++ [class.union]p2: 3713 // For the purpose of name lookup, after the anonymous union 3714 // definition, the members of the anonymous union are 3715 // considered to have been defined in the scope in which the 3716 // anonymous union is declared. 3717 unsigned OldChainingSize = Chaining.size(); 3718 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD)) 3719 for (auto *PI : IF->chain()) 3720 Chaining.push_back(PI); 3721 else 3722 Chaining.push_back(VD); 3723 3724 assert(Chaining.size() >= 2); 3725 NamedDecl **NamedChain = 3726 new (SemaRef.Context)NamedDecl*[Chaining.size()]; 3727 for (unsigned i = 0; i < Chaining.size(); i++) 3728 NamedChain[i] = Chaining[i]; 3729 3730 IndirectFieldDecl* IndirectField = 3731 IndirectFieldDecl::Create(SemaRef.Context, Owner, VD->getLocation(), 3732 VD->getIdentifier(), VD->getType(), 3733 NamedChain, Chaining.size()); 3734 3735 IndirectField->setAccess(AS); 3736 IndirectField->setImplicit(); 3737 SemaRef.PushOnScopeChains(IndirectField, S); 3738 3739 // That includes picking up the appropriate access specifier. 3740 if (AS != AS_none) IndirectField->setAccess(AS); 3741 3742 Chaining.resize(OldChainingSize); 3743 } 3744 } 3745 } 3746 3747 return Invalid; 3748 } 3749 3750 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to 3751 /// a VarDecl::StorageClass. Any error reporting is up to the caller: 3752 /// illegal input values are mapped to SC_None. 3753 static StorageClass 3754 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) { 3755 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec(); 3756 assert(StorageClassSpec != DeclSpec::SCS_typedef && 3757 "Parser allowed 'typedef' as storage class VarDecl."); 3758 switch (StorageClassSpec) { 3759 case DeclSpec::SCS_unspecified: return SC_None; 3760 case DeclSpec::SCS_extern: 3761 if (DS.isExternInLinkageSpec()) 3762 return SC_None; 3763 return SC_Extern; 3764 case DeclSpec::SCS_static: return SC_Static; 3765 case DeclSpec::SCS_auto: return SC_Auto; 3766 case DeclSpec::SCS_register: return SC_Register; 3767 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 3768 // Illegal SCSs map to None: error reporting is up to the caller. 3769 case DeclSpec::SCS_mutable: // Fall through. 3770 case DeclSpec::SCS_typedef: return SC_None; 3771 } 3772 llvm_unreachable("unknown storage class specifier"); 3773 } 3774 3775 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) { 3776 assert(Record->hasInClassInitializer()); 3777 3778 for (const auto *I : Record->decls()) { 3779 const auto *FD = dyn_cast<FieldDecl>(I); 3780 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 3781 FD = IFD->getAnonField(); 3782 if (FD && FD->hasInClassInitializer()) 3783 return FD->getLocation(); 3784 } 3785 3786 llvm_unreachable("couldn't find in-class initializer"); 3787 } 3788 3789 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3790 SourceLocation DefaultInitLoc) { 3791 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3792 return; 3793 3794 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization); 3795 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0; 3796 } 3797 3798 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, 3799 CXXRecordDecl *AnonUnion) { 3800 if (!Parent->isUnion() || !Parent->hasInClassInitializer()) 3801 return; 3802 3803 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion)); 3804 } 3805 3806 /// BuildAnonymousStructOrUnion - Handle the declaration of an 3807 /// anonymous structure or union. Anonymous unions are a C++ feature 3808 /// (C++ [class.union]) and a C11 feature; anonymous structures 3809 /// are a C11 feature and GNU C++ extension. 3810 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 3811 AccessSpecifier AS, 3812 RecordDecl *Record, 3813 const PrintingPolicy &Policy) { 3814 DeclContext *Owner = Record->getDeclContext(); 3815 3816 // Diagnose whether this anonymous struct/union is an extension. 3817 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11) 3818 Diag(Record->getLocation(), diag::ext_anonymous_union); 3819 else if (!Record->isUnion() && getLangOpts().CPlusPlus) 3820 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct); 3821 else if (!Record->isUnion() && !getLangOpts().C11) 3822 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct); 3823 3824 // C and C++ require different kinds of checks for anonymous 3825 // structs/unions. 3826 bool Invalid = false; 3827 if (getLangOpts().CPlusPlus) { 3828 const char *PrevSpec = nullptr; 3829 unsigned DiagID; 3830 if (Record->isUnion()) { 3831 // C++ [class.union]p6: 3832 // Anonymous unions declared in a named namespace or in the 3833 // global namespace shall be declared static. 3834 if (DS.getStorageClassSpec() != DeclSpec::SCS_static && 3835 (isa<TranslationUnitDecl>(Owner) || 3836 (isa<NamespaceDecl>(Owner) && 3837 cast<NamespaceDecl>(Owner)->getDeclName()))) { 3838 Diag(Record->getLocation(), diag::err_anonymous_union_not_static) 3839 << FixItHint::CreateInsertion(Record->getLocation(), "static "); 3840 3841 // Recover by adding 'static'. 3842 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(), 3843 PrevSpec, DiagID, Policy); 3844 } 3845 // C++ [class.union]p6: 3846 // A storage class is not allowed in a declaration of an 3847 // anonymous union in a class scope. 3848 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified && 3849 isa<RecordDecl>(Owner)) { 3850 Diag(DS.getStorageClassSpecLoc(), 3851 diag::err_anonymous_union_with_storage_spec) 3852 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 3853 3854 // Recover by removing the storage specifier. 3855 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified, 3856 SourceLocation(), 3857 PrevSpec, DiagID, Context.getPrintingPolicy()); 3858 } 3859 } 3860 3861 // Ignore const/volatile/restrict qualifiers. 3862 if (DS.getTypeQualifiers()) { 3863 if (DS.getTypeQualifiers() & DeclSpec::TQ_const) 3864 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified) 3865 << Record->isUnion() << "const" 3866 << FixItHint::CreateRemoval(DS.getConstSpecLoc()); 3867 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile) 3868 Diag(DS.getVolatileSpecLoc(), 3869 diag::ext_anonymous_struct_union_qualified) 3870 << Record->isUnion() << "volatile" 3871 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc()); 3872 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict) 3873 Diag(DS.getRestrictSpecLoc(), 3874 diag::ext_anonymous_struct_union_qualified) 3875 << Record->isUnion() << "restrict" 3876 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc()); 3877 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic) 3878 Diag(DS.getAtomicSpecLoc(), 3879 diag::ext_anonymous_struct_union_qualified) 3880 << Record->isUnion() << "_Atomic" 3881 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc()); 3882 3883 DS.ClearTypeQualifiers(); 3884 } 3885 3886 // C++ [class.union]p2: 3887 // The member-specification of an anonymous union shall only 3888 // define non-static data members. [Note: nested types and 3889 // functions cannot be declared within an anonymous union. ] 3890 for (auto *Mem : Record->decls()) { 3891 if (auto *FD = dyn_cast<FieldDecl>(Mem)) { 3892 // C++ [class.union]p3: 3893 // An anonymous union shall not have private or protected 3894 // members (clause 11). 3895 assert(FD->getAccess() != AS_none); 3896 if (FD->getAccess() != AS_public) { 3897 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member) 3898 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected); 3899 Invalid = true; 3900 } 3901 3902 // C++ [class.union]p1 3903 // An object of a class with a non-trivial constructor, a non-trivial 3904 // copy constructor, a non-trivial destructor, or a non-trivial copy 3905 // assignment operator cannot be a member of a union, nor can an 3906 // array of such objects. 3907 if (CheckNontrivialField(FD)) 3908 Invalid = true; 3909 } else if (Mem->isImplicit()) { 3910 // Any implicit members are fine. 3911 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) { 3912 // This is a type that showed up in an 3913 // elaborated-type-specifier inside the anonymous struct or 3914 // union, but which actually declares a type outside of the 3915 // anonymous struct or union. It's okay. 3916 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) { 3917 if (!MemRecord->isAnonymousStructOrUnion() && 3918 MemRecord->getDeclName()) { 3919 // Visual C++ allows type definition in anonymous struct or union. 3920 if (getLangOpts().MicrosoftExt) 3921 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type) 3922 << (int)Record->isUnion(); 3923 else { 3924 // This is a nested type declaration. 3925 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type) 3926 << (int)Record->isUnion(); 3927 Invalid = true; 3928 } 3929 } else { 3930 // This is an anonymous type definition within another anonymous type. 3931 // This is a popular extension, provided by Plan9, MSVC and GCC, but 3932 // not part of standard C++. 3933 Diag(MemRecord->getLocation(), 3934 diag::ext_anonymous_record_with_anonymous_type) 3935 << (int)Record->isUnion(); 3936 } 3937 } else if (isa<AccessSpecDecl>(Mem)) { 3938 // Any access specifier is fine. 3939 } else if (isa<StaticAssertDecl>(Mem)) { 3940 // In C++1z, static_assert declarations are also fine. 3941 } else { 3942 // We have something that isn't a non-static data 3943 // member. Complain about it. 3944 unsigned DK = diag::err_anonymous_record_bad_member; 3945 if (isa<TypeDecl>(Mem)) 3946 DK = diag::err_anonymous_record_with_type; 3947 else if (isa<FunctionDecl>(Mem)) 3948 DK = diag::err_anonymous_record_with_function; 3949 else if (isa<VarDecl>(Mem)) 3950 DK = diag::err_anonymous_record_with_static; 3951 3952 // Visual C++ allows type definition in anonymous struct or union. 3953 if (getLangOpts().MicrosoftExt && 3954 DK == diag::err_anonymous_record_with_type) 3955 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type) 3956 << (int)Record->isUnion(); 3957 else { 3958 Diag(Mem->getLocation(), DK) 3959 << (int)Record->isUnion(); 3960 Invalid = true; 3961 } 3962 } 3963 } 3964 3965 // C++11 [class.union]p8 (DR1460): 3966 // At most one variant member of a union may have a 3967 // brace-or-equal-initializer. 3968 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() && 3969 Owner->isRecord()) 3970 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner), 3971 cast<CXXRecordDecl>(Record)); 3972 } 3973 3974 if (!Record->isUnion() && !Owner->isRecord()) { 3975 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member) 3976 << (int)getLangOpts().CPlusPlus; 3977 Invalid = true; 3978 } 3979 3980 // Mock up a declarator. 3981 Declarator Dc(DS, Declarator::MemberContext); 3982 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 3983 assert(TInfo && "couldn't build declarator info for anonymous struct/union"); 3984 3985 // Create a declaration for this anonymous struct/union. 3986 NamedDecl *Anon = nullptr; 3987 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) { 3988 Anon = FieldDecl::Create(Context, OwningClass, 3989 DS.getLocStart(), 3990 Record->getLocation(), 3991 /*IdentifierInfo=*/nullptr, 3992 Context.getTypeDeclType(Record), 3993 TInfo, 3994 /*BitWidth=*/nullptr, /*Mutable=*/false, 3995 /*InitStyle=*/ICIS_NoInit); 3996 Anon->setAccess(AS); 3997 if (getLangOpts().CPlusPlus) 3998 FieldCollector->Add(cast<FieldDecl>(Anon)); 3999 } else { 4000 DeclSpec::SCS SCSpec = DS.getStorageClassSpec(); 4001 VarDecl::StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS); 4002 if (SCSpec == DeclSpec::SCS_mutable) { 4003 // mutable can only appear on non-static class members, so it's always 4004 // an error here 4005 Diag(Record->getLocation(), diag::err_mutable_nonmember); 4006 Invalid = true; 4007 SC = SC_None; 4008 } 4009 4010 Anon = VarDecl::Create(Context, Owner, 4011 DS.getLocStart(), 4012 Record->getLocation(), /*IdentifierInfo=*/nullptr, 4013 Context.getTypeDeclType(Record), 4014 TInfo, SC); 4015 4016 // Default-initialize the implicit variable. This initialization will be 4017 // trivial in almost all cases, except if a union member has an in-class 4018 // initializer: 4019 // union { int n = 0; }; 4020 ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false); 4021 } 4022 Anon->setImplicit(); 4023 4024 // Mark this as an anonymous struct/union type. 4025 Record->setAnonymousStructOrUnion(true); 4026 4027 // Add the anonymous struct/union object to the current 4028 // context. We'll be referencing this object when we refer to one of 4029 // its members. 4030 Owner->addDecl(Anon); 4031 4032 // Inject the members of the anonymous struct/union into the owning 4033 // context and into the identifier resolver chain for name lookup 4034 // purposes. 4035 SmallVector<NamedDecl*, 2> Chain; 4036 Chain.push_back(Anon); 4037 4038 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, 4039 Chain, false)) 4040 Invalid = true; 4041 4042 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) { 4043 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 4044 Decl *ManglingContextDecl; 4045 if (MangleNumberingContext *MCtx = 4046 getCurrentMangleNumberContext(NewVD->getDeclContext(), 4047 ManglingContextDecl)) { 4048 Context.setManglingNumber(NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 4049 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 4050 } 4051 } 4052 } 4053 4054 if (Invalid) 4055 Anon->setInvalidDecl(); 4056 4057 return Anon; 4058 } 4059 4060 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an 4061 /// Microsoft C anonymous structure. 4062 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx 4063 /// Example: 4064 /// 4065 /// struct A { int a; }; 4066 /// struct B { struct A; int b; }; 4067 /// 4068 /// void foo() { 4069 /// B var; 4070 /// var.a = 3; 4071 /// } 4072 /// 4073 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 4074 RecordDecl *Record) { 4075 assert(Record && "expected a record!"); 4076 4077 // Mock up a declarator. 4078 Declarator Dc(DS, Declarator::TypeNameContext); 4079 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S); 4080 assert(TInfo && "couldn't build declarator info for anonymous struct"); 4081 4082 auto *ParentDecl = cast<RecordDecl>(CurContext); 4083 QualType RecTy = Context.getTypeDeclType(Record); 4084 4085 // Create a declaration for this anonymous struct. 4086 NamedDecl *Anon = FieldDecl::Create(Context, 4087 ParentDecl, 4088 DS.getLocStart(), 4089 DS.getLocStart(), 4090 /*IdentifierInfo=*/nullptr, 4091 RecTy, 4092 TInfo, 4093 /*BitWidth=*/nullptr, /*Mutable=*/false, 4094 /*InitStyle=*/ICIS_NoInit); 4095 Anon->setImplicit(); 4096 4097 // Add the anonymous struct object to the current context. 4098 CurContext->addDecl(Anon); 4099 4100 // Inject the members of the anonymous struct into the current 4101 // context and into the identifier resolver chain for name lookup 4102 // purposes. 4103 SmallVector<NamedDecl*, 2> Chain; 4104 Chain.push_back(Anon); 4105 4106 RecordDecl *RecordDef = Record->getDefinition(); 4107 if (RequireCompleteType(Anon->getLocation(), RecTy, 4108 diag::err_field_incomplete) || 4109 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef, 4110 AS_none, Chain, true)) { 4111 Anon->setInvalidDecl(); 4112 ParentDecl->setInvalidDecl(); 4113 } 4114 4115 return Anon; 4116 } 4117 4118 /// GetNameForDeclarator - Determine the full declaration name for the 4119 /// given Declarator. 4120 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) { 4121 return GetNameFromUnqualifiedId(D.getName()); 4122 } 4123 4124 /// \brief Retrieves the declaration name from a parsed unqualified-id. 4125 DeclarationNameInfo 4126 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) { 4127 DeclarationNameInfo NameInfo; 4128 NameInfo.setLoc(Name.StartLocation); 4129 4130 switch (Name.getKind()) { 4131 4132 case UnqualifiedId::IK_ImplicitSelfParam: 4133 case UnqualifiedId::IK_Identifier: 4134 NameInfo.setName(Name.Identifier); 4135 NameInfo.setLoc(Name.StartLocation); 4136 return NameInfo; 4137 4138 case UnqualifiedId::IK_OperatorFunctionId: 4139 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName( 4140 Name.OperatorFunctionId.Operator)); 4141 NameInfo.setLoc(Name.StartLocation); 4142 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc 4143 = Name.OperatorFunctionId.SymbolLocations[0]; 4144 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc 4145 = Name.EndLocation.getRawEncoding(); 4146 return NameInfo; 4147 4148 case UnqualifiedId::IK_LiteralOperatorId: 4149 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName( 4150 Name.Identifier)); 4151 NameInfo.setLoc(Name.StartLocation); 4152 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation); 4153 return NameInfo; 4154 4155 case UnqualifiedId::IK_ConversionFunctionId: { 4156 TypeSourceInfo *TInfo; 4157 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo); 4158 if (Ty.isNull()) 4159 return DeclarationNameInfo(); 4160 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName( 4161 Context.getCanonicalType(Ty))); 4162 NameInfo.setLoc(Name.StartLocation); 4163 NameInfo.setNamedTypeInfo(TInfo); 4164 return NameInfo; 4165 } 4166 4167 case UnqualifiedId::IK_ConstructorName: { 4168 TypeSourceInfo *TInfo; 4169 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo); 4170 if (Ty.isNull()) 4171 return DeclarationNameInfo(); 4172 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4173 Context.getCanonicalType(Ty))); 4174 NameInfo.setLoc(Name.StartLocation); 4175 NameInfo.setNamedTypeInfo(TInfo); 4176 return NameInfo; 4177 } 4178 4179 case UnqualifiedId::IK_ConstructorTemplateId: { 4180 // In well-formed code, we can only have a constructor 4181 // template-id that refers to the current context, so go there 4182 // to find the actual type being constructed. 4183 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext); 4184 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name) 4185 return DeclarationNameInfo(); 4186 4187 // Determine the type of the class being constructed. 4188 QualType CurClassType = Context.getTypeDeclType(CurClass); 4189 4190 // FIXME: Check two things: that the template-id names the same type as 4191 // CurClassType, and that the template-id does not occur when the name 4192 // was qualified. 4193 4194 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName( 4195 Context.getCanonicalType(CurClassType))); 4196 NameInfo.setLoc(Name.StartLocation); 4197 // FIXME: should we retrieve TypeSourceInfo? 4198 NameInfo.setNamedTypeInfo(nullptr); 4199 return NameInfo; 4200 } 4201 4202 case UnqualifiedId::IK_DestructorName: { 4203 TypeSourceInfo *TInfo; 4204 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo); 4205 if (Ty.isNull()) 4206 return DeclarationNameInfo(); 4207 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName( 4208 Context.getCanonicalType(Ty))); 4209 NameInfo.setLoc(Name.StartLocation); 4210 NameInfo.setNamedTypeInfo(TInfo); 4211 return NameInfo; 4212 } 4213 4214 case UnqualifiedId::IK_TemplateId: { 4215 TemplateName TName = Name.TemplateId->Template.get(); 4216 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc; 4217 return Context.getNameForTemplate(TName, TNameLoc); 4218 } 4219 4220 } // switch (Name.getKind()) 4221 4222 llvm_unreachable("Unknown name kind"); 4223 } 4224 4225 static QualType getCoreType(QualType Ty) { 4226 do { 4227 if (Ty->isPointerType() || Ty->isReferenceType()) 4228 Ty = Ty->getPointeeType(); 4229 else if (Ty->isArrayType()) 4230 Ty = Ty->castAsArrayTypeUnsafe()->getElementType(); 4231 else 4232 return Ty.withoutLocalFastQualifiers(); 4233 } while (true); 4234 } 4235 4236 /// hasSimilarParameters - Determine whether the C++ functions Declaration 4237 /// and Definition have "nearly" matching parameters. This heuristic is 4238 /// used to improve diagnostics in the case where an out-of-line function 4239 /// definition doesn't match any declaration within the class or namespace. 4240 /// Also sets Params to the list of indices to the parameters that differ 4241 /// between the declaration and the definition. If hasSimilarParameters 4242 /// returns true and Params is empty, then all of the parameters match. 4243 static bool hasSimilarParameters(ASTContext &Context, 4244 FunctionDecl *Declaration, 4245 FunctionDecl *Definition, 4246 SmallVectorImpl<unsigned> &Params) { 4247 Params.clear(); 4248 if (Declaration->param_size() != Definition->param_size()) 4249 return false; 4250 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) { 4251 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType(); 4252 QualType DefParamTy = Definition->getParamDecl(Idx)->getType(); 4253 4254 // The parameter types are identical 4255 if (Context.hasSameType(DefParamTy, DeclParamTy)) 4256 continue; 4257 4258 QualType DeclParamBaseTy = getCoreType(DeclParamTy); 4259 QualType DefParamBaseTy = getCoreType(DefParamTy); 4260 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier(); 4261 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier(); 4262 4263 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) || 4264 (DeclTyName && DeclTyName == DefTyName)) 4265 Params.push_back(Idx); 4266 else // The two parameters aren't even close 4267 return false; 4268 } 4269 4270 return true; 4271 } 4272 4273 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given 4274 /// declarator needs to be rebuilt in the current instantiation. 4275 /// Any bits of declarator which appear before the name are valid for 4276 /// consideration here. That's specifically the type in the decl spec 4277 /// and the base type in any member-pointer chunks. 4278 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, 4279 DeclarationName Name) { 4280 // The types we specifically need to rebuild are: 4281 // - typenames, typeofs, and decltypes 4282 // - types which will become injected class names 4283 // Of course, we also need to rebuild any type referencing such a 4284 // type. It's safest to just say "dependent", but we call out a 4285 // few cases here. 4286 4287 DeclSpec &DS = D.getMutableDeclSpec(); 4288 switch (DS.getTypeSpecType()) { 4289 case DeclSpec::TST_typename: 4290 case DeclSpec::TST_typeofType: 4291 case DeclSpec::TST_underlyingType: 4292 case DeclSpec::TST_atomic: { 4293 // Grab the type from the parser. 4294 TypeSourceInfo *TSI = nullptr; 4295 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI); 4296 if (T.isNull() || !T->isDependentType()) break; 4297 4298 // Make sure there's a type source info. This isn't really much 4299 // of a waste; most dependent types should have type source info 4300 // attached already. 4301 if (!TSI) 4302 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc()); 4303 4304 // Rebuild the type in the current instantiation. 4305 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name); 4306 if (!TSI) return true; 4307 4308 // Store the new type back in the decl spec. 4309 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI); 4310 DS.UpdateTypeRep(LocType); 4311 break; 4312 } 4313 4314 case DeclSpec::TST_decltype: 4315 case DeclSpec::TST_typeofExpr: { 4316 Expr *E = DS.getRepAsExpr(); 4317 ExprResult Result = S.RebuildExprInCurrentInstantiation(E); 4318 if (Result.isInvalid()) return true; 4319 DS.UpdateExprRep(Result.get()); 4320 break; 4321 } 4322 4323 default: 4324 // Nothing to do for these decl specs. 4325 break; 4326 } 4327 4328 // It doesn't matter what order we do this in. 4329 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) { 4330 DeclaratorChunk &Chunk = D.getTypeObject(I); 4331 4332 // The only type information in the declarator which can come 4333 // before the declaration name is the base type of a member 4334 // pointer. 4335 if (Chunk.Kind != DeclaratorChunk::MemberPointer) 4336 continue; 4337 4338 // Rebuild the scope specifier in-place. 4339 CXXScopeSpec &SS = Chunk.Mem.Scope(); 4340 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS)) 4341 return true; 4342 } 4343 4344 return false; 4345 } 4346 4347 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) { 4348 D.setFunctionDefinitionKind(FDK_Declaration); 4349 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg()); 4350 4351 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() && 4352 Dcl && Dcl->getDeclContext()->isFileContext()) 4353 Dcl->setTopLevelDeclInObjCContainer(); 4354 4355 return Dcl; 4356 } 4357 4358 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13: 4359 /// If T is the name of a class, then each of the following shall have a 4360 /// name different from T: 4361 /// - every static data member of class T; 4362 /// - every member function of class T 4363 /// - every member of class T that is itself a type; 4364 /// \returns true if the declaration name violates these rules. 4365 bool Sema::DiagnoseClassNameShadow(DeclContext *DC, 4366 DeclarationNameInfo NameInfo) { 4367 DeclarationName Name = NameInfo.getName(); 4368 4369 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) 4370 if (Record->getIdentifier() && Record->getDeclName() == Name) { 4371 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name; 4372 return true; 4373 } 4374 4375 return false; 4376 } 4377 4378 /// \brief Diagnose a declaration whose declarator-id has the given 4379 /// nested-name-specifier. 4380 /// 4381 /// \param SS The nested-name-specifier of the declarator-id. 4382 /// 4383 /// \param DC The declaration context to which the nested-name-specifier 4384 /// resolves. 4385 /// 4386 /// \param Name The name of the entity being declared. 4387 /// 4388 /// \param Loc The location of the name of the entity being declared. 4389 /// 4390 /// \returns true if we cannot safely recover from this error, false otherwise. 4391 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 4392 DeclarationName Name, 4393 SourceLocation Loc) { 4394 DeclContext *Cur = CurContext; 4395 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur)) 4396 Cur = Cur->getParent(); 4397 4398 // If the user provided a superfluous scope specifier that refers back to the 4399 // class in which the entity is already declared, diagnose and ignore it. 4400 // 4401 // class X { 4402 // void X::f(); 4403 // }; 4404 // 4405 // Note, it was once ill-formed to give redundant qualification in all 4406 // contexts, but that rule was removed by DR482. 4407 if (Cur->Equals(DC)) { 4408 if (Cur->isRecord()) { 4409 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification 4410 : diag::err_member_extra_qualification) 4411 << Name << FixItHint::CreateRemoval(SS.getRange()); 4412 SS.clear(); 4413 } else { 4414 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name; 4415 } 4416 return false; 4417 } 4418 4419 // Check whether the qualifying scope encloses the scope of the original 4420 // declaration. 4421 if (!Cur->Encloses(DC)) { 4422 if (Cur->isRecord()) 4423 Diag(Loc, diag::err_member_qualification) 4424 << Name << SS.getRange(); 4425 else if (isa<TranslationUnitDecl>(DC)) 4426 Diag(Loc, diag::err_invalid_declarator_global_scope) 4427 << Name << SS.getRange(); 4428 else if (isa<FunctionDecl>(Cur)) 4429 Diag(Loc, diag::err_invalid_declarator_in_function) 4430 << Name << SS.getRange(); 4431 else if (isa<BlockDecl>(Cur)) 4432 Diag(Loc, diag::err_invalid_declarator_in_block) 4433 << Name << SS.getRange(); 4434 else 4435 Diag(Loc, diag::err_invalid_declarator_scope) 4436 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange(); 4437 4438 return true; 4439 } 4440 4441 if (Cur->isRecord()) { 4442 // Cannot qualify members within a class. 4443 Diag(Loc, diag::err_member_qualification) 4444 << Name << SS.getRange(); 4445 SS.clear(); 4446 4447 // C++ constructors and destructors with incorrect scopes can break 4448 // our AST invariants by having the wrong underlying types. If 4449 // that's the case, then drop this declaration entirely. 4450 if ((Name.getNameKind() == DeclarationName::CXXConstructorName || 4451 Name.getNameKind() == DeclarationName::CXXDestructorName) && 4452 !Context.hasSameType(Name.getCXXNameType(), 4453 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur)))) 4454 return true; 4455 4456 return false; 4457 } 4458 4459 // C++11 [dcl.meaning]p1: 4460 // [...] "The nested-name-specifier of the qualified declarator-id shall 4461 // not begin with a decltype-specifer" 4462 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data()); 4463 while (SpecLoc.getPrefix()) 4464 SpecLoc = SpecLoc.getPrefix(); 4465 if (dyn_cast_or_null<DecltypeType>( 4466 SpecLoc.getNestedNameSpecifier()->getAsType())) 4467 Diag(Loc, diag::err_decltype_in_declarator) 4468 << SpecLoc.getTypeLoc().getSourceRange(); 4469 4470 return false; 4471 } 4472 4473 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D, 4474 MultiTemplateParamsArg TemplateParamLists) { 4475 // TODO: consider using NameInfo for diagnostic. 4476 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 4477 DeclarationName Name = NameInfo.getName(); 4478 4479 // All of these full declarators require an identifier. If it doesn't have 4480 // one, the ParsedFreeStandingDeclSpec action should be used. 4481 if (!Name) { 4482 if (!D.isInvalidType()) // Reject this if we think it is valid. 4483 Diag(D.getDeclSpec().getLocStart(), 4484 diag::err_declarator_need_ident) 4485 << D.getDeclSpec().getSourceRange() << D.getSourceRange(); 4486 return nullptr; 4487 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType)) 4488 return nullptr; 4489 4490 // The scope passed in may not be a decl scope. Zip up the scope tree until 4491 // we find one that is. 4492 while ((S->getFlags() & Scope::DeclScope) == 0 || 4493 (S->getFlags() & Scope::TemplateParamScope) != 0) 4494 S = S->getParent(); 4495 4496 DeclContext *DC = CurContext; 4497 if (D.getCXXScopeSpec().isInvalid()) 4498 D.setInvalidType(); 4499 else if (D.getCXXScopeSpec().isSet()) { 4500 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(), 4501 UPPC_DeclarationQualifier)) 4502 return nullptr; 4503 4504 bool EnteringContext = !D.getDeclSpec().isFriendSpecified(); 4505 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext); 4506 if (!DC || isa<EnumDecl>(DC)) { 4507 // If we could not compute the declaration context, it's because the 4508 // declaration context is dependent but does not refer to a class, 4509 // class template, or class template partial specialization. Complain 4510 // and return early, to avoid the coming semantic disaster. 4511 Diag(D.getIdentifierLoc(), 4512 diag::err_template_qualified_declarator_no_match) 4513 << D.getCXXScopeSpec().getScopeRep() 4514 << D.getCXXScopeSpec().getRange(); 4515 return nullptr; 4516 } 4517 bool IsDependentContext = DC->isDependentContext(); 4518 4519 if (!IsDependentContext && 4520 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC)) 4521 return nullptr; 4522 4523 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) { 4524 Diag(D.getIdentifierLoc(), 4525 diag::err_member_def_undefined_record) 4526 << Name << DC << D.getCXXScopeSpec().getRange(); 4527 D.setInvalidType(); 4528 } else if (!D.getDeclSpec().isFriendSpecified()) { 4529 if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC, 4530 Name, D.getIdentifierLoc())) { 4531 if (DC->isRecord()) 4532 return nullptr; 4533 4534 D.setInvalidType(); 4535 } 4536 } 4537 4538 // Check whether we need to rebuild the type of the given 4539 // declaration in the current instantiation. 4540 if (EnteringContext && IsDependentContext && 4541 TemplateParamLists.size() != 0) { 4542 ContextRAII SavedContext(*this, DC); 4543 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name)) 4544 D.setInvalidType(); 4545 } 4546 } 4547 4548 if (DiagnoseClassNameShadow(DC, NameInfo)) 4549 // If this is a typedef, we'll end up spewing multiple diagnostics. 4550 // Just return early; it's safer. 4551 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4552 return nullptr; 4553 4554 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4555 QualType R = TInfo->getType(); 4556 4557 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 4558 UPPC_DeclarationType)) 4559 D.setInvalidType(); 4560 4561 LookupResult Previous(*this, NameInfo, LookupOrdinaryName, 4562 ForRedeclaration); 4563 4564 // See if this is a redefinition of a variable in the same scope. 4565 if (!D.getCXXScopeSpec().isSet()) { 4566 bool IsLinkageLookup = false; 4567 bool CreateBuiltins = false; 4568 4569 // If the declaration we're planning to build will be a function 4570 // or object with linkage, then look for another declaration with 4571 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6). 4572 // 4573 // If the declaration we're planning to build will be declared with 4574 // external linkage in the translation unit, create any builtin with 4575 // the same name. 4576 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 4577 /* Do nothing*/; 4578 else if (CurContext->isFunctionOrMethod() && 4579 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern || 4580 R->isFunctionType())) { 4581 IsLinkageLookup = true; 4582 CreateBuiltins = 4583 CurContext->getEnclosingNamespaceContext()->isTranslationUnit(); 4584 } else if (CurContext->getRedeclContext()->isTranslationUnit() && 4585 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) 4586 CreateBuiltins = true; 4587 4588 if (IsLinkageLookup) 4589 Previous.clear(LookupRedeclarationWithLinkage); 4590 4591 LookupName(Previous, S, CreateBuiltins); 4592 } else { // Something like "int foo::x;" 4593 LookupQualifiedName(Previous, DC); 4594 4595 // C++ [dcl.meaning]p1: 4596 // When the declarator-id is qualified, the declaration shall refer to a 4597 // previously declared member of the class or namespace to which the 4598 // qualifier refers (or, in the case of a namespace, of an element of the 4599 // inline namespace set of that namespace (7.3.1)) or to a specialization 4600 // thereof; [...] 4601 // 4602 // Note that we already checked the context above, and that we do not have 4603 // enough information to make sure that Previous contains the declaration 4604 // we want to match. For example, given: 4605 // 4606 // class X { 4607 // void f(); 4608 // void f(float); 4609 // }; 4610 // 4611 // void X::f(int) { } // ill-formed 4612 // 4613 // In this case, Previous will point to the overload set 4614 // containing the two f's declared in X, but neither of them 4615 // matches. 4616 4617 // C++ [dcl.meaning]p1: 4618 // [...] the member shall not merely have been introduced by a 4619 // using-declaration in the scope of the class or namespace nominated by 4620 // the nested-name-specifier of the declarator-id. 4621 RemoveUsingDecls(Previous); 4622 } 4623 4624 if (Previous.isSingleResult() && 4625 Previous.getFoundDecl()->isTemplateParameter()) { 4626 // Maybe we will complain about the shadowed template parameter. 4627 if (!D.isInvalidType()) 4628 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), 4629 Previous.getFoundDecl()); 4630 4631 // Just pretend that we didn't see the previous declaration. 4632 Previous.clear(); 4633 } 4634 4635 // In C++, the previous declaration we find might be a tag type 4636 // (class or enum). In this case, the new declaration will hide the 4637 // tag type. Note that this does does not apply if we're declaring a 4638 // typedef (C++ [dcl.typedef]p4). 4639 if (Previous.isSingleTagDecl() && 4640 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef) 4641 Previous.clear(); 4642 4643 // Check that there are no default arguments other than in the parameters 4644 // of a function declaration (C++ only). 4645 if (getLangOpts().CPlusPlus) 4646 CheckExtraCXXDefaultArguments(D); 4647 4648 NamedDecl *New; 4649 4650 bool AddToScope = true; 4651 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) { 4652 if (TemplateParamLists.size()) { 4653 Diag(D.getIdentifierLoc(), diag::err_template_typedef); 4654 return nullptr; 4655 } 4656 4657 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous); 4658 } else if (R->isFunctionType()) { 4659 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous, 4660 TemplateParamLists, 4661 AddToScope); 4662 } else { 4663 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists, 4664 AddToScope); 4665 } 4666 4667 if (!New) 4668 return nullptr; 4669 4670 // If this has an identifier and is not an invalid redeclaration or 4671 // function template specialization, add it to the scope stack. 4672 if (New->getDeclName() && AddToScope && 4673 !(D.isRedeclaration() && New->isInvalidDecl())) { 4674 // Only make a locally-scoped extern declaration visible if it is the first 4675 // declaration of this entity. Qualified lookup for such an entity should 4676 // only find this declaration if there is no visible declaration of it. 4677 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl(); 4678 PushOnScopeChains(New, S, AddToContext); 4679 if (!AddToContext) 4680 CurContext->addHiddenDecl(New); 4681 } 4682 4683 return New; 4684 } 4685 4686 /// Helper method to turn variable array types into constant array 4687 /// types in certain situations which would otherwise be errors (for 4688 /// GCC compatibility). 4689 static QualType TryToFixInvalidVariablyModifiedType(QualType T, 4690 ASTContext &Context, 4691 bool &SizeIsNegative, 4692 llvm::APSInt &Oversized) { 4693 // This method tries to turn a variable array into a constant 4694 // array even when the size isn't an ICE. This is necessary 4695 // for compatibility with code that depends on gcc's buggy 4696 // constant expression folding, like struct {char x[(int)(char*)2];} 4697 SizeIsNegative = false; 4698 Oversized = 0; 4699 4700 if (T->isDependentType()) 4701 return QualType(); 4702 4703 QualifierCollector Qs; 4704 const Type *Ty = Qs.strip(T); 4705 4706 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) { 4707 QualType Pointee = PTy->getPointeeType(); 4708 QualType FixedType = 4709 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative, 4710 Oversized); 4711 if (FixedType.isNull()) return FixedType; 4712 FixedType = Context.getPointerType(FixedType); 4713 return Qs.apply(Context, FixedType); 4714 } 4715 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) { 4716 QualType Inner = PTy->getInnerType(); 4717 QualType FixedType = 4718 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative, 4719 Oversized); 4720 if (FixedType.isNull()) return FixedType; 4721 FixedType = Context.getParenType(FixedType); 4722 return Qs.apply(Context, FixedType); 4723 } 4724 4725 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T); 4726 if (!VLATy) 4727 return QualType(); 4728 // FIXME: We should probably handle this case 4729 if (VLATy->getElementType()->isVariablyModifiedType()) 4730 return QualType(); 4731 4732 llvm::APSInt Res; 4733 if (!VLATy->getSizeExpr() || 4734 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context)) 4735 return QualType(); 4736 4737 // Check whether the array size is negative. 4738 if (Res.isSigned() && Res.isNegative()) { 4739 SizeIsNegative = true; 4740 return QualType(); 4741 } 4742 4743 // Check whether the array is too large to be addressed. 4744 unsigned ActiveSizeBits 4745 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(), 4746 Res); 4747 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) { 4748 Oversized = Res; 4749 return QualType(); 4750 } 4751 4752 return Context.getConstantArrayType(VLATy->getElementType(), 4753 Res, ArrayType::Normal, 0); 4754 } 4755 4756 static void 4757 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) { 4758 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) { 4759 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>(); 4760 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(), 4761 DstPTL.getPointeeLoc()); 4762 DstPTL.setStarLoc(SrcPTL.getStarLoc()); 4763 return; 4764 } 4765 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) { 4766 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>(); 4767 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(), 4768 DstPTL.getInnerLoc()); 4769 DstPTL.setLParenLoc(SrcPTL.getLParenLoc()); 4770 DstPTL.setRParenLoc(SrcPTL.getRParenLoc()); 4771 return; 4772 } 4773 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>(); 4774 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>(); 4775 TypeLoc SrcElemTL = SrcATL.getElementLoc(); 4776 TypeLoc DstElemTL = DstATL.getElementLoc(); 4777 DstElemTL.initializeFullCopy(SrcElemTL); 4778 DstATL.setLBracketLoc(SrcATL.getLBracketLoc()); 4779 DstATL.setSizeExpr(SrcATL.getSizeExpr()); 4780 DstATL.setRBracketLoc(SrcATL.getRBracketLoc()); 4781 } 4782 4783 /// Helper method to turn variable array types into constant array 4784 /// types in certain situations which would otherwise be errors (for 4785 /// GCC compatibility). 4786 static TypeSourceInfo* 4787 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, 4788 ASTContext &Context, 4789 bool &SizeIsNegative, 4790 llvm::APSInt &Oversized) { 4791 QualType FixedTy 4792 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context, 4793 SizeIsNegative, Oversized); 4794 if (FixedTy.isNull()) 4795 return nullptr; 4796 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy); 4797 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(), 4798 FixedTInfo->getTypeLoc()); 4799 return FixedTInfo; 4800 } 4801 4802 /// \brief Register the given locally-scoped extern "C" declaration so 4803 /// that it can be found later for redeclarations. We include any extern "C" 4804 /// declaration that is not visible in the translation unit here, not just 4805 /// function-scope declarations. 4806 void 4807 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) { 4808 if (!getLangOpts().CPlusPlus && 4809 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit()) 4810 // Don't need to track declarations in the TU in C. 4811 return; 4812 4813 // Note that we have a locally-scoped external with this name. 4814 // FIXME: There can be multiple such declarations if they are functions marked 4815 // __attribute__((overloadable)) declared in function scope in C. 4816 LocallyScopedExternCDecls[ND->getDeclName()] = ND; 4817 } 4818 4819 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) { 4820 if (ExternalSource) { 4821 // Load locally-scoped external decls from the external source. 4822 // FIXME: This is inefficient. Maybe add a DeclContext for extern "C" decls? 4823 SmallVector<NamedDecl *, 4> Decls; 4824 ExternalSource->ReadLocallyScopedExternCDecls(Decls); 4825 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 4826 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos 4827 = LocallyScopedExternCDecls.find(Decls[I]->getDeclName()); 4828 if (Pos == LocallyScopedExternCDecls.end()) 4829 LocallyScopedExternCDecls[Decls[I]->getDeclName()] = Decls[I]; 4830 } 4831 } 4832 4833 NamedDecl *D = LocallyScopedExternCDecls.lookup(Name); 4834 return D ? D->getMostRecentDecl() : nullptr; 4835 } 4836 4837 /// \brief Diagnose function specifiers on a declaration of an identifier that 4838 /// does not identify a function. 4839 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) { 4840 // FIXME: We should probably indicate the identifier in question to avoid 4841 // confusion for constructs like "inline int a(), b;" 4842 if (DS.isInlineSpecified()) 4843 Diag(DS.getInlineSpecLoc(), 4844 diag::err_inline_non_function); 4845 4846 if (DS.isVirtualSpecified()) 4847 Diag(DS.getVirtualSpecLoc(), 4848 diag::err_virtual_non_function); 4849 4850 if (DS.isExplicitSpecified()) 4851 Diag(DS.getExplicitSpecLoc(), 4852 diag::err_explicit_non_function); 4853 4854 if (DS.isNoreturnSpecified()) 4855 Diag(DS.getNoreturnSpecLoc(), 4856 diag::err_noreturn_non_function); 4857 } 4858 4859 NamedDecl* 4860 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 4861 TypeSourceInfo *TInfo, LookupResult &Previous) { 4862 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1). 4863 if (D.getCXXScopeSpec().isSet()) { 4864 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator) 4865 << D.getCXXScopeSpec().getRange(); 4866 D.setInvalidType(); 4867 // Pretend we didn't see the scope specifier. 4868 DC = CurContext; 4869 Previous.clear(); 4870 } 4871 4872 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4873 4874 if (D.getDeclSpec().isConstexprSpecified()) 4875 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr) 4876 << 1; 4877 4878 if (D.getName().Kind != UnqualifiedId::IK_Identifier) { 4879 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier) 4880 << D.getName().getSourceRange(); 4881 return nullptr; 4882 } 4883 4884 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo); 4885 if (!NewTD) return nullptr; 4886 4887 // Handle attributes prior to checking for duplicates in MergeVarDecl 4888 ProcessDeclAttributes(S, NewTD, D); 4889 4890 CheckTypedefForVariablyModifiedType(S, NewTD); 4891 4892 bool Redeclaration = D.isRedeclaration(); 4893 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration); 4894 D.setRedeclaration(Redeclaration); 4895 return ND; 4896 } 4897 4898 void 4899 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) { 4900 // C99 6.7.7p2: If a typedef name specifies a variably modified type 4901 // then it shall have block scope. 4902 // Note that variably modified types must be fixed before merging the decl so 4903 // that redeclarations will match. 4904 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo(); 4905 QualType T = TInfo->getType(); 4906 if (T->isVariablyModifiedType()) { 4907 getCurFunction()->setHasBranchProtectedScope(); 4908 4909 if (S->getFnParent() == nullptr) { 4910 bool SizeIsNegative; 4911 llvm::APSInt Oversized; 4912 TypeSourceInfo *FixedTInfo = 4913 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 4914 SizeIsNegative, 4915 Oversized); 4916 if (FixedTInfo) { 4917 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size); 4918 NewTD->setTypeSourceInfo(FixedTInfo); 4919 } else { 4920 if (SizeIsNegative) 4921 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size); 4922 else if (T->isVariableArrayType()) 4923 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope); 4924 else if (Oversized.getBoolValue()) 4925 Diag(NewTD->getLocation(), diag::err_array_too_large) 4926 << Oversized.toString(10); 4927 else 4928 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope); 4929 NewTD->setInvalidDecl(); 4930 } 4931 } 4932 } 4933 } 4934 4935 4936 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which 4937 /// declares a typedef-name, either using the 'typedef' type specifier or via 4938 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'. 4939 NamedDecl* 4940 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD, 4941 LookupResult &Previous, bool &Redeclaration) { 4942 // Merge the decl with the existing one if appropriate. If the decl is 4943 // in an outer scope, it isn't the same thing. 4944 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false, 4945 /*AllowInlineNamespace*/false); 4946 filterNonConflictingPreviousTypedefDecls(Context, NewTD, Previous); 4947 if (!Previous.empty()) { 4948 Redeclaration = true; 4949 MergeTypedefNameDecl(NewTD, Previous); 4950 } 4951 4952 // If this is the C FILE type, notify the AST context. 4953 if (IdentifierInfo *II = NewTD->getIdentifier()) 4954 if (!NewTD->isInvalidDecl() && 4955 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 4956 if (II->isStr("FILE")) 4957 Context.setFILEDecl(NewTD); 4958 else if (II->isStr("jmp_buf")) 4959 Context.setjmp_bufDecl(NewTD); 4960 else if (II->isStr("sigjmp_buf")) 4961 Context.setsigjmp_bufDecl(NewTD); 4962 else if (II->isStr("ucontext_t")) 4963 Context.setucontext_tDecl(NewTD); 4964 } 4965 4966 return NewTD; 4967 } 4968 4969 /// \brief Determines whether the given declaration is an out-of-scope 4970 /// previous declaration. 4971 /// 4972 /// This routine should be invoked when name lookup has found a 4973 /// previous declaration (PrevDecl) that is not in the scope where a 4974 /// new declaration by the same name is being introduced. If the new 4975 /// declaration occurs in a local scope, previous declarations with 4976 /// linkage may still be considered previous declarations (C99 4977 /// 6.2.2p4-5, C++ [basic.link]p6). 4978 /// 4979 /// \param PrevDecl the previous declaration found by name 4980 /// lookup 4981 /// 4982 /// \param DC the context in which the new declaration is being 4983 /// declared. 4984 /// 4985 /// \returns true if PrevDecl is an out-of-scope previous declaration 4986 /// for a new delcaration with the same name. 4987 static bool 4988 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC, 4989 ASTContext &Context) { 4990 if (!PrevDecl) 4991 return false; 4992 4993 if (!PrevDecl->hasLinkage()) 4994 return false; 4995 4996 if (Context.getLangOpts().CPlusPlus) { 4997 // C++ [basic.link]p6: 4998 // If there is a visible declaration of an entity with linkage 4999 // having the same name and type, ignoring entities declared 5000 // outside the innermost enclosing namespace scope, the block 5001 // scope declaration declares that same entity and receives the 5002 // linkage of the previous declaration. 5003 DeclContext *OuterContext = DC->getRedeclContext(); 5004 if (!OuterContext->isFunctionOrMethod()) 5005 // This rule only applies to block-scope declarations. 5006 return false; 5007 5008 DeclContext *PrevOuterContext = PrevDecl->getDeclContext(); 5009 if (PrevOuterContext->isRecord()) 5010 // We found a member function: ignore it. 5011 return false; 5012 5013 // Find the innermost enclosing namespace for the new and 5014 // previous declarations. 5015 OuterContext = OuterContext->getEnclosingNamespaceContext(); 5016 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext(); 5017 5018 // The previous declaration is in a different namespace, so it 5019 // isn't the same function. 5020 if (!OuterContext->Equals(PrevOuterContext)) 5021 return false; 5022 } 5023 5024 return true; 5025 } 5026 5027 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) { 5028 CXXScopeSpec &SS = D.getCXXScopeSpec(); 5029 if (!SS.isSet()) return; 5030 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext())); 5031 } 5032 5033 bool Sema::inferObjCARCLifetime(ValueDecl *decl) { 5034 QualType type = decl->getType(); 5035 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 5036 if (lifetime == Qualifiers::OCL_Autoreleasing) { 5037 // Various kinds of declaration aren't allowed to be __autoreleasing. 5038 unsigned kind = -1U; 5039 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5040 if (var->hasAttr<BlocksAttr>()) 5041 kind = 0; // __block 5042 else if (!var->hasLocalStorage()) 5043 kind = 1; // global 5044 } else if (isa<ObjCIvarDecl>(decl)) { 5045 kind = 3; // ivar 5046 } else if (isa<FieldDecl>(decl)) { 5047 kind = 2; // field 5048 } 5049 5050 if (kind != -1U) { 5051 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) 5052 << kind; 5053 } 5054 } else if (lifetime == Qualifiers::OCL_None) { 5055 // Try to infer lifetime. 5056 if (!type->isObjCLifetimeType()) 5057 return false; 5058 5059 lifetime = type->getObjCARCImplicitLifetime(); 5060 type = Context.getLifetimeQualifiedType(type, lifetime); 5061 decl->setType(type); 5062 } 5063 5064 if (VarDecl *var = dyn_cast<VarDecl>(decl)) { 5065 // Thread-local variables cannot have lifetime. 5066 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone && 5067 var->getTLSKind()) { 5068 Diag(var->getLocation(), diag::err_arc_thread_ownership) 5069 << var->getType(); 5070 return true; 5071 } 5072 } 5073 5074 return false; 5075 } 5076 5077 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) { 5078 // Ensure that an auto decl is deduced otherwise the checks below might cache 5079 // the wrong linkage. 5080 assert(S.ParsingInitForAutoVars.count(&ND) == 0); 5081 5082 // 'weak' only applies to declarations with external linkage. 5083 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) { 5084 if (!ND.isExternallyVisible()) { 5085 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static); 5086 ND.dropAttr<WeakAttr>(); 5087 } 5088 } 5089 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) { 5090 if (ND.isExternallyVisible()) { 5091 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static); 5092 ND.dropAttr<WeakRefAttr>(); 5093 } 5094 } 5095 5096 // 'selectany' only applies to externally visible varable declarations. 5097 // It does not apply to functions. 5098 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) { 5099 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) { 5100 S.Diag(Attr->getLocation(), diag::err_attribute_selectany_non_extern_data); 5101 ND.dropAttr<SelectAnyAttr>(); 5102 } 5103 } 5104 5105 // dll attributes require external linkage. 5106 if (const DLLImportAttr *Attr = ND.getAttr<DLLImportAttr>()) { 5107 if (!ND.isExternallyVisible()) { 5108 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5109 << &ND << Attr; 5110 ND.setInvalidDecl(); 5111 } 5112 } 5113 if (const DLLExportAttr *Attr = ND.getAttr<DLLExportAttr>()) { 5114 if (!ND.isExternallyVisible()) { 5115 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern) 5116 << &ND << Attr; 5117 ND.setInvalidDecl(); 5118 } 5119 } 5120 } 5121 5122 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, 5123 NamedDecl *NewDecl, 5124 bool IsSpecialization) { 5125 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) 5126 OldDecl = OldTD->getTemplatedDecl(); 5127 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) 5128 NewDecl = NewTD->getTemplatedDecl(); 5129 5130 if (!OldDecl || !NewDecl) 5131 return; 5132 5133 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>(); 5134 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>(); 5135 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>(); 5136 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>(); 5137 5138 // dllimport and dllexport are inheritable attributes so we have to exclude 5139 // inherited attribute instances. 5140 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) || 5141 (NewExportAttr && !NewExportAttr->isInherited()); 5142 5143 // A redeclaration is not allowed to add a dllimport or dllexport attribute, 5144 // the only exception being explicit specializations. 5145 // Implicitly generated declarations are also excluded for now because there 5146 // is no other way to switch these to use dllimport or dllexport. 5147 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr; 5148 5149 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) { 5150 // If the declaration hasn't been used yet, allow with a warning for 5151 // free functions and global variables. 5152 bool JustWarn = false; 5153 if (!OldDecl->isUsed() && OldDecl->getDeclContext()->isFileContext()) { 5154 auto *VD = dyn_cast<VarDecl>(OldDecl); 5155 if (VD && !VD->getDescribedVarTemplate()) 5156 JustWarn = true; 5157 auto *FD = dyn_cast<FunctionDecl>(OldDecl); 5158 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) 5159 JustWarn = true; 5160 } 5161 5162 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration 5163 : diag::err_attribute_dll_redeclaration; 5164 S.Diag(NewDecl->getLocation(), DiagID) 5165 << NewDecl 5166 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr); 5167 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5168 if (!JustWarn) { 5169 NewDecl->setInvalidDecl(); 5170 return; 5171 } 5172 } 5173 5174 // A redeclaration is not allowed to drop a dllimport attribute, the only 5175 // exceptions being inline function definitions, local extern declarations, 5176 // and qualified friend declarations. 5177 // NB: MSVC converts such a declaration to dllexport. 5178 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false; 5179 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) 5180 // Ignore static data because out-of-line definitions are diagnosed 5181 // separately. 5182 IsStaticDataMember = VD->isStaticDataMember(); 5183 else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) { 5184 IsInline = FD->isInlined(); 5185 IsQualifiedFriend = FD->getQualifier() && 5186 FD->getFriendObjectKind() == Decl::FOK_Declared; 5187 } 5188 5189 if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember && 5190 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) { 5191 S.Diag(NewDecl->getLocation(), 5192 diag::warn_redeclaration_without_attribute_prev_attribute_ignored) 5193 << NewDecl << OldImportAttr; 5194 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration); 5195 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute); 5196 OldDecl->dropAttr<DLLImportAttr>(); 5197 NewDecl->dropAttr<DLLImportAttr>(); 5198 } 5199 } 5200 5201 /// Given that we are within the definition of the given function, 5202 /// will that definition behave like C99's 'inline', where the 5203 /// definition is discarded except for optimization purposes? 5204 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) { 5205 // Try to avoid calling GetGVALinkageForFunction. 5206 5207 // All cases of this require the 'inline' keyword. 5208 if (!FD->isInlined()) return false; 5209 5210 // This is only possible in C++ with the gnu_inline attribute. 5211 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>()) 5212 return false; 5213 5214 // Okay, go ahead and call the relatively-more-expensive function. 5215 5216 #ifndef NDEBUG 5217 // AST quite reasonably asserts that it's working on a function 5218 // definition. We don't really have a way to tell it that we're 5219 // currently defining the function, so just lie to it in +Asserts 5220 // builds. This is an awful hack. 5221 FD->setLazyBody(1); 5222 #endif 5223 5224 bool isC99Inline = 5225 S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally; 5226 5227 #ifndef NDEBUG 5228 FD->setLazyBody(0); 5229 #endif 5230 5231 return isC99Inline; 5232 } 5233 5234 /// Determine whether a variable is extern "C" prior to attaching 5235 /// an initializer. We can't just call isExternC() here, because that 5236 /// will also compute and cache whether the declaration is externally 5237 /// visible, which might change when we attach the initializer. 5238 /// 5239 /// This can only be used if the declaration is known to not be a 5240 /// redeclaration of an internal linkage declaration. 5241 /// 5242 /// For instance: 5243 /// 5244 /// auto x = []{}; 5245 /// 5246 /// Attaching the initializer here makes this declaration not externally 5247 /// visible, because its type has internal linkage. 5248 /// 5249 /// FIXME: This is a hack. 5250 template<typename T> 5251 static bool isIncompleteDeclExternC(Sema &S, const T *D) { 5252 if (S.getLangOpts().CPlusPlus) { 5253 // In C++, the overloadable attribute negates the effects of extern "C". 5254 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>()) 5255 return false; 5256 } 5257 return D->isExternC(); 5258 } 5259 5260 static bool shouldConsiderLinkage(const VarDecl *VD) { 5261 const DeclContext *DC = VD->getDeclContext()->getRedeclContext(); 5262 if (DC->isFunctionOrMethod()) 5263 return VD->hasExternalStorage(); 5264 if (DC->isFileContext()) 5265 return true; 5266 if (DC->isRecord()) 5267 return false; 5268 llvm_unreachable("Unexpected context"); 5269 } 5270 5271 static bool shouldConsiderLinkage(const FunctionDecl *FD) { 5272 const DeclContext *DC = FD->getDeclContext()->getRedeclContext(); 5273 if (DC->isFileContext() || DC->isFunctionOrMethod()) 5274 return true; 5275 if (DC->isRecord()) 5276 return false; 5277 llvm_unreachable("Unexpected context"); 5278 } 5279 5280 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList, 5281 AttributeList::Kind Kind) { 5282 for (const AttributeList *L = AttrList; L; L = L->getNext()) 5283 if (L->getKind() == Kind) 5284 return true; 5285 return false; 5286 } 5287 5288 static bool hasParsedAttr(Scope *S, const Declarator &PD, 5289 AttributeList::Kind Kind) { 5290 // Check decl attributes on the DeclSpec. 5291 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind)) 5292 return true; 5293 5294 // Walk the declarator structure, checking decl attributes that were in a type 5295 // position to the decl itself. 5296 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) { 5297 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind)) 5298 return true; 5299 } 5300 5301 // Finally, check attributes on the decl itself. 5302 return hasParsedAttr(S, PD.getAttributes(), Kind); 5303 } 5304 5305 /// Adjust the \c DeclContext for a function or variable that might be a 5306 /// function-local external declaration. 5307 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) { 5308 if (!DC->isFunctionOrMethod()) 5309 return false; 5310 5311 // If this is a local extern function or variable declared within a function 5312 // template, don't add it into the enclosing namespace scope until it is 5313 // instantiated; it might have a dependent type right now. 5314 if (DC->isDependentContext()) 5315 return true; 5316 5317 // C++11 [basic.link]p7: 5318 // When a block scope declaration of an entity with linkage is not found to 5319 // refer to some other declaration, then that entity is a member of the 5320 // innermost enclosing namespace. 5321 // 5322 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a 5323 // semantically-enclosing namespace, not a lexically-enclosing one. 5324 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC)) 5325 DC = DC->getParent(); 5326 return true; 5327 } 5328 5329 NamedDecl * 5330 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, 5331 TypeSourceInfo *TInfo, LookupResult &Previous, 5332 MultiTemplateParamsArg TemplateParamLists, 5333 bool &AddToScope) { 5334 QualType R = TInfo->getType(); 5335 DeclarationName Name = GetNameForDeclarator(D).getName(); 5336 5337 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec(); 5338 VarDecl::StorageClass SC = 5339 StorageClassSpecToVarDeclStorageClass(D.getDeclSpec()); 5340 5341 // dllimport globals without explicit storage class are treated as extern. We 5342 // have to change the storage class this early to get the right DeclContext. 5343 if (SC == SC_None && !DC->isRecord() && 5344 hasParsedAttr(S, D, AttributeList::AT_DLLImport) && 5345 !hasParsedAttr(S, D, AttributeList::AT_DLLExport)) 5346 SC = SC_Extern; 5347 5348 DeclContext *OriginalDC = DC; 5349 bool IsLocalExternDecl = SC == SC_Extern && 5350 adjustContextForLocalExternDecl(DC); 5351 5352 if (getLangOpts().OpenCL) { 5353 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed. 5354 QualType NR = R; 5355 while (NR->isPointerType()) { 5356 if (NR->isFunctionPointerType()) { 5357 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable); 5358 D.setInvalidType(); 5359 break; 5360 } 5361 NR = NR->getPointeeType(); 5362 } 5363 5364 if (!getOpenCLOptions().cl_khr_fp16) { 5365 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and 5366 // half array type (unless the cl_khr_fp16 extension is enabled). 5367 if (Context.getBaseElementType(R)->isHalfType()) { 5368 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R; 5369 D.setInvalidType(); 5370 } 5371 } 5372 } 5373 5374 if (SCSpec == DeclSpec::SCS_mutable) { 5375 // mutable can only appear on non-static class members, so it's always 5376 // an error here 5377 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember); 5378 D.setInvalidType(); 5379 SC = SC_None; 5380 } 5381 5382 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register && 5383 !D.getAsmLabel() && !getSourceManager().isInSystemMacro( 5384 D.getDeclSpec().getStorageClassSpecLoc())) { 5385 // In C++11, the 'register' storage class specifier is deprecated. 5386 // Suppress the warning in system macros, it's used in macros in some 5387 // popular C system headers, such as in glibc's htonl() macro. 5388 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5389 diag::warn_deprecated_register) 5390 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5391 } 5392 5393 IdentifierInfo *II = Name.getAsIdentifierInfo(); 5394 if (!II) { 5395 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) 5396 << Name; 5397 return nullptr; 5398 } 5399 5400 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 5401 5402 if (!DC->isRecord() && S->getFnParent() == nullptr) { 5403 // C99 6.9p2: The storage-class specifiers auto and register shall not 5404 // appear in the declaration specifiers in an external declaration. 5405 // Global Register+Asm is a GNU extension we support. 5406 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) { 5407 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope); 5408 D.setInvalidType(); 5409 } 5410 } 5411 5412 if (getLangOpts().OpenCL) { 5413 // Set up the special work-group-local storage class for variables in the 5414 // OpenCL __local address space. 5415 if (R.getAddressSpace() == LangAS::opencl_local) { 5416 SC = SC_OpenCLWorkGroupLocal; 5417 } 5418 5419 // OpenCL v1.2 s6.9.b p4: 5420 // The sampler type cannot be used with the __local and __global address 5421 // space qualifiers. 5422 if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local || 5423 R.getAddressSpace() == LangAS::opencl_global)) { 5424 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace); 5425 } 5426 5427 // OpenCL 1.2 spec, p6.9 r: 5428 // The event type cannot be used to declare a program scope variable. 5429 // The event type cannot be used with the __local, __constant and __global 5430 // address space qualifiers. 5431 if (R->isEventT()) { 5432 if (S->getParent() == nullptr) { 5433 Diag(D.getLocStart(), diag::err_event_t_global_var); 5434 D.setInvalidType(); 5435 } 5436 5437 if (R.getAddressSpace()) { 5438 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual); 5439 D.setInvalidType(); 5440 } 5441 } 5442 } 5443 5444 bool IsExplicitSpecialization = false; 5445 bool IsVariableTemplateSpecialization = false; 5446 bool IsPartialSpecialization = false; 5447 bool IsVariableTemplate = false; 5448 VarDecl *NewVD = nullptr; 5449 VarTemplateDecl *NewTemplate = nullptr; 5450 TemplateParameterList *TemplateParams = nullptr; 5451 if (!getLangOpts().CPlusPlus) { 5452 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5453 D.getIdentifierLoc(), II, 5454 R, TInfo, SC); 5455 5456 if (D.isInvalidType()) 5457 NewVD->setInvalidDecl(); 5458 } else { 5459 bool Invalid = false; 5460 5461 if (DC->isRecord() && !CurContext->isRecord()) { 5462 // This is an out-of-line definition of a static data member. 5463 switch (SC) { 5464 case SC_None: 5465 break; 5466 case SC_Static: 5467 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5468 diag::err_static_out_of_line) 5469 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5470 break; 5471 case SC_Auto: 5472 case SC_Register: 5473 case SC_Extern: 5474 // [dcl.stc] p2: The auto or register specifiers shall be applied only 5475 // to names of variables declared in a block or to function parameters. 5476 // [dcl.stc] p6: The extern specifier cannot be used in the declaration 5477 // of class members 5478 5479 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5480 diag::err_storage_class_for_static_member) 5481 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 5482 break; 5483 case SC_PrivateExtern: 5484 llvm_unreachable("C storage class in c++!"); 5485 case SC_OpenCLWorkGroupLocal: 5486 llvm_unreachable("OpenCL storage class in c++!"); 5487 } 5488 } 5489 5490 if (SC == SC_Static && CurContext->isRecord()) { 5491 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) { 5492 if (RD->isLocalClass()) 5493 Diag(D.getIdentifierLoc(), 5494 diag::err_static_data_member_not_allowed_in_local_class) 5495 << Name << RD->getDeclName(); 5496 5497 // C++98 [class.union]p1: If a union contains a static data member, 5498 // the program is ill-formed. C++11 drops this restriction. 5499 if (RD->isUnion()) 5500 Diag(D.getIdentifierLoc(), 5501 getLangOpts().CPlusPlus11 5502 ? diag::warn_cxx98_compat_static_data_member_in_union 5503 : diag::ext_static_data_member_in_union) << Name; 5504 // We conservatively disallow static data members in anonymous structs. 5505 else if (!RD->getDeclName()) 5506 Diag(D.getIdentifierLoc(), 5507 diag::err_static_data_member_not_allowed_in_anon_struct) 5508 << Name << RD->isUnion(); 5509 } 5510 } 5511 5512 // Match up the template parameter lists with the scope specifier, then 5513 // determine whether we have a template or a template specialization. 5514 TemplateParams = MatchTemplateParametersToScopeSpecifier( 5515 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 5516 D.getCXXScopeSpec(), 5517 D.getName().getKind() == UnqualifiedId::IK_TemplateId 5518 ? D.getName().TemplateId 5519 : nullptr, 5520 TemplateParamLists, 5521 /*never a friend*/ false, IsExplicitSpecialization, Invalid); 5522 5523 if (TemplateParams) { 5524 if (!TemplateParams->size() && 5525 D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 5526 // There is an extraneous 'template<>' for this variable. Complain 5527 // about it, but allow the declaration of the variable. 5528 Diag(TemplateParams->getTemplateLoc(), 5529 diag::err_template_variable_noparams) 5530 << II 5531 << SourceRange(TemplateParams->getTemplateLoc(), 5532 TemplateParams->getRAngleLoc()); 5533 TemplateParams = nullptr; 5534 } else { 5535 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 5536 // This is an explicit specialization or a partial specialization. 5537 // FIXME: Check that we can declare a specialization here. 5538 IsVariableTemplateSpecialization = true; 5539 IsPartialSpecialization = TemplateParams->size() > 0; 5540 } else { // if (TemplateParams->size() > 0) 5541 // This is a template declaration. 5542 IsVariableTemplate = true; 5543 5544 // Check that we can declare a template here. 5545 if (CheckTemplateDeclScope(S, TemplateParams)) 5546 return nullptr; 5547 5548 // Only C++1y supports variable templates (N3651). 5549 Diag(D.getIdentifierLoc(), 5550 getLangOpts().CPlusPlus14 5551 ? diag::warn_cxx11_compat_variable_template 5552 : diag::ext_variable_template); 5553 } 5554 } 5555 } else { 5556 assert(D.getName().getKind() != UnqualifiedId::IK_TemplateId && 5557 "should have a 'template<>' for this decl"); 5558 } 5559 5560 if (IsVariableTemplateSpecialization) { 5561 SourceLocation TemplateKWLoc = 5562 TemplateParamLists.size() > 0 5563 ? TemplateParamLists[0]->getTemplateLoc() 5564 : SourceLocation(); 5565 DeclResult Res = ActOnVarTemplateSpecialization( 5566 S, D, TInfo, TemplateKWLoc, TemplateParams, SC, 5567 IsPartialSpecialization); 5568 if (Res.isInvalid()) 5569 return nullptr; 5570 NewVD = cast<VarDecl>(Res.get()); 5571 AddToScope = false; 5572 } else 5573 NewVD = VarDecl::Create(Context, DC, D.getLocStart(), 5574 D.getIdentifierLoc(), II, R, TInfo, SC); 5575 5576 // If this is supposed to be a variable template, create it as such. 5577 if (IsVariableTemplate) { 5578 NewTemplate = 5579 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name, 5580 TemplateParams, NewVD); 5581 NewVD->setDescribedVarTemplate(NewTemplate); 5582 } 5583 5584 // If this decl has an auto type in need of deduction, make a note of the 5585 // Decl so we can diagnose uses of it in its own initializer. 5586 if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType()) 5587 ParsingInitForAutoVars.insert(NewVD); 5588 5589 if (D.isInvalidType() || Invalid) { 5590 NewVD->setInvalidDecl(); 5591 if (NewTemplate) 5592 NewTemplate->setInvalidDecl(); 5593 } 5594 5595 SetNestedNameSpecifier(NewVD, D); 5596 5597 // If we have any template parameter lists that don't directly belong to 5598 // the variable (matching the scope specifier), store them. 5599 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0; 5600 if (TemplateParamLists.size() > VDTemplateParamLists) 5601 NewVD->setTemplateParameterListsInfo( 5602 Context, TemplateParamLists.size() - VDTemplateParamLists, 5603 TemplateParamLists.data()); 5604 5605 if (D.getDeclSpec().isConstexprSpecified()) 5606 NewVD->setConstexpr(true); 5607 } 5608 5609 // Set the lexical context. If the declarator has a C++ scope specifier, the 5610 // lexical context will be different from the semantic context. 5611 NewVD->setLexicalDeclContext(CurContext); 5612 if (NewTemplate) 5613 NewTemplate->setLexicalDeclContext(CurContext); 5614 5615 if (IsLocalExternDecl) 5616 NewVD->setLocalExternDecl(); 5617 5618 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) { 5619 if (NewVD->hasLocalStorage()) { 5620 // C++11 [dcl.stc]p4: 5621 // When thread_local is applied to a variable of block scope the 5622 // storage-class-specifier static is implied if it does not appear 5623 // explicitly. 5624 // Core issue: 'static' is not implied if the variable is declared 5625 // 'extern'. 5626 if (SCSpec == DeclSpec::SCS_unspecified && 5627 TSCS == DeclSpec::TSCS_thread_local && 5628 DC->isFunctionOrMethod()) 5629 NewVD->setTSCSpec(TSCS); 5630 else 5631 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5632 diag::err_thread_non_global) 5633 << DeclSpec::getSpecifierName(TSCS); 5634 } else if (!Context.getTargetInfo().isTLSSupported()) 5635 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 5636 diag::err_thread_unsupported); 5637 else 5638 NewVD->setTSCSpec(TSCS); 5639 } 5640 5641 // C99 6.7.4p3 5642 // An inline definition of a function with external linkage shall 5643 // not contain a definition of a modifiable object with static or 5644 // thread storage duration... 5645 // We only apply this when the function is required to be defined 5646 // elsewhere, i.e. when the function is not 'extern inline'. Note 5647 // that a local variable with thread storage duration still has to 5648 // be marked 'static'. Also note that it's possible to get these 5649 // semantics in C++ using __attribute__((gnu_inline)). 5650 if (SC == SC_Static && S->getFnParent() != nullptr && 5651 !NewVD->getType().isConstQualified()) { 5652 FunctionDecl *CurFD = getCurFunctionDecl(); 5653 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) { 5654 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 5655 diag::warn_static_local_in_extern_inline); 5656 MaybeSuggestAddingStaticToDecl(CurFD); 5657 } 5658 } 5659 5660 if (D.getDeclSpec().isModulePrivateSpecified()) { 5661 if (IsVariableTemplateSpecialization) 5662 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5663 << (IsPartialSpecialization ? 1 : 0) 5664 << FixItHint::CreateRemoval( 5665 D.getDeclSpec().getModulePrivateSpecLoc()); 5666 else if (IsExplicitSpecialization) 5667 Diag(NewVD->getLocation(), diag::err_module_private_specialization) 5668 << 2 5669 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5670 else if (NewVD->hasLocalStorage()) 5671 Diag(NewVD->getLocation(), diag::err_module_private_local) 5672 << 0 << NewVD->getDeclName() 5673 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 5674 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 5675 else { 5676 NewVD->setModulePrivate(); 5677 if (NewTemplate) 5678 NewTemplate->setModulePrivate(); 5679 } 5680 } 5681 5682 // Handle attributes prior to checking for duplicates in MergeVarDecl 5683 ProcessDeclAttributes(S, NewVD, D); 5684 5685 if (getLangOpts().CUDA) { 5686 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static 5687 // storage [duration]." 5688 if (SC == SC_None && S->getFnParent() != nullptr && 5689 (NewVD->hasAttr<CUDASharedAttr>() || 5690 NewVD->hasAttr<CUDAConstantAttr>())) { 5691 NewVD->setStorageClass(SC_Static); 5692 } 5693 } 5694 5695 // Ensure that dllimport globals without explicit storage class are treated as 5696 // extern. The storage class is set above using parsed attributes. Now we can 5697 // check the VarDecl itself. 5698 assert(!NewVD->hasAttr<DLLImportAttr>() || 5699 NewVD->getAttr<DLLImportAttr>()->isInherited() || 5700 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None); 5701 5702 // In auto-retain/release, infer strong retension for variables of 5703 // retainable type. 5704 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD)) 5705 NewVD->setInvalidDecl(); 5706 5707 // Handle GNU asm-label extension (encoded as an attribute). 5708 if (Expr *E = (Expr*)D.getAsmLabel()) { 5709 // The parser guarantees this is a string. 5710 StringLiteral *SE = cast<StringLiteral>(E); 5711 StringRef Label = SE->getString(); 5712 if (S->getFnParent() != nullptr) { 5713 switch (SC) { 5714 case SC_None: 5715 case SC_Auto: 5716 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label; 5717 break; 5718 case SC_Register: 5719 // Local Named register 5720 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5721 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5722 break; 5723 case SC_Static: 5724 case SC_Extern: 5725 case SC_PrivateExtern: 5726 case SC_OpenCLWorkGroupLocal: 5727 break; 5728 } 5729 } else if (SC == SC_Register) { 5730 // Global Named register 5731 if (!Context.getTargetInfo().isValidGCCRegisterName(Label)) 5732 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label; 5733 if (!R->isIntegralType(Context) && !R->isPointerType()) { 5734 Diag(D.getLocStart(), diag::err_asm_bad_register_type); 5735 NewVD->setInvalidDecl(true); 5736 } 5737 } 5738 5739 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), 5740 Context, Label, 0)); 5741 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 5742 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 5743 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier()); 5744 if (I != ExtnameUndeclaredIdentifiers.end()) { 5745 NewVD->addAttr(I->second); 5746 ExtnameUndeclaredIdentifiers.erase(I); 5747 } 5748 } 5749 5750 // Diagnose shadowed variables before filtering for scope. 5751 if (D.getCXXScopeSpec().isEmpty()) 5752 CheckShadow(S, NewVD, Previous); 5753 5754 // Don't consider existing declarations that are in a different 5755 // scope and are out-of-semantic-context declarations (if the new 5756 // declaration has linkage). 5757 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD), 5758 D.getCXXScopeSpec().isNotEmpty() || 5759 IsExplicitSpecialization || 5760 IsVariableTemplateSpecialization); 5761 5762 // Check whether the previous declaration is in the same block scope. This 5763 // affects whether we merge types with it, per C++11 [dcl.array]p3. 5764 if (getLangOpts().CPlusPlus && 5765 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage()) 5766 NewVD->setPreviousDeclInSameBlockScope( 5767 Previous.isSingleResult() && !Previous.isShadowed() && 5768 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false)); 5769 5770 if (!getLangOpts().CPlusPlus) { 5771 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5772 } else { 5773 // If this is an explicit specialization of a static data member, check it. 5774 if (IsExplicitSpecialization && !NewVD->isInvalidDecl() && 5775 CheckMemberSpecialization(NewVD, Previous)) 5776 NewVD->setInvalidDecl(); 5777 5778 // Merge the decl with the existing one if appropriate. 5779 if (!Previous.empty()) { 5780 if (Previous.isSingleResult() && 5781 isa<FieldDecl>(Previous.getFoundDecl()) && 5782 D.getCXXScopeSpec().isSet()) { 5783 // The user tried to define a non-static data member 5784 // out-of-line (C++ [dcl.meaning]p1). 5785 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line) 5786 << D.getCXXScopeSpec().getRange(); 5787 Previous.clear(); 5788 NewVD->setInvalidDecl(); 5789 } 5790 } else if (D.getCXXScopeSpec().isSet()) { 5791 // No previous declaration in the qualifying scope. 5792 Diag(D.getIdentifierLoc(), diag::err_no_member) 5793 << Name << computeDeclContext(D.getCXXScopeSpec(), true) 5794 << D.getCXXScopeSpec().getRange(); 5795 NewVD->setInvalidDecl(); 5796 } 5797 5798 if (!IsVariableTemplateSpecialization) 5799 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous)); 5800 5801 if (NewTemplate) { 5802 VarTemplateDecl *PrevVarTemplate = 5803 NewVD->getPreviousDecl() 5804 ? NewVD->getPreviousDecl()->getDescribedVarTemplate() 5805 : nullptr; 5806 5807 // Check the template parameter list of this declaration, possibly 5808 // merging in the template parameter list from the previous variable 5809 // template declaration. 5810 if (CheckTemplateParameterList( 5811 TemplateParams, 5812 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters() 5813 : nullptr, 5814 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() && 5815 DC->isDependentContext()) 5816 ? TPC_ClassTemplateMember 5817 : TPC_VarTemplate)) 5818 NewVD->setInvalidDecl(); 5819 5820 // If we are providing an explicit specialization of a static variable 5821 // template, make a note of that. 5822 if (PrevVarTemplate && 5823 PrevVarTemplate->getInstantiatedFromMemberTemplate()) 5824 PrevVarTemplate->setMemberSpecialization(); 5825 } 5826 } 5827 5828 ProcessPragmaWeak(S, NewVD); 5829 5830 // If this is the first declaration of an extern C variable, update 5831 // the map of such variables. 5832 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() && 5833 isIncompleteDeclExternC(*this, NewVD)) 5834 RegisterLocallyScopedExternCDecl(NewVD, S); 5835 5836 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) { 5837 Decl *ManglingContextDecl; 5838 if (MangleNumberingContext *MCtx = 5839 getCurrentMangleNumberContext(NewVD->getDeclContext(), 5840 ManglingContextDecl)) { 5841 Context.setManglingNumber( 5842 NewVD, MCtx->getManglingNumber(NewVD, S->getMSLocalManglingNumber())); 5843 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD)); 5844 } 5845 } 5846 5847 if (D.isRedeclaration() && !Previous.empty()) { 5848 checkDLLAttributeRedeclaration( 5849 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD, 5850 IsExplicitSpecialization); 5851 } 5852 5853 if (NewTemplate) { 5854 if (NewVD->isInvalidDecl()) 5855 NewTemplate->setInvalidDecl(); 5856 ActOnDocumentableDecl(NewTemplate); 5857 return NewTemplate; 5858 } 5859 5860 return NewVD; 5861 } 5862 5863 /// \brief Diagnose variable or built-in function shadowing. Implements 5864 /// -Wshadow. 5865 /// 5866 /// This method is called whenever a VarDecl is added to a "useful" 5867 /// scope. 5868 /// 5869 /// \param S the scope in which the shadowing name is being declared 5870 /// \param R the lookup of the name 5871 /// 5872 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) { 5873 // Return if warning is ignored. 5874 if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc())) 5875 return; 5876 5877 // Don't diagnose declarations at file scope. 5878 if (D->hasGlobalStorage()) 5879 return; 5880 5881 DeclContext *NewDC = D->getDeclContext(); 5882 5883 // Only diagnose if we're shadowing an unambiguous field or variable. 5884 if (R.getResultKind() != LookupResult::Found) 5885 return; 5886 5887 NamedDecl* ShadowedDecl = R.getFoundDecl(); 5888 if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl)) 5889 return; 5890 5891 // Fields are not shadowed by variables in C++ static methods. 5892 if (isa<FieldDecl>(ShadowedDecl)) 5893 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC)) 5894 if (MD->isStatic()) 5895 return; 5896 5897 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl)) 5898 if (shadowedVar->isExternC()) { 5899 // For shadowing external vars, make sure that we point to the global 5900 // declaration, not a locally scoped extern declaration. 5901 for (auto I : shadowedVar->redecls()) 5902 if (I->isFileVarDecl()) { 5903 ShadowedDecl = I; 5904 break; 5905 } 5906 } 5907 5908 DeclContext *OldDC = ShadowedDecl->getDeclContext(); 5909 5910 // Only warn about certain kinds of shadowing for class members. 5911 if (NewDC && NewDC->isRecord()) { 5912 // In particular, don't warn about shadowing non-class members. 5913 if (!OldDC->isRecord()) 5914 return; 5915 5916 // TODO: should we warn about static data members shadowing 5917 // static data members from base classes? 5918 5919 // TODO: don't diagnose for inaccessible shadowed members. 5920 // This is hard to do perfectly because we might friend the 5921 // shadowing context, but that's just a false negative. 5922 } 5923 5924 // Determine what kind of declaration we're shadowing. 5925 unsigned Kind; 5926 if (isa<RecordDecl>(OldDC)) { 5927 if (isa<FieldDecl>(ShadowedDecl)) 5928 Kind = 3; // field 5929 else 5930 Kind = 2; // static data member 5931 } else if (OldDC->isFileContext()) 5932 Kind = 1; // global 5933 else 5934 Kind = 0; // local 5935 5936 DeclarationName Name = R.getLookupName(); 5937 5938 // Emit warning and note. 5939 if (getSourceManager().isInSystemMacro(R.getNameLoc())) 5940 return; 5941 Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC; 5942 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration); 5943 } 5944 5945 /// \brief Check -Wshadow without the advantage of a previous lookup. 5946 void Sema::CheckShadow(Scope *S, VarDecl *D) { 5947 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation())) 5948 return; 5949 5950 LookupResult R(*this, D->getDeclName(), D->getLocation(), 5951 Sema::LookupOrdinaryName, Sema::ForRedeclaration); 5952 LookupName(R, S); 5953 CheckShadow(S, D, R); 5954 } 5955 5956 /// Check for conflict between this global or extern "C" declaration and 5957 /// previous global or extern "C" declarations. This is only used in C++. 5958 template<typename T> 5959 static bool checkGlobalOrExternCConflict( 5960 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) { 5961 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\""); 5962 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName()); 5963 5964 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) { 5965 // The common case: this global doesn't conflict with any extern "C" 5966 // declaration. 5967 return false; 5968 } 5969 5970 if (Prev) { 5971 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) { 5972 // Both the old and new declarations have C language linkage. This is a 5973 // redeclaration. 5974 Previous.clear(); 5975 Previous.addDecl(Prev); 5976 return true; 5977 } 5978 5979 // This is a global, non-extern "C" declaration, and there is a previous 5980 // non-global extern "C" declaration. Diagnose if this is a variable 5981 // declaration. 5982 if (!isa<VarDecl>(ND)) 5983 return false; 5984 } else { 5985 // The declaration is extern "C". Check for any declaration in the 5986 // translation unit which might conflict. 5987 if (IsGlobal) { 5988 // We have already performed the lookup into the translation unit. 5989 IsGlobal = false; 5990 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 5991 I != E; ++I) { 5992 if (isa<VarDecl>(*I)) { 5993 Prev = *I; 5994 break; 5995 } 5996 } 5997 } else { 5998 DeclContext::lookup_result R = 5999 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName()); 6000 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end(); 6001 I != E; ++I) { 6002 if (isa<VarDecl>(*I)) { 6003 Prev = *I; 6004 break; 6005 } 6006 // FIXME: If we have any other entity with this name in global scope, 6007 // the declaration is ill-formed, but that is a defect: it breaks the 6008 // 'stat' hack, for instance. Only variables can have mangled name 6009 // clashes with extern "C" declarations, so only they deserve a 6010 // diagnostic. 6011 } 6012 } 6013 6014 if (!Prev) 6015 return false; 6016 } 6017 6018 // Use the first declaration's location to ensure we point at something which 6019 // is lexically inside an extern "C" linkage-spec. 6020 assert(Prev && "should have found a previous declaration to diagnose"); 6021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev)) 6022 Prev = FD->getFirstDecl(); 6023 else 6024 Prev = cast<VarDecl>(Prev)->getFirstDecl(); 6025 6026 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict) 6027 << IsGlobal << ND; 6028 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict) 6029 << IsGlobal; 6030 return false; 6031 } 6032 6033 /// Apply special rules for handling extern "C" declarations. Returns \c true 6034 /// if we have found that this is a redeclaration of some prior entity. 6035 /// 6036 /// Per C++ [dcl.link]p6: 6037 /// Two declarations [for a function or variable] with C language linkage 6038 /// with the same name that appear in different scopes refer to the same 6039 /// [entity]. An entity with C language linkage shall not be declared with 6040 /// the same name as an entity in global scope. 6041 template<typename T> 6042 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, 6043 LookupResult &Previous) { 6044 if (!S.getLangOpts().CPlusPlus) { 6045 // In C, when declaring a global variable, look for a corresponding 'extern' 6046 // variable declared in function scope. We don't need this in C++, because 6047 // we find local extern decls in the surrounding file-scope DeclContext. 6048 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 6049 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) { 6050 Previous.clear(); 6051 Previous.addDecl(Prev); 6052 return true; 6053 } 6054 } 6055 return false; 6056 } 6057 6058 // A declaration in the translation unit can conflict with an extern "C" 6059 // declaration. 6060 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) 6061 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous); 6062 6063 // An extern "C" declaration can conflict with a declaration in the 6064 // translation unit or can be a redeclaration of an extern "C" declaration 6065 // in another scope. 6066 if (isIncompleteDeclExternC(S,ND)) 6067 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous); 6068 6069 // Neither global nor extern "C": nothing to do. 6070 return false; 6071 } 6072 6073 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) { 6074 // If the decl is already known invalid, don't check it. 6075 if (NewVD->isInvalidDecl()) 6076 return; 6077 6078 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo(); 6079 QualType T = TInfo->getType(); 6080 6081 // Defer checking an 'auto' type until its initializer is attached. 6082 if (T->isUndeducedType()) 6083 return; 6084 6085 if (NewVD->hasAttrs()) 6086 CheckAlignasUnderalignment(NewVD); 6087 6088 if (T->isObjCObjectType()) { 6089 Diag(NewVD->getLocation(), diag::err_statically_allocated_object) 6090 << FixItHint::CreateInsertion(NewVD->getLocation(), "*"); 6091 T = Context.getObjCObjectPointerType(T); 6092 NewVD->setType(T); 6093 } 6094 6095 // Emit an error if an address space was applied to decl with local storage. 6096 // This includes arrays of objects with address space qualifiers, but not 6097 // automatic variables that point to other address spaces. 6098 // ISO/IEC TR 18037 S5.1.2 6099 if (NewVD->hasLocalStorage() && T.getAddressSpace() != 0) { 6100 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl); 6101 NewVD->setInvalidDecl(); 6102 return; 6103 } 6104 6105 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the 6106 // __constant address space. 6107 if (getLangOpts().OpenCL && NewVD->isFileVarDecl() 6108 && T.getAddressSpace() != LangAS::opencl_constant 6109 && !T->isSamplerT()){ 6110 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space); 6111 NewVD->setInvalidDecl(); 6112 return; 6113 } 6114 6115 // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program 6116 // scope. 6117 if ((getLangOpts().OpenCLVersion >= 120) 6118 && NewVD->isStaticLocal()) { 6119 Diag(NewVD->getLocation(), diag::err_static_function_scope); 6120 NewVD->setInvalidDecl(); 6121 return; 6122 } 6123 6124 if (NewVD->hasLocalStorage() && T.isObjCGCWeak() 6125 && !NewVD->hasAttr<BlocksAttr>()) { 6126 if (getLangOpts().getGC() != LangOptions::NonGC) 6127 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local); 6128 else { 6129 assert(!getLangOpts().ObjCAutoRefCount); 6130 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local); 6131 } 6132 } 6133 6134 bool isVM = T->isVariablyModifiedType(); 6135 if (isVM || NewVD->hasAttr<CleanupAttr>() || 6136 NewVD->hasAttr<BlocksAttr>()) 6137 getCurFunction()->setHasBranchProtectedScope(); 6138 6139 if ((isVM && NewVD->hasLinkage()) || 6140 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) { 6141 bool SizeIsNegative; 6142 llvm::APSInt Oversized; 6143 TypeSourceInfo *FixedTInfo = 6144 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 6145 SizeIsNegative, Oversized); 6146 if (!FixedTInfo && T->isVariableArrayType()) { 6147 const VariableArrayType *VAT = Context.getAsVariableArrayType(T); 6148 // FIXME: This won't give the correct result for 6149 // int a[10][n]; 6150 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange(); 6151 6152 if (NewVD->isFileVarDecl()) 6153 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope) 6154 << SizeRange; 6155 else if (NewVD->isStaticLocal()) 6156 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage) 6157 << SizeRange; 6158 else 6159 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage) 6160 << SizeRange; 6161 NewVD->setInvalidDecl(); 6162 return; 6163 } 6164 6165 if (!FixedTInfo) { 6166 if (NewVD->isFileVarDecl()) 6167 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope); 6168 else 6169 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage); 6170 NewVD->setInvalidDecl(); 6171 return; 6172 } 6173 6174 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size); 6175 NewVD->setType(FixedTInfo->getType()); 6176 NewVD->setTypeSourceInfo(FixedTInfo); 6177 } 6178 6179 if (T->isVoidType()) { 6180 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names 6181 // of objects and functions. 6182 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) { 6183 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type) 6184 << T; 6185 NewVD->setInvalidDecl(); 6186 return; 6187 } 6188 } 6189 6190 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) { 6191 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal); 6192 NewVD->setInvalidDecl(); 6193 return; 6194 } 6195 6196 if (isVM && NewVD->hasAttr<BlocksAttr>()) { 6197 Diag(NewVD->getLocation(), diag::err_block_on_vm); 6198 NewVD->setInvalidDecl(); 6199 return; 6200 } 6201 6202 if (NewVD->isConstexpr() && !T->isDependentType() && 6203 RequireLiteralType(NewVD->getLocation(), T, 6204 diag::err_constexpr_var_non_literal)) { 6205 NewVD->setInvalidDecl(); 6206 return; 6207 } 6208 } 6209 6210 /// \brief Perform semantic checking on a newly-created variable 6211 /// declaration. 6212 /// 6213 /// This routine performs all of the type-checking required for a 6214 /// variable declaration once it has been built. It is used both to 6215 /// check variables after they have been parsed and their declarators 6216 /// have been translated into a declaration, and to check variables 6217 /// that have been instantiated from a template. 6218 /// 6219 /// Sets NewVD->isInvalidDecl() if an error was encountered. 6220 /// 6221 /// Returns true if the variable declaration is a redeclaration. 6222 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) { 6223 CheckVariableDeclarationType(NewVD); 6224 6225 // If the decl is already known invalid, don't check it. 6226 if (NewVD->isInvalidDecl()) 6227 return false; 6228 6229 // If we did not find anything by this name, look for a non-visible 6230 // extern "C" declaration with the same name. 6231 if (Previous.empty() && 6232 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous)) 6233 Previous.setShadowed(); 6234 6235 // Filter out any non-conflicting previous declarations. 6236 filterNonConflictingPreviousDecls(Context, NewVD, Previous); 6237 6238 if (!Previous.empty()) { 6239 MergeVarDecl(NewVD, Previous); 6240 return true; 6241 } 6242 return false; 6243 } 6244 6245 /// \brief Data used with FindOverriddenMethod 6246 struct FindOverriddenMethodData { 6247 Sema *S; 6248 CXXMethodDecl *Method; 6249 }; 6250 6251 /// \brief Member lookup function that determines whether a given C++ 6252 /// method overrides a method in a base class, to be used with 6253 /// CXXRecordDecl::lookupInBases(). 6254 static bool FindOverriddenMethod(const CXXBaseSpecifier *Specifier, 6255 CXXBasePath &Path, 6256 void *UserData) { 6257 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); 6258 6259 FindOverriddenMethodData *Data 6260 = reinterpret_cast<FindOverriddenMethodData*>(UserData); 6261 6262 DeclarationName Name = Data->Method->getDeclName(); 6263 6264 // FIXME: Do we care about other names here too? 6265 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6266 // We really want to find the base class destructor here. 6267 QualType T = Data->S->Context.getTypeDeclType(BaseRecord); 6268 CanQualType CT = Data->S->Context.getCanonicalType(T); 6269 6270 Name = Data->S->Context.DeclarationNames.getCXXDestructorName(CT); 6271 } 6272 6273 for (Path.Decls = BaseRecord->lookup(Name); 6274 !Path.Decls.empty(); 6275 Path.Decls = Path.Decls.slice(1)) { 6276 NamedDecl *D = Path.Decls.front(); 6277 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 6278 if (MD->isVirtual() && !Data->S->IsOverload(Data->Method, MD, false)) 6279 return true; 6280 } 6281 } 6282 6283 return false; 6284 } 6285 6286 namespace { 6287 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted }; 6288 } 6289 /// \brief Report an error regarding overriding, along with any relevant 6290 /// overriden methods. 6291 /// 6292 /// \param DiagID the primary error to report. 6293 /// \param MD the overriding method. 6294 /// \param OEK which overrides to include as notes. 6295 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD, 6296 OverrideErrorKind OEK = OEK_All) { 6297 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName(); 6298 for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(), 6299 E = MD->end_overridden_methods(); 6300 I != E; ++I) { 6301 // This check (& the OEK parameter) could be replaced by a predicate, but 6302 // without lambdas that would be overkill. This is still nicer than writing 6303 // out the diag loop 3 times. 6304 if ((OEK == OEK_All) || 6305 (OEK == OEK_NonDeleted && !(*I)->isDeleted()) || 6306 (OEK == OEK_Deleted && (*I)->isDeleted())) 6307 S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function); 6308 } 6309 } 6310 6311 /// AddOverriddenMethods - See if a method overrides any in the base classes, 6312 /// and if so, check that it's a valid override and remember it. 6313 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) { 6314 // Look for virtual methods in base classes that this method might override. 6315 CXXBasePaths Paths; 6316 FindOverriddenMethodData Data; 6317 Data.Method = MD; 6318 Data.S = this; 6319 bool hasDeletedOverridenMethods = false; 6320 bool hasNonDeletedOverridenMethods = false; 6321 bool AddedAny = false; 6322 if (DC->lookupInBases(&FindOverriddenMethod, &Data, Paths)) { 6323 for (auto *I : Paths.found_decls()) { 6324 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) { 6325 MD->addOverriddenMethod(OldMD->getCanonicalDecl()); 6326 if (!CheckOverridingFunctionReturnType(MD, OldMD) && 6327 !CheckOverridingFunctionAttributes(MD, OldMD) && 6328 !CheckOverridingFunctionExceptionSpec(MD, OldMD) && 6329 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) { 6330 hasDeletedOverridenMethods |= OldMD->isDeleted(); 6331 hasNonDeletedOverridenMethods |= !OldMD->isDeleted(); 6332 AddedAny = true; 6333 } 6334 } 6335 } 6336 } 6337 6338 if (hasDeletedOverridenMethods && !MD->isDeleted()) { 6339 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted); 6340 } 6341 if (hasNonDeletedOverridenMethods && MD->isDeleted()) { 6342 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted); 6343 } 6344 6345 return AddedAny; 6346 } 6347 6348 namespace { 6349 // Struct for holding all of the extra arguments needed by 6350 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator. 6351 struct ActOnFDArgs { 6352 Scope *S; 6353 Declarator &D; 6354 MultiTemplateParamsArg TemplateParamLists; 6355 bool AddToScope; 6356 }; 6357 } 6358 6359 namespace { 6360 6361 // Callback to only accept typo corrections that have a non-zero edit distance. 6362 // Also only accept corrections that have the same parent decl. 6363 class DifferentNameValidatorCCC : public CorrectionCandidateCallback { 6364 public: 6365 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD, 6366 CXXRecordDecl *Parent) 6367 : Context(Context), OriginalFD(TypoFD), 6368 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {} 6369 6370 bool ValidateCandidate(const TypoCorrection &candidate) override { 6371 if (candidate.getEditDistance() == 0) 6372 return false; 6373 6374 SmallVector<unsigned, 1> MismatchedParams; 6375 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(), 6376 CDeclEnd = candidate.end(); 6377 CDecl != CDeclEnd; ++CDecl) { 6378 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6379 6380 if (FD && !FD->hasBody() && 6381 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) { 6382 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 6383 CXXRecordDecl *Parent = MD->getParent(); 6384 if (Parent && Parent->getCanonicalDecl() == ExpectedParent) 6385 return true; 6386 } else if (!ExpectedParent) { 6387 return true; 6388 } 6389 } 6390 } 6391 6392 return false; 6393 } 6394 6395 private: 6396 ASTContext &Context; 6397 FunctionDecl *OriginalFD; 6398 CXXRecordDecl *ExpectedParent; 6399 }; 6400 6401 } 6402 6403 /// \brief Generate diagnostics for an invalid function redeclaration. 6404 /// 6405 /// This routine handles generating the diagnostic messages for an invalid 6406 /// function redeclaration, including finding possible similar declarations 6407 /// or performing typo correction if there are no previous declarations with 6408 /// the same name. 6409 /// 6410 /// Returns a NamedDecl iff typo correction was performed and substituting in 6411 /// the new declaration name does not cause new errors. 6412 static NamedDecl *DiagnoseInvalidRedeclaration( 6413 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, 6414 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) { 6415 DeclarationName Name = NewFD->getDeclName(); 6416 DeclContext *NewDC = NewFD->getDeclContext(); 6417 SmallVector<unsigned, 1> MismatchedParams; 6418 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches; 6419 TypoCorrection Correction; 6420 bool IsDefinition = ExtraArgs.D.isFunctionDefinition(); 6421 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend 6422 : diag::err_member_decl_does_not_match; 6423 LookupResult Prev(SemaRef, Name, NewFD->getLocation(), 6424 IsLocalFriend ? Sema::LookupLocalFriendName 6425 : Sema::LookupOrdinaryName, 6426 Sema::ForRedeclaration); 6427 6428 NewFD->setInvalidDecl(); 6429 if (IsLocalFriend) 6430 SemaRef.LookupName(Prev, S); 6431 else 6432 SemaRef.LookupQualifiedName(Prev, NewDC); 6433 assert(!Prev.isAmbiguous() && 6434 "Cannot have an ambiguity in previous-declaration lookup"); 6435 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 6436 DifferentNameValidatorCCC Validator(SemaRef.Context, NewFD, 6437 MD ? MD->getParent() : nullptr); 6438 if (!Prev.empty()) { 6439 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end(); 6440 Func != FuncEnd; ++Func) { 6441 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func); 6442 if (FD && 6443 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6444 // Add 1 to the index so that 0 can mean the mismatch didn't 6445 // involve a parameter 6446 unsigned ParamNum = 6447 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1; 6448 NearMatches.push_back(std::make_pair(FD, ParamNum)); 6449 } 6450 } 6451 // If the qualified name lookup yielded nothing, try typo correction 6452 } else if ((Correction = SemaRef.CorrectTypo( 6453 Prev.getLookupNameInfo(), Prev.getLookupKind(), S, 6454 &ExtraArgs.D.getCXXScopeSpec(), Validator, 6455 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) { 6456 // Set up everything for the call to ActOnFunctionDeclarator 6457 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(), 6458 ExtraArgs.D.getIdentifierLoc()); 6459 Previous.clear(); 6460 Previous.setLookupName(Correction.getCorrection()); 6461 for (TypoCorrection::decl_iterator CDecl = Correction.begin(), 6462 CDeclEnd = Correction.end(); 6463 CDecl != CDeclEnd; ++CDecl) { 6464 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl); 6465 if (FD && !FD->hasBody() && 6466 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) { 6467 Previous.addDecl(FD); 6468 } 6469 } 6470 bool wasRedeclaration = ExtraArgs.D.isRedeclaration(); 6471 6472 NamedDecl *Result; 6473 // Retry building the function declaration with the new previous 6474 // declarations, and with errors suppressed. 6475 { 6476 // Trap errors. 6477 Sema::SFINAETrap Trap(SemaRef); 6478 6479 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the 6480 // pieces need to verify the typo-corrected C++ declaration and hopefully 6481 // eliminate the need for the parameter pack ExtraArgs. 6482 Result = SemaRef.ActOnFunctionDeclarator( 6483 ExtraArgs.S, ExtraArgs.D, 6484 Correction.getCorrectionDecl()->getDeclContext(), 6485 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists, 6486 ExtraArgs.AddToScope); 6487 6488 if (Trap.hasErrorOccurred()) 6489 Result = nullptr; 6490 } 6491 6492 if (Result) { 6493 // Determine which correction we picked. 6494 Decl *Canonical = Result->getCanonicalDecl(); 6495 for (LookupResult::iterator I = Previous.begin(), E = Previous.end(); 6496 I != E; ++I) 6497 if ((*I)->getCanonicalDecl() == Canonical) 6498 Correction.setCorrectionDecl(*I); 6499 6500 SemaRef.diagnoseTypo( 6501 Correction, 6502 SemaRef.PDiag(IsLocalFriend 6503 ? diag::err_no_matching_local_friend_suggest 6504 : diag::err_member_decl_does_not_match_suggest) 6505 << Name << NewDC << IsDefinition); 6506 return Result; 6507 } 6508 6509 // Pretend the typo correction never occurred 6510 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(), 6511 ExtraArgs.D.getIdentifierLoc()); 6512 ExtraArgs.D.setRedeclaration(wasRedeclaration); 6513 Previous.clear(); 6514 Previous.setLookupName(Name); 6515 } 6516 6517 SemaRef.Diag(NewFD->getLocation(), DiagMsg) 6518 << Name << NewDC << IsDefinition << NewFD->getLocation(); 6519 6520 bool NewFDisConst = false; 6521 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD)) 6522 NewFDisConst = NewMD->isConst(); 6523 6524 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator 6525 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end(); 6526 NearMatch != NearMatchEnd; ++NearMatch) { 6527 FunctionDecl *FD = NearMatch->first; 6528 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD); 6529 bool FDisConst = MD && MD->isConst(); 6530 bool IsMember = MD || !IsLocalFriend; 6531 6532 // FIXME: These notes are poorly worded for the local friend case. 6533 if (unsigned Idx = NearMatch->second) { 6534 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1); 6535 SourceLocation Loc = FDParam->getTypeSpecStartLoc(); 6536 if (Loc.isInvalid()) Loc = FD->getLocation(); 6537 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match 6538 : diag::note_local_decl_close_param_match) 6539 << Idx << FDParam->getType() 6540 << NewFD->getParamDecl(Idx - 1)->getType(); 6541 } else if (FDisConst != NewFDisConst) { 6542 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match) 6543 << NewFDisConst << FD->getSourceRange().getEnd(); 6544 } else 6545 SemaRef.Diag(FD->getLocation(), 6546 IsMember ? diag::note_member_def_close_match 6547 : diag::note_local_decl_close_match); 6548 } 6549 return nullptr; 6550 } 6551 6552 static FunctionDecl::StorageClass getFunctionStorageClass(Sema &SemaRef, 6553 Declarator &D) { 6554 switch (D.getDeclSpec().getStorageClassSpec()) { 6555 default: llvm_unreachable("Unknown storage class!"); 6556 case DeclSpec::SCS_auto: 6557 case DeclSpec::SCS_register: 6558 case DeclSpec::SCS_mutable: 6559 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6560 diag::err_typecheck_sclass_func); 6561 D.setInvalidType(); 6562 break; 6563 case DeclSpec::SCS_unspecified: break; 6564 case DeclSpec::SCS_extern: 6565 if (D.getDeclSpec().isExternInLinkageSpec()) 6566 return SC_None; 6567 return SC_Extern; 6568 case DeclSpec::SCS_static: { 6569 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) { 6570 // C99 6.7.1p5: 6571 // The declaration of an identifier for a function that has 6572 // block scope shall have no explicit storage-class specifier 6573 // other than extern 6574 // See also (C++ [dcl.stc]p4). 6575 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(), 6576 diag::err_static_block_func); 6577 break; 6578 } else 6579 return SC_Static; 6580 } 6581 case DeclSpec::SCS_private_extern: return SC_PrivateExtern; 6582 } 6583 6584 // No explicit storage class has already been returned 6585 return SC_None; 6586 } 6587 6588 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, 6589 DeclContext *DC, QualType &R, 6590 TypeSourceInfo *TInfo, 6591 FunctionDecl::StorageClass SC, 6592 bool &IsVirtualOkay) { 6593 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D); 6594 DeclarationName Name = NameInfo.getName(); 6595 6596 FunctionDecl *NewFD = nullptr; 6597 bool isInline = D.getDeclSpec().isInlineSpecified(); 6598 6599 if (!SemaRef.getLangOpts().CPlusPlus) { 6600 // Determine whether the function was written with a 6601 // prototype. This true when: 6602 // - there is a prototype in the declarator, or 6603 // - the type R of the function is some kind of typedef or other reference 6604 // to a type name (which eventually refers to a function type). 6605 bool HasPrototype = 6606 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) || 6607 (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType()); 6608 6609 NewFD = FunctionDecl::Create(SemaRef.Context, DC, 6610 D.getLocStart(), NameInfo, R, 6611 TInfo, SC, isInline, 6612 HasPrototype, false); 6613 if (D.isInvalidType()) 6614 NewFD->setInvalidDecl(); 6615 6616 // Set the lexical context. 6617 NewFD->setLexicalDeclContext(SemaRef.CurContext); 6618 6619 return NewFD; 6620 } 6621 6622 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6623 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6624 6625 // Check that the return type is not an abstract class type. 6626 // For record types, this is done by the AbstractClassUsageDiagnoser once 6627 // the class has been completely parsed. 6628 if (!DC->isRecord() && 6629 SemaRef.RequireNonAbstractType( 6630 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(), 6631 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType)) 6632 D.setInvalidType(); 6633 6634 if (Name.getNameKind() == DeclarationName::CXXConstructorName) { 6635 // This is a C++ constructor declaration. 6636 assert(DC->isRecord() && 6637 "Constructors can only be declared in a member context"); 6638 6639 R = SemaRef.CheckConstructorDeclarator(D, R, SC); 6640 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6641 D.getLocStart(), NameInfo, 6642 R, TInfo, isExplicit, isInline, 6643 /*isImplicitlyDeclared=*/false, 6644 isConstexpr); 6645 6646 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 6647 // This is a C++ destructor declaration. 6648 if (DC->isRecord()) { 6649 R = SemaRef.CheckDestructorDeclarator(D, R, SC); 6650 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); 6651 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create( 6652 SemaRef.Context, Record, 6653 D.getLocStart(), 6654 NameInfo, R, TInfo, isInline, 6655 /*isImplicitlyDeclared=*/false); 6656 6657 // If the class is complete, then we now create the implicit exception 6658 // specification. If the class is incomplete or dependent, we can't do 6659 // it yet. 6660 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() && 6661 Record->getDefinition() && !Record->isBeingDefined() && 6662 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) { 6663 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD); 6664 } 6665 6666 IsVirtualOkay = true; 6667 return NewDD; 6668 6669 } else { 6670 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member); 6671 D.setInvalidType(); 6672 6673 // Create a FunctionDecl to satisfy the function definition parsing 6674 // code path. 6675 return FunctionDecl::Create(SemaRef.Context, DC, 6676 D.getLocStart(), 6677 D.getIdentifierLoc(), Name, R, TInfo, 6678 SC, isInline, 6679 /*hasPrototype=*/true, isConstexpr); 6680 } 6681 6682 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) { 6683 if (!DC->isRecord()) { 6684 SemaRef.Diag(D.getIdentifierLoc(), 6685 diag::err_conv_function_not_member); 6686 return nullptr; 6687 } 6688 6689 SemaRef.CheckConversionDeclarator(D, R, SC); 6690 IsVirtualOkay = true; 6691 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC), 6692 D.getLocStart(), NameInfo, 6693 R, TInfo, isInline, isExplicit, 6694 isConstexpr, SourceLocation()); 6695 6696 } else if (DC->isRecord()) { 6697 // If the name of the function is the same as the name of the record, 6698 // then this must be an invalid constructor that has a return type. 6699 // (The parser checks for a return type and makes the declarator a 6700 // constructor if it has no return type). 6701 if (Name.getAsIdentifierInfo() && 6702 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){ 6703 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type) 6704 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()) 6705 << SourceRange(D.getIdentifierLoc()); 6706 return nullptr; 6707 } 6708 6709 // This is a C++ method declaration. 6710 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context, 6711 cast<CXXRecordDecl>(DC), 6712 D.getLocStart(), NameInfo, R, 6713 TInfo, SC, isInline, 6714 isConstexpr, SourceLocation()); 6715 IsVirtualOkay = !Ret->isStatic(); 6716 return Ret; 6717 } else { 6718 // Determine whether the function was written with a 6719 // prototype. This true when: 6720 // - we're in C++ (where every function has a prototype), 6721 return FunctionDecl::Create(SemaRef.Context, DC, 6722 D.getLocStart(), 6723 NameInfo, R, TInfo, SC, isInline, 6724 true/*HasPrototype*/, isConstexpr); 6725 } 6726 } 6727 6728 enum OpenCLParamType { 6729 ValidKernelParam, 6730 PtrPtrKernelParam, 6731 PtrKernelParam, 6732 PrivatePtrKernelParam, 6733 InvalidKernelParam, 6734 RecordKernelParam 6735 }; 6736 6737 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) { 6738 if (PT->isPointerType()) { 6739 QualType PointeeType = PT->getPointeeType(); 6740 if (PointeeType->isPointerType()) 6741 return PtrPtrKernelParam; 6742 return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam 6743 : PtrKernelParam; 6744 } 6745 6746 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can 6747 // be used as builtin types. 6748 6749 if (PT->isImageType()) 6750 return PtrKernelParam; 6751 6752 if (PT->isBooleanType()) 6753 return InvalidKernelParam; 6754 6755 if (PT->isEventT()) 6756 return InvalidKernelParam; 6757 6758 if (PT->isHalfType()) 6759 return InvalidKernelParam; 6760 6761 if (PT->isRecordType()) 6762 return RecordKernelParam; 6763 6764 return ValidKernelParam; 6765 } 6766 6767 static void checkIsValidOpenCLKernelParameter( 6768 Sema &S, 6769 Declarator &D, 6770 ParmVarDecl *Param, 6771 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) { 6772 QualType PT = Param->getType(); 6773 6774 // Cache the valid types we encounter to avoid rechecking structs that are 6775 // used again 6776 if (ValidTypes.count(PT.getTypePtr())) 6777 return; 6778 6779 switch (getOpenCLKernelParameterType(PT)) { 6780 case PtrPtrKernelParam: 6781 // OpenCL v1.2 s6.9.a: 6782 // A kernel function argument cannot be declared as a 6783 // pointer to a pointer type. 6784 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param); 6785 D.setInvalidType(); 6786 return; 6787 6788 case PrivatePtrKernelParam: 6789 // OpenCL v1.2 s6.9.a: 6790 // A kernel function argument cannot be declared as a 6791 // pointer to the private address space. 6792 S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param); 6793 D.setInvalidType(); 6794 return; 6795 6796 // OpenCL v1.2 s6.9.k: 6797 // Arguments to kernel functions in a program cannot be declared with the 6798 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and 6799 // uintptr_t or a struct and/or union that contain fields declared to be 6800 // one of these built-in scalar types. 6801 6802 case InvalidKernelParam: 6803 // OpenCL v1.2 s6.8 n: 6804 // A kernel function argument cannot be declared 6805 // of event_t type. 6806 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6807 D.setInvalidType(); 6808 return; 6809 6810 case PtrKernelParam: 6811 case ValidKernelParam: 6812 ValidTypes.insert(PT.getTypePtr()); 6813 return; 6814 6815 case RecordKernelParam: 6816 break; 6817 } 6818 6819 // Track nested structs we will inspect 6820 SmallVector<const Decl *, 4> VisitStack; 6821 6822 // Track where we are in the nested structs. Items will migrate from 6823 // VisitStack to HistoryStack as we do the DFS for bad field. 6824 SmallVector<const FieldDecl *, 4> HistoryStack; 6825 HistoryStack.push_back(nullptr); 6826 6827 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl(); 6828 VisitStack.push_back(PD); 6829 6830 assert(VisitStack.back() && "First decl null?"); 6831 6832 do { 6833 const Decl *Next = VisitStack.pop_back_val(); 6834 if (!Next) { 6835 assert(!HistoryStack.empty()); 6836 // Found a marker, we have gone up a level 6837 if (const FieldDecl *Hist = HistoryStack.pop_back_val()) 6838 ValidTypes.insert(Hist->getType().getTypePtr()); 6839 6840 continue; 6841 } 6842 6843 // Adds everything except the original parameter declaration (which is not a 6844 // field itself) to the history stack. 6845 const RecordDecl *RD; 6846 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) { 6847 HistoryStack.push_back(Field); 6848 RD = Field->getType()->castAs<RecordType>()->getDecl(); 6849 } else { 6850 RD = cast<RecordDecl>(Next); 6851 } 6852 6853 // Add a null marker so we know when we've gone back up a level 6854 VisitStack.push_back(nullptr); 6855 6856 for (const auto *FD : RD->fields()) { 6857 QualType QT = FD->getType(); 6858 6859 if (ValidTypes.count(QT.getTypePtr())) 6860 continue; 6861 6862 OpenCLParamType ParamType = getOpenCLKernelParameterType(QT); 6863 if (ParamType == ValidKernelParam) 6864 continue; 6865 6866 if (ParamType == RecordKernelParam) { 6867 VisitStack.push_back(FD); 6868 continue; 6869 } 6870 6871 // OpenCL v1.2 s6.9.p: 6872 // Arguments to kernel functions that are declared to be a struct or union 6873 // do not allow OpenCL objects to be passed as elements of the struct or 6874 // union. 6875 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam || 6876 ParamType == PrivatePtrKernelParam) { 6877 S.Diag(Param->getLocation(), 6878 diag::err_record_with_pointers_kernel_param) 6879 << PT->isUnionType() 6880 << PT; 6881 } else { 6882 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT; 6883 } 6884 6885 S.Diag(PD->getLocation(), diag::note_within_field_of_type) 6886 << PD->getDeclName(); 6887 6888 // We have an error, now let's go back up through history and show where 6889 // the offending field came from 6890 for (ArrayRef<const FieldDecl *>::const_iterator I = HistoryStack.begin() + 1, 6891 E = HistoryStack.end(); I != E; ++I) { 6892 const FieldDecl *OuterField = *I; 6893 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type) 6894 << OuterField->getType(); 6895 } 6896 6897 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here) 6898 << QT->isPointerType() 6899 << QT; 6900 D.setInvalidType(); 6901 return; 6902 } 6903 } while (!VisitStack.empty()); 6904 } 6905 6906 NamedDecl* 6907 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, 6908 TypeSourceInfo *TInfo, LookupResult &Previous, 6909 MultiTemplateParamsArg TemplateParamLists, 6910 bool &AddToScope) { 6911 QualType R = TInfo->getType(); 6912 6913 assert(R.getTypePtr()->isFunctionType()); 6914 6915 // TODO: consider using NameInfo for diagnostic. 6916 DeclarationNameInfo NameInfo = GetNameForDeclarator(D); 6917 DeclarationName Name = NameInfo.getName(); 6918 FunctionDecl::StorageClass SC = getFunctionStorageClass(*this, D); 6919 6920 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 6921 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 6922 diag::err_invalid_thread) 6923 << DeclSpec::getSpecifierName(TSCS); 6924 6925 if (D.isFirstDeclarationOfMember()) 6926 adjustMemberFunctionCC(R, D.isStaticMember()); 6927 6928 bool isFriend = false; 6929 FunctionTemplateDecl *FunctionTemplate = nullptr; 6930 bool isExplicitSpecialization = false; 6931 bool isFunctionTemplateSpecialization = false; 6932 6933 bool isDependentClassScopeExplicitSpecialization = false; 6934 bool HasExplicitTemplateArgs = false; 6935 TemplateArgumentListInfo TemplateArgs; 6936 6937 bool isVirtualOkay = false; 6938 6939 DeclContext *OriginalDC = DC; 6940 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC); 6941 6942 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC, 6943 isVirtualOkay); 6944 if (!NewFD) return nullptr; 6945 6946 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer()) 6947 NewFD->setTopLevelDeclInObjCContainer(); 6948 6949 // Set the lexical context. If this is a function-scope declaration, or has a 6950 // C++ scope specifier, or is the object of a friend declaration, the lexical 6951 // context will be different from the semantic context. 6952 NewFD->setLexicalDeclContext(CurContext); 6953 6954 if (IsLocalExternDecl) 6955 NewFD->setLocalExternDecl(); 6956 6957 if (getLangOpts().CPlusPlus) { 6958 bool isInline = D.getDeclSpec().isInlineSpecified(); 6959 bool isVirtual = D.getDeclSpec().isVirtualSpecified(); 6960 bool isExplicit = D.getDeclSpec().isExplicitSpecified(); 6961 bool isConstexpr = D.getDeclSpec().isConstexprSpecified(); 6962 isFriend = D.getDeclSpec().isFriendSpecified(); 6963 if (isFriend && !isInline && D.isFunctionDefinition()) { 6964 // C++ [class.friend]p5 6965 // A function can be defined in a friend declaration of a 6966 // class . . . . Such a function is implicitly inline. 6967 NewFD->setImplicitlyInline(); 6968 } 6969 6970 // If this is a method defined in an __interface, and is not a constructor 6971 // or an overloaded operator, then set the pure flag (isVirtual will already 6972 // return true). 6973 if (const CXXRecordDecl *Parent = 6974 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) { 6975 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided()) 6976 NewFD->setPure(true); 6977 } 6978 6979 SetNestedNameSpecifier(NewFD, D); 6980 isExplicitSpecialization = false; 6981 isFunctionTemplateSpecialization = false; 6982 if (D.isInvalidType()) 6983 NewFD->setInvalidDecl(); 6984 6985 // Match up the template parameter lists with the scope specifier, then 6986 // determine whether we have a template or a template specialization. 6987 bool Invalid = false; 6988 if (TemplateParameterList *TemplateParams = 6989 MatchTemplateParametersToScopeSpecifier( 6990 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(), 6991 D.getCXXScopeSpec(), 6992 D.getName().getKind() == UnqualifiedId::IK_TemplateId 6993 ? D.getName().TemplateId 6994 : nullptr, 6995 TemplateParamLists, isFriend, isExplicitSpecialization, 6996 Invalid)) { 6997 if (TemplateParams->size() > 0) { 6998 // This is a function template 6999 7000 // Check that we can declare a template here. 7001 if (CheckTemplateDeclScope(S, TemplateParams)) 7002 return nullptr; 7003 7004 // A destructor cannot be a template. 7005 if (Name.getNameKind() == DeclarationName::CXXDestructorName) { 7006 Diag(NewFD->getLocation(), diag::err_destructor_template); 7007 return nullptr; 7008 } 7009 7010 // If we're adding a template to a dependent context, we may need to 7011 // rebuilding some of the types used within the template parameter list, 7012 // now that we know what the current instantiation is. 7013 if (DC->isDependentContext()) { 7014 ContextRAII SavedContext(*this, DC); 7015 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams)) 7016 Invalid = true; 7017 } 7018 7019 7020 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC, 7021 NewFD->getLocation(), 7022 Name, TemplateParams, 7023 NewFD); 7024 FunctionTemplate->setLexicalDeclContext(CurContext); 7025 NewFD->setDescribedFunctionTemplate(FunctionTemplate); 7026 7027 // For source fidelity, store the other template param lists. 7028 if (TemplateParamLists.size() > 1) { 7029 NewFD->setTemplateParameterListsInfo(Context, 7030 TemplateParamLists.size() - 1, 7031 TemplateParamLists.data()); 7032 } 7033 } else { 7034 // This is a function template specialization. 7035 isFunctionTemplateSpecialization = true; 7036 // For source fidelity, store all the template param lists. 7037 if (TemplateParamLists.size() > 0) 7038 NewFD->setTemplateParameterListsInfo(Context, 7039 TemplateParamLists.size(), 7040 TemplateParamLists.data()); 7041 7042 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);". 7043 if (isFriend) { 7044 // We want to remove the "template<>", found here. 7045 SourceRange RemoveRange = TemplateParams->getSourceRange(); 7046 7047 // If we remove the template<> and the name is not a 7048 // template-id, we're actually silently creating a problem: 7049 // the friend declaration will refer to an untemplated decl, 7050 // and clearly the user wants a template specialization. So 7051 // we need to insert '<>' after the name. 7052 SourceLocation InsertLoc; 7053 if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) { 7054 InsertLoc = D.getName().getSourceRange().getEnd(); 7055 InsertLoc = getLocForEndOfToken(InsertLoc); 7056 } 7057 7058 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend) 7059 << Name << RemoveRange 7060 << FixItHint::CreateRemoval(RemoveRange) 7061 << FixItHint::CreateInsertion(InsertLoc, "<>"); 7062 } 7063 } 7064 } 7065 else { 7066 // All template param lists were matched against the scope specifier: 7067 // this is NOT (an explicit specialization of) a template. 7068 if (TemplateParamLists.size() > 0) 7069 // For source fidelity, store all the template param lists. 7070 NewFD->setTemplateParameterListsInfo(Context, 7071 TemplateParamLists.size(), 7072 TemplateParamLists.data()); 7073 } 7074 7075 if (Invalid) { 7076 NewFD->setInvalidDecl(); 7077 if (FunctionTemplate) 7078 FunctionTemplate->setInvalidDecl(); 7079 } 7080 7081 // C++ [dcl.fct.spec]p5: 7082 // The virtual specifier shall only be used in declarations of 7083 // nonstatic class member functions that appear within a 7084 // member-specification of a class declaration; see 10.3. 7085 // 7086 if (isVirtual && !NewFD->isInvalidDecl()) { 7087 if (!isVirtualOkay) { 7088 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7089 diag::err_virtual_non_function); 7090 } else if (!CurContext->isRecord()) { 7091 // 'virtual' was specified outside of the class. 7092 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7093 diag::err_virtual_out_of_class) 7094 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7095 } else if (NewFD->getDescribedFunctionTemplate()) { 7096 // C++ [temp.mem]p3: 7097 // A member function template shall not be virtual. 7098 Diag(D.getDeclSpec().getVirtualSpecLoc(), 7099 diag::err_virtual_member_function_template) 7100 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc()); 7101 } else { 7102 // Okay: Add virtual to the method. 7103 NewFD->setVirtualAsWritten(true); 7104 } 7105 7106 if (getLangOpts().CPlusPlus14 && 7107 NewFD->getReturnType()->isUndeducedType()) 7108 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual); 7109 } 7110 7111 if (getLangOpts().CPlusPlus14 && 7112 (NewFD->isDependentContext() || 7113 (isFriend && CurContext->isDependentContext())) && 7114 NewFD->getReturnType()->isUndeducedType()) { 7115 // If the function template is referenced directly (for instance, as a 7116 // member of the current instantiation), pretend it has a dependent type. 7117 // This is not really justified by the standard, but is the only sane 7118 // thing to do. 7119 // FIXME: For a friend function, we have not marked the function as being 7120 // a friend yet, so 'isDependentContext' on the FD doesn't work. 7121 const FunctionProtoType *FPT = 7122 NewFD->getType()->castAs<FunctionProtoType>(); 7123 QualType Result = 7124 SubstAutoType(FPT->getReturnType(), Context.DependentTy); 7125 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(), 7126 FPT->getExtProtoInfo())); 7127 } 7128 7129 // C++ [dcl.fct.spec]p3: 7130 // The inline specifier shall not appear on a block scope function 7131 // declaration. 7132 if (isInline && !NewFD->isInvalidDecl()) { 7133 if (CurContext->isFunctionOrMethod()) { 7134 // 'inline' is not allowed on block scope function declaration. 7135 Diag(D.getDeclSpec().getInlineSpecLoc(), 7136 diag::err_inline_declaration_block_scope) << Name 7137 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc()); 7138 } 7139 } 7140 7141 // C++ [dcl.fct.spec]p6: 7142 // The explicit specifier shall be used only in the declaration of a 7143 // constructor or conversion function within its class definition; 7144 // see 12.3.1 and 12.3.2. 7145 if (isExplicit && !NewFD->isInvalidDecl()) { 7146 if (!CurContext->isRecord()) { 7147 // 'explicit' was specified outside of the class. 7148 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7149 diag::err_explicit_out_of_class) 7150 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7151 } else if (!isa<CXXConstructorDecl>(NewFD) && 7152 !isa<CXXConversionDecl>(NewFD)) { 7153 // 'explicit' was specified on a function that wasn't a constructor 7154 // or conversion function. 7155 Diag(D.getDeclSpec().getExplicitSpecLoc(), 7156 diag::err_explicit_non_ctor_or_conv_function) 7157 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc()); 7158 } 7159 } 7160 7161 if (isConstexpr) { 7162 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors 7163 // are implicitly inline. 7164 NewFD->setImplicitlyInline(); 7165 7166 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to 7167 // be either constructors or to return a literal type. Therefore, 7168 // destructors cannot be declared constexpr. 7169 if (isa<CXXDestructorDecl>(NewFD)) 7170 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor); 7171 } 7172 7173 // If __module_private__ was specified, mark the function accordingly. 7174 if (D.getDeclSpec().isModulePrivateSpecified()) { 7175 if (isFunctionTemplateSpecialization) { 7176 SourceLocation ModulePrivateLoc 7177 = D.getDeclSpec().getModulePrivateSpecLoc(); 7178 Diag(ModulePrivateLoc, diag::err_module_private_specialization) 7179 << 0 7180 << FixItHint::CreateRemoval(ModulePrivateLoc); 7181 } else { 7182 NewFD->setModulePrivate(); 7183 if (FunctionTemplate) 7184 FunctionTemplate->setModulePrivate(); 7185 } 7186 } 7187 7188 if (isFriend) { 7189 if (FunctionTemplate) { 7190 FunctionTemplate->setObjectOfFriendDecl(); 7191 FunctionTemplate->setAccess(AS_public); 7192 } 7193 NewFD->setObjectOfFriendDecl(); 7194 NewFD->setAccess(AS_public); 7195 } 7196 7197 // If a function is defined as defaulted or deleted, mark it as such now. 7198 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function 7199 // definition kind to FDK_Definition. 7200 switch (D.getFunctionDefinitionKind()) { 7201 case FDK_Declaration: 7202 case FDK_Definition: 7203 break; 7204 7205 case FDK_Defaulted: 7206 NewFD->setDefaulted(); 7207 break; 7208 7209 case FDK_Deleted: 7210 NewFD->setDeletedAsWritten(); 7211 break; 7212 } 7213 7214 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext && 7215 D.isFunctionDefinition()) { 7216 // C++ [class.mfct]p2: 7217 // A member function may be defined (8.4) in its class definition, in 7218 // which case it is an inline member function (7.1.2) 7219 NewFD->setImplicitlyInline(); 7220 } 7221 7222 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) && 7223 !CurContext->isRecord()) { 7224 // C++ [class.static]p1: 7225 // A data or function member of a class may be declared static 7226 // in a class definition, in which case it is a static member of 7227 // the class. 7228 7229 // Complain about the 'static' specifier if it's on an out-of-line 7230 // member function definition. 7231 Diag(D.getDeclSpec().getStorageClassSpecLoc(), 7232 diag::err_static_out_of_line) 7233 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc()); 7234 } 7235 7236 // C++11 [except.spec]p15: 7237 // A deallocation function with no exception-specification is treated 7238 // as if it were specified with noexcept(true). 7239 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>(); 7240 if ((Name.getCXXOverloadedOperator() == OO_Delete || 7241 Name.getCXXOverloadedOperator() == OO_Array_Delete) && 7242 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec()) 7243 NewFD->setType(Context.getFunctionType( 7244 FPT->getReturnType(), FPT->getParamTypes(), 7245 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept))); 7246 } 7247 7248 // Filter out previous declarations that don't match the scope. 7249 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD), 7250 D.getCXXScopeSpec().isNotEmpty() || 7251 isExplicitSpecialization || 7252 isFunctionTemplateSpecialization); 7253 7254 // Handle GNU asm-label extension (encoded as an attribute). 7255 if (Expr *E = (Expr*) D.getAsmLabel()) { 7256 // The parser guarantees this is a string. 7257 StringLiteral *SE = cast<StringLiteral>(E); 7258 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context, 7259 SE->getString(), 0)); 7260 } else if (!ExtnameUndeclaredIdentifiers.empty()) { 7261 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I = 7262 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier()); 7263 if (I != ExtnameUndeclaredIdentifiers.end()) { 7264 NewFD->addAttr(I->second); 7265 ExtnameUndeclaredIdentifiers.erase(I); 7266 } 7267 } 7268 7269 // Copy the parameter declarations from the declarator D to the function 7270 // declaration NewFD, if they are available. First scavenge them into Params. 7271 SmallVector<ParmVarDecl*, 16> Params; 7272 if (D.isFunctionDeclarator()) { 7273 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 7274 7275 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs 7276 // function that takes no arguments, not a function that takes a 7277 // single void argument. 7278 // We let through "const void" here because Sema::GetTypeForDeclarator 7279 // already checks for that case. 7280 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) { 7281 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) { 7282 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param); 7283 assert(Param->getDeclContext() != NewFD && "Was set before ?"); 7284 Param->setDeclContext(NewFD); 7285 Params.push_back(Param); 7286 7287 if (Param->isInvalidDecl()) 7288 NewFD->setInvalidDecl(); 7289 } 7290 } 7291 7292 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) { 7293 // When we're declaring a function with a typedef, typeof, etc as in the 7294 // following example, we'll need to synthesize (unnamed) 7295 // parameters for use in the declaration. 7296 // 7297 // @code 7298 // typedef void fn(int); 7299 // fn f; 7300 // @endcode 7301 7302 // Synthesize a parameter for each argument type. 7303 for (const auto &AI : FT->param_types()) { 7304 ParmVarDecl *Param = 7305 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI); 7306 Param->setScopeInfo(0, Params.size()); 7307 Params.push_back(Param); 7308 } 7309 } else { 7310 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && 7311 "Should not need args for typedef of non-prototype fn"); 7312 } 7313 7314 // Finally, we know we have the right number of parameters, install them. 7315 NewFD->setParams(Params); 7316 7317 // Find all anonymous symbols defined during the declaration of this function 7318 // and add to NewFD. This lets us track decls such 'enum Y' in: 7319 // 7320 // void f(enum Y {AA} x) {} 7321 // 7322 // which would otherwise incorrectly end up in the translation unit scope. 7323 NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope); 7324 DeclsInPrototypeScope.clear(); 7325 7326 if (D.getDeclSpec().isNoreturnSpecified()) 7327 NewFD->addAttr( 7328 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(), 7329 Context, 0)); 7330 7331 // Functions returning a variably modified type violate C99 6.7.5.2p2 7332 // because all functions have linkage. 7333 if (!NewFD->isInvalidDecl() && 7334 NewFD->getReturnType()->isVariablyModifiedType()) { 7335 Diag(NewFD->getLocation(), diag::err_vm_func_decl); 7336 NewFD->setInvalidDecl(); 7337 } 7338 7339 if (D.isFunctionDefinition() && CodeSegStack.CurrentValue && 7340 !NewFD->hasAttr<SectionAttr>()) { 7341 NewFD->addAttr( 7342 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 7343 CodeSegStack.CurrentValue->getString(), 7344 CodeSegStack.CurrentPragmaLocation)); 7345 if (UnifySection(CodeSegStack.CurrentValue->getString(), 7346 PSF_Implicit | PSF_Execute | PSF_Read, NewFD)) 7347 NewFD->dropAttr<SectionAttr>(); 7348 } 7349 7350 // Handle attributes. 7351 ProcessDeclAttributes(S, NewFD, D); 7352 7353 QualType RetType = NewFD->getReturnType(); 7354 const CXXRecordDecl *Ret = RetType->isRecordType() ? 7355 RetType->getAsCXXRecordDecl() : RetType->getPointeeCXXRecordDecl(); 7356 if (!NewFD->isInvalidDecl() && !NewFD->hasAttr<WarnUnusedResultAttr>() && 7357 Ret && Ret->hasAttr<WarnUnusedResultAttr>()) { 7358 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7359 // Attach WarnUnusedResult to functions returning types with that attribute. 7360 // Don't apply the attribute to that type's own non-static member functions 7361 // (to avoid warning on things like assignment operators) 7362 if (!MD || MD->getParent() != Ret) 7363 NewFD->addAttr(WarnUnusedResultAttr::CreateImplicit(Context)); 7364 } 7365 7366 if (getLangOpts().OpenCL) { 7367 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return 7368 // type declaration will generate a compilation error. 7369 unsigned AddressSpace = RetType.getAddressSpace(); 7370 if (AddressSpace == LangAS::opencl_local || 7371 AddressSpace == LangAS::opencl_global || 7372 AddressSpace == LangAS::opencl_constant) { 7373 Diag(NewFD->getLocation(), 7374 diag::err_opencl_return_value_with_address_space); 7375 NewFD->setInvalidDecl(); 7376 } 7377 } 7378 7379 if (!getLangOpts().CPlusPlus) { 7380 // Perform semantic checking on the function declaration. 7381 bool isExplicitSpecialization=false; 7382 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7383 CheckMain(NewFD, D.getDeclSpec()); 7384 7385 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7386 CheckMSVCRTEntryPoint(NewFD); 7387 7388 if (!NewFD->isInvalidDecl()) 7389 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7390 isExplicitSpecialization)); 7391 else if (!Previous.empty()) 7392 // Make graceful recovery from an invalid redeclaration. 7393 D.setRedeclaration(true); 7394 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7395 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7396 "previous declaration set still overloaded"); 7397 } else { 7398 // C++11 [replacement.functions]p3: 7399 // The program's definitions shall not be specified as inline. 7400 // 7401 // N.B. We diagnose declarations instead of definitions per LWG issue 2340. 7402 // 7403 // Suppress the diagnostic if the function is __attribute__((used)), since 7404 // that forces an external definition to be emitted. 7405 if (D.getDeclSpec().isInlineSpecified() && 7406 NewFD->isReplaceableGlobalAllocationFunction() && 7407 !NewFD->hasAttr<UsedAttr>()) 7408 Diag(D.getDeclSpec().getInlineSpecLoc(), 7409 diag::ext_operator_new_delete_declared_inline) 7410 << NewFD->getDeclName(); 7411 7412 // If the declarator is a template-id, translate the parser's template 7413 // argument list into our AST format. 7414 if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) { 7415 TemplateIdAnnotation *TemplateId = D.getName().TemplateId; 7416 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc); 7417 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc); 7418 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), 7419 TemplateId->NumArgs); 7420 translateTemplateArguments(TemplateArgsPtr, 7421 TemplateArgs); 7422 7423 HasExplicitTemplateArgs = true; 7424 7425 if (NewFD->isInvalidDecl()) { 7426 HasExplicitTemplateArgs = false; 7427 } else if (FunctionTemplate) { 7428 // Function template with explicit template arguments. 7429 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec) 7430 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc); 7431 7432 HasExplicitTemplateArgs = false; 7433 } else { 7434 assert((isFunctionTemplateSpecialization || 7435 D.getDeclSpec().isFriendSpecified()) && 7436 "should have a 'template<>' for this decl"); 7437 // "friend void foo<>(int);" is an implicit specialization decl. 7438 isFunctionTemplateSpecialization = true; 7439 } 7440 } else if (isFriend && isFunctionTemplateSpecialization) { 7441 // This combination is only possible in a recovery case; the user 7442 // wrote something like: 7443 // template <> friend void foo(int); 7444 // which we're recovering from as if the user had written: 7445 // friend void foo<>(int); 7446 // Go ahead and fake up a template id. 7447 HasExplicitTemplateArgs = true; 7448 TemplateArgs.setLAngleLoc(D.getIdentifierLoc()); 7449 TemplateArgs.setRAngleLoc(D.getIdentifierLoc()); 7450 } 7451 7452 // If it's a friend (and only if it's a friend), it's possible 7453 // that either the specialized function type or the specialized 7454 // template is dependent, and therefore matching will fail. In 7455 // this case, don't check the specialization yet. 7456 bool InstantiationDependent = false; 7457 if (isFunctionTemplateSpecialization && isFriend && 7458 (NewFD->getType()->isDependentType() || DC->isDependentContext() || 7459 TemplateSpecializationType::anyDependentTemplateArguments( 7460 TemplateArgs.getArgumentArray(), TemplateArgs.size(), 7461 InstantiationDependent))) { 7462 assert(HasExplicitTemplateArgs && 7463 "friend function specialization without template args"); 7464 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs, 7465 Previous)) 7466 NewFD->setInvalidDecl(); 7467 } else if (isFunctionTemplateSpecialization) { 7468 if (CurContext->isDependentContext() && CurContext->isRecord() 7469 && !isFriend) { 7470 isDependentClassScopeExplicitSpecialization = true; 7471 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 7472 diag::ext_function_specialization_in_class : 7473 diag::err_function_specialization_in_class) 7474 << NewFD->getDeclName(); 7475 } else if (CheckFunctionTemplateSpecialization(NewFD, 7476 (HasExplicitTemplateArgs ? &TemplateArgs 7477 : nullptr), 7478 Previous)) 7479 NewFD->setInvalidDecl(); 7480 7481 // C++ [dcl.stc]p1: 7482 // A storage-class-specifier shall not be specified in an explicit 7483 // specialization (14.7.3) 7484 FunctionTemplateSpecializationInfo *Info = 7485 NewFD->getTemplateSpecializationInfo(); 7486 if (Info && SC != SC_None) { 7487 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass()) 7488 Diag(NewFD->getLocation(), 7489 diag::err_explicit_specialization_inconsistent_storage_class) 7490 << SC 7491 << FixItHint::CreateRemoval( 7492 D.getDeclSpec().getStorageClassSpecLoc()); 7493 7494 else 7495 Diag(NewFD->getLocation(), 7496 diag::ext_explicit_specialization_storage_class) 7497 << FixItHint::CreateRemoval( 7498 D.getDeclSpec().getStorageClassSpecLoc()); 7499 } 7500 7501 } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) { 7502 if (CheckMemberSpecialization(NewFD, Previous)) 7503 NewFD->setInvalidDecl(); 7504 } 7505 7506 // Perform semantic checking on the function declaration. 7507 if (!isDependentClassScopeExplicitSpecialization) { 7508 if (!NewFD->isInvalidDecl() && NewFD->isMain()) 7509 CheckMain(NewFD, D.getDeclSpec()); 7510 7511 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint()) 7512 CheckMSVCRTEntryPoint(NewFD); 7513 7514 if (!NewFD->isInvalidDecl()) 7515 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous, 7516 isExplicitSpecialization)); 7517 } 7518 7519 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() || 7520 Previous.getResultKind() != LookupResult::FoundOverloaded) && 7521 "previous declaration set still overloaded"); 7522 7523 NamedDecl *PrincipalDecl = (FunctionTemplate 7524 ? cast<NamedDecl>(FunctionTemplate) 7525 : NewFD); 7526 7527 if (isFriend && D.isRedeclaration()) { 7528 AccessSpecifier Access = AS_public; 7529 if (!NewFD->isInvalidDecl()) 7530 Access = NewFD->getPreviousDecl()->getAccess(); 7531 7532 NewFD->setAccess(Access); 7533 if (FunctionTemplate) FunctionTemplate->setAccess(Access); 7534 } 7535 7536 if (NewFD->isOverloadedOperator() && !DC->isRecord() && 7537 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 7538 PrincipalDecl->setNonMemberOperator(); 7539 7540 // If we have a function template, check the template parameter 7541 // list. This will check and merge default template arguments. 7542 if (FunctionTemplate) { 7543 FunctionTemplateDecl *PrevTemplate = 7544 FunctionTemplate->getPreviousDecl(); 7545 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(), 7546 PrevTemplate ? PrevTemplate->getTemplateParameters() 7547 : nullptr, 7548 D.getDeclSpec().isFriendSpecified() 7549 ? (D.isFunctionDefinition() 7550 ? TPC_FriendFunctionTemplateDefinition 7551 : TPC_FriendFunctionTemplate) 7552 : (D.getCXXScopeSpec().isSet() && 7553 DC && DC->isRecord() && 7554 DC->isDependentContext()) 7555 ? TPC_ClassTemplateMember 7556 : TPC_FunctionTemplate); 7557 } 7558 7559 if (NewFD->isInvalidDecl()) { 7560 // Ignore all the rest of this. 7561 } else if (!D.isRedeclaration()) { 7562 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists, 7563 AddToScope }; 7564 // Fake up an access specifier if it's supposed to be a class member. 7565 if (isa<CXXRecordDecl>(NewFD->getDeclContext())) 7566 NewFD->setAccess(AS_public); 7567 7568 // Qualified decls generally require a previous declaration. 7569 if (D.getCXXScopeSpec().isSet()) { 7570 // ...with the major exception of templated-scope or 7571 // dependent-scope friend declarations. 7572 7573 // TODO: we currently also suppress this check in dependent 7574 // contexts because (1) the parameter depth will be off when 7575 // matching friend templates and (2) we might actually be 7576 // selecting a friend based on a dependent factor. But there 7577 // are situations where these conditions don't apply and we 7578 // can actually do this check immediately. 7579 if (isFriend && 7580 (TemplateParamLists.size() || 7581 D.getCXXScopeSpec().getScopeRep()->isDependent() || 7582 CurContext->isDependentContext())) { 7583 // ignore these 7584 } else { 7585 // The user tried to provide an out-of-line definition for a 7586 // function that is a member of a class or namespace, but there 7587 // was no such member function declared (C++ [class.mfct]p2, 7588 // C++ [namespace.memdef]p2). For example: 7589 // 7590 // class X { 7591 // void f() const; 7592 // }; 7593 // 7594 // void X::f() { } // ill-formed 7595 // 7596 // Complain about this problem, and attempt to suggest close 7597 // matches (e.g., those that differ only in cv-qualifiers and 7598 // whether the parameter types are references). 7599 7600 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7601 *this, Previous, NewFD, ExtraArgs, false, nullptr)) { 7602 AddToScope = ExtraArgs.AddToScope; 7603 return Result; 7604 } 7605 } 7606 7607 // Unqualified local friend declarations are required to resolve 7608 // to something. 7609 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) { 7610 if (NamedDecl *Result = DiagnoseInvalidRedeclaration( 7611 *this, Previous, NewFD, ExtraArgs, true, S)) { 7612 AddToScope = ExtraArgs.AddToScope; 7613 return Result; 7614 } 7615 } 7616 7617 } else if (!D.isFunctionDefinition() && 7618 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() && 7619 !isFriend && !isFunctionTemplateSpecialization && 7620 !isExplicitSpecialization) { 7621 // An out-of-line member function declaration must also be a 7622 // definition (C++ [class.mfct]p2). 7623 // Note that this is not the case for explicit specializations of 7624 // function templates or member functions of class templates, per 7625 // C++ [temp.expl.spec]p2. We also allow these declarations as an 7626 // extension for compatibility with old SWIG code which likes to 7627 // generate them. 7628 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration) 7629 << D.getCXXScopeSpec().getRange(); 7630 } 7631 } 7632 7633 ProcessPragmaWeak(S, NewFD); 7634 checkAttributesAfterMerging(*this, *NewFD); 7635 7636 AddKnownFunctionAttributes(NewFD); 7637 7638 if (NewFD->hasAttr<OverloadableAttr>() && 7639 !NewFD->getType()->getAs<FunctionProtoType>()) { 7640 Diag(NewFD->getLocation(), 7641 diag::err_attribute_overloadable_no_prototype) 7642 << NewFD; 7643 7644 // Turn this into a variadic function with no parameters. 7645 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>(); 7646 FunctionProtoType::ExtProtoInfo EPI( 7647 Context.getDefaultCallingConvention(true, false)); 7648 EPI.Variadic = true; 7649 EPI.ExtInfo = FT->getExtInfo(); 7650 7651 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI); 7652 NewFD->setType(R); 7653 } 7654 7655 // If there's a #pragma GCC visibility in scope, and this isn't a class 7656 // member, set the visibility of this function. 7657 if (!DC->isRecord() && NewFD->isExternallyVisible()) 7658 AddPushedVisibilityAttribute(NewFD); 7659 7660 // If there's a #pragma clang arc_cf_code_audited in scope, consider 7661 // marking the function. 7662 AddCFAuditedAttribute(NewFD); 7663 7664 // If this is a function definition, check if we have to apply optnone due to 7665 // a pragma. 7666 if(D.isFunctionDefinition()) 7667 AddRangeBasedOptnone(NewFD); 7668 7669 // If this is the first declaration of an extern C variable, update 7670 // the map of such variables. 7671 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() && 7672 isIncompleteDeclExternC(*this, NewFD)) 7673 RegisterLocallyScopedExternCDecl(NewFD, S); 7674 7675 // Set this FunctionDecl's range up to the right paren. 7676 NewFD->setRangeEnd(D.getSourceRange().getEnd()); 7677 7678 if (D.isRedeclaration() && !Previous.empty()) { 7679 checkDLLAttributeRedeclaration( 7680 *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD, 7681 isExplicitSpecialization || isFunctionTemplateSpecialization); 7682 } 7683 7684 if (getLangOpts().CPlusPlus) { 7685 if (FunctionTemplate) { 7686 if (NewFD->isInvalidDecl()) 7687 FunctionTemplate->setInvalidDecl(); 7688 return FunctionTemplate; 7689 } 7690 } 7691 7692 if (NewFD->hasAttr<OpenCLKernelAttr>()) { 7693 // OpenCL v1.2 s6.8 static is invalid for kernel functions. 7694 if ((getLangOpts().OpenCLVersion >= 120) 7695 && (SC == SC_Static)) { 7696 Diag(D.getIdentifierLoc(), diag::err_static_kernel); 7697 D.setInvalidType(); 7698 } 7699 7700 // OpenCL v1.2, s6.9 -- Kernels can only have return type void. 7701 if (!NewFD->getReturnType()->isVoidType()) { 7702 SourceRange RTRange = NewFD->getReturnTypeSourceRange(); 7703 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type) 7704 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 7705 : FixItHint()); 7706 D.setInvalidType(); 7707 } 7708 7709 llvm::SmallPtrSet<const Type *, 16> ValidTypes; 7710 for (auto Param : NewFD->params()) 7711 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes); 7712 } 7713 7714 MarkUnusedFileScopedDecl(NewFD); 7715 7716 if (getLangOpts().CUDA) 7717 if (IdentifierInfo *II = NewFD->getIdentifier()) 7718 if (!NewFD->isInvalidDecl() && 7719 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) { 7720 if (II->isStr("cudaConfigureCall")) { 7721 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType()) 7722 Diag(NewFD->getLocation(), diag::err_config_scalar_return); 7723 7724 Context.setcudaConfigureCallDecl(NewFD); 7725 } 7726 } 7727 7728 // Here we have an function template explicit specialization at class scope. 7729 // The actually specialization will be postponed to template instatiation 7730 // time via the ClassScopeFunctionSpecializationDecl node. 7731 if (isDependentClassScopeExplicitSpecialization) { 7732 ClassScopeFunctionSpecializationDecl *NewSpec = 7733 ClassScopeFunctionSpecializationDecl::Create( 7734 Context, CurContext, SourceLocation(), 7735 cast<CXXMethodDecl>(NewFD), 7736 HasExplicitTemplateArgs, TemplateArgs); 7737 CurContext->addDecl(NewSpec); 7738 AddToScope = false; 7739 } 7740 7741 return NewFD; 7742 } 7743 7744 /// \brief Perform semantic checking of a new function declaration. 7745 /// 7746 /// Performs semantic analysis of the new function declaration 7747 /// NewFD. This routine performs all semantic checking that does not 7748 /// require the actual declarator involved in the declaration, and is 7749 /// used both for the declaration of functions as they are parsed 7750 /// (called via ActOnDeclarator) and for the declaration of functions 7751 /// that have been instantiated via C++ template instantiation (called 7752 /// via InstantiateDecl). 7753 /// 7754 /// \param IsExplicitSpecialization whether this new function declaration is 7755 /// an explicit specialization of the previous declaration. 7756 /// 7757 /// This sets NewFD->isInvalidDecl() to true if there was an error. 7758 /// 7759 /// \returns true if the function declaration is a redeclaration. 7760 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, 7761 LookupResult &Previous, 7762 bool IsExplicitSpecialization) { 7763 assert(!NewFD->getReturnType()->isVariablyModifiedType() && 7764 "Variably modified return types are not handled here"); 7765 7766 // Determine whether the type of this function should be merged with 7767 // a previous visible declaration. This never happens for functions in C++, 7768 // and always happens in C if the previous declaration was visible. 7769 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus && 7770 !Previous.isShadowed(); 7771 7772 // Filter out any non-conflicting previous declarations. 7773 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7774 7775 bool Redeclaration = false; 7776 NamedDecl *OldDecl = nullptr; 7777 7778 // Merge or overload the declaration with an existing declaration of 7779 // the same name, if appropriate. 7780 if (!Previous.empty()) { 7781 // Determine whether NewFD is an overload of PrevDecl or 7782 // a declaration that requires merging. If it's an overload, 7783 // there's no more work to do here; we'll just add the new 7784 // function to the scope. 7785 if (!AllowOverloadingOfFunction(Previous, Context)) { 7786 NamedDecl *Candidate = Previous.getFoundDecl(); 7787 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) { 7788 Redeclaration = true; 7789 OldDecl = Candidate; 7790 } 7791 } else { 7792 switch (CheckOverload(S, NewFD, Previous, OldDecl, 7793 /*NewIsUsingDecl*/ false)) { 7794 case Ovl_Match: 7795 Redeclaration = true; 7796 break; 7797 7798 case Ovl_NonFunction: 7799 Redeclaration = true; 7800 break; 7801 7802 case Ovl_Overload: 7803 Redeclaration = false; 7804 break; 7805 } 7806 7807 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7808 // If a function name is overloadable in C, then every function 7809 // with that name must be marked "overloadable". 7810 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7811 << Redeclaration << NewFD; 7812 NamedDecl *OverloadedDecl = nullptr; 7813 if (Redeclaration) 7814 OverloadedDecl = OldDecl; 7815 else if (!Previous.empty()) 7816 OverloadedDecl = Previous.getRepresentativeDecl(); 7817 if (OverloadedDecl) 7818 Diag(OverloadedDecl->getLocation(), 7819 diag::note_attribute_overloadable_prev_overload); 7820 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7821 } 7822 } 7823 } 7824 7825 // Check for a previous extern "C" declaration with this name. 7826 if (!Redeclaration && 7827 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) { 7828 filterNonConflictingPreviousDecls(Context, NewFD, Previous); 7829 if (!Previous.empty()) { 7830 // This is an extern "C" declaration with the same name as a previous 7831 // declaration, and thus redeclares that entity... 7832 Redeclaration = true; 7833 OldDecl = Previous.getFoundDecl(); 7834 MergeTypeWithPrevious = false; 7835 7836 // ... except in the presence of __attribute__((overloadable)). 7837 if (OldDecl->hasAttr<OverloadableAttr>()) { 7838 if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) { 7839 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing) 7840 << Redeclaration << NewFD; 7841 Diag(Previous.getFoundDecl()->getLocation(), 7842 diag::note_attribute_overloadable_prev_overload); 7843 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context)); 7844 } 7845 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) { 7846 Redeclaration = false; 7847 OldDecl = nullptr; 7848 } 7849 } 7850 } 7851 } 7852 7853 // C++11 [dcl.constexpr]p8: 7854 // A constexpr specifier for a non-static member function that is not 7855 // a constructor declares that member function to be const. 7856 // 7857 // This needs to be delayed until we know whether this is an out-of-line 7858 // definition of a static member function. 7859 // 7860 // This rule is not present in C++1y, so we produce a backwards 7861 // compatibility warning whenever it happens in C++11. 7862 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD); 7863 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() && 7864 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) && 7865 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) { 7866 CXXMethodDecl *OldMD = nullptr; 7867 if (OldDecl) 7868 OldMD = dyn_cast<CXXMethodDecl>(OldDecl->getAsFunction()); 7869 if (!OldMD || !OldMD->isStatic()) { 7870 const FunctionProtoType *FPT = 7871 MD->getType()->castAs<FunctionProtoType>(); 7872 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 7873 EPI.TypeQuals |= Qualifiers::Const; 7874 MD->setType(Context.getFunctionType(FPT->getReturnType(), 7875 FPT->getParamTypes(), EPI)); 7876 7877 // Warn that we did this, if we're not performing template instantiation. 7878 // In that case, we'll have warned already when the template was defined. 7879 if (ActiveTemplateInstantiations.empty()) { 7880 SourceLocation AddConstLoc; 7881 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc() 7882 .IgnoreParens().getAs<FunctionTypeLoc>()) 7883 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc()); 7884 7885 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const) 7886 << FixItHint::CreateInsertion(AddConstLoc, " const"); 7887 } 7888 } 7889 } 7890 7891 if (Redeclaration) { 7892 // NewFD and OldDecl represent declarations that need to be 7893 // merged. 7894 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) { 7895 NewFD->setInvalidDecl(); 7896 return Redeclaration; 7897 } 7898 7899 Previous.clear(); 7900 Previous.addDecl(OldDecl); 7901 7902 if (FunctionTemplateDecl *OldTemplateDecl 7903 = dyn_cast<FunctionTemplateDecl>(OldDecl)) { 7904 NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl()); 7905 FunctionTemplateDecl *NewTemplateDecl 7906 = NewFD->getDescribedFunctionTemplate(); 7907 assert(NewTemplateDecl && "Template/non-template mismatch"); 7908 if (CXXMethodDecl *Method 7909 = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) { 7910 Method->setAccess(OldTemplateDecl->getAccess()); 7911 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess()); 7912 } 7913 7914 // If this is an explicit specialization of a member that is a function 7915 // template, mark it as a member specialization. 7916 if (IsExplicitSpecialization && 7917 NewTemplateDecl->getInstantiatedFromMemberTemplate()) { 7918 NewTemplateDecl->setMemberSpecialization(); 7919 assert(OldTemplateDecl->isMemberSpecialization()); 7920 } 7921 7922 } else { 7923 // This needs to happen first so that 'inline' propagates. 7924 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl)); 7925 7926 if (isa<CXXMethodDecl>(NewFD)) { 7927 // A valid redeclaration of a C++ method must be out-of-line, 7928 // but (unfortunately) it's not necessarily a definition 7929 // because of templates, which means that the previous 7930 // declaration is not necessarily from the class definition. 7931 7932 // For just setting the access, that doesn't matter. 7933 CXXMethodDecl *oldMethod = cast<CXXMethodDecl>(OldDecl); 7934 NewFD->setAccess(oldMethod->getAccess()); 7935 7936 // Update the key-function state if necessary for this ABI. 7937 if (NewFD->isInlined() && 7938 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) { 7939 // setNonKeyFunction needs to work with the original 7940 // declaration from the class definition, and isVirtual() is 7941 // just faster in that case, so map back to that now. 7942 oldMethod = cast<CXXMethodDecl>(oldMethod->getFirstDecl()); 7943 if (oldMethod->isVirtual()) { 7944 Context.setNonKeyFunction(oldMethod); 7945 } 7946 } 7947 } 7948 } 7949 } 7950 7951 // Semantic checking for this function declaration (in isolation). 7952 7953 // Diagnose the use of callee-cleanup calls on unprototyped functions. 7954 QualType NewQType = Context.getCanonicalType(NewFD->getType()); 7955 const FunctionType *NewType = cast<FunctionType>(NewQType); 7956 if (isa<FunctionNoProtoType>(NewType)) { 7957 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo(); 7958 if (isCalleeCleanup(NewTypeInfo.getCC())) { 7959 // Windows system headers sometimes accidentally use stdcall without 7960 // (void) parameters, so use a default-error warning in this case :-/ 7961 int DiagID = NewTypeInfo.getCC() == CC_X86StdCall 7962 ? diag::warn_cconv_knr : diag::err_cconv_knr; 7963 Diag(NewFD->getLocation(), DiagID) 7964 << FunctionType::getNameForCallConv(NewTypeInfo.getCC()); 7965 } 7966 } 7967 7968 if (getLangOpts().CPlusPlus) { 7969 // C++-specific checks. 7970 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) { 7971 CheckConstructor(Constructor); 7972 } else if (CXXDestructorDecl *Destructor = 7973 dyn_cast<CXXDestructorDecl>(NewFD)) { 7974 CXXRecordDecl *Record = Destructor->getParent(); 7975 QualType ClassType = Context.getTypeDeclType(Record); 7976 7977 // FIXME: Shouldn't we be able to perform this check even when the class 7978 // type is dependent? Both gcc and edg can handle that. 7979 if (!ClassType->isDependentType()) { 7980 DeclarationName Name 7981 = Context.DeclarationNames.getCXXDestructorName( 7982 Context.getCanonicalType(ClassType)); 7983 if (NewFD->getDeclName() != Name) { 7984 Diag(NewFD->getLocation(), diag::err_destructor_name); 7985 NewFD->setInvalidDecl(); 7986 return Redeclaration; 7987 } 7988 } 7989 } else if (CXXConversionDecl *Conversion 7990 = dyn_cast<CXXConversionDecl>(NewFD)) { 7991 ActOnConversionDeclarator(Conversion); 7992 } 7993 7994 // Find any virtual functions that this function overrides. 7995 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) { 7996 if (!Method->isFunctionTemplateSpecialization() && 7997 !Method->getDescribedFunctionTemplate() && 7998 Method->isCanonicalDecl()) { 7999 if (AddOverriddenMethods(Method->getParent(), Method)) { 8000 // If the function was marked as "static", we have a problem. 8001 if (NewFD->getStorageClass() == SC_Static) { 8002 ReportOverrides(*this, diag::err_static_overrides_virtual, Method); 8003 } 8004 } 8005 } 8006 8007 if (Method->isStatic()) 8008 checkThisInStaticMemberFunctionType(Method); 8009 } 8010 8011 // Extra checking for C++ overloaded operators (C++ [over.oper]). 8012 if (NewFD->isOverloadedOperator() && 8013 CheckOverloadedOperatorDeclaration(NewFD)) { 8014 NewFD->setInvalidDecl(); 8015 return Redeclaration; 8016 } 8017 8018 // Extra checking for C++0x literal operators (C++0x [over.literal]). 8019 if (NewFD->getLiteralIdentifier() && 8020 CheckLiteralOperatorDeclaration(NewFD)) { 8021 NewFD->setInvalidDecl(); 8022 return Redeclaration; 8023 } 8024 8025 // In C++, check default arguments now that we have merged decls. Unless 8026 // the lexical context is the class, because in this case this is done 8027 // during delayed parsing anyway. 8028 if (!CurContext->isRecord()) 8029 CheckCXXDefaultArguments(NewFD); 8030 8031 // If this function declares a builtin function, check the type of this 8032 // declaration against the expected type for the builtin. 8033 if (unsigned BuiltinID = NewFD->getBuiltinID()) { 8034 ASTContext::GetBuiltinTypeError Error; 8035 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier()); 8036 QualType T = Context.GetBuiltinType(BuiltinID, Error); 8037 if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) { 8038 // The type of this function differs from the type of the builtin, 8039 // so forget about the builtin entirely. 8040 Context.BuiltinInfo.ForgetBuiltin(BuiltinID, Context.Idents); 8041 } 8042 } 8043 8044 // If this function is declared as being extern "C", then check to see if 8045 // the function returns a UDT (class, struct, or union type) that is not C 8046 // compatible, and if it does, warn the user. 8047 // But, issue any diagnostic on the first declaration only. 8048 if (NewFD->isExternC() && Previous.empty()) { 8049 QualType R = NewFD->getReturnType(); 8050 if (R->isIncompleteType() && !R->isVoidType()) 8051 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete) 8052 << NewFD << R; 8053 else if (!R.isPODType(Context) && !R->isVoidType() && 8054 !R->isObjCObjectPointerType()) 8055 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R; 8056 } 8057 } 8058 return Redeclaration; 8059 } 8060 8061 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) { 8062 // C++11 [basic.start.main]p3: 8063 // A program that [...] declares main to be inline, static or 8064 // constexpr is ill-formed. 8065 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall 8066 // appear in a declaration of main. 8067 // static main is not an error under C99, but we should warn about it. 8068 // We accept _Noreturn main as an extension. 8069 if (FD->getStorageClass() == SC_Static) 8070 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus 8071 ? diag::err_static_main : diag::warn_static_main) 8072 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc()); 8073 if (FD->isInlineSpecified()) 8074 Diag(DS.getInlineSpecLoc(), diag::err_inline_main) 8075 << FixItHint::CreateRemoval(DS.getInlineSpecLoc()); 8076 if (DS.isNoreturnSpecified()) { 8077 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc(); 8078 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc)); 8079 Diag(NoreturnLoc, diag::ext_noreturn_main); 8080 Diag(NoreturnLoc, diag::note_main_remove_noreturn) 8081 << FixItHint::CreateRemoval(NoreturnRange); 8082 } 8083 if (FD->isConstexpr()) { 8084 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main) 8085 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc()); 8086 FD->setConstexpr(false); 8087 } 8088 8089 if (getLangOpts().OpenCL) { 8090 Diag(FD->getLocation(), diag::err_opencl_no_main) 8091 << FD->hasAttr<OpenCLKernelAttr>(); 8092 FD->setInvalidDecl(); 8093 return; 8094 } 8095 8096 QualType T = FD->getType(); 8097 assert(T->isFunctionType() && "function decl is not of function type"); 8098 const FunctionType* FT = T->castAs<FunctionType>(); 8099 8100 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) { 8101 // In C with GNU extensions we allow main() to have non-integer return 8102 // type, but we should warn about the extension, and we disable the 8103 // implicit-return-zero rule. 8104 8105 // GCC in C mode accepts qualified 'int'. 8106 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy)) 8107 FD->setHasImplicitReturnZero(true); 8108 else { 8109 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint); 8110 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8111 if (RTRange.isValid()) 8112 Diag(RTRange.getBegin(), diag::note_main_change_return_type) 8113 << FixItHint::CreateReplacement(RTRange, "int"); 8114 } 8115 } else { 8116 // In C and C++, main magically returns 0 if you fall off the end; 8117 // set the flag which tells us that. 8118 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3. 8119 8120 // All the standards say that main() should return 'int'. 8121 if (Context.hasSameType(FT->getReturnType(), Context.IntTy)) 8122 FD->setHasImplicitReturnZero(true); 8123 else { 8124 // Otherwise, this is just a flat-out error. 8125 SourceRange RTRange = FD->getReturnTypeSourceRange(); 8126 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint) 8127 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int") 8128 : FixItHint()); 8129 FD->setInvalidDecl(true); 8130 } 8131 } 8132 8133 // Treat protoless main() as nullary. 8134 if (isa<FunctionNoProtoType>(FT)) return; 8135 8136 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT); 8137 unsigned nparams = FTP->getNumParams(); 8138 assert(FD->getNumParams() == nparams); 8139 8140 bool HasExtraParameters = (nparams > 3); 8141 8142 // Darwin passes an undocumented fourth argument of type char**. If 8143 // other platforms start sprouting these, the logic below will start 8144 // getting shifty. 8145 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin()) 8146 HasExtraParameters = false; 8147 8148 if (HasExtraParameters) { 8149 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams; 8150 FD->setInvalidDecl(true); 8151 nparams = 3; 8152 } 8153 8154 // FIXME: a lot of the following diagnostics would be improved 8155 // if we had some location information about types. 8156 8157 QualType CharPP = 8158 Context.getPointerType(Context.getPointerType(Context.CharTy)); 8159 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP }; 8160 8161 for (unsigned i = 0; i < nparams; ++i) { 8162 QualType AT = FTP->getParamType(i); 8163 8164 bool mismatch = true; 8165 8166 if (Context.hasSameUnqualifiedType(AT, Expected[i])) 8167 mismatch = false; 8168 else if (Expected[i] == CharPP) { 8169 // As an extension, the following forms are okay: 8170 // char const ** 8171 // char const * const * 8172 // char * const * 8173 8174 QualifierCollector qs; 8175 const PointerType* PT; 8176 if ((PT = qs.strip(AT)->getAs<PointerType>()) && 8177 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) && 8178 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0), 8179 Context.CharTy)) { 8180 qs.removeConst(); 8181 mismatch = !qs.empty(); 8182 } 8183 } 8184 8185 if (mismatch) { 8186 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i]; 8187 // TODO: suggest replacing given type with expected type 8188 FD->setInvalidDecl(true); 8189 } 8190 } 8191 8192 if (nparams == 1 && !FD->isInvalidDecl()) { 8193 Diag(FD->getLocation(), diag::warn_main_one_arg); 8194 } 8195 8196 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8197 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8198 FD->setInvalidDecl(); 8199 } 8200 } 8201 8202 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) { 8203 QualType T = FD->getType(); 8204 assert(T->isFunctionType() && "function decl is not of function type"); 8205 const FunctionType *FT = T->castAs<FunctionType>(); 8206 8207 // Set an implicit return of 'zero' if the function can return some integral, 8208 // enumeration, pointer or nullptr type. 8209 if (FT->getReturnType()->isIntegralOrEnumerationType() || 8210 FT->getReturnType()->isAnyPointerType() || 8211 FT->getReturnType()->isNullPtrType()) 8212 // DllMain is exempt because a return value of zero means it failed. 8213 if (FD->getName() != "DllMain") 8214 FD->setHasImplicitReturnZero(true); 8215 8216 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) { 8217 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD; 8218 FD->setInvalidDecl(); 8219 } 8220 } 8221 8222 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) { 8223 // FIXME: Need strict checking. In C89, we need to check for 8224 // any assignment, increment, decrement, function-calls, or 8225 // commas outside of a sizeof. In C99, it's the same list, 8226 // except that the aforementioned are allowed in unevaluated 8227 // expressions. Everything else falls under the 8228 // "may accept other forms of constant expressions" exception. 8229 // (We never end up here for C++, so the constant expression 8230 // rules there don't matter.) 8231 const Expr *Culprit; 8232 if (Init->isConstantInitializer(Context, false, &Culprit)) 8233 return false; 8234 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant) 8235 << Culprit->getSourceRange(); 8236 return true; 8237 } 8238 8239 namespace { 8240 // Visits an initialization expression to see if OrigDecl is evaluated in 8241 // its own initialization and throws a warning if it does. 8242 class SelfReferenceChecker 8243 : public EvaluatedExprVisitor<SelfReferenceChecker> { 8244 Sema &S; 8245 Decl *OrigDecl; 8246 bool isRecordType; 8247 bool isPODType; 8248 bool isReferenceType; 8249 8250 bool isInitList; 8251 llvm::SmallVector<unsigned, 4> InitFieldIndex; 8252 public: 8253 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited; 8254 8255 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context), 8256 S(S), OrigDecl(OrigDecl) { 8257 isPODType = false; 8258 isRecordType = false; 8259 isReferenceType = false; 8260 isInitList = false; 8261 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) { 8262 isPODType = VD->getType().isPODType(S.Context); 8263 isRecordType = VD->getType()->isRecordType(); 8264 isReferenceType = VD->getType()->isReferenceType(); 8265 } 8266 } 8267 8268 // For most expressions, just call the visitor. For initializer lists, 8269 // track the index of the field being initialized since fields are 8270 // initialized in order allowing use of previously initialized fields. 8271 void CheckExpr(Expr *E) { 8272 InitListExpr *InitList = dyn_cast<InitListExpr>(E); 8273 if (!InitList) { 8274 Visit(E); 8275 return; 8276 } 8277 8278 // Track and increment the index here. 8279 isInitList = true; 8280 InitFieldIndex.push_back(0); 8281 for (auto Child : InitList->children()) { 8282 CheckExpr(cast<Expr>(Child)); 8283 ++InitFieldIndex.back(); 8284 } 8285 InitFieldIndex.pop_back(); 8286 } 8287 8288 // Returns true if MemberExpr is checked and no futher checking is needed. 8289 // Returns false if additional checking is required. 8290 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) { 8291 llvm::SmallVector<FieldDecl*, 4> Fields; 8292 Expr *Base = E; 8293 bool ReferenceField = false; 8294 8295 // Get the field memebers used. 8296 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8297 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 8298 if (!FD) 8299 return false; 8300 Fields.push_back(FD); 8301 if (FD->getType()->isReferenceType()) 8302 ReferenceField = true; 8303 Base = ME->getBase()->IgnoreParenImpCasts(); 8304 } 8305 8306 // Keep checking only if the base Decl is the same. 8307 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base); 8308 if (!DRE || DRE->getDecl() != OrigDecl) 8309 return false; 8310 8311 // A reference field can be bound to an unininitialized field. 8312 if (CheckReference && !ReferenceField) 8313 return true; 8314 8315 // Convert FieldDecls to their index number. 8316 llvm::SmallVector<unsigned, 4> UsedFieldIndex; 8317 for (auto I = Fields.rbegin(), E = Fields.rend(); I != E; ++I) { 8318 UsedFieldIndex.push_back((*I)->getFieldIndex()); 8319 } 8320 8321 // See if a warning is needed by checking the first difference in index 8322 // numbers. If field being used has index less than the field being 8323 // initialized, then the use is safe. 8324 for (auto UsedIter = UsedFieldIndex.begin(), 8325 UsedEnd = UsedFieldIndex.end(), 8326 OrigIter = InitFieldIndex.begin(), 8327 OrigEnd = InitFieldIndex.end(); 8328 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) { 8329 if (*UsedIter < *OrigIter) 8330 return true; 8331 if (*UsedIter > *OrigIter) 8332 break; 8333 } 8334 8335 // TODO: Add a different warning which will print the field names. 8336 HandleDeclRefExpr(DRE); 8337 return true; 8338 } 8339 8340 // For most expressions, the cast is directly above the DeclRefExpr. 8341 // For conditional operators, the cast can be outside the conditional 8342 // operator if both expressions are DeclRefExpr's. 8343 void HandleValue(Expr *E) { 8344 E = E->IgnoreParens(); 8345 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) { 8346 HandleDeclRefExpr(DRE); 8347 return; 8348 } 8349 8350 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8351 Visit(CO->getCond()); 8352 HandleValue(CO->getTrueExpr()); 8353 HandleValue(CO->getFalseExpr()); 8354 return; 8355 } 8356 8357 if (BinaryConditionalOperator *BCO = 8358 dyn_cast<BinaryConditionalOperator>(E)) { 8359 Visit(BCO->getCond()); 8360 HandleValue(BCO->getFalseExpr()); 8361 return; 8362 } 8363 8364 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) { 8365 HandleValue(OVE->getSourceExpr()); 8366 return; 8367 } 8368 8369 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 8370 if (BO->getOpcode() == BO_Comma) { 8371 Visit(BO->getLHS()); 8372 HandleValue(BO->getRHS()); 8373 return; 8374 } 8375 } 8376 8377 if (isa<MemberExpr>(E)) { 8378 if (isInitList) { 8379 if (CheckInitListMemberExpr(cast<MemberExpr>(E), 8380 false /*CheckReference*/)) 8381 return; 8382 } 8383 8384 Expr *Base = E->IgnoreParenImpCasts(); 8385 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8386 // Check for static member variables and don't warn on them. 8387 if (!isa<FieldDecl>(ME->getMemberDecl())) 8388 return; 8389 Base = ME->getBase()->IgnoreParenImpCasts(); 8390 } 8391 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) 8392 HandleDeclRefExpr(DRE); 8393 return; 8394 } 8395 8396 Visit(E); 8397 } 8398 8399 // Reference types not handled in HandleValue are handled here since all 8400 // uses of references are bad, not just r-value uses. 8401 void VisitDeclRefExpr(DeclRefExpr *E) { 8402 if (isReferenceType) 8403 HandleDeclRefExpr(E); 8404 } 8405 8406 void VisitImplicitCastExpr(ImplicitCastExpr *E) { 8407 if (E->getCastKind() == CK_LValueToRValue) { 8408 HandleValue(E->getSubExpr()); 8409 return; 8410 } 8411 8412 Inherited::VisitImplicitCastExpr(E); 8413 } 8414 8415 void VisitMemberExpr(MemberExpr *E) { 8416 if (isInitList) { 8417 if (CheckInitListMemberExpr(E, true /*CheckReference*/)) 8418 return; 8419 } 8420 8421 // Don't warn on arrays since they can be treated as pointers. 8422 if (E->getType()->canDecayToPointerType()) return; 8423 8424 // Warn when a non-static method call is followed by non-static member 8425 // field accesses, which is followed by a DeclRefExpr. 8426 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl()); 8427 bool Warn = (MD && !MD->isStatic()); 8428 Expr *Base = E->getBase()->IgnoreParenImpCasts(); 8429 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) { 8430 if (!isa<FieldDecl>(ME->getMemberDecl())) 8431 Warn = false; 8432 Base = ME->getBase()->IgnoreParenImpCasts(); 8433 } 8434 8435 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 8436 if (Warn) 8437 HandleDeclRefExpr(DRE); 8438 return; 8439 } 8440 8441 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr. 8442 // Visit that expression. 8443 Visit(Base); 8444 } 8445 8446 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { 8447 if (E->getNumArgs() > 0) 8448 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->getArg(0))) 8449 HandleDeclRefExpr(DRE); 8450 8451 Inherited::VisitCXXOperatorCallExpr(E); 8452 } 8453 8454 void VisitUnaryOperator(UnaryOperator *E) { 8455 // For POD record types, addresses of its own members are well-defined. 8456 if (E->getOpcode() == UO_AddrOf && isRecordType && 8457 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) { 8458 if (!isPODType) 8459 HandleValue(E->getSubExpr()); 8460 return; 8461 } 8462 8463 if (E->isIncrementDecrementOp()) { 8464 HandleValue(E->getSubExpr()); 8465 return; 8466 } 8467 8468 Inherited::VisitUnaryOperator(E); 8469 } 8470 8471 void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; } 8472 8473 void VisitCXXConstructExpr(CXXConstructExpr *E) { 8474 if (E->getConstructor()->isCopyConstructor()) { 8475 Expr *ArgExpr = E->getArg(0); 8476 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr)) 8477 if (ILE->getNumInits() == 1) 8478 ArgExpr = ILE->getInit(0); 8479 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr)) 8480 if (ICE->getCastKind() == CK_NoOp) 8481 ArgExpr = ICE->getSubExpr(); 8482 HandleValue(ArgExpr); 8483 return; 8484 } 8485 Inherited::VisitCXXConstructExpr(E); 8486 } 8487 8488 void VisitCallExpr(CallExpr *E) { 8489 // Treat std::move as a use. 8490 if (E->getNumArgs() == 1) { 8491 if (FunctionDecl *FD = E->getDirectCallee()) { 8492 if (FD->getIdentifier() && FD->getIdentifier()->isStr("move")) { 8493 HandleValue(E->getArg(0)); 8494 return; 8495 } 8496 } 8497 } 8498 8499 Inherited::VisitCallExpr(E); 8500 } 8501 8502 void VisitBinaryOperator(BinaryOperator *E) { 8503 if (E->isCompoundAssignmentOp()) { 8504 HandleValue(E->getLHS()); 8505 Visit(E->getRHS()); 8506 return; 8507 } 8508 8509 Inherited::VisitBinaryOperator(E); 8510 } 8511 8512 // A custom visitor for BinaryConditionalOperator is needed because the 8513 // regular visitor would check the condition and true expression separately 8514 // but both point to the same place giving duplicate diagnostics. 8515 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) { 8516 Visit(E->getCond()); 8517 Visit(E->getFalseExpr()); 8518 } 8519 8520 void HandleDeclRefExpr(DeclRefExpr *DRE) { 8521 Decl* ReferenceDecl = DRE->getDecl(); 8522 if (OrigDecl != ReferenceDecl) return; 8523 unsigned diag; 8524 if (isReferenceType) { 8525 diag = diag::warn_uninit_self_reference_in_reference_init; 8526 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) { 8527 diag = diag::warn_static_self_reference_in_init; 8528 } else { 8529 diag = diag::warn_uninit_self_reference_in_init; 8530 } 8531 8532 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE, 8533 S.PDiag(diag) 8534 << DRE->getNameInfo().getName() 8535 << OrigDecl->getLocation() 8536 << DRE->getSourceRange()); 8537 } 8538 }; 8539 8540 /// CheckSelfReference - Warns if OrigDecl is used in expression E. 8541 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E, 8542 bool DirectInit) { 8543 // Parameters arguments are occassionially constructed with itself, 8544 // for instance, in recursive functions. Skip them. 8545 if (isa<ParmVarDecl>(OrigDecl)) 8546 return; 8547 8548 E = E->IgnoreParens(); 8549 8550 // Skip checking T a = a where T is not a record or reference type. 8551 // Doing so is a way to silence uninitialized warnings. 8552 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType()) 8553 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) 8554 if (ICE->getCastKind() == CK_LValueToRValue) 8555 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr())) 8556 if (DRE->getDecl() == OrigDecl) 8557 return; 8558 8559 SelfReferenceChecker(S, OrigDecl).CheckExpr(E); 8560 } 8561 } 8562 8563 /// AddInitializerToDecl - Adds the initializer Init to the 8564 /// declaration dcl. If DirectInit is true, this is C++ direct 8565 /// initialization rather than copy initialization. 8566 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, 8567 bool DirectInit, bool TypeMayContainAuto) { 8568 // If there is no declaration, there was an error parsing it. Just ignore 8569 // the initializer. 8570 if (!RealDecl || RealDecl->isInvalidDecl()) 8571 return; 8572 8573 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) { 8574 // With declarators parsed the way they are, the parser cannot 8575 // distinguish between a normal initializer and a pure-specifier. 8576 // Thus this grotesque test. 8577 IntegerLiteral *IL; 8578 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 && 8579 Context.getCanonicalType(IL->getType()) == Context.IntTy) 8580 CheckPureMethod(Method, Init->getSourceRange()); 8581 else { 8582 Diag(Method->getLocation(), diag::err_member_function_initialization) 8583 << Method->getDeclName() << Init->getSourceRange(); 8584 Method->setInvalidDecl(); 8585 } 8586 return; 8587 } 8588 8589 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl); 8590 if (!VDecl) { 8591 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here"); 8592 Diag(RealDecl->getLocation(), diag::err_illegal_initializer); 8593 RealDecl->setInvalidDecl(); 8594 return; 8595 } 8596 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); 8597 8598 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for. 8599 if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) { 8600 Expr *DeduceInit = Init; 8601 // Initializer could be a C++ direct-initializer. Deduction only works if it 8602 // contains exactly one expression. 8603 if (CXXDirectInit) { 8604 if (CXXDirectInit->getNumExprs() == 0) { 8605 // It isn't possible to write this directly, but it is possible to 8606 // end up in this situation with "auto x(some_pack...);" 8607 Diag(CXXDirectInit->getLocStart(), 8608 VDecl->isInitCapture() ? diag::err_init_capture_no_expression 8609 : diag::err_auto_var_init_no_expression) 8610 << VDecl->getDeclName() << VDecl->getType() 8611 << VDecl->getSourceRange(); 8612 RealDecl->setInvalidDecl(); 8613 return; 8614 } else if (CXXDirectInit->getNumExprs() > 1) { 8615 Diag(CXXDirectInit->getExpr(1)->getLocStart(), 8616 VDecl->isInitCapture() 8617 ? diag::err_init_capture_multiple_expressions 8618 : diag::err_auto_var_init_multiple_expressions) 8619 << VDecl->getDeclName() << VDecl->getType() 8620 << VDecl->getSourceRange(); 8621 RealDecl->setInvalidDecl(); 8622 return; 8623 } else { 8624 DeduceInit = CXXDirectInit->getExpr(0); 8625 if (isa<InitListExpr>(DeduceInit)) 8626 Diag(CXXDirectInit->getLocStart(), 8627 diag::err_auto_var_init_paren_braces) 8628 << VDecl->getDeclName() << VDecl->getType() 8629 << VDecl->getSourceRange(); 8630 } 8631 } 8632 8633 // Expressions default to 'id' when we're in a debugger. 8634 bool DefaultedToAuto = false; 8635 if (getLangOpts().DebuggerCastResultToId && 8636 Init->getType() == Context.UnknownAnyTy) { 8637 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8638 if (Result.isInvalid()) { 8639 VDecl->setInvalidDecl(); 8640 return; 8641 } 8642 Init = Result.get(); 8643 DefaultedToAuto = true; 8644 } 8645 8646 QualType DeducedType; 8647 if (DeduceAutoType(VDecl->getTypeSourceInfo(), DeduceInit, DeducedType) == 8648 DAR_Failed) 8649 DiagnoseAutoDeductionFailure(VDecl, DeduceInit); 8650 if (DeducedType.isNull()) { 8651 RealDecl->setInvalidDecl(); 8652 return; 8653 } 8654 VDecl->setType(DeducedType); 8655 assert(VDecl->isLinkageValid()); 8656 8657 // In ARC, infer lifetime. 8658 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl)) 8659 VDecl->setInvalidDecl(); 8660 8661 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using 8662 // 'id' instead of a specific object type prevents most of our usual checks. 8663 // We only want to warn outside of template instantiations, though: 8664 // inside a template, the 'id' could have come from a parameter. 8665 if (ActiveTemplateInstantiations.empty() && !DefaultedToAuto && 8666 DeducedType->isObjCIdType()) { 8667 SourceLocation Loc = 8668 VDecl->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 8669 Diag(Loc, diag::warn_auto_var_is_id) 8670 << VDecl->getDeclName() << DeduceInit->getSourceRange(); 8671 } 8672 8673 // If this is a redeclaration, check that the type we just deduced matches 8674 // the previously declared type. 8675 if (VarDecl *Old = VDecl->getPreviousDecl()) { 8676 // We never need to merge the type, because we cannot form an incomplete 8677 // array of auto, nor deduce such a type. 8678 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/false); 8679 } 8680 8681 // Check the deduced type is valid for a variable declaration. 8682 CheckVariableDeclarationType(VDecl); 8683 if (VDecl->isInvalidDecl()) 8684 return; 8685 } 8686 8687 // dllimport cannot be used on variable definitions. 8688 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) { 8689 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition); 8690 VDecl->setInvalidDecl(); 8691 return; 8692 } 8693 8694 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) { 8695 // C99 6.7.8p5. C++ has no such restriction, but that is a defect. 8696 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init); 8697 VDecl->setInvalidDecl(); 8698 return; 8699 } 8700 8701 if (!VDecl->getType()->isDependentType()) { 8702 // A definition must end up with a complete type, which means it must be 8703 // complete with the restriction that an array type might be completed by 8704 // the initializer; note that later code assumes this restriction. 8705 QualType BaseDeclType = VDecl->getType(); 8706 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType)) 8707 BaseDeclType = Array->getElementType(); 8708 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType, 8709 diag::err_typecheck_decl_incomplete_type)) { 8710 RealDecl->setInvalidDecl(); 8711 return; 8712 } 8713 8714 // The variable can not have an abstract class type. 8715 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(), 8716 diag::err_abstract_type_in_decl, 8717 AbstractVariableType)) 8718 VDecl->setInvalidDecl(); 8719 } 8720 8721 const VarDecl *Def; 8722 if ((Def = VDecl->getDefinition()) && Def != VDecl) { 8723 Diag(VDecl->getLocation(), diag::err_redefinition) 8724 << VDecl->getDeclName(); 8725 Diag(Def->getLocation(), diag::note_previous_definition); 8726 VDecl->setInvalidDecl(); 8727 return; 8728 } 8729 8730 const VarDecl *PrevInit = nullptr; 8731 if (getLangOpts().CPlusPlus) { 8732 // C++ [class.static.data]p4 8733 // If a static data member is of const integral or const 8734 // enumeration type, its declaration in the class definition can 8735 // specify a constant-initializer which shall be an integral 8736 // constant expression (5.19). In that case, the member can appear 8737 // in integral constant expressions. The member shall still be 8738 // defined in a namespace scope if it is used in the program and the 8739 // namespace scope definition shall not contain an initializer. 8740 // 8741 // We already performed a redefinition check above, but for static 8742 // data members we also need to check whether there was an in-class 8743 // declaration with an initializer. 8744 if (VDecl->isStaticDataMember() && VDecl->getAnyInitializer(PrevInit)) { 8745 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization) 8746 << VDecl->getDeclName(); 8747 Diag(PrevInit->getInit()->getExprLoc(), diag::note_previous_initializer) << 0; 8748 return; 8749 } 8750 8751 if (VDecl->hasLocalStorage()) 8752 getCurFunction()->setHasBranchProtectedScope(); 8753 8754 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) { 8755 VDecl->setInvalidDecl(); 8756 return; 8757 } 8758 } 8759 8760 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside 8761 // a kernel function cannot be initialized." 8762 if (VDecl->getStorageClass() == SC_OpenCLWorkGroupLocal) { 8763 Diag(VDecl->getLocation(), diag::err_local_cant_init); 8764 VDecl->setInvalidDecl(); 8765 return; 8766 } 8767 8768 // Get the decls type and save a reference for later, since 8769 // CheckInitializerTypes may change it. 8770 QualType DclT = VDecl->getType(), SavT = DclT; 8771 8772 // Expressions default to 'id' when we're in a debugger 8773 // and we are assigning it to a variable of Objective-C pointer type. 8774 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() && 8775 Init->getType() == Context.UnknownAnyTy) { 8776 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType()); 8777 if (Result.isInvalid()) { 8778 VDecl->setInvalidDecl(); 8779 return; 8780 } 8781 Init = Result.get(); 8782 } 8783 8784 // Perform the initialization. 8785 if (!VDecl->isInvalidDecl()) { 8786 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl); 8787 InitializationKind Kind 8788 = DirectInit ? 8789 CXXDirectInit ? InitializationKind::CreateDirect(VDecl->getLocation(), 8790 Init->getLocStart(), 8791 Init->getLocEnd()) 8792 : InitializationKind::CreateDirectList( 8793 VDecl->getLocation()) 8794 : InitializationKind::CreateCopy(VDecl->getLocation(), 8795 Init->getLocStart()); 8796 8797 MultiExprArg Args = Init; 8798 if (CXXDirectInit) 8799 Args = MultiExprArg(CXXDirectInit->getExprs(), 8800 CXXDirectInit->getNumExprs()); 8801 8802 InitializationSequence InitSeq(*this, Entity, Kind, Args); 8803 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); 8804 if (Result.isInvalid()) { 8805 VDecl->setInvalidDecl(); 8806 return; 8807 } 8808 8809 Init = Result.getAs<Expr>(); 8810 } 8811 8812 // Check for self-references within variable initializers. 8813 // Variables declared within a function/method body (except for references) 8814 // are handled by a dataflow analysis. 8815 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() || 8816 VDecl->getType()->isReferenceType()) { 8817 CheckSelfReference(*this, RealDecl, Init, DirectInit); 8818 } 8819 8820 // If the type changed, it means we had an incomplete type that was 8821 // completed by the initializer. For example: 8822 // int ary[] = { 1, 3, 5 }; 8823 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType. 8824 if (!VDecl->isInvalidDecl() && (DclT != SavT)) 8825 VDecl->setType(DclT); 8826 8827 if (!VDecl->isInvalidDecl()) { 8828 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init); 8829 8830 if (VDecl->hasAttr<BlocksAttr>()) 8831 checkRetainCycles(VDecl, Init); 8832 8833 // It is safe to assign a weak reference into a strong variable. 8834 // Although this code can still have problems: 8835 // id x = self.weakProp; 8836 // id y = self.weakProp; 8837 // we do not warn to warn spuriously when 'x' and 'y' are on separate 8838 // paths through the function. This should be revisited if 8839 // -Wrepeated-use-of-weak is made flow-sensitive. 8840 if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong && 8841 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 8842 Init->getLocStart())) 8843 getCurFunction()->markSafeWeakUse(Init); 8844 } 8845 8846 // The initialization is usually a full-expression. 8847 // 8848 // FIXME: If this is a braced initialization of an aggregate, it is not 8849 // an expression, and each individual field initializer is a separate 8850 // full-expression. For instance, in: 8851 // 8852 // struct Temp { ~Temp(); }; 8853 // struct S { S(Temp); }; 8854 // struct T { S a, b; } t = { Temp(), Temp() } 8855 // 8856 // we should destroy the first Temp before constructing the second. 8857 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(), 8858 false, 8859 VDecl->isConstexpr()); 8860 if (Result.isInvalid()) { 8861 VDecl->setInvalidDecl(); 8862 return; 8863 } 8864 Init = Result.get(); 8865 8866 // Attach the initializer to the decl. 8867 VDecl->setInit(Init); 8868 8869 if (VDecl->isLocalVarDecl()) { 8870 // C99 6.7.8p4: All the expressions in an initializer for an object that has 8871 // static storage duration shall be constant expressions or string literals. 8872 // C++ does not have this restriction. 8873 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) { 8874 const Expr *Culprit; 8875 if (VDecl->getStorageClass() == SC_Static) 8876 CheckForConstantInitializer(Init, DclT); 8877 // C89 is stricter than C99 for non-static aggregate types. 8878 // C89 6.5.7p3: All the expressions [...] in an initializer list 8879 // for an object that has aggregate or union type shall be 8880 // constant expressions. 8881 else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() && 8882 isa<InitListExpr>(Init) && 8883 !Init->isConstantInitializer(Context, false, &Culprit)) 8884 Diag(Culprit->getExprLoc(), 8885 diag::ext_aggregate_init_not_constant) 8886 << Culprit->getSourceRange(); 8887 } 8888 } else if (VDecl->isStaticDataMember() && 8889 VDecl->getLexicalDeclContext()->isRecord()) { 8890 // This is an in-class initialization for a static data member, e.g., 8891 // 8892 // struct S { 8893 // static const int value = 17; 8894 // }; 8895 8896 // C++ [class.mem]p4: 8897 // A member-declarator can contain a constant-initializer only 8898 // if it declares a static member (9.4) of const integral or 8899 // const enumeration type, see 9.4.2. 8900 // 8901 // C++11 [class.static.data]p3: 8902 // If a non-volatile const static data member is of integral or 8903 // enumeration type, its declaration in the class definition can 8904 // specify a brace-or-equal-initializer in which every initalizer-clause 8905 // that is an assignment-expression is a constant expression. A static 8906 // data member of literal type can be declared in the class definition 8907 // with the constexpr specifier; if so, its declaration shall specify a 8908 // brace-or-equal-initializer in which every initializer-clause that is 8909 // an assignment-expression is a constant expression. 8910 8911 // Do nothing on dependent types. 8912 if (DclT->isDependentType()) { 8913 8914 // Allow any 'static constexpr' members, whether or not they are of literal 8915 // type. We separately check that every constexpr variable is of literal 8916 // type. 8917 } else if (VDecl->isConstexpr()) { 8918 8919 // Require constness. 8920 } else if (!DclT.isConstQualified()) { 8921 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const) 8922 << Init->getSourceRange(); 8923 VDecl->setInvalidDecl(); 8924 8925 // We allow integer constant expressions in all cases. 8926 } else if (DclT->isIntegralOrEnumerationType()) { 8927 // Check whether the expression is a constant expression. 8928 SourceLocation Loc; 8929 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified()) 8930 // In C++11, a non-constexpr const static data member with an 8931 // in-class initializer cannot be volatile. 8932 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile); 8933 else if (Init->isValueDependent()) 8934 ; // Nothing to check. 8935 else if (Init->isIntegerConstantExpr(Context, &Loc)) 8936 ; // Ok, it's an ICE! 8937 else if (Init->isEvaluatable(Context)) { 8938 // If we can constant fold the initializer through heroics, accept it, 8939 // but report this as a use of an extension for -pedantic. 8940 Diag(Loc, diag::ext_in_class_initializer_non_constant) 8941 << Init->getSourceRange(); 8942 } else { 8943 // Otherwise, this is some crazy unknown case. Report the issue at the 8944 // location provided by the isIntegerConstantExpr failed check. 8945 Diag(Loc, diag::err_in_class_initializer_non_constant) 8946 << Init->getSourceRange(); 8947 VDecl->setInvalidDecl(); 8948 } 8949 8950 // We allow foldable floating-point constants as an extension. 8951 } else if (DclT->isFloatingType()) { // also permits complex, which is ok 8952 // In C++98, this is a GNU extension. In C++11, it is not, but we support 8953 // it anyway and provide a fixit to add the 'constexpr'. 8954 if (getLangOpts().CPlusPlus11) { 8955 Diag(VDecl->getLocation(), 8956 diag::ext_in_class_initializer_float_type_cxx11) 8957 << DclT << Init->getSourceRange(); 8958 Diag(VDecl->getLocStart(), 8959 diag::note_in_class_initializer_float_type_cxx11) 8960 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8961 } else { 8962 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type) 8963 << DclT << Init->getSourceRange(); 8964 8965 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) { 8966 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant) 8967 << Init->getSourceRange(); 8968 VDecl->setInvalidDecl(); 8969 } 8970 } 8971 8972 // Suggest adding 'constexpr' in C++11 for literal types. 8973 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) { 8974 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type) 8975 << DclT << Init->getSourceRange() 8976 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr "); 8977 VDecl->setConstexpr(true); 8978 8979 } else { 8980 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type) 8981 << DclT << Init->getSourceRange(); 8982 VDecl->setInvalidDecl(); 8983 } 8984 } else if (VDecl->isFileVarDecl()) { 8985 if (VDecl->getStorageClass() == SC_Extern && 8986 (!getLangOpts().CPlusPlus || 8987 !(Context.getBaseElementType(VDecl->getType()).isConstQualified() || 8988 VDecl->isExternC())) && 8989 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind())) 8990 Diag(VDecl->getLocation(), diag::warn_extern_init); 8991 8992 // C99 6.7.8p4. All file scoped initializers need to be constant. 8993 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) 8994 CheckForConstantInitializer(Init, DclT); 8995 } 8996 8997 // We will represent direct-initialization similarly to copy-initialization: 8998 // int x(1); -as-> int x = 1; 8999 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c); 9000 // 9001 // Clients that want to distinguish between the two forms, can check for 9002 // direct initializer using VarDecl::getInitStyle(). 9003 // A major benefit is that clients that don't particularly care about which 9004 // exactly form was it (like the CodeGen) can handle both cases without 9005 // special case code. 9006 9007 // C++ 8.5p11: 9008 // The form of initialization (using parentheses or '=') is generally 9009 // insignificant, but does matter when the entity being initialized has a 9010 // class type. 9011 if (CXXDirectInit) { 9012 assert(DirectInit && "Call-style initializer must be direct init."); 9013 VDecl->setInitStyle(VarDecl::CallInit); 9014 } else if (DirectInit) { 9015 // This must be list-initialization. No other way is direct-initialization. 9016 VDecl->setInitStyle(VarDecl::ListInit); 9017 } 9018 9019 CheckCompleteVariableDeclaration(VDecl); 9020 } 9021 9022 /// ActOnInitializerError - Given that there was an error parsing an 9023 /// initializer for the given declaration, try to return to some form 9024 /// of sanity. 9025 void Sema::ActOnInitializerError(Decl *D) { 9026 // Our main concern here is re-establishing invariants like "a 9027 // variable's type is either dependent or complete". 9028 if (!D || D->isInvalidDecl()) return; 9029 9030 VarDecl *VD = dyn_cast<VarDecl>(D); 9031 if (!VD) return; 9032 9033 // Auto types are meaningless if we can't make sense of the initializer. 9034 if (ParsingInitForAutoVars.count(D)) { 9035 D->setInvalidDecl(); 9036 return; 9037 } 9038 9039 QualType Ty = VD->getType(); 9040 if (Ty->isDependentType()) return; 9041 9042 // Require a complete type. 9043 if (RequireCompleteType(VD->getLocation(), 9044 Context.getBaseElementType(Ty), 9045 diag::err_typecheck_decl_incomplete_type)) { 9046 VD->setInvalidDecl(); 9047 return; 9048 } 9049 9050 // Require a non-abstract type. 9051 if (RequireNonAbstractType(VD->getLocation(), Ty, 9052 diag::err_abstract_type_in_decl, 9053 AbstractVariableType)) { 9054 VD->setInvalidDecl(); 9055 return; 9056 } 9057 9058 // Don't bother complaining about constructors or destructors, 9059 // though. 9060 } 9061 9062 void Sema::ActOnUninitializedDecl(Decl *RealDecl, 9063 bool TypeMayContainAuto) { 9064 // If there is no declaration, there was an error parsing it. Just ignore it. 9065 if (!RealDecl) 9066 return; 9067 9068 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) { 9069 QualType Type = Var->getType(); 9070 9071 // C++11 [dcl.spec.auto]p3 9072 if (TypeMayContainAuto && Type->getContainedAutoType()) { 9073 Diag(Var->getLocation(), diag::err_auto_var_requires_init) 9074 << Var->getDeclName() << Type; 9075 Var->setInvalidDecl(); 9076 return; 9077 } 9078 9079 // C++11 [class.static.data]p3: A static data member can be declared with 9080 // the constexpr specifier; if so, its declaration shall specify 9081 // a brace-or-equal-initializer. 9082 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to 9083 // the definition of a variable [...] or the declaration of a static data 9084 // member. 9085 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) { 9086 if (Var->isStaticDataMember()) 9087 Diag(Var->getLocation(), 9088 diag::err_constexpr_static_mem_var_requires_init) 9089 << Var->getDeclName(); 9090 else 9091 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl); 9092 Var->setInvalidDecl(); 9093 return; 9094 } 9095 9096 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must 9097 // be initialized. 9098 if (!Var->isInvalidDecl() && 9099 Var->getType().getAddressSpace() == LangAS::opencl_constant && 9100 Var->getStorageClass() != SC_Extern && !Var->getInit()) { 9101 Diag(Var->getLocation(), diag::err_opencl_constant_no_init); 9102 Var->setInvalidDecl(); 9103 return; 9104 } 9105 9106 switch (Var->isThisDeclarationADefinition()) { 9107 case VarDecl::Definition: 9108 if (!Var->isStaticDataMember() || !Var->getAnyInitializer()) 9109 break; 9110 9111 // We have an out-of-line definition of a static data member 9112 // that has an in-class initializer, so we type-check this like 9113 // a declaration. 9114 // 9115 // Fall through 9116 9117 case VarDecl::DeclarationOnly: 9118 // It's only a declaration. 9119 9120 // Block scope. C99 6.7p7: If an identifier for an object is 9121 // declared with no linkage (C99 6.2.2p6), the type for the 9122 // object shall be complete. 9123 if (!Type->isDependentType() && Var->isLocalVarDecl() && 9124 !Var->hasLinkage() && !Var->isInvalidDecl() && 9125 RequireCompleteType(Var->getLocation(), Type, 9126 diag::err_typecheck_decl_incomplete_type)) 9127 Var->setInvalidDecl(); 9128 9129 // Make sure that the type is not abstract. 9130 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9131 RequireNonAbstractType(Var->getLocation(), Type, 9132 diag::err_abstract_type_in_decl, 9133 AbstractVariableType)) 9134 Var->setInvalidDecl(); 9135 if (!Type->isDependentType() && !Var->isInvalidDecl() && 9136 Var->getStorageClass() == SC_PrivateExtern) { 9137 Diag(Var->getLocation(), diag::warn_private_extern); 9138 Diag(Var->getLocation(), diag::note_private_extern); 9139 } 9140 9141 return; 9142 9143 case VarDecl::TentativeDefinition: 9144 // File scope. C99 6.9.2p2: A declaration of an identifier for an 9145 // object that has file scope without an initializer, and without a 9146 // storage-class specifier or with the storage-class specifier "static", 9147 // constitutes a tentative definition. Note: A tentative definition with 9148 // external linkage is valid (C99 6.2.2p5). 9149 if (!Var->isInvalidDecl()) { 9150 if (const IncompleteArrayType *ArrayT 9151 = Context.getAsIncompleteArrayType(Type)) { 9152 if (RequireCompleteType(Var->getLocation(), 9153 ArrayT->getElementType(), 9154 diag::err_illegal_decl_array_incomplete_type)) 9155 Var->setInvalidDecl(); 9156 } else if (Var->getStorageClass() == SC_Static) { 9157 // C99 6.9.2p3: If the declaration of an identifier for an object is 9158 // a tentative definition and has internal linkage (C99 6.2.2p3), the 9159 // declared type shall not be an incomplete type. 9160 // NOTE: code such as the following 9161 // static struct s; 9162 // struct s { int a; }; 9163 // is accepted by gcc. Hence here we issue a warning instead of 9164 // an error and we do not invalidate the static declaration. 9165 // NOTE: to avoid multiple warnings, only check the first declaration. 9166 if (Var->isFirstDecl()) 9167 RequireCompleteType(Var->getLocation(), Type, 9168 diag::ext_typecheck_decl_incomplete_type); 9169 } 9170 } 9171 9172 // Record the tentative definition; we're done. 9173 if (!Var->isInvalidDecl()) 9174 TentativeDefinitions.push_back(Var); 9175 return; 9176 } 9177 9178 // Provide a specific diagnostic for uninitialized variable 9179 // definitions with incomplete array type. 9180 if (Type->isIncompleteArrayType()) { 9181 Diag(Var->getLocation(), 9182 diag::err_typecheck_incomplete_array_needs_initializer); 9183 Var->setInvalidDecl(); 9184 return; 9185 } 9186 9187 // Provide a specific diagnostic for uninitialized variable 9188 // definitions with reference type. 9189 if (Type->isReferenceType()) { 9190 Diag(Var->getLocation(), diag::err_reference_var_requires_init) 9191 << Var->getDeclName() 9192 << SourceRange(Var->getLocation(), Var->getLocation()); 9193 Var->setInvalidDecl(); 9194 return; 9195 } 9196 9197 // Do not attempt to type-check the default initializer for a 9198 // variable with dependent type. 9199 if (Type->isDependentType()) 9200 return; 9201 9202 if (Var->isInvalidDecl()) 9203 return; 9204 9205 if (!Var->hasAttr<AliasAttr>()) { 9206 if (RequireCompleteType(Var->getLocation(), 9207 Context.getBaseElementType(Type), 9208 diag::err_typecheck_decl_incomplete_type)) { 9209 Var->setInvalidDecl(); 9210 return; 9211 } 9212 } 9213 9214 // The variable can not have an abstract class type. 9215 if (RequireNonAbstractType(Var->getLocation(), Type, 9216 diag::err_abstract_type_in_decl, 9217 AbstractVariableType)) { 9218 Var->setInvalidDecl(); 9219 return; 9220 } 9221 9222 // Check for jumps past the implicit initializer. C++0x 9223 // clarifies that this applies to a "variable with automatic 9224 // storage duration", not a "local variable". 9225 // C++11 [stmt.dcl]p3 9226 // A program that jumps from a point where a variable with automatic 9227 // storage duration is not in scope to a point where it is in scope is 9228 // ill-formed unless the variable has scalar type, class type with a 9229 // trivial default constructor and a trivial destructor, a cv-qualified 9230 // version of one of these types, or an array of one of the preceding 9231 // types and is declared without an initializer. 9232 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) { 9233 if (const RecordType *Record 9234 = Context.getBaseElementType(Type)->getAs<RecordType>()) { 9235 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl()); 9236 // Mark the function for further checking even if the looser rules of 9237 // C++11 do not require such checks, so that we can diagnose 9238 // incompatibilities with C++98. 9239 if (!CXXRecord->isPOD()) 9240 getCurFunction()->setHasBranchProtectedScope(); 9241 } 9242 } 9243 9244 // C++03 [dcl.init]p9: 9245 // If no initializer is specified for an object, and the 9246 // object is of (possibly cv-qualified) non-POD class type (or 9247 // array thereof), the object shall be default-initialized; if 9248 // the object is of const-qualified type, the underlying class 9249 // type shall have a user-declared default 9250 // constructor. Otherwise, if no initializer is specified for 9251 // a non- static object, the object and its subobjects, if 9252 // any, have an indeterminate initial value); if the object 9253 // or any of its subobjects are of const-qualified type, the 9254 // program is ill-formed. 9255 // C++0x [dcl.init]p11: 9256 // If no initializer is specified for an object, the object is 9257 // default-initialized; [...]. 9258 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var); 9259 InitializationKind Kind 9260 = InitializationKind::CreateDefault(Var->getLocation()); 9261 9262 InitializationSequence InitSeq(*this, Entity, Kind, None); 9263 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None); 9264 if (Init.isInvalid()) 9265 Var->setInvalidDecl(); 9266 else if (Init.get()) { 9267 Var->setInit(MaybeCreateExprWithCleanups(Init.get())); 9268 // This is important for template substitution. 9269 Var->setInitStyle(VarDecl::CallInit); 9270 } 9271 9272 CheckCompleteVariableDeclaration(Var); 9273 } 9274 } 9275 9276 void Sema::ActOnCXXForRangeDecl(Decl *D) { 9277 VarDecl *VD = dyn_cast<VarDecl>(D); 9278 if (!VD) { 9279 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var); 9280 D->setInvalidDecl(); 9281 return; 9282 } 9283 9284 VD->setCXXForRangeDecl(true); 9285 9286 // for-range-declaration cannot be given a storage class specifier. 9287 int Error = -1; 9288 switch (VD->getStorageClass()) { 9289 case SC_None: 9290 break; 9291 case SC_Extern: 9292 Error = 0; 9293 break; 9294 case SC_Static: 9295 Error = 1; 9296 break; 9297 case SC_PrivateExtern: 9298 Error = 2; 9299 break; 9300 case SC_Auto: 9301 Error = 3; 9302 break; 9303 case SC_Register: 9304 Error = 4; 9305 break; 9306 case SC_OpenCLWorkGroupLocal: 9307 llvm_unreachable("Unexpected storage class"); 9308 } 9309 if (VD->isConstexpr()) 9310 Error = 5; 9311 if (Error != -1) { 9312 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class) 9313 << VD->getDeclName() << Error; 9314 D->setInvalidDecl(); 9315 } 9316 } 9317 9318 StmtResult 9319 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, 9320 IdentifierInfo *Ident, 9321 ParsedAttributes &Attrs, 9322 SourceLocation AttrEnd) { 9323 // C++1y [stmt.iter]p1: 9324 // A range-based for statement of the form 9325 // for ( for-range-identifier : for-range-initializer ) statement 9326 // is equivalent to 9327 // for ( auto&& for-range-identifier : for-range-initializer ) statement 9328 DeclSpec DS(Attrs.getPool().getFactory()); 9329 9330 const char *PrevSpec; 9331 unsigned DiagID; 9332 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID, 9333 getPrintingPolicy()); 9334 9335 Declarator D(DS, Declarator::ForContext); 9336 D.SetIdentifier(Ident, IdentLoc); 9337 D.takeAttributes(Attrs, AttrEnd); 9338 9339 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory()); 9340 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false), 9341 EmptyAttrs, IdentLoc); 9342 Decl *Var = ActOnDeclarator(S, D); 9343 cast<VarDecl>(Var)->setCXXForRangeDecl(true); 9344 FinalizeDeclaration(Var); 9345 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc, 9346 AttrEnd.isValid() ? AttrEnd : IdentLoc); 9347 } 9348 9349 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) { 9350 if (var->isInvalidDecl()) return; 9351 9352 // In ARC, don't allow jumps past the implicit initialization of a 9353 // local retaining variable. 9354 if (getLangOpts().ObjCAutoRefCount && 9355 var->hasLocalStorage()) { 9356 switch (var->getType().getObjCLifetime()) { 9357 case Qualifiers::OCL_None: 9358 case Qualifiers::OCL_ExplicitNone: 9359 case Qualifiers::OCL_Autoreleasing: 9360 break; 9361 9362 case Qualifiers::OCL_Weak: 9363 case Qualifiers::OCL_Strong: 9364 getCurFunction()->setHasBranchProtectedScope(); 9365 break; 9366 } 9367 } 9368 9369 // Warn about externally-visible variables being defined without a 9370 // prior declaration. We only want to do this for global 9371 // declarations, but we also specifically need to avoid doing it for 9372 // class members because the linkage of an anonymous class can 9373 // change if it's later given a typedef name. 9374 if (var->isThisDeclarationADefinition() && 9375 var->getDeclContext()->getRedeclContext()->isFileContext() && 9376 var->isExternallyVisible() && var->hasLinkage() && 9377 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations, 9378 var->getLocation())) { 9379 // Find a previous declaration that's not a definition. 9380 VarDecl *prev = var->getPreviousDecl(); 9381 while (prev && prev->isThisDeclarationADefinition()) 9382 prev = prev->getPreviousDecl(); 9383 9384 if (!prev) 9385 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var; 9386 } 9387 9388 if (var->getTLSKind() == VarDecl::TLS_Static) { 9389 const Expr *Culprit; 9390 if (var->getType().isDestructedType()) { 9391 // GNU C++98 edits for __thread, [basic.start.term]p3: 9392 // The type of an object with thread storage duration shall not 9393 // have a non-trivial destructor. 9394 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor); 9395 if (getLangOpts().CPlusPlus11) 9396 Diag(var->getLocation(), diag::note_use_thread_local); 9397 } else if (getLangOpts().CPlusPlus && var->hasInit() && 9398 !var->getInit()->isConstantInitializer( 9399 Context, var->getType()->isReferenceType(), &Culprit)) { 9400 // GNU C++98 edits for __thread, [basic.start.init]p4: 9401 // An object of thread storage duration shall not require dynamic 9402 // initialization. 9403 // FIXME: Need strict checking here. 9404 Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init) 9405 << Culprit->getSourceRange(); 9406 if (getLangOpts().CPlusPlus11) 9407 Diag(var->getLocation(), diag::note_use_thread_local); 9408 } 9409 9410 } 9411 9412 if (var->isThisDeclarationADefinition() && 9413 ActiveTemplateInstantiations.empty()) { 9414 PragmaStack<StringLiteral *> *Stack = nullptr; 9415 int SectionFlags = PSF_Implicit | PSF_Read; 9416 if (var->getType().isConstQualified()) 9417 Stack = &ConstSegStack; 9418 else if (!var->getInit()) { 9419 Stack = &BSSSegStack; 9420 SectionFlags |= PSF_Write; 9421 } else { 9422 Stack = &DataSegStack; 9423 SectionFlags |= PSF_Write; 9424 } 9425 if (!var->hasAttr<SectionAttr>() && Stack->CurrentValue) 9426 var->addAttr( 9427 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate, 9428 Stack->CurrentValue->getString(), 9429 Stack->CurrentPragmaLocation)); 9430 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) 9431 if (UnifySection(SA->getName(), SectionFlags, var)) 9432 var->dropAttr<SectionAttr>(); 9433 9434 // Apply the init_seg attribute if this has an initializer. If the 9435 // initializer turns out to not be dynamic, we'll end up ignoring this 9436 // attribute. 9437 if (CurInitSeg && var->getInit()) 9438 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(), 9439 CurInitSegLoc)); 9440 } 9441 9442 // All the following checks are C++ only. 9443 if (!getLangOpts().CPlusPlus) return; 9444 9445 QualType type = var->getType(); 9446 if (type->isDependentType()) return; 9447 9448 // __block variables might require us to capture a copy-initializer. 9449 if (var->hasAttr<BlocksAttr>()) { 9450 // It's currently invalid to ever have a __block variable with an 9451 // array type; should we diagnose that here? 9452 9453 // Regardless, we don't want to ignore array nesting when 9454 // constructing this copy. 9455 if (type->isStructureOrClassType()) { 9456 EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated); 9457 SourceLocation poi = var->getLocation(); 9458 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi); 9459 ExprResult result 9460 = PerformMoveOrCopyInitialization( 9461 InitializedEntity::InitializeBlock(poi, type, false), 9462 var, var->getType(), varRef, /*AllowNRVO=*/true); 9463 if (!result.isInvalid()) { 9464 result = MaybeCreateExprWithCleanups(result); 9465 Expr *init = result.getAs<Expr>(); 9466 Context.setBlockVarCopyInits(var, init); 9467 } 9468 } 9469 } 9470 9471 Expr *Init = var->getInit(); 9472 bool IsGlobal = var->hasGlobalStorage() && !var->isStaticLocal(); 9473 QualType baseType = Context.getBaseElementType(type); 9474 9475 if (!var->getDeclContext()->isDependentContext() && 9476 Init && !Init->isValueDependent()) { 9477 if (IsGlobal && !var->isConstexpr() && 9478 !getDiagnostics().isIgnored(diag::warn_global_constructor, 9479 var->getLocation())) { 9480 // Warn about globals which don't have a constant initializer. Don't 9481 // warn about globals with a non-trivial destructor because we already 9482 // warned about them. 9483 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl(); 9484 if (!(RD && !RD->hasTrivialDestructor()) && 9485 !Init->isConstantInitializer(Context, baseType->isReferenceType())) 9486 Diag(var->getLocation(), diag::warn_global_constructor) 9487 << Init->getSourceRange(); 9488 } 9489 9490 if (var->isConstexpr()) { 9491 SmallVector<PartialDiagnosticAt, 8> Notes; 9492 if (!var->evaluateValue(Notes) || !var->isInitICE()) { 9493 SourceLocation DiagLoc = var->getLocation(); 9494 // If the note doesn't add any useful information other than a source 9495 // location, fold it into the primary diagnostic. 9496 if (Notes.size() == 1 && Notes[0].second.getDiagID() == 9497 diag::note_invalid_subexpr_in_const_expr) { 9498 DiagLoc = Notes[0].first; 9499 Notes.clear(); 9500 } 9501 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init) 9502 << var << Init->getSourceRange(); 9503 for (unsigned I = 0, N = Notes.size(); I != N; ++I) 9504 Diag(Notes[I].first, Notes[I].second); 9505 } 9506 } else if (var->isUsableInConstantExpressions(Context)) { 9507 // Check whether the initializer of a const variable of integral or 9508 // enumeration type is an ICE now, since we can't tell whether it was 9509 // initialized by a constant expression if we check later. 9510 var->checkInitIsICE(); 9511 } 9512 } 9513 9514 // Require the destructor. 9515 if (const RecordType *recordType = baseType->getAs<RecordType>()) 9516 FinalizeVarWithDestructor(var, recordType); 9517 } 9518 9519 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform 9520 /// any semantic actions necessary after any initializer has been attached. 9521 void 9522 Sema::FinalizeDeclaration(Decl *ThisDecl) { 9523 // Note that we are no longer parsing the initializer for this declaration. 9524 ParsingInitForAutoVars.erase(ThisDecl); 9525 9526 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl); 9527 if (!VD) 9528 return; 9529 9530 checkAttributesAfterMerging(*this, *VD); 9531 9532 // Static locals inherit dll attributes from their function. 9533 if (VD->isStaticLocal()) { 9534 if (FunctionDecl *FD = 9535 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) { 9536 if (Attr *A = getDLLAttr(FD)) { 9537 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext())); 9538 NewAttr->setInherited(true); 9539 VD->addAttr(NewAttr); 9540 } 9541 } 9542 } 9543 9544 // Imported static data members cannot be defined out-of-line. 9545 if (const DLLImportAttr *IA = VD->getAttr<DLLImportAttr>()) { 9546 if (VD->isStaticDataMember() && VD->isOutOfLine() && 9547 VD->isThisDeclarationADefinition()) { 9548 // We allow definitions of dllimport class template static data members 9549 // with a warning. 9550 CXXRecordDecl *Context = 9551 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext()); 9552 bool IsClassTemplateMember = 9553 isa<ClassTemplatePartialSpecializationDecl>(Context) || 9554 Context->getDescribedClassTemplate(); 9555 9556 Diag(VD->getLocation(), 9557 IsClassTemplateMember 9558 ? diag::warn_attribute_dllimport_static_field_definition 9559 : diag::err_attribute_dllimport_static_field_definition); 9560 Diag(IA->getLocation(), diag::note_attribute); 9561 if (!IsClassTemplateMember) 9562 VD->setInvalidDecl(); 9563 } 9564 } 9565 9566 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) { 9567 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) { 9568 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr; 9569 VD->dropAttr<UsedAttr>(); 9570 } 9571 } 9572 9573 if (!VD->isInvalidDecl() && 9574 VD->isThisDeclarationADefinition() == VarDecl::TentativeDefinition) { 9575 if (const VarDecl *Def = VD->getDefinition()) { 9576 if (Def->hasAttr<AliasAttr>()) { 9577 Diag(VD->getLocation(), diag::err_tentative_after_alias) 9578 << VD->getDeclName(); 9579 Diag(Def->getLocation(), diag::note_previous_definition); 9580 VD->setInvalidDecl(); 9581 } 9582 } 9583 } 9584 9585 const DeclContext *DC = VD->getDeclContext(); 9586 // If there's a #pragma GCC visibility in scope, and this isn't a class 9587 // member, set the visibility of this variable. 9588 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible()) 9589 AddPushedVisibilityAttribute(VD); 9590 9591 // FIXME: Warn on unused templates. 9592 if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() && 9593 !isa<VarTemplatePartialSpecializationDecl>(VD)) 9594 MarkUnusedFileScopedDecl(VD); 9595 9596 // Now we have parsed the initializer and can update the table of magic 9597 // tag values. 9598 if (!VD->hasAttr<TypeTagForDatatypeAttr>() || 9599 !VD->getType()->isIntegralOrEnumerationType()) 9600 return; 9601 9602 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) { 9603 const Expr *MagicValueExpr = VD->getInit(); 9604 if (!MagicValueExpr) { 9605 continue; 9606 } 9607 llvm::APSInt MagicValueInt; 9608 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) { 9609 Diag(I->getRange().getBegin(), 9610 diag::err_type_tag_for_datatype_not_ice) 9611 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9612 continue; 9613 } 9614 if (MagicValueInt.getActiveBits() > 64) { 9615 Diag(I->getRange().getBegin(), 9616 diag::err_type_tag_for_datatype_too_large) 9617 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange(); 9618 continue; 9619 } 9620 uint64_t MagicValue = MagicValueInt.getZExtValue(); 9621 RegisterTypeTagForDatatype(I->getArgumentKind(), 9622 MagicValue, 9623 I->getMatchingCType(), 9624 I->getLayoutCompatible(), 9625 I->getMustBeNull()); 9626 } 9627 } 9628 9629 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 9630 ArrayRef<Decl *> Group) { 9631 SmallVector<Decl*, 8> Decls; 9632 9633 if (DS.isTypeSpecOwned()) 9634 Decls.push_back(DS.getRepAsDecl()); 9635 9636 DeclaratorDecl *FirstDeclaratorInGroup = nullptr; 9637 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9638 if (Decl *D = Group[i]) { 9639 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) 9640 if (!FirstDeclaratorInGroup) 9641 FirstDeclaratorInGroup = DD; 9642 Decls.push_back(D); 9643 } 9644 9645 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) { 9646 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) { 9647 HandleTagNumbering(*this, Tag, S); 9648 if (!Tag->hasNameForLinkage() && !Tag->hasDeclaratorForAnonDecl()) 9649 Tag->setDeclaratorForAnonDecl(FirstDeclaratorInGroup); 9650 } 9651 } 9652 9653 return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType()); 9654 } 9655 9656 /// BuildDeclaratorGroup - convert a list of declarations into a declaration 9657 /// group, performing any necessary semantic checking. 9658 Sema::DeclGroupPtrTy 9659 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group, 9660 bool TypeMayContainAuto) { 9661 // C++0x [dcl.spec.auto]p7: 9662 // If the type deduced for the template parameter U is not the same in each 9663 // deduction, the program is ill-formed. 9664 // FIXME: When initializer-list support is added, a distinction is needed 9665 // between the deduced type U and the deduced type which 'auto' stands for. 9666 // auto a = 0, b = { 1, 2, 3 }; 9667 // is legal because the deduced type U is 'int' in both cases. 9668 if (TypeMayContainAuto && Group.size() > 1) { 9669 QualType Deduced; 9670 CanQualType DeducedCanon; 9671 VarDecl *DeducedDecl = nullptr; 9672 for (unsigned i = 0, e = Group.size(); i != e; ++i) { 9673 if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) { 9674 AutoType *AT = D->getType()->getContainedAutoType(); 9675 // Don't reissue diagnostics when instantiating a template. 9676 if (AT && D->isInvalidDecl()) 9677 break; 9678 QualType U = AT ? AT->getDeducedType() : QualType(); 9679 if (!U.isNull()) { 9680 CanQualType UCanon = Context.getCanonicalType(U); 9681 if (Deduced.isNull()) { 9682 Deduced = U; 9683 DeducedCanon = UCanon; 9684 DeducedDecl = D; 9685 } else if (DeducedCanon != UCanon) { 9686 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(), 9687 diag::err_auto_different_deductions) 9688 << (AT->isDecltypeAuto() ? 1 : 0) 9689 << Deduced << DeducedDecl->getDeclName() 9690 << U << D->getDeclName() 9691 << DeducedDecl->getInit()->getSourceRange() 9692 << D->getInit()->getSourceRange(); 9693 D->setInvalidDecl(); 9694 break; 9695 } 9696 } 9697 } 9698 } 9699 } 9700 9701 ActOnDocumentableDecls(Group); 9702 9703 return DeclGroupPtrTy::make( 9704 DeclGroupRef::Create(Context, Group.data(), Group.size())); 9705 } 9706 9707 void Sema::ActOnDocumentableDecl(Decl *D) { 9708 ActOnDocumentableDecls(D); 9709 } 9710 9711 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) { 9712 // Don't parse the comment if Doxygen diagnostics are ignored. 9713 if (Group.empty() || !Group[0]) 9714 return; 9715 9716 if (Diags.isIgnored(diag::warn_doc_param_not_found, Group[0]->getLocation())) 9717 return; 9718 9719 if (Group.size() >= 2) { 9720 // This is a decl group. Normally it will contain only declarations 9721 // produced from declarator list. But in case we have any definitions or 9722 // additional declaration references: 9723 // 'typedef struct S {} S;' 9724 // 'typedef struct S *S;' 9725 // 'struct S *pS;' 9726 // FinalizeDeclaratorGroup adds these as separate declarations. 9727 Decl *MaybeTagDecl = Group[0]; 9728 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) { 9729 Group = Group.slice(1); 9730 } 9731 } 9732 9733 // See if there are any new comments that are not attached to a decl. 9734 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments(); 9735 if (!Comments.empty() && 9736 !Comments.back()->isAttached()) { 9737 // There is at least one comment that not attached to a decl. 9738 // Maybe it should be attached to one of these decls? 9739 // 9740 // Note that this way we pick up not only comments that precede the 9741 // declaration, but also comments that *follow* the declaration -- thanks to 9742 // the lookahead in the lexer: we've consumed the semicolon and looked 9743 // ahead through comments. 9744 for (unsigned i = 0, e = Group.size(); i != e; ++i) 9745 Context.getCommentForDecl(Group[i], &PP); 9746 } 9747 } 9748 9749 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() 9750 /// to introduce parameters into function prototype scope. 9751 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) { 9752 const DeclSpec &DS = D.getDeclSpec(); 9753 9754 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'. 9755 9756 // C++03 [dcl.stc]p2 also permits 'auto'. 9757 VarDecl::StorageClass StorageClass = SC_None; 9758 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 9759 StorageClass = SC_Register; 9760 } else if (getLangOpts().CPlusPlus && 9761 DS.getStorageClassSpec() == DeclSpec::SCS_auto) { 9762 StorageClass = SC_Auto; 9763 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 9764 Diag(DS.getStorageClassSpecLoc(), 9765 diag::err_invalid_storage_class_in_func_decl); 9766 D.getMutableDeclSpec().ClearStorageClassSpecs(); 9767 } 9768 9769 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec()) 9770 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread) 9771 << DeclSpec::getSpecifierName(TSCS); 9772 if (DS.isConstexprSpecified()) 9773 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr) 9774 << 0; 9775 9776 DiagnoseFunctionSpecifiers(DS); 9777 9778 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 9779 QualType parmDeclType = TInfo->getType(); 9780 9781 if (getLangOpts().CPlusPlus) { 9782 // Check that there are no default arguments inside the type of this 9783 // parameter. 9784 CheckExtraCXXDefaultArguments(D); 9785 9786 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 9787 if (D.getCXXScopeSpec().isSet()) { 9788 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator) 9789 << D.getCXXScopeSpec().getRange(); 9790 D.getCXXScopeSpec().clear(); 9791 } 9792 } 9793 9794 // Ensure we have a valid name 9795 IdentifierInfo *II = nullptr; 9796 if (D.hasName()) { 9797 II = D.getIdentifier(); 9798 if (!II) { 9799 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name) 9800 << GetNameForDeclarator(D).getName(); 9801 D.setInvalidType(true); 9802 } 9803 } 9804 9805 // Check for redeclaration of parameters, e.g. int foo(int x, int x); 9806 if (II) { 9807 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName, 9808 ForRedeclaration); 9809 LookupName(R, S); 9810 if (R.isSingleResult()) { 9811 NamedDecl *PrevDecl = R.getFoundDecl(); 9812 if (PrevDecl->isTemplateParameter()) { 9813 // Maybe we will complain about the shadowed template parameter. 9814 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 9815 // Just pretend that we didn't see the previous declaration. 9816 PrevDecl = nullptr; 9817 } else if (S->isDeclScope(PrevDecl)) { 9818 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II; 9819 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 9820 9821 // Recover by removing the name 9822 II = nullptr; 9823 D.SetIdentifier(nullptr, D.getIdentifierLoc()); 9824 D.setInvalidType(true); 9825 } 9826 } 9827 } 9828 9829 // Temporarily put parameter variables in the translation unit, not 9830 // the enclosing context. This prevents them from accidentally 9831 // looking like class members in C++. 9832 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(), 9833 D.getLocStart(), 9834 D.getIdentifierLoc(), II, 9835 parmDeclType, TInfo, 9836 StorageClass); 9837 9838 if (D.isInvalidType()) 9839 New->setInvalidDecl(); 9840 9841 assert(S->isFunctionPrototypeScope()); 9842 assert(S->getFunctionPrototypeDepth() >= 1); 9843 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1, 9844 S->getNextFunctionPrototypeIndex()); 9845 9846 // Add the parameter declaration into this scope. 9847 S->AddDecl(New); 9848 if (II) 9849 IdResolver.AddDecl(New); 9850 9851 ProcessDeclAttributes(S, New, D); 9852 9853 if (D.getDeclSpec().isModulePrivateSpecified()) 9854 Diag(New->getLocation(), diag::err_module_private_local) 9855 << 1 << New->getDeclName() 9856 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 9857 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 9858 9859 if (New->hasAttr<BlocksAttr>()) { 9860 Diag(New->getLocation(), diag::err_block_on_nonlocal); 9861 } 9862 return New; 9863 } 9864 9865 /// \brief Synthesizes a variable for a parameter arising from a 9866 /// typedef. 9867 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC, 9868 SourceLocation Loc, 9869 QualType T) { 9870 /* FIXME: setting StartLoc == Loc. 9871 Would it be worth to modify callers so as to provide proper source 9872 location for the unnamed parameters, embedding the parameter's type? */ 9873 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr, 9874 T, Context.getTrivialTypeSourceInfo(T, Loc), 9875 SC_None, nullptr); 9876 Param->setImplicit(); 9877 return Param; 9878 } 9879 9880 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param, 9881 ParmVarDecl * const *ParamEnd) { 9882 // Don't diagnose unused-parameter errors in template instantiations; we 9883 // will already have done so in the template itself. 9884 if (!ActiveTemplateInstantiations.empty()) 9885 return; 9886 9887 for (; Param != ParamEnd; ++Param) { 9888 if (!(*Param)->isReferenced() && (*Param)->getDeclName() && 9889 !(*Param)->hasAttr<UnusedAttr>()) { 9890 Diag((*Param)->getLocation(), diag::warn_unused_parameter) 9891 << (*Param)->getDeclName(); 9892 } 9893 } 9894 } 9895 9896 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param, 9897 ParmVarDecl * const *ParamEnd, 9898 QualType ReturnTy, 9899 NamedDecl *D) { 9900 if (LangOpts.NumLargeByValueCopy == 0) // No check. 9901 return; 9902 9903 // Warn if the return value is pass-by-value and larger than the specified 9904 // threshold. 9905 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) { 9906 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity(); 9907 if (Size > LangOpts.NumLargeByValueCopy) 9908 Diag(D->getLocation(), diag::warn_return_value_size) 9909 << D->getDeclName() << Size; 9910 } 9911 9912 // Warn if any parameter is pass-by-value and larger than the specified 9913 // threshold. 9914 for (; Param != ParamEnd; ++Param) { 9915 QualType T = (*Param)->getType(); 9916 if (T->isDependentType() || !T.isPODType(Context)) 9917 continue; 9918 unsigned Size = Context.getTypeSizeInChars(T).getQuantity(); 9919 if (Size > LangOpts.NumLargeByValueCopy) 9920 Diag((*Param)->getLocation(), diag::warn_parameter_size) 9921 << (*Param)->getDeclName() << Size; 9922 } 9923 } 9924 9925 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc, 9926 SourceLocation NameLoc, IdentifierInfo *Name, 9927 QualType T, TypeSourceInfo *TSInfo, 9928 VarDecl::StorageClass StorageClass) { 9929 // In ARC, infer a lifetime qualifier for appropriate parameter types. 9930 if (getLangOpts().ObjCAutoRefCount && 9931 T.getObjCLifetime() == Qualifiers::OCL_None && 9932 T->isObjCLifetimeType()) { 9933 9934 Qualifiers::ObjCLifetime lifetime; 9935 9936 // Special cases for arrays: 9937 // - if it's const, use __unsafe_unretained 9938 // - otherwise, it's an error 9939 if (T->isArrayType()) { 9940 if (!T.isConstQualified()) { 9941 DelayedDiagnostics.add( 9942 sema::DelayedDiagnostic::makeForbiddenType( 9943 NameLoc, diag::err_arc_array_param_no_ownership, T, false)); 9944 } 9945 lifetime = Qualifiers::OCL_ExplicitNone; 9946 } else { 9947 lifetime = T->getObjCARCImplicitLifetime(); 9948 } 9949 T = Context.getLifetimeQualifiedType(T, lifetime); 9950 } 9951 9952 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name, 9953 Context.getAdjustedParameterType(T), 9954 TSInfo, 9955 StorageClass, nullptr); 9956 9957 // Parameters can not be abstract class types. 9958 // For record types, this is done by the AbstractClassUsageDiagnoser once 9959 // the class has been completely parsed. 9960 if (!CurContext->isRecord() && 9961 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl, 9962 AbstractParamType)) 9963 New->setInvalidDecl(); 9964 9965 // Parameter declarators cannot be interface types. All ObjC objects are 9966 // passed by reference. 9967 if (T->isObjCObjectType()) { 9968 SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd(); 9969 Diag(NameLoc, 9970 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T 9971 << FixItHint::CreateInsertion(TypeEndLoc, "*"); 9972 T = Context.getObjCObjectPointerType(T); 9973 New->setType(T); 9974 } 9975 9976 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 9977 // duration shall not be qualified by an address-space qualifier." 9978 // Since all parameters have automatic store duration, they can not have 9979 // an address space. 9980 if (T.getAddressSpace() != 0) { 9981 // OpenCL allows function arguments declared to be an array of a type 9982 // to be qualified with an address space. 9983 if (!(getLangOpts().OpenCL && T->isArrayType())) { 9984 Diag(NameLoc, diag::err_arg_with_address_space); 9985 New->setInvalidDecl(); 9986 } 9987 } 9988 9989 return New; 9990 } 9991 9992 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 9993 SourceLocation LocAfterDecls) { 9994 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo(); 9995 9996 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared' 9997 // for a K&R function. 9998 if (!FTI.hasPrototype) { 9999 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) { 10000 --i; 10001 if (FTI.Params[i].Param == nullptr) { 10002 SmallString<256> Code; 10003 llvm::raw_svector_ostream(Code) 10004 << " int " << FTI.Params[i].Ident->getName() << ";\n"; 10005 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared) 10006 << FTI.Params[i].Ident 10007 << FixItHint::CreateInsertion(LocAfterDecls, Code.str()); 10008 10009 // Implicitly declare the argument as type 'int' for lack of a better 10010 // type. 10011 AttributeFactory attrs; 10012 DeclSpec DS(attrs); 10013 const char* PrevSpec; // unused 10014 unsigned DiagID; // unused 10015 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec, 10016 DiagID, Context.getPrintingPolicy()); 10017 // Use the identifier location for the type source range. 10018 DS.SetRangeStart(FTI.Params[i].IdentLoc); 10019 DS.SetRangeEnd(FTI.Params[i].IdentLoc); 10020 Declarator ParamD(DS, Declarator::KNRTypeListContext); 10021 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc); 10022 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD); 10023 } 10024 } 10025 } 10026 } 10027 10028 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) { 10029 assert(getCurFunctionDecl() == nullptr && "Function parsing confused"); 10030 assert(D.isFunctionDeclarator() && "Not a function declarator!"); 10031 Scope *ParentScope = FnBodyScope->getParent(); 10032 10033 D.setFunctionDefinitionKind(FDK_Definition); 10034 Decl *DP = HandleDeclarator(ParentScope, D, MultiTemplateParamsArg()); 10035 return ActOnStartOfFunctionDef(FnBodyScope, DP); 10036 } 10037 10038 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) { 10039 Consumer.HandleInlineMethodDefinition(D); 10040 } 10041 10042 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, 10043 const FunctionDecl*& PossibleZeroParamPrototype) { 10044 // Don't warn about invalid declarations. 10045 if (FD->isInvalidDecl()) 10046 return false; 10047 10048 // Or declarations that aren't global. 10049 if (!FD->isGlobal()) 10050 return false; 10051 10052 // Don't warn about C++ member functions. 10053 if (isa<CXXMethodDecl>(FD)) 10054 return false; 10055 10056 // Don't warn about 'main'. 10057 if (FD->isMain()) 10058 return false; 10059 10060 // Don't warn about inline functions. 10061 if (FD->isInlined()) 10062 return false; 10063 10064 // Don't warn about function templates. 10065 if (FD->getDescribedFunctionTemplate()) 10066 return false; 10067 10068 // Don't warn about function template specializations. 10069 if (FD->isFunctionTemplateSpecialization()) 10070 return false; 10071 10072 // Don't warn for OpenCL kernels. 10073 if (FD->hasAttr<OpenCLKernelAttr>()) 10074 return false; 10075 10076 bool MissingPrototype = true; 10077 for (const FunctionDecl *Prev = FD->getPreviousDecl(); 10078 Prev; Prev = Prev->getPreviousDecl()) { 10079 // Ignore any declarations that occur in function or method 10080 // scope, because they aren't visible from the header. 10081 if (Prev->getLexicalDeclContext()->isFunctionOrMethod()) 10082 continue; 10083 10084 MissingPrototype = !Prev->getType()->isFunctionProtoType(); 10085 if (FD->getNumParams() == 0) 10086 PossibleZeroParamPrototype = Prev; 10087 break; 10088 } 10089 10090 return MissingPrototype; 10091 } 10092 10093 void 10094 Sema::CheckForFunctionRedefinition(FunctionDecl *FD, 10095 const FunctionDecl *EffectiveDefinition) { 10096 // Don't complain if we're in GNU89 mode and the previous definition 10097 // was an extern inline function. 10098 const FunctionDecl *Definition = EffectiveDefinition; 10099 if (!Definition) 10100 if (!FD->isDefined(Definition)) 10101 return; 10102 10103 if (canRedefineFunction(Definition, getLangOpts())) 10104 return; 10105 10106 if (getLangOpts().GNUMode && Definition->isInlineSpecified() && 10107 Definition->getStorageClass() == SC_Extern) 10108 Diag(FD->getLocation(), diag::err_redefinition_extern_inline) 10109 << FD->getDeclName() << getLangOpts().CPlusPlus; 10110 else 10111 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName(); 10112 10113 Diag(Definition->getLocation(), diag::note_previous_definition); 10114 FD->setInvalidDecl(); 10115 } 10116 10117 10118 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, 10119 Sema &S) { 10120 CXXRecordDecl *const LambdaClass = CallOperator->getParent(); 10121 10122 LambdaScopeInfo *LSI = S.PushLambdaScope(); 10123 LSI->CallOperator = CallOperator; 10124 LSI->Lambda = LambdaClass; 10125 LSI->ReturnType = CallOperator->getReturnType(); 10126 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault(); 10127 10128 if (LCD == LCD_None) 10129 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None; 10130 else if (LCD == LCD_ByCopy) 10131 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval; 10132 else if (LCD == LCD_ByRef) 10133 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref; 10134 DeclarationNameInfo DNI = CallOperator->getNameInfo(); 10135 10136 LSI->IntroducerRange = DNI.getCXXOperatorNameRange(); 10137 LSI->Mutable = !CallOperator->isConst(); 10138 10139 // Add the captures to the LSI so they can be noted as already 10140 // captured within tryCaptureVar. 10141 auto I = LambdaClass->field_begin(); 10142 for (const auto &C : LambdaClass->captures()) { 10143 if (C.capturesVariable()) { 10144 VarDecl *VD = C.getCapturedVar(); 10145 if (VD->isInitCapture()) 10146 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD); 10147 QualType CaptureType = VD->getType(); 10148 const bool ByRef = C.getCaptureKind() == LCK_ByRef; 10149 LSI->addCapture(VD, /*IsBlock*/false, ByRef, 10150 /*RefersToEnclosingLocal*/true, C.getLocation(), 10151 /*EllipsisLoc*/C.isPackExpansion() 10152 ? C.getEllipsisLoc() : SourceLocation(), 10153 CaptureType, /*Expr*/ nullptr); 10154 10155 } else if (C.capturesThis()) { 10156 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), 10157 S.getCurrentThisType(), /*Expr*/ nullptr); 10158 } else { 10159 LSI->addVLATypeCapture(C.getLocation(), I->getType()); 10160 } 10161 ++I; 10162 } 10163 } 10164 10165 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D) { 10166 // Clear the last template instantiation error context. 10167 LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation(); 10168 10169 if (!D) 10170 return D; 10171 FunctionDecl *FD = nullptr; 10172 10173 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) 10174 FD = FunTmpl->getTemplatedDecl(); 10175 else 10176 FD = cast<FunctionDecl>(D); 10177 // If we are instantiating a generic lambda call operator, push 10178 // a LambdaScopeInfo onto the function stack. But use the information 10179 // that's already been calculated (ActOnLambdaExpr) to prime the current 10180 // LambdaScopeInfo. 10181 // When the template operator is being specialized, the LambdaScopeInfo, 10182 // has to be properly restored so that tryCaptureVariable doesn't try 10183 // and capture any new variables. In addition when calculating potential 10184 // captures during transformation of nested lambdas, it is necessary to 10185 // have the LSI properly restored. 10186 if (isGenericLambdaCallOperatorSpecialization(FD)) { 10187 assert(ActiveTemplateInstantiations.size() && 10188 "There should be an active template instantiation on the stack " 10189 "when instantiating a generic lambda!"); 10190 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this); 10191 } 10192 else 10193 // Enter a new function scope 10194 PushFunctionScope(); 10195 10196 // See if this is a redefinition. 10197 if (!FD->isLateTemplateParsed()) 10198 CheckForFunctionRedefinition(FD); 10199 10200 // Builtin functions cannot be defined. 10201 if (unsigned BuiltinID = FD->getBuiltinID()) { 10202 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) && 10203 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) { 10204 Diag(FD->getLocation(), diag::err_builtin_definition) << FD; 10205 FD->setInvalidDecl(); 10206 } 10207 } 10208 10209 // The return type of a function definition must be complete 10210 // (C99 6.9.1p3, C++ [dcl.fct]p6). 10211 QualType ResultType = FD->getReturnType(); 10212 if (!ResultType->isDependentType() && !ResultType->isVoidType() && 10213 !FD->isInvalidDecl() && 10214 RequireCompleteType(FD->getLocation(), ResultType, 10215 diag::err_func_def_incomplete_result)) 10216 FD->setInvalidDecl(); 10217 10218 // GNU warning -Wmissing-prototypes: 10219 // Warn if a global function is defined without a previous 10220 // prototype declaration. This warning is issued even if the 10221 // definition itself provides a prototype. The aim is to detect 10222 // global functions that fail to be declared in header files. 10223 const FunctionDecl *PossibleZeroParamPrototype = nullptr; 10224 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) { 10225 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD; 10226 10227 if (PossibleZeroParamPrototype) { 10228 // We found a declaration that is not a prototype, 10229 // but that could be a zero-parameter prototype 10230 if (TypeSourceInfo *TI = 10231 PossibleZeroParamPrototype->getTypeSourceInfo()) { 10232 TypeLoc TL = TI->getTypeLoc(); 10233 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>()) 10234 Diag(PossibleZeroParamPrototype->getLocation(), 10235 diag::note_declaration_not_a_prototype) 10236 << PossibleZeroParamPrototype 10237 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void"); 10238 } 10239 } 10240 } 10241 10242 if (FnBodyScope) 10243 PushDeclContext(FnBodyScope, FD); 10244 10245 // Check the validity of our function parameters 10246 CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(), 10247 /*CheckParameterNames=*/true); 10248 10249 // Introduce our parameters into the function scope 10250 for (auto Param : FD->params()) { 10251 Param->setOwningFunction(FD); 10252 10253 // If this has an identifier, add it to the scope stack. 10254 if (Param->getIdentifier() && FnBodyScope) { 10255 CheckShadow(FnBodyScope, Param); 10256 10257 PushOnScopeChains(Param, FnBodyScope); 10258 } 10259 } 10260 10261 // If we had any tags defined in the function prototype, 10262 // introduce them into the function scope. 10263 if (FnBodyScope) { 10264 for (ArrayRef<NamedDecl *>::iterator 10265 I = FD->getDeclsInPrototypeScope().begin(), 10266 E = FD->getDeclsInPrototypeScope().end(); 10267 I != E; ++I) { 10268 NamedDecl *D = *I; 10269 10270 // Some of these decls (like enums) may have been pinned to the translation unit 10271 // for lack of a real context earlier. If so, remove from the translation unit 10272 // and reattach to the current context. 10273 if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) { 10274 // Is the decl actually in the context? 10275 for (const auto *DI : Context.getTranslationUnitDecl()->decls()) { 10276 if (DI == D) { 10277 Context.getTranslationUnitDecl()->removeDecl(D); 10278 break; 10279 } 10280 } 10281 // Either way, reassign the lexical decl context to our FunctionDecl. 10282 D->setLexicalDeclContext(CurContext); 10283 } 10284 10285 // If the decl has a non-null name, make accessible in the current scope. 10286 if (!D->getName().empty()) 10287 PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false); 10288 10289 // Similarly, dive into enums and fish their constants out, making them 10290 // accessible in this scope. 10291 if (auto *ED = dyn_cast<EnumDecl>(D)) { 10292 for (auto *EI : ED->enumerators()) 10293 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false); 10294 } 10295 } 10296 } 10297 10298 // Ensure that the function's exception specification is instantiated. 10299 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>()) 10300 ResolveExceptionSpec(D->getLocation(), FPT); 10301 10302 // dllimport cannot be applied to non-inline function definitions. 10303 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() && 10304 !FD->isTemplateInstantiation()) { 10305 assert(!FD->hasAttr<DLLExportAttr>()); 10306 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition); 10307 FD->setInvalidDecl(); 10308 return D; 10309 } 10310 // We want to attach documentation to original Decl (which might be 10311 // a function template). 10312 ActOnDocumentableDecl(D); 10313 if (getCurLexicalContext()->isObjCContainer() && 10314 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 10315 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) 10316 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container); 10317 10318 return D; 10319 } 10320 10321 /// \brief Given the set of return statements within a function body, 10322 /// compute the variables that are subject to the named return value 10323 /// optimization. 10324 /// 10325 /// Each of the variables that is subject to the named return value 10326 /// optimization will be marked as NRVO variables in the AST, and any 10327 /// return statement that has a marked NRVO variable as its NRVO candidate can 10328 /// use the named return value optimization. 10329 /// 10330 /// This function applies a very simplistic algorithm for NRVO: if every return 10331 /// statement in the scope of a variable has the same NRVO candidate, that 10332 /// candidate is an NRVO variable. 10333 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) { 10334 ReturnStmt **Returns = Scope->Returns.data(); 10335 10336 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) { 10337 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) { 10338 if (!NRVOCandidate->isNRVOVariable()) 10339 Returns[I]->setNRVOCandidate(nullptr); 10340 } 10341 } 10342 } 10343 10344 bool Sema::canDelayFunctionBody(const Declarator &D) { 10345 // We can't delay parsing the body of a constexpr function template (yet). 10346 if (D.getDeclSpec().isConstexprSpecified()) 10347 return false; 10348 10349 // We can't delay parsing the body of a function template with a deduced 10350 // return type (yet). 10351 if (D.getDeclSpec().containsPlaceholderType()) { 10352 // If the placeholder introduces a non-deduced trailing return type, 10353 // we can still delay parsing it. 10354 if (D.getNumTypeObjects()) { 10355 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1); 10356 if (Outer.Kind == DeclaratorChunk::Function && 10357 Outer.Fun.hasTrailingReturnType()) { 10358 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType()); 10359 return Ty.isNull() || !Ty->isUndeducedType(); 10360 } 10361 } 10362 return false; 10363 } 10364 10365 return true; 10366 } 10367 10368 bool Sema::canSkipFunctionBody(Decl *D) { 10369 // We cannot skip the body of a function (or function template) which is 10370 // constexpr, since we may need to evaluate its body in order to parse the 10371 // rest of the file. 10372 // We cannot skip the body of a function with an undeduced return type, 10373 // because any callers of that function need to know the type. 10374 if (const FunctionDecl *FD = D->getAsFunction()) 10375 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType()) 10376 return false; 10377 return Consumer.shouldSkipFunctionBody(D); 10378 } 10379 10380 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) { 10381 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl)) 10382 FD->setHasSkippedBody(); 10383 else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl)) 10384 MD->setHasSkippedBody(); 10385 return ActOnFinishFunctionBody(Decl, nullptr); 10386 } 10387 10388 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) { 10389 return ActOnFinishFunctionBody(D, BodyArg, false); 10390 } 10391 10392 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body, 10393 bool IsInstantiation) { 10394 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr; 10395 10396 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy(); 10397 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr; 10398 10399 if (FD) { 10400 FD->setBody(Body); 10401 10402 if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body && 10403 !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) { 10404 // If the function has a deduced result type but contains no 'return' 10405 // statements, the result type as written must be exactly 'auto', and 10406 // the deduced result type is 'void'. 10407 if (!FD->getReturnType()->getAs<AutoType>()) { 10408 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto) 10409 << FD->getReturnType(); 10410 FD->setInvalidDecl(); 10411 } else { 10412 // Substitute 'void' for the 'auto' in the type. 10413 TypeLoc ResultType = FD->getTypeSourceInfo()->getTypeLoc(). 10414 IgnoreParens().castAs<FunctionProtoTypeLoc>().getReturnLoc(); 10415 Context.adjustDeducedFunctionResultType( 10416 FD, SubstAutoType(ResultType.getType(), Context.VoidTy)); 10417 } 10418 } 10419 10420 // The only way to be included in UndefinedButUsed is if there is an 10421 // ODR use before the definition. Avoid the expensive map lookup if this 10422 // is the first declaration. 10423 if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) { 10424 if (!FD->isExternallyVisible()) 10425 UndefinedButUsed.erase(FD); 10426 else if (FD->isInlined() && 10427 (LangOpts.CPlusPlus || !LangOpts.GNUInline) && 10428 (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>())) 10429 UndefinedButUsed.erase(FD); 10430 } 10431 10432 // If the function implicitly returns zero (like 'main') or is naked, 10433 // don't complain about missing return statements. 10434 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>()) 10435 WP.disableCheckFallThrough(); 10436 10437 // MSVC permits the use of pure specifier (=0) on function definition, 10438 // defined at class scope, warn about this non-standard construct. 10439 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl()) 10440 Diag(FD->getLocation(), diag::ext_pure_function_definition); 10441 10442 if (!FD->isInvalidDecl()) { 10443 // Don't diagnose unused parameters of defaulted or deleted functions. 10444 if (Body) 10445 DiagnoseUnusedParameters(FD->param_begin(), FD->param_end()); 10446 DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(), 10447 FD->getReturnType(), FD); 10448 10449 // If this is a constructor, we need a vtable. 10450 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD)) 10451 MarkVTableUsed(FD->getLocation(), Constructor->getParent()); 10452 10453 // Try to apply the named return value optimization. We have to check 10454 // if we can do this here because lambdas keep return statements around 10455 // to deduce an implicit return type. 10456 if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() && 10457 !FD->isDependentContext()) 10458 computeNRVO(Body, getCurFunction()); 10459 } 10460 10461 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && 10462 "Function parsing confused"); 10463 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) { 10464 assert(MD == getCurMethodDecl() && "Method parsing confused"); 10465 MD->setBody(Body); 10466 if (!MD->isInvalidDecl()) { 10467 DiagnoseUnusedParameters(MD->param_begin(), MD->param_end()); 10468 DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(), 10469 MD->getReturnType(), MD); 10470 10471 if (Body) 10472 computeNRVO(Body, getCurFunction()); 10473 } 10474 if (getCurFunction()->ObjCShouldCallSuper) { 10475 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call) 10476 << MD->getSelector().getAsString(); 10477 getCurFunction()->ObjCShouldCallSuper = false; 10478 } 10479 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) { 10480 const ObjCMethodDecl *InitMethod = nullptr; 10481 bool isDesignated = 10482 MD->isDesignatedInitializerForTheInterface(&InitMethod); 10483 assert(isDesignated && InitMethod); 10484 (void)isDesignated; 10485 10486 auto superIsNSObject = [&](const ObjCMethodDecl *MD) { 10487 auto IFace = MD->getClassInterface(); 10488 if (!IFace) 10489 return false; 10490 auto SuperD = IFace->getSuperClass(); 10491 if (!SuperD) 10492 return false; 10493 return SuperD->getIdentifier() == 10494 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 10495 }; 10496 // Don't issue this warning for unavailable inits or direct subclasses 10497 // of NSObject. 10498 if (!MD->isUnavailable() && !superIsNSObject(MD)) { 10499 Diag(MD->getLocation(), 10500 diag::warn_objc_designated_init_missing_super_call); 10501 Diag(InitMethod->getLocation(), 10502 diag::note_objc_designated_init_marked_here); 10503 } 10504 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; 10505 } 10506 if (getCurFunction()->ObjCWarnForNoInitDelegation) { 10507 // Don't issue this warning for unavaialable inits. 10508 if (!MD->isUnavailable()) 10509 Diag(MD->getLocation(), diag::warn_objc_secondary_init_missing_init_call); 10510 getCurFunction()->ObjCWarnForNoInitDelegation = false; 10511 } 10512 } else { 10513 return nullptr; 10514 } 10515 10516 assert(!getCurFunction()->ObjCShouldCallSuper && 10517 "This should only be set for ObjC methods, which should have been " 10518 "handled in the block above."); 10519 10520 // Verify and clean out per-function state. 10521 if (Body) { 10522 // C++ constructors that have function-try-blocks can't have return 10523 // statements in the handlers of that block. (C++ [except.handle]p14) 10524 // Verify this. 10525 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body)) 10526 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body)); 10527 10528 // Verify that gotos and switch cases don't jump into scopes illegally. 10529 if (getCurFunction()->NeedsScopeChecking() && 10530 !PP.isCodeCompletionEnabled()) 10531 DiagnoseInvalidJumps(Body); 10532 10533 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) { 10534 if (!Destructor->getParent()->isDependentType()) 10535 CheckDestructor(Destructor); 10536 10537 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(), 10538 Destructor->getParent()); 10539 } 10540 10541 // If any errors have occurred, clear out any temporaries that may have 10542 // been leftover. This ensures that these temporaries won't be picked up for 10543 // deletion in some later function. 10544 if (getDiagnostics().hasErrorOccurred() || 10545 getDiagnostics().getSuppressAllDiagnostics()) { 10546 DiscardCleanupsInEvaluationContext(); 10547 } 10548 if (!getDiagnostics().hasUncompilableErrorOccurred() && 10549 !isa<FunctionTemplateDecl>(dcl)) { 10550 // Since the body is valid, issue any analysis-based warnings that are 10551 // enabled. 10552 ActivePolicy = &WP; 10553 } 10554 10555 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() && 10556 (!CheckConstexprFunctionDecl(FD) || 10557 !CheckConstexprFunctionBody(FD, Body))) 10558 FD->setInvalidDecl(); 10559 10560 if (FD && FD->hasAttr<NakedAttr>()) { 10561 for (const Stmt *S : Body->children()) { 10562 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) { 10563 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function); 10564 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute); 10565 FD->setInvalidDecl(); 10566 break; 10567 } 10568 } 10569 } 10570 10571 assert(ExprCleanupObjects.empty() && "Leftover temporaries in function"); 10572 assert(!ExprNeedsCleanups && "Unaccounted cleanups in function"); 10573 assert(MaybeODRUseExprs.empty() && 10574 "Leftover expressions for odr-use checking"); 10575 } 10576 10577 if (!IsInstantiation) 10578 PopDeclContext(); 10579 10580 PopFunctionScopeInfo(ActivePolicy, dcl); 10581 // If any errors have occurred, clear out any temporaries that may have 10582 // been leftover. This ensures that these temporaries won't be picked up for 10583 // deletion in some later function. 10584 if (getDiagnostics().hasErrorOccurred()) { 10585 DiscardCleanupsInEvaluationContext(); 10586 } 10587 10588 return dcl; 10589 } 10590 10591 10592 /// When we finish delayed parsing of an attribute, we must attach it to the 10593 /// relevant Decl. 10594 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D, 10595 ParsedAttributes &Attrs) { 10596 // Always attach attributes to the underlying decl. 10597 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) 10598 D = TD->getTemplatedDecl(); 10599 ProcessDeclAttributeList(S, D, Attrs.getList()); 10600 10601 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D)) 10602 if (Method->isStatic()) 10603 checkThisInStaticMemberFunctionAttributes(Method); 10604 } 10605 10606 10607 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function 10608 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2). 10609 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc, 10610 IdentifierInfo &II, Scope *S) { 10611 // Before we produce a declaration for an implicitly defined 10612 // function, see whether there was a locally-scoped declaration of 10613 // this name as a function or variable. If so, use that 10614 // (non-visible) declaration, and complain about it. 10615 if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) { 10616 Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev; 10617 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration); 10618 return ExternCPrev; 10619 } 10620 10621 // Extension in C99. Legal in C90, but warn about it. 10622 unsigned diag_id; 10623 if (II.getName().startswith("__builtin_")) 10624 diag_id = diag::warn_builtin_unknown; 10625 else if (getLangOpts().C99) 10626 diag_id = diag::ext_implicit_function_decl; 10627 else 10628 diag_id = diag::warn_implicit_function_decl; 10629 Diag(Loc, diag_id) << &II; 10630 10631 // Because typo correction is expensive, only do it if the implicit 10632 // function declaration is going to be treated as an error. 10633 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) { 10634 TypoCorrection Corrected; 10635 DeclFilterCCC<FunctionDecl> Validator; 10636 if (S && (Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), 10637 LookupOrdinaryName, S, nullptr, Validator, 10638 CTK_NonError))) 10639 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion), 10640 /*ErrorRecovery*/false); 10641 } 10642 10643 // Set a Declarator for the implicit definition: int foo(); 10644 const char *Dummy; 10645 AttributeFactory attrFactory; 10646 DeclSpec DS(attrFactory); 10647 unsigned DiagID; 10648 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID, 10649 Context.getPrintingPolicy()); 10650 (void)Error; // Silence warning. 10651 assert(!Error && "Error setting up implicit decl!"); 10652 SourceLocation NoLoc; 10653 Declarator D(DS, Declarator::BlockContext); 10654 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false, 10655 /*IsAmbiguous=*/false, 10656 /*LParenLoc=*/NoLoc, 10657 /*Params=*/nullptr, 10658 /*NumParams=*/0, 10659 /*EllipsisLoc=*/NoLoc, 10660 /*RParenLoc=*/NoLoc, 10661 /*TypeQuals=*/0, 10662 /*RefQualifierIsLvalueRef=*/true, 10663 /*RefQualifierLoc=*/NoLoc, 10664 /*ConstQualifierLoc=*/NoLoc, 10665 /*VolatileQualifierLoc=*/NoLoc, 10666 /*MutableLoc=*/NoLoc, 10667 EST_None, 10668 /*ESpecLoc=*/NoLoc, 10669 /*Exceptions=*/nullptr, 10670 /*ExceptionRanges=*/nullptr, 10671 /*NumExceptions=*/0, 10672 /*NoexceptExpr=*/nullptr, 10673 Loc, Loc, D), 10674 DS.getAttributes(), 10675 SourceLocation()); 10676 D.SetIdentifier(&II, Loc); 10677 10678 // Insert this function into translation-unit scope. 10679 10680 DeclContext *PrevDC = CurContext; 10681 CurContext = Context.getTranslationUnitDecl(); 10682 10683 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D)); 10684 FD->setImplicit(); 10685 10686 CurContext = PrevDC; 10687 10688 AddKnownFunctionAttributes(FD); 10689 10690 return FD; 10691 } 10692 10693 /// \brief Adds any function attributes that we know a priori based on 10694 /// the declaration of this function. 10695 /// 10696 /// These attributes can apply both to implicitly-declared builtins 10697 /// (like __builtin___printf_chk) or to library-declared functions 10698 /// like NSLog or printf. 10699 /// 10700 /// We need to check for duplicate attributes both here and where user-written 10701 /// attributes are applied to declarations. 10702 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) { 10703 if (FD->isInvalidDecl()) 10704 return; 10705 10706 // If this is a built-in function, map its builtin attributes to 10707 // actual attributes. 10708 if (unsigned BuiltinID = FD->getBuiltinID()) { 10709 // Handle printf-formatting attributes. 10710 unsigned FormatIdx; 10711 bool HasVAListArg; 10712 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) { 10713 if (!FD->hasAttr<FormatAttr>()) { 10714 const char *fmt = "printf"; 10715 unsigned int NumParams = FD->getNumParams(); 10716 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf) 10717 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType()) 10718 fmt = "NSString"; 10719 FD->addAttr(FormatAttr::CreateImplicit(Context, 10720 &Context.Idents.get(fmt), 10721 FormatIdx+1, 10722 HasVAListArg ? 0 : FormatIdx+2, 10723 FD->getLocation())); 10724 } 10725 } 10726 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx, 10727 HasVAListArg)) { 10728 if (!FD->hasAttr<FormatAttr>()) 10729 FD->addAttr(FormatAttr::CreateImplicit(Context, 10730 &Context.Idents.get("scanf"), 10731 FormatIdx+1, 10732 HasVAListArg ? 0 : FormatIdx+2, 10733 FD->getLocation())); 10734 } 10735 10736 // Mark const if we don't care about errno and that is the only 10737 // thing preventing the function from being const. This allows 10738 // IRgen to use LLVM intrinsics for such functions. 10739 if (!getLangOpts().MathErrno && 10740 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) { 10741 if (!FD->hasAttr<ConstAttr>()) 10742 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10743 } 10744 10745 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) && 10746 !FD->hasAttr<ReturnsTwiceAttr>()) 10747 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context, 10748 FD->getLocation())); 10749 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>()) 10750 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation())); 10751 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>()) 10752 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation())); 10753 } 10754 10755 IdentifierInfo *Name = FD->getIdentifier(); 10756 if (!Name) 10757 return; 10758 if ((!getLangOpts().CPlusPlus && 10759 FD->getDeclContext()->isTranslationUnit()) || 10760 (isa<LinkageSpecDecl>(FD->getDeclContext()) && 10761 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() == 10762 LinkageSpecDecl::lang_c)) { 10763 // Okay: this could be a libc/libm/Objective-C function we know 10764 // about. 10765 } else 10766 return; 10767 10768 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) { 10769 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be 10770 // target-specific builtins, perhaps? 10771 if (!FD->hasAttr<FormatAttr>()) 10772 FD->addAttr(FormatAttr::CreateImplicit(Context, 10773 &Context.Idents.get("printf"), 2, 10774 Name->isStr("vasprintf") ? 0 : 3, 10775 FD->getLocation())); 10776 } 10777 10778 if (Name->isStr("__CFStringMakeConstantString")) { 10779 // We already have a __builtin___CFStringMakeConstantString, 10780 // but builds that use -fno-constant-cfstrings don't go through that. 10781 if (!FD->hasAttr<FormatArgAttr>()) 10782 FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1, 10783 FD->getLocation())); 10784 } 10785 } 10786 10787 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 10788 TypeSourceInfo *TInfo) { 10789 assert(D.getIdentifier() && "Wrong callback for declspec without declarator"); 10790 assert(!T.isNull() && "GetTypeForDeclarator() returned null type"); 10791 10792 if (!TInfo) { 10793 assert(D.isInvalidType() && "no declarator info for valid type"); 10794 TInfo = Context.getTrivialTypeSourceInfo(T); 10795 } 10796 10797 // Scope manipulation handled by caller. 10798 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext, 10799 D.getLocStart(), 10800 D.getIdentifierLoc(), 10801 D.getIdentifier(), 10802 TInfo); 10803 10804 // Bail out immediately if we have an invalid declaration. 10805 if (D.isInvalidType()) { 10806 NewTD->setInvalidDecl(); 10807 return NewTD; 10808 } 10809 10810 if (D.getDeclSpec().isModulePrivateSpecified()) { 10811 if (CurContext->isFunctionOrMethod()) 10812 Diag(NewTD->getLocation(), diag::err_module_private_local) 10813 << 2 << NewTD->getDeclName() 10814 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc()) 10815 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc()); 10816 else 10817 NewTD->setModulePrivate(); 10818 } 10819 10820 // C++ [dcl.typedef]p8: 10821 // If the typedef declaration defines an unnamed class (or 10822 // enum), the first typedef-name declared by the declaration 10823 // to be that class type (or enum type) is used to denote the 10824 // class type (or enum type) for linkage purposes only. 10825 // We need to check whether the type was declared in the declaration. 10826 switch (D.getDeclSpec().getTypeSpecType()) { 10827 case TST_enum: 10828 case TST_struct: 10829 case TST_interface: 10830 case TST_union: 10831 case TST_class: { 10832 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl()); 10833 10834 // Do nothing if the tag is not anonymous or already has an 10835 // associated typedef (from an earlier typedef in this decl group). 10836 if (tagFromDeclSpec->getIdentifier()) break; 10837 if (tagFromDeclSpec->getTypedefNameForAnonDecl()) break; 10838 10839 // A well-formed anonymous tag must always be a TUK_Definition. 10840 assert(tagFromDeclSpec->isThisDeclarationADefinition()); 10841 10842 // The type must match the tag exactly; no qualifiers allowed. 10843 if (!Context.hasSameType(T, Context.getTagDeclType(tagFromDeclSpec))) 10844 break; 10845 10846 // If we've already computed linkage for the anonymous tag, then 10847 // adding a typedef name for the anonymous decl can change that 10848 // linkage, which might be a serious problem. Diagnose this as 10849 // unsupported and ignore the typedef name. TODO: we should 10850 // pursue this as a language defect and establish a formal rule 10851 // for how to handle it. 10852 if (tagFromDeclSpec->hasLinkageBeenComputed()) { 10853 Diag(D.getIdentifierLoc(), diag::err_typedef_changes_linkage); 10854 10855 SourceLocation tagLoc = D.getDeclSpec().getTypeSpecTypeLoc(); 10856 tagLoc = getLocForEndOfToken(tagLoc); 10857 10858 llvm::SmallString<40> textToInsert; 10859 textToInsert += ' '; 10860 textToInsert += D.getIdentifier()->getName(); 10861 Diag(tagLoc, diag::note_typedef_changes_linkage) 10862 << FixItHint::CreateInsertion(tagLoc, textToInsert); 10863 break; 10864 } 10865 10866 // Otherwise, set this is the anon-decl typedef for the tag. 10867 tagFromDeclSpec->setTypedefNameForAnonDecl(NewTD); 10868 break; 10869 } 10870 10871 default: 10872 break; 10873 } 10874 10875 return NewTD; 10876 } 10877 10878 10879 /// \brief Check that this is a valid underlying type for an enum declaration. 10880 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) { 10881 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); 10882 QualType T = TI->getType(); 10883 10884 if (T->isDependentType()) 10885 return false; 10886 10887 if (const BuiltinType *BT = T->getAs<BuiltinType>()) 10888 if (BT->isInteger()) 10889 return false; 10890 10891 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T; 10892 return true; 10893 } 10894 10895 /// Check whether this is a valid redeclaration of a previous enumeration. 10896 /// \return true if the redeclaration was invalid. 10897 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 10898 QualType EnumUnderlyingTy, 10899 const EnumDecl *Prev) { 10900 bool IsFixed = !EnumUnderlyingTy.isNull(); 10901 10902 if (IsScoped != Prev->isScoped()) { 10903 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch) 10904 << Prev->isScoped(); 10905 Diag(Prev->getLocation(), diag::note_previous_declaration); 10906 return true; 10907 } 10908 10909 if (IsFixed && Prev->isFixed()) { 10910 if (!EnumUnderlyingTy->isDependentType() && 10911 !Prev->getIntegerType()->isDependentType() && 10912 !Context.hasSameUnqualifiedType(EnumUnderlyingTy, 10913 Prev->getIntegerType())) { 10914 // TODO: Highlight the underlying type of the redeclaration. 10915 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch) 10916 << EnumUnderlyingTy << Prev->getIntegerType(); 10917 Diag(Prev->getLocation(), diag::note_previous_declaration) 10918 << Prev->getIntegerTypeRange(); 10919 return true; 10920 } 10921 } else if (IsFixed != Prev->isFixed()) { 10922 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch) 10923 << Prev->isFixed(); 10924 Diag(Prev->getLocation(), diag::note_previous_declaration); 10925 return true; 10926 } 10927 10928 return false; 10929 } 10930 10931 /// \brief Get diagnostic %select index for tag kind for 10932 /// redeclaration diagnostic message. 10933 /// WARNING: Indexes apply to particular diagnostics only! 10934 /// 10935 /// \returns diagnostic %select index. 10936 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) { 10937 switch (Tag) { 10938 case TTK_Struct: return 0; 10939 case TTK_Interface: return 1; 10940 case TTK_Class: return 2; 10941 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!"); 10942 } 10943 } 10944 10945 /// \brief Determine if tag kind is a class-key compatible with 10946 /// class for redeclaration (class, struct, or __interface). 10947 /// 10948 /// \returns true iff the tag kind is compatible. 10949 static bool isClassCompatTagKind(TagTypeKind Tag) 10950 { 10951 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface; 10952 } 10953 10954 /// \brief Determine whether a tag with a given kind is acceptable 10955 /// as a redeclaration of the given tag declaration. 10956 /// 10957 /// \returns true if the new tag kind is acceptable, false otherwise. 10958 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous, 10959 TagTypeKind NewTag, bool isDefinition, 10960 SourceLocation NewTagLoc, 10961 const IdentifierInfo &Name) { 10962 // C++ [dcl.type.elab]p3: 10963 // The class-key or enum keyword present in the 10964 // elaborated-type-specifier shall agree in kind with the 10965 // declaration to which the name in the elaborated-type-specifier 10966 // refers. This rule also applies to the form of 10967 // elaborated-type-specifier that declares a class-name or 10968 // friend class since it can be construed as referring to the 10969 // definition of the class. Thus, in any 10970 // elaborated-type-specifier, the enum keyword shall be used to 10971 // refer to an enumeration (7.2), the union class-key shall be 10972 // used to refer to a union (clause 9), and either the class or 10973 // struct class-key shall be used to refer to a class (clause 9) 10974 // declared using the class or struct class-key. 10975 TagTypeKind OldTag = Previous->getTagKind(); 10976 if (!isDefinition || !isClassCompatTagKind(NewTag)) 10977 if (OldTag == NewTag) 10978 return true; 10979 10980 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) { 10981 // Warn about the struct/class tag mismatch. 10982 bool isTemplate = false; 10983 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous)) 10984 isTemplate = Record->getDescribedClassTemplate(); 10985 10986 if (!ActiveTemplateInstantiations.empty()) { 10987 // In a template instantiation, do not offer fix-its for tag mismatches 10988 // since they usually mess up the template instead of fixing the problem. 10989 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 10990 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 10991 << getRedeclDiagFromTagKind(OldTag); 10992 return true; 10993 } 10994 10995 if (isDefinition) { 10996 // On definitions, check previous tags and issue a fix-it for each 10997 // one that doesn't match the current tag. 10998 if (Previous->getDefinition()) { 10999 // Don't suggest fix-its for redefinitions. 11000 return true; 11001 } 11002 11003 bool previousMismatch = false; 11004 for (auto I : Previous->redecls()) { 11005 if (I->getTagKind() != NewTag) { 11006 if (!previousMismatch) { 11007 previousMismatch = true; 11008 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch) 11009 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11010 << getRedeclDiagFromTagKind(I->getTagKind()); 11011 } 11012 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion) 11013 << getRedeclDiagFromTagKind(NewTag) 11014 << FixItHint::CreateReplacement(I->getInnerLocStart(), 11015 TypeWithKeyword::getTagTypeKindName(NewTag)); 11016 } 11017 } 11018 return true; 11019 } 11020 11021 // Check for a previous definition. If current tag and definition 11022 // are same type, do nothing. If no definition, but disagree with 11023 // with previous tag type, give a warning, but no fix-it. 11024 const TagDecl *Redecl = Previous->getDefinition() ? 11025 Previous->getDefinition() : Previous; 11026 if (Redecl->getTagKind() == NewTag) { 11027 return true; 11028 } 11029 11030 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch) 11031 << getRedeclDiagFromTagKind(NewTag) << isTemplate << &Name 11032 << getRedeclDiagFromTagKind(OldTag); 11033 Diag(Redecl->getLocation(), diag::note_previous_use); 11034 11035 // If there is a previous definition, suggest a fix-it. 11036 if (Previous->getDefinition()) { 11037 Diag(NewTagLoc, diag::note_struct_class_suggestion) 11038 << getRedeclDiagFromTagKind(Redecl->getTagKind()) 11039 << FixItHint::CreateReplacement(SourceRange(NewTagLoc), 11040 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind())); 11041 } 11042 11043 return true; 11044 } 11045 return false; 11046 } 11047 11048 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name 11049 /// from an outer enclosing namespace or file scope inside a friend declaration. 11050 /// This should provide the commented out code in the following snippet: 11051 /// namespace N { 11052 /// struct X; 11053 /// namespace M { 11054 /// struct Y { friend struct /*N::*/ X; }; 11055 /// } 11056 /// } 11057 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, 11058 SourceLocation NameLoc) { 11059 // While the decl is in a namespace, do repeated lookup of that name and see 11060 // if we get the same namespace back. If we do not, continue until 11061 // translation unit scope, at which point we have a fully qualified NNS. 11062 SmallVector<IdentifierInfo *, 4> Namespaces; 11063 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11064 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 11065 // This tag should be declared in a namespace, which can only be enclosed by 11066 // other namespaces. Bail if there's an anonymous namespace in the chain. 11067 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC); 11068 if (!Namespace || Namespace->isAnonymousNamespace()) 11069 return FixItHint(); 11070 IdentifierInfo *II = Namespace->getIdentifier(); 11071 Namespaces.push_back(II); 11072 NamedDecl *Lookup = SemaRef.LookupSingleName( 11073 S, II, NameLoc, Sema::LookupNestedNameSpecifierName); 11074 if (Lookup == Namespace) 11075 break; 11076 } 11077 11078 // Once we have all the namespaces, reverse them to go outermost first, and 11079 // build an NNS. 11080 SmallString<64> Insertion; 11081 llvm::raw_svector_ostream OS(Insertion); 11082 if (DC->isTranslationUnit()) 11083 OS << "::"; 11084 std::reverse(Namespaces.begin(), Namespaces.end()); 11085 for (auto *II : Namespaces) 11086 OS << II->getName() << "::"; 11087 OS.flush(); 11088 return FixItHint::CreateInsertion(NameLoc, Insertion); 11089 } 11090 11091 /// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the 11092 /// former case, Name will be non-null. In the later case, Name will be null. 11093 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a 11094 /// reference/declaration/definition of a tag. 11095 /// 11096 /// IsTypeSpecifier is true if this is a type-specifier (or 11097 /// trailing-type-specifier) other than one in an alias-declaration. 11098 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 11099 SourceLocation KWLoc, CXXScopeSpec &SS, 11100 IdentifierInfo *Name, SourceLocation NameLoc, 11101 AttributeList *Attr, AccessSpecifier AS, 11102 SourceLocation ModulePrivateLoc, 11103 MultiTemplateParamsArg TemplateParameterLists, 11104 bool &OwnedDecl, bool &IsDependent, 11105 SourceLocation ScopedEnumKWLoc, 11106 bool ScopedEnumUsesClassTag, 11107 TypeResult UnderlyingType, 11108 bool IsTypeSpecifier) { 11109 // If this is not a definition, it must have a name. 11110 IdentifierInfo *OrigName = Name; 11111 assert((Name != nullptr || TUK == TUK_Definition) && 11112 "Nameless record must be a definition!"); 11113 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference); 11114 11115 OwnedDecl = false; 11116 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec); 11117 bool ScopedEnum = ScopedEnumKWLoc.isValid(); 11118 11119 // FIXME: Check explicit specializations more carefully. 11120 bool isExplicitSpecialization = false; 11121 bool Invalid = false; 11122 11123 // We only need to do this matching if we have template parameters 11124 // or a scope specifier, which also conveniently avoids this work 11125 // for non-C++ cases. 11126 if (TemplateParameterLists.size() > 0 || 11127 (SS.isNotEmpty() && TUK != TUK_Reference)) { 11128 if (TemplateParameterList *TemplateParams = 11129 MatchTemplateParametersToScopeSpecifier( 11130 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists, 11131 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) { 11132 if (Kind == TTK_Enum) { 11133 Diag(KWLoc, diag::err_enum_template); 11134 return nullptr; 11135 } 11136 11137 if (TemplateParams->size() > 0) { 11138 // This is a declaration or definition of a class template (which may 11139 // be a member of another template). 11140 11141 if (Invalid) 11142 return nullptr; 11143 11144 OwnedDecl = false; 11145 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc, 11146 SS, Name, NameLoc, Attr, 11147 TemplateParams, AS, 11148 ModulePrivateLoc, 11149 /*FriendLoc*/SourceLocation(), 11150 TemplateParameterLists.size()-1, 11151 TemplateParameterLists.data()); 11152 return Result.get(); 11153 } else { 11154 // The "template<>" header is extraneous. 11155 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams) 11156 << TypeWithKeyword::getTagTypeKindName(Kind) << Name; 11157 isExplicitSpecialization = true; 11158 } 11159 } 11160 } 11161 11162 // Figure out the underlying type if this a enum declaration. We need to do 11163 // this early, because it's needed to detect if this is an incompatible 11164 // redeclaration. 11165 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying; 11166 11167 if (Kind == TTK_Enum) { 11168 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) 11169 // No underlying type explicitly specified, or we failed to parse the 11170 // type, default to int. 11171 EnumUnderlying = Context.IntTy.getTypePtr(); 11172 else if (UnderlyingType.get()) { 11173 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an 11174 // integral type; any cv-qualification is ignored. 11175 TypeSourceInfo *TI = nullptr; 11176 GetTypeFromParser(UnderlyingType.get(), &TI); 11177 EnumUnderlying = TI; 11178 11179 if (CheckEnumUnderlyingType(TI)) 11180 // Recover by falling back to int. 11181 EnumUnderlying = Context.IntTy.getTypePtr(); 11182 11183 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI, 11184 UPPC_FixedUnderlyingType)) 11185 EnumUnderlying = Context.IntTy.getTypePtr(); 11186 11187 } else if (getLangOpts().MSVCCompat) 11188 // Microsoft enums are always of int type. 11189 EnumUnderlying = Context.IntTy.getTypePtr(); 11190 } 11191 11192 DeclContext *SearchDC = CurContext; 11193 DeclContext *DC = CurContext; 11194 bool isStdBadAlloc = false; 11195 11196 RedeclarationKind Redecl = ForRedeclaration; 11197 if (TUK == TUK_Friend || TUK == TUK_Reference) 11198 Redecl = NotForRedeclaration; 11199 11200 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl); 11201 if (Name && SS.isNotEmpty()) { 11202 // We have a nested-name tag ('struct foo::bar'). 11203 11204 // Check for invalid 'foo::'. 11205 if (SS.isInvalid()) { 11206 Name = nullptr; 11207 goto CreateNewDecl; 11208 } 11209 11210 // If this is a friend or a reference to a class in a dependent 11211 // context, don't try to make a decl for it. 11212 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11213 DC = computeDeclContext(SS, false); 11214 if (!DC) { 11215 IsDependent = true; 11216 return nullptr; 11217 } 11218 } else { 11219 DC = computeDeclContext(SS, true); 11220 if (!DC) { 11221 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec) 11222 << SS.getRange(); 11223 return nullptr; 11224 } 11225 } 11226 11227 if (RequireCompleteDeclContext(SS, DC)) 11228 return nullptr; 11229 11230 SearchDC = DC; 11231 // Look-up name inside 'foo::'. 11232 LookupQualifiedName(Previous, DC); 11233 11234 if (Previous.isAmbiguous()) 11235 return nullptr; 11236 11237 if (Previous.empty()) { 11238 // Name lookup did not find anything. However, if the 11239 // nested-name-specifier refers to the current instantiation, 11240 // and that current instantiation has any dependent base 11241 // classes, we might find something at instantiation time: treat 11242 // this as a dependent elaborated-type-specifier. 11243 // But this only makes any sense for reference-like lookups. 11244 if (Previous.wasNotFoundInCurrentInstantiation() && 11245 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11246 IsDependent = true; 11247 return nullptr; 11248 } 11249 11250 // A tag 'foo::bar' must already exist. 11251 Diag(NameLoc, diag::err_not_tag_in_scope) 11252 << Kind << Name << DC << SS.getRange(); 11253 Name = nullptr; 11254 Invalid = true; 11255 goto CreateNewDecl; 11256 } 11257 } else if (Name) { 11258 // If this is a named struct, check to see if there was a previous forward 11259 // declaration or definition. 11260 // FIXME: We're looking into outer scopes here, even when we 11261 // shouldn't be. Doing so can result in ambiguities that we 11262 // shouldn't be diagnosing. 11263 LookupName(Previous, S); 11264 11265 // When declaring or defining a tag, ignore ambiguities introduced 11266 // by types using'ed into this scope. 11267 if (Previous.isAmbiguous() && 11268 (TUK == TUK_Definition || TUK == TUK_Declaration)) { 11269 LookupResult::Filter F = Previous.makeFilter(); 11270 while (F.hasNext()) { 11271 NamedDecl *ND = F.next(); 11272 if (ND->getDeclContext()->getRedeclContext() != SearchDC) 11273 F.erase(); 11274 } 11275 F.done(); 11276 } 11277 11278 // C++11 [namespace.memdef]p3: 11279 // If the name in a friend declaration is neither qualified nor 11280 // a template-id and the declaration is a function or an 11281 // elaborated-type-specifier, the lookup to determine whether 11282 // the entity has been previously declared shall not consider 11283 // any scopes outside the innermost enclosing namespace. 11284 // 11285 // MSVC doesn't implement the above rule for types, so a friend tag 11286 // declaration may be a redeclaration of a type declared in an enclosing 11287 // scope. They do implement this rule for friend functions. 11288 // 11289 // Does it matter that this should be by scope instead of by 11290 // semantic context? 11291 if (!Previous.empty() && TUK == TUK_Friend) { 11292 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext(); 11293 LookupResult::Filter F = Previous.makeFilter(); 11294 bool FriendSawTagOutsideEnclosingNamespace = false; 11295 while (F.hasNext()) { 11296 NamedDecl *ND = F.next(); 11297 DeclContext *DC = ND->getDeclContext()->getRedeclContext(); 11298 if (DC->isFileContext() && 11299 !EnclosingNS->Encloses(ND->getDeclContext())) { 11300 if (getLangOpts().MSVCCompat) 11301 FriendSawTagOutsideEnclosingNamespace = true; 11302 else 11303 F.erase(); 11304 } 11305 } 11306 F.done(); 11307 11308 // Diagnose this MSVC extension in the easy case where lookup would have 11309 // unambiguously found something outside the enclosing namespace. 11310 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) { 11311 NamedDecl *ND = Previous.getFoundDecl(); 11312 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace) 11313 << createFriendTagNNSFixIt(*this, ND, S, NameLoc); 11314 } 11315 } 11316 11317 // Note: there used to be some attempt at recovery here. 11318 if (Previous.isAmbiguous()) 11319 return nullptr; 11320 11321 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) { 11322 // FIXME: This makes sure that we ignore the contexts associated 11323 // with C structs, unions, and enums when looking for a matching 11324 // tag declaration or definition. See the similar lookup tweak 11325 // in Sema::LookupName; is there a better way to deal with this? 11326 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC)) 11327 SearchDC = SearchDC->getParent(); 11328 } 11329 } 11330 11331 if (Previous.isSingleResult() && 11332 Previous.getFoundDecl()->isTemplateParameter()) { 11333 // Maybe we will complain about the shadowed template parameter. 11334 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl()); 11335 // Just pretend that we didn't see the previous declaration. 11336 Previous.clear(); 11337 } 11338 11339 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace && 11340 DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) { 11341 // This is a declaration of or a reference to "std::bad_alloc". 11342 isStdBadAlloc = true; 11343 11344 if (Previous.empty() && StdBadAlloc) { 11345 // std::bad_alloc has been implicitly declared (but made invisible to 11346 // name lookup). Fill in this implicit declaration as the previous 11347 // declaration, so that the declarations get chained appropriately. 11348 Previous.addDecl(getStdBadAlloc()); 11349 } 11350 } 11351 11352 // If we didn't find a previous declaration, and this is a reference 11353 // (or friend reference), move to the correct scope. In C++, we 11354 // also need to do a redeclaration lookup there, just in case 11355 // there's a shadow friend decl. 11356 if (Name && Previous.empty() && 11357 (TUK == TUK_Reference || TUK == TUK_Friend)) { 11358 if (Invalid) goto CreateNewDecl; 11359 assert(SS.isEmpty()); 11360 11361 if (TUK == TUK_Reference) { 11362 // C++ [basic.scope.pdecl]p5: 11363 // -- for an elaborated-type-specifier of the form 11364 // 11365 // class-key identifier 11366 // 11367 // if the elaborated-type-specifier is used in the 11368 // decl-specifier-seq or parameter-declaration-clause of a 11369 // function defined in namespace scope, the identifier is 11370 // declared as a class-name in the namespace that contains 11371 // the declaration; otherwise, except as a friend 11372 // declaration, the identifier is declared in the smallest 11373 // non-class, non-function-prototype scope that contains the 11374 // declaration. 11375 // 11376 // C99 6.7.2.3p8 has a similar (but not identical!) provision for 11377 // C structs and unions. 11378 // 11379 // It is an error in C++ to declare (rather than define) an enum 11380 // type, including via an elaborated type specifier. We'll 11381 // diagnose that later; for now, declare the enum in the same 11382 // scope as we would have picked for any other tag type. 11383 // 11384 // GNU C also supports this behavior as part of its incomplete 11385 // enum types extension, while GNU C++ does not. 11386 // 11387 // Find the context where we'll be declaring the tag. 11388 // FIXME: We would like to maintain the current DeclContext as the 11389 // lexical context, 11390 while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod()) 11391 SearchDC = SearchDC->getParent(); 11392 11393 // Find the scope where we'll be declaring the tag. 11394 while (S->isClassScope() || 11395 (getLangOpts().CPlusPlus && 11396 S->isFunctionPrototypeScope()) || 11397 ((S->getFlags() & Scope::DeclScope) == 0) || 11398 (S->getEntity() && S->getEntity()->isTransparentContext())) 11399 S = S->getParent(); 11400 } else { 11401 assert(TUK == TUK_Friend); 11402 // C++ [namespace.memdef]p3: 11403 // If a friend declaration in a non-local class first declares a 11404 // class or function, the friend class or function is a member of 11405 // the innermost enclosing namespace. 11406 SearchDC = SearchDC->getEnclosingNamespaceContext(); 11407 } 11408 11409 // In C++, we need to do a redeclaration lookup to properly 11410 // diagnose some problems. 11411 if (getLangOpts().CPlusPlus) { 11412 Previous.setRedeclarationKind(ForRedeclaration); 11413 LookupQualifiedName(Previous, SearchDC); 11414 } 11415 } 11416 11417 if (!Previous.empty()) { 11418 NamedDecl *PrevDecl = Previous.getFoundDecl(); 11419 NamedDecl *DirectPrevDecl = 11420 getLangOpts().MSVCCompat ? *Previous.begin() : PrevDecl; 11421 11422 // It's okay to have a tag decl in the same scope as a typedef 11423 // which hides a tag decl in the same scope. Finding this 11424 // insanity with a redeclaration lookup can only actually happen 11425 // in C++. 11426 // 11427 // This is also okay for elaborated-type-specifiers, which is 11428 // technically forbidden by the current standard but which is 11429 // okay according to the likely resolution of an open issue; 11430 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407 11431 if (getLangOpts().CPlusPlus) { 11432 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11433 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) { 11434 TagDecl *Tag = TT->getDecl(); 11435 if (Tag->getDeclName() == Name && 11436 Tag->getDeclContext()->getRedeclContext() 11437 ->Equals(TD->getDeclContext()->getRedeclContext())) { 11438 PrevDecl = Tag; 11439 Previous.clear(); 11440 Previous.addDecl(Tag); 11441 Previous.resolveKind(); 11442 } 11443 } 11444 } 11445 } 11446 11447 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) { 11448 // If this is a use of a previous tag, or if the tag is already declared 11449 // in the same scope (so that the definition/declaration completes or 11450 // rementions the tag), reuse the decl. 11451 if (TUK == TUK_Reference || TUK == TUK_Friend || 11452 isDeclInScope(DirectPrevDecl, SearchDC, S, 11453 SS.isNotEmpty() || isExplicitSpecialization)) { 11454 // Make sure that this wasn't declared as an enum and now used as a 11455 // struct or something similar. 11456 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind, 11457 TUK == TUK_Definition, KWLoc, 11458 *Name)) { 11459 bool SafeToContinue 11460 = (PrevTagDecl->getTagKind() != TTK_Enum && 11461 Kind != TTK_Enum); 11462 if (SafeToContinue) 11463 Diag(KWLoc, diag::err_use_with_wrong_tag) 11464 << Name 11465 << FixItHint::CreateReplacement(SourceRange(KWLoc), 11466 PrevTagDecl->getKindName()); 11467 else 11468 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name; 11469 Diag(PrevTagDecl->getLocation(), diag::note_previous_use); 11470 11471 if (SafeToContinue) 11472 Kind = PrevTagDecl->getTagKind(); 11473 else { 11474 // Recover by making this an anonymous redefinition. 11475 Name = nullptr; 11476 Previous.clear(); 11477 Invalid = true; 11478 } 11479 } 11480 11481 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) { 11482 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl); 11483 11484 // If this is an elaborated-type-specifier for a scoped enumeration, 11485 // the 'class' keyword is not necessary and not permitted. 11486 if (TUK == TUK_Reference || TUK == TUK_Friend) { 11487 if (ScopedEnum) 11488 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference) 11489 << PrevEnum->isScoped() 11490 << FixItHint::CreateRemoval(ScopedEnumKWLoc); 11491 return PrevTagDecl; 11492 } 11493 11494 QualType EnumUnderlyingTy; 11495 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11496 EnumUnderlyingTy = TI->getType().getUnqualifiedType(); 11497 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>()) 11498 EnumUnderlyingTy = QualType(T, 0); 11499 11500 // All conflicts with previous declarations are recovered by 11501 // returning the previous declaration, unless this is a definition, 11502 // in which case we want the caller to bail out. 11503 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc, 11504 ScopedEnum, EnumUnderlyingTy, PrevEnum)) 11505 return TUK == TUK_Declaration ? PrevTagDecl : nullptr; 11506 } 11507 11508 // C++11 [class.mem]p1: 11509 // A member shall not be declared twice in the member-specification, 11510 // except that a nested class or member class template can be declared 11511 // and then later defined. 11512 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() && 11513 S->isDeclScope(PrevDecl)) { 11514 Diag(NameLoc, diag::ext_member_redeclared); 11515 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration); 11516 } 11517 11518 if (!Invalid) { 11519 // If this is a use, just return the declaration we found, unless 11520 // we have attributes. 11521 11522 // FIXME: In the future, return a variant or some other clue 11523 // for the consumer of this Decl to know it doesn't own it. 11524 // For our current ASTs this shouldn't be a problem, but will 11525 // need to be changed with DeclGroups. 11526 if (!Attr && 11527 ((TUK == TUK_Reference && 11528 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt)) 11529 || TUK == TUK_Friend)) 11530 return PrevTagDecl; 11531 11532 // Diagnose attempts to redefine a tag. 11533 if (TUK == TUK_Definition) { 11534 if (TagDecl *Def = PrevTagDecl->getDefinition()) { 11535 // If we're defining a specialization and the previous definition 11536 // is from an implicit instantiation, don't emit an error 11537 // here; we'll catch this in the general case below. 11538 bool IsExplicitSpecializationAfterInstantiation = false; 11539 if (isExplicitSpecialization) { 11540 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def)) 11541 IsExplicitSpecializationAfterInstantiation = 11542 RD->getTemplateSpecializationKind() != 11543 TSK_ExplicitSpecialization; 11544 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def)) 11545 IsExplicitSpecializationAfterInstantiation = 11546 ED->getTemplateSpecializationKind() != 11547 TSK_ExplicitSpecialization; 11548 } 11549 11550 if (!IsExplicitSpecializationAfterInstantiation) { 11551 // A redeclaration in function prototype scope in C isn't 11552 // visible elsewhere, so merely issue a warning. 11553 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope()) 11554 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name; 11555 else 11556 Diag(NameLoc, diag::err_redefinition) << Name; 11557 Diag(Def->getLocation(), diag::note_previous_definition); 11558 // If this is a redefinition, recover by making this 11559 // struct be anonymous, which will make any later 11560 // references get the previous definition. 11561 Name = nullptr; 11562 Previous.clear(); 11563 Invalid = true; 11564 } 11565 } else { 11566 // If the type is currently being defined, complain 11567 // about a nested redefinition. 11568 const TagType *Tag 11569 = cast<TagType>(Context.getTagDeclType(PrevTagDecl)); 11570 if (Tag->isBeingDefined()) { 11571 Diag(NameLoc, diag::err_nested_redefinition) << Name; 11572 Diag(PrevTagDecl->getLocation(), 11573 diag::note_previous_definition); 11574 Name = nullptr; 11575 Previous.clear(); 11576 Invalid = true; 11577 } 11578 } 11579 11580 // Okay, this is definition of a previously declared or referenced 11581 // tag. We're going to create a new Decl for it. 11582 } 11583 11584 // Okay, we're going to make a redeclaration. If this is some kind 11585 // of reference, make sure we build the redeclaration in the same DC 11586 // as the original, and ignore the current access specifier. 11587 if (TUK == TUK_Friend || TUK == TUK_Reference) { 11588 SearchDC = PrevTagDecl->getDeclContext(); 11589 AS = AS_none; 11590 } 11591 } 11592 // If we get here we have (another) forward declaration or we 11593 // have a definition. Just create a new decl. 11594 11595 } else { 11596 // If we get here, this is a definition of a new tag type in a nested 11597 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a 11598 // new decl/type. We set PrevDecl to NULL so that the entities 11599 // have distinct types. 11600 Previous.clear(); 11601 } 11602 // If we get here, we're going to create a new Decl. If PrevDecl 11603 // is non-NULL, it's a definition of the tag declared by 11604 // PrevDecl. If it's NULL, we have a new definition. 11605 11606 11607 // Otherwise, PrevDecl is not a tag, but was found with tag 11608 // lookup. This is only actually possible in C++, where a few 11609 // things like templates still live in the tag namespace. 11610 } else { 11611 // Use a better diagnostic if an elaborated-type-specifier 11612 // found the wrong kind of type on the first 11613 // (non-redeclaration) lookup. 11614 if ((TUK == TUK_Reference || TUK == TUK_Friend) && 11615 !Previous.isForRedeclaration()) { 11616 unsigned Kind = 0; 11617 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11618 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11619 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11620 Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind; 11621 Diag(PrevDecl->getLocation(), diag::note_declared_at); 11622 Invalid = true; 11623 11624 // Otherwise, only diagnose if the declaration is in scope. 11625 } else if (!isDeclInScope(PrevDecl, SearchDC, S, 11626 SS.isNotEmpty() || isExplicitSpecialization)) { 11627 // do nothing 11628 11629 // Diagnose implicit declarations introduced by elaborated types. 11630 } else if (TUK == TUK_Reference || TUK == TUK_Friend) { 11631 unsigned Kind = 0; 11632 if (isa<TypedefDecl>(PrevDecl)) Kind = 1; 11633 else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2; 11634 else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3; 11635 Diag(NameLoc, diag::err_tag_reference_conflict) << Kind; 11636 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11637 Invalid = true; 11638 11639 // Otherwise it's a declaration. Call out a particularly common 11640 // case here. 11641 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) { 11642 unsigned Kind = 0; 11643 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1; 11644 Diag(NameLoc, diag::err_tag_definition_of_typedef) 11645 << Name << Kind << TND->getUnderlyingType(); 11646 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl; 11647 Invalid = true; 11648 11649 // Otherwise, diagnose. 11650 } else { 11651 // The tag name clashes with something else in the target scope, 11652 // issue an error and recover by making this tag be anonymous. 11653 Diag(NameLoc, diag::err_redefinition_different_kind) << Name; 11654 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 11655 Name = nullptr; 11656 Invalid = true; 11657 } 11658 11659 // The existing declaration isn't relevant to us; we're in a 11660 // new scope, so clear out the previous declaration. 11661 Previous.clear(); 11662 } 11663 } 11664 11665 CreateNewDecl: 11666 11667 TagDecl *PrevDecl = nullptr; 11668 if (Previous.isSingleResult()) 11669 PrevDecl = cast<TagDecl>(Previous.getFoundDecl()); 11670 11671 // If there is an identifier, use the location of the identifier as the 11672 // location of the decl, otherwise use the location of the struct/union 11673 // keyword. 11674 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc; 11675 11676 // Otherwise, create a new declaration. If there is a previous 11677 // declaration of the same entity, the two will be linked via 11678 // PrevDecl. 11679 TagDecl *New; 11680 11681 bool IsForwardReference = false; 11682 if (Kind == TTK_Enum) { 11683 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11684 // enum X { A, B, C } D; D should chain to X. 11685 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, 11686 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum, 11687 ScopedEnumUsesClassTag, !EnumUnderlying.isNull()); 11688 // If this is an undefined enum, warn. 11689 if (TUK != TUK_Definition && !Invalid) { 11690 TagDecl *Def; 11691 if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) && 11692 cast<EnumDecl>(New)->isFixed()) { 11693 // C++0x: 7.2p2: opaque-enum-declaration. 11694 // Conflicts are diagnosed above. Do nothing. 11695 } 11696 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) { 11697 Diag(Loc, diag::ext_forward_ref_enum_def) 11698 << New; 11699 Diag(Def->getLocation(), diag::note_previous_definition); 11700 } else { 11701 unsigned DiagID = diag::ext_forward_ref_enum; 11702 if (getLangOpts().MSVCCompat) 11703 DiagID = diag::ext_ms_forward_ref_enum; 11704 else if (getLangOpts().CPlusPlus) 11705 DiagID = diag::err_forward_ref_enum; 11706 Diag(Loc, DiagID); 11707 11708 // If this is a forward-declared reference to an enumeration, make a 11709 // note of it; we won't actually be introducing the declaration into 11710 // the declaration context. 11711 if (TUK == TUK_Reference) 11712 IsForwardReference = true; 11713 } 11714 } 11715 11716 if (EnumUnderlying) { 11717 EnumDecl *ED = cast<EnumDecl>(New); 11718 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>()) 11719 ED->setIntegerTypeSourceInfo(TI); 11720 else 11721 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0)); 11722 ED->setPromotionType(ED->getIntegerType()); 11723 } 11724 11725 } else { 11726 // struct/union/class 11727 11728 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.: 11729 // struct X { int A; } D; D should chain to X. 11730 if (getLangOpts().CPlusPlus) { 11731 // FIXME: Look for a way to use RecordDecl for simple structs. 11732 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11733 cast_or_null<CXXRecordDecl>(PrevDecl)); 11734 11735 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit())) 11736 StdBadAlloc = cast<CXXRecordDecl>(New); 11737 } else 11738 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name, 11739 cast_or_null<RecordDecl>(PrevDecl)); 11740 } 11741 11742 // C++11 [dcl.type]p3: 11743 // A type-specifier-seq shall not define a class or enumeration [...]. 11744 if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) { 11745 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier) 11746 << Context.getTagDeclType(New); 11747 Invalid = true; 11748 } 11749 11750 // Maybe add qualifier info. 11751 if (SS.isNotEmpty()) { 11752 if (SS.isSet()) { 11753 // If this is either a declaration or a definition, check the 11754 // nested-name-specifier against the current context. We don't do this 11755 // for explicit specializations, because they have similar checking 11756 // (with more specific diagnostics) in the call to 11757 // CheckMemberSpecialization, below. 11758 if (!isExplicitSpecialization && 11759 (TUK == TUK_Definition || TUK == TUK_Declaration) && 11760 diagnoseQualifiedDeclaration(SS, DC, OrigName, NameLoc)) 11761 Invalid = true; 11762 11763 New->setQualifierInfo(SS.getWithLocInContext(Context)); 11764 if (TemplateParameterLists.size() > 0) { 11765 New->setTemplateParameterListsInfo(Context, 11766 TemplateParameterLists.size(), 11767 TemplateParameterLists.data()); 11768 } 11769 } 11770 else 11771 Invalid = true; 11772 } 11773 11774 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) { 11775 // Add alignment attributes if necessary; these attributes are checked when 11776 // the ASTContext lays out the structure. 11777 // 11778 // It is important for implementing the correct semantics that this 11779 // happen here (in act on tag decl). The #pragma pack stack is 11780 // maintained as a result of parser callbacks which can occur at 11781 // many points during the parsing of a struct declaration (because 11782 // the #pragma tokens are effectively skipped over during the 11783 // parsing of the struct). 11784 if (TUK == TUK_Definition) { 11785 AddAlignmentAttributesForRecord(RD); 11786 AddMsStructLayoutForRecord(RD); 11787 } 11788 } 11789 11790 if (ModulePrivateLoc.isValid()) { 11791 if (isExplicitSpecialization) 11792 Diag(New->getLocation(), diag::err_module_private_specialization) 11793 << 2 11794 << FixItHint::CreateRemoval(ModulePrivateLoc); 11795 // __module_private__ does not apply to local classes. However, we only 11796 // diagnose this as an error when the declaration specifiers are 11797 // freestanding. Here, we just ignore the __module_private__. 11798 else if (!SearchDC->isFunctionOrMethod()) 11799 New->setModulePrivate(); 11800 } 11801 11802 // If this is a specialization of a member class (of a class template), 11803 // check the specialization. 11804 if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous)) 11805 Invalid = true; 11806 11807 // If we're declaring or defining a tag in function prototype scope in C, 11808 // note that this type can only be used within the function and add it to 11809 // the list of decls to inject into the function definition scope. 11810 if ((Name || Kind == TTK_Enum) && 11811 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) { 11812 if (getLangOpts().CPlusPlus) { 11813 // C++ [dcl.fct]p6: 11814 // Types shall not be defined in return or parameter types. 11815 if (TUK == TUK_Definition && !IsTypeSpecifier) { 11816 Diag(Loc, diag::err_type_defined_in_param_type) 11817 << Name; 11818 Invalid = true; 11819 } 11820 } else { 11821 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New); 11822 } 11823 DeclsInPrototypeScope.push_back(New); 11824 } 11825 11826 if (Invalid) 11827 New->setInvalidDecl(); 11828 11829 if (Attr) 11830 ProcessDeclAttributeList(S, New, Attr); 11831 11832 // Set the lexical context. If the tag has a C++ scope specifier, the 11833 // lexical context will be different from the semantic context. 11834 New->setLexicalDeclContext(CurContext); 11835 11836 // Mark this as a friend decl if applicable. 11837 // In Microsoft mode, a friend declaration also acts as a forward 11838 // declaration so we always pass true to setObjectOfFriendDecl to make 11839 // the tag name visible. 11840 if (TUK == TUK_Friend) 11841 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat); 11842 11843 // Set the access specifier. 11844 if (!Invalid && SearchDC->isRecord()) 11845 SetMemberAccessSpecifier(New, PrevDecl, AS); 11846 11847 if (TUK == TUK_Definition) 11848 New->startDefinition(); 11849 11850 // If this has an identifier, add it to the scope stack. 11851 if (TUK == TUK_Friend) { 11852 // We might be replacing an existing declaration in the lookup tables; 11853 // if so, borrow its access specifier. 11854 if (PrevDecl) 11855 New->setAccess(PrevDecl->getAccess()); 11856 11857 DeclContext *DC = New->getDeclContext()->getRedeclContext(); 11858 DC->makeDeclVisibleInContext(New); 11859 if (Name) // can be null along some error paths 11860 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC)) 11861 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false); 11862 } else if (Name) { 11863 S = getNonFieldDeclScope(S); 11864 PushOnScopeChains(New, S, !IsForwardReference); 11865 if (IsForwardReference) 11866 SearchDC->makeDeclVisibleInContext(New); 11867 11868 } else { 11869 CurContext->addDecl(New); 11870 } 11871 11872 // If this is the C FILE type, notify the AST context. 11873 if (IdentifierInfo *II = New->getIdentifier()) 11874 if (!New->isInvalidDecl() && 11875 New->getDeclContext()->getRedeclContext()->isTranslationUnit() && 11876 II->isStr("FILE")) 11877 Context.setFILEDecl(New); 11878 11879 if (PrevDecl) 11880 mergeDeclAttributes(New, PrevDecl); 11881 11882 // If there's a #pragma GCC visibility in scope, set the visibility of this 11883 // record. 11884 AddPushedVisibilityAttribute(New); 11885 11886 OwnedDecl = true; 11887 // In C++, don't return an invalid declaration. We can't recover well from 11888 // the cases where we make the type anonymous. 11889 return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New; 11890 } 11891 11892 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) { 11893 AdjustDeclIfTemplate(TagD); 11894 TagDecl *Tag = cast<TagDecl>(TagD); 11895 11896 // Enter the tag context. 11897 PushDeclContext(S, Tag); 11898 11899 ActOnDocumentableDecl(TagD); 11900 11901 // If there's a #pragma GCC visibility in scope, set the visibility of this 11902 // record. 11903 AddPushedVisibilityAttribute(Tag); 11904 } 11905 11906 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) { 11907 assert(isa<ObjCContainerDecl>(IDecl) && 11908 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"); 11909 DeclContext *OCD = cast<DeclContext>(IDecl); 11910 assert(getContainingDC(OCD) == CurContext && 11911 "The next DeclContext should be lexically contained in the current one."); 11912 CurContext = OCD; 11913 return IDecl; 11914 } 11915 11916 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD, 11917 SourceLocation FinalLoc, 11918 bool IsFinalSpelledSealed, 11919 SourceLocation LBraceLoc) { 11920 AdjustDeclIfTemplate(TagD); 11921 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD); 11922 11923 FieldCollector->StartClass(); 11924 11925 if (!Record->getIdentifier()) 11926 return; 11927 11928 if (FinalLoc.isValid()) 11929 Record->addAttr(new (Context) 11930 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed)); 11931 11932 // C++ [class]p2: 11933 // [...] The class-name is also inserted into the scope of the 11934 // class itself; this is known as the injected-class-name. For 11935 // purposes of access checking, the injected-class-name is treated 11936 // as if it were a public member name. 11937 CXXRecordDecl *InjectedClassName 11938 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext, 11939 Record->getLocStart(), Record->getLocation(), 11940 Record->getIdentifier(), 11941 /*PrevDecl=*/nullptr, 11942 /*DelayTypeCreation=*/true); 11943 Context.getTypeDeclType(InjectedClassName, Record); 11944 InjectedClassName->setImplicit(); 11945 InjectedClassName->setAccess(AS_public); 11946 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate()) 11947 InjectedClassName->setDescribedClassTemplate(Template); 11948 PushOnScopeChains(InjectedClassName, S); 11949 assert(InjectedClassName->isInjectedClassName() && 11950 "Broken injected-class-name"); 11951 } 11952 11953 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD, 11954 SourceLocation RBraceLoc) { 11955 AdjustDeclIfTemplate(TagD); 11956 TagDecl *Tag = cast<TagDecl>(TagD); 11957 Tag->setRBraceLoc(RBraceLoc); 11958 11959 // Make sure we "complete" the definition even it is invalid. 11960 if (Tag->isBeingDefined()) { 11961 assert(Tag->isInvalidDecl() && "We should already have completed it"); 11962 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 11963 RD->completeDefinition(); 11964 } 11965 11966 if (isa<CXXRecordDecl>(Tag)) 11967 FieldCollector->FinishClass(); 11968 11969 // Exit this scope of this tag's definition. 11970 PopDeclContext(); 11971 11972 if (getCurLexicalContext()->isObjCContainer() && 11973 Tag->getDeclContext()->isFileContext()) 11974 Tag->setTopLevelDeclInObjCContainer(); 11975 11976 // Notify the consumer that we've defined a tag. 11977 if (!Tag->isInvalidDecl()) 11978 Consumer.HandleTagDeclDefinition(Tag); 11979 } 11980 11981 void Sema::ActOnObjCContainerFinishDefinition() { 11982 // Exit this scope of this interface definition. 11983 PopDeclContext(); 11984 } 11985 11986 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) { 11987 assert(DC == CurContext && "Mismatch of container contexts"); 11988 OriginalLexicalContext = DC; 11989 ActOnObjCContainerFinishDefinition(); 11990 } 11991 11992 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) { 11993 ActOnObjCContainerStartDefinition(cast<Decl>(DC)); 11994 OriginalLexicalContext = nullptr; 11995 } 11996 11997 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) { 11998 AdjustDeclIfTemplate(TagD); 11999 TagDecl *Tag = cast<TagDecl>(TagD); 12000 Tag->setInvalidDecl(); 12001 12002 // Make sure we "complete" the definition even it is invalid. 12003 if (Tag->isBeingDefined()) { 12004 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) 12005 RD->completeDefinition(); 12006 } 12007 12008 // We're undoing ActOnTagStartDefinition here, not 12009 // ActOnStartCXXMemberDeclarations, so we don't have to mess with 12010 // the FieldCollector. 12011 12012 PopDeclContext(); 12013 } 12014 12015 // Note that FieldName may be null for anonymous bitfields. 12016 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc, 12017 IdentifierInfo *FieldName, 12018 QualType FieldTy, bool IsMsStruct, 12019 Expr *BitWidth, bool *ZeroWidth) { 12020 // Default to true; that shouldn't confuse checks for emptiness 12021 if (ZeroWidth) 12022 *ZeroWidth = true; 12023 12024 // C99 6.7.2.1p4 - verify the field type. 12025 // C++ 9.6p3: A bit-field shall have integral or enumeration type. 12026 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) { 12027 // Handle incomplete types with specific error. 12028 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete)) 12029 return ExprError(); 12030 if (FieldName) 12031 return Diag(FieldLoc, diag::err_not_integral_type_bitfield) 12032 << FieldName << FieldTy << BitWidth->getSourceRange(); 12033 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield) 12034 << FieldTy << BitWidth->getSourceRange(); 12035 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth), 12036 UPPC_BitFieldWidth)) 12037 return ExprError(); 12038 12039 // If the bit-width is type- or value-dependent, don't try to check 12040 // it now. 12041 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent()) 12042 return BitWidth; 12043 12044 llvm::APSInt Value; 12045 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value); 12046 if (ICE.isInvalid()) 12047 return ICE; 12048 BitWidth = ICE.get(); 12049 12050 if (Value != 0 && ZeroWidth) 12051 *ZeroWidth = false; 12052 12053 // Zero-width bitfield is ok for anonymous field. 12054 if (Value == 0 && FieldName) 12055 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName; 12056 12057 if (Value.isSigned() && Value.isNegative()) { 12058 if (FieldName) 12059 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) 12060 << FieldName << Value.toString(10); 12061 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width) 12062 << Value.toString(10); 12063 } 12064 12065 if (!FieldTy->isDependentType()) { 12066 uint64_t TypeSize = Context.getTypeSize(FieldTy); 12067 if (Value.getZExtValue() > TypeSize) { 12068 if (!getLangOpts().CPlusPlus || IsMsStruct || 12069 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 12070 if (FieldName) 12071 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size) 12072 << FieldName << (unsigned)Value.getZExtValue() 12073 << (unsigned)TypeSize; 12074 12075 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_size) 12076 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12077 } 12078 12079 if (FieldName) 12080 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_size) 12081 << FieldName << (unsigned)Value.getZExtValue() 12082 << (unsigned)TypeSize; 12083 else 12084 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_size) 12085 << (unsigned)Value.getZExtValue() << (unsigned)TypeSize; 12086 } 12087 } 12088 12089 return BitWidth; 12090 } 12091 12092 /// ActOnField - Each field of a C struct/union is passed into this in order 12093 /// to create a FieldDecl object for it. 12094 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 12095 Declarator &D, Expr *BitfieldWidth) { 12096 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD), 12097 DeclStart, D, static_cast<Expr*>(BitfieldWidth), 12098 /*InitStyle=*/ICIS_NoInit, AS_public); 12099 return Res; 12100 } 12101 12102 /// HandleField - Analyze a field of a C struct or a C++ data member. 12103 /// 12104 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record, 12105 SourceLocation DeclStart, 12106 Declarator &D, Expr *BitWidth, 12107 InClassInitStyle InitStyle, 12108 AccessSpecifier AS) { 12109 IdentifierInfo *II = D.getIdentifier(); 12110 SourceLocation Loc = DeclStart; 12111 if (II) Loc = D.getIdentifierLoc(); 12112 12113 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12114 QualType T = TInfo->getType(); 12115 if (getLangOpts().CPlusPlus) { 12116 CheckExtraCXXDefaultArguments(D); 12117 12118 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo, 12119 UPPC_DataMemberType)) { 12120 D.setInvalidType(); 12121 T = Context.IntTy; 12122 TInfo = Context.getTrivialTypeSourceInfo(T, Loc); 12123 } 12124 } 12125 12126 // TR 18037 does not allow fields to be declared with address spaces. 12127 if (T.getQualifiers().hasAddressSpace()) { 12128 Diag(Loc, diag::err_field_with_address_space); 12129 D.setInvalidType(); 12130 } 12131 12132 // OpenCL 1.2 spec, s6.9 r: 12133 // The event type cannot be used to declare a structure or union field. 12134 if (LangOpts.OpenCL && T->isEventT()) { 12135 Diag(Loc, diag::err_event_t_struct_field); 12136 D.setInvalidType(); 12137 } 12138 12139 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 12140 12141 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 12142 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 12143 diag::err_invalid_thread) 12144 << DeclSpec::getSpecifierName(TSCS); 12145 12146 // Check to see if this name was declared as a member previously 12147 NamedDecl *PrevDecl = nullptr; 12148 LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration); 12149 LookupName(Previous, S); 12150 switch (Previous.getResultKind()) { 12151 case LookupResult::Found: 12152 case LookupResult::FoundUnresolvedValue: 12153 PrevDecl = Previous.getAsSingle<NamedDecl>(); 12154 break; 12155 12156 case LookupResult::FoundOverloaded: 12157 PrevDecl = Previous.getRepresentativeDecl(); 12158 break; 12159 12160 case LookupResult::NotFound: 12161 case LookupResult::NotFoundInCurrentInstantiation: 12162 case LookupResult::Ambiguous: 12163 break; 12164 } 12165 Previous.suppressDiagnostics(); 12166 12167 if (PrevDecl && PrevDecl->isTemplateParameter()) { 12168 // Maybe we will complain about the shadowed template parameter. 12169 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl); 12170 // Just pretend that we didn't see the previous declaration. 12171 PrevDecl = nullptr; 12172 } 12173 12174 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S)) 12175 PrevDecl = nullptr; 12176 12177 bool Mutable 12178 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable); 12179 SourceLocation TSSL = D.getLocStart(); 12180 FieldDecl *NewFD 12181 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle, 12182 TSSL, AS, PrevDecl, &D); 12183 12184 if (NewFD->isInvalidDecl()) 12185 Record->setInvalidDecl(); 12186 12187 if (D.getDeclSpec().isModulePrivateSpecified()) 12188 NewFD->setModulePrivate(); 12189 12190 if (NewFD->isInvalidDecl() && PrevDecl) { 12191 // Don't introduce NewFD into scope; there's already something 12192 // with the same name in the same scope. 12193 } else if (II) { 12194 PushOnScopeChains(NewFD, S); 12195 } else 12196 Record->addDecl(NewFD); 12197 12198 return NewFD; 12199 } 12200 12201 /// \brief Build a new FieldDecl and check its well-formedness. 12202 /// 12203 /// This routine builds a new FieldDecl given the fields name, type, 12204 /// record, etc. \p PrevDecl should refer to any previous declaration 12205 /// with the same name and in the same scope as the field to be 12206 /// created. 12207 /// 12208 /// \returns a new FieldDecl. 12209 /// 12210 /// \todo The Declarator argument is a hack. It will be removed once 12211 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T, 12212 TypeSourceInfo *TInfo, 12213 RecordDecl *Record, SourceLocation Loc, 12214 bool Mutable, Expr *BitWidth, 12215 InClassInitStyle InitStyle, 12216 SourceLocation TSSL, 12217 AccessSpecifier AS, NamedDecl *PrevDecl, 12218 Declarator *D) { 12219 IdentifierInfo *II = Name.getAsIdentifierInfo(); 12220 bool InvalidDecl = false; 12221 if (D) InvalidDecl = D->isInvalidType(); 12222 12223 // If we receive a broken type, recover by assuming 'int' and 12224 // marking this declaration as invalid. 12225 if (T.isNull()) { 12226 InvalidDecl = true; 12227 T = Context.IntTy; 12228 } 12229 12230 QualType EltTy = Context.getBaseElementType(T); 12231 if (!EltTy->isDependentType()) { 12232 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) { 12233 // Fields of incomplete type force their record to be invalid. 12234 Record->setInvalidDecl(); 12235 InvalidDecl = true; 12236 } else { 12237 NamedDecl *Def; 12238 EltTy->isIncompleteType(&Def); 12239 if (Def && Def->isInvalidDecl()) { 12240 Record->setInvalidDecl(); 12241 InvalidDecl = true; 12242 } 12243 } 12244 } 12245 12246 // OpenCL v1.2 s6.9.c: bitfields are not supported. 12247 if (BitWidth && getLangOpts().OpenCL) { 12248 Diag(Loc, diag::err_opencl_bitfields); 12249 InvalidDecl = true; 12250 } 12251 12252 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12253 // than a variably modified type. 12254 if (!InvalidDecl && T->isVariablyModifiedType()) { 12255 bool SizeIsNegative; 12256 llvm::APSInt Oversized; 12257 12258 TypeSourceInfo *FixedTInfo = 12259 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context, 12260 SizeIsNegative, 12261 Oversized); 12262 if (FixedTInfo) { 12263 Diag(Loc, diag::warn_illegal_constant_array_size); 12264 TInfo = FixedTInfo; 12265 T = FixedTInfo->getType(); 12266 } else { 12267 if (SizeIsNegative) 12268 Diag(Loc, diag::err_typecheck_negative_array_size); 12269 else if (Oversized.getBoolValue()) 12270 Diag(Loc, diag::err_array_too_large) 12271 << Oversized.toString(10); 12272 else 12273 Diag(Loc, diag::err_typecheck_field_variable_size); 12274 InvalidDecl = true; 12275 } 12276 } 12277 12278 // Fields can not have abstract class types 12279 if (!InvalidDecl && RequireNonAbstractType(Loc, T, 12280 diag::err_abstract_type_in_decl, 12281 AbstractFieldType)) 12282 InvalidDecl = true; 12283 12284 bool ZeroWidth = false; 12285 // If this is declared as a bit-field, check the bit-field. 12286 if (!InvalidDecl && BitWidth) { 12287 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth, 12288 &ZeroWidth).get(); 12289 if (!BitWidth) { 12290 InvalidDecl = true; 12291 BitWidth = nullptr; 12292 ZeroWidth = false; 12293 } 12294 } 12295 12296 // Check that 'mutable' is consistent with the type of the declaration. 12297 if (!InvalidDecl && Mutable) { 12298 unsigned DiagID = 0; 12299 if (T->isReferenceType()) 12300 DiagID = diag::err_mutable_reference; 12301 else if (T.isConstQualified()) 12302 DiagID = diag::err_mutable_const; 12303 12304 if (DiagID) { 12305 SourceLocation ErrLoc = Loc; 12306 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid()) 12307 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc(); 12308 Diag(ErrLoc, DiagID); 12309 Mutable = false; 12310 InvalidDecl = true; 12311 } 12312 } 12313 12314 // C++11 [class.union]p8 (DR1460): 12315 // At most one variant member of a union may have a 12316 // brace-or-equal-initializer. 12317 if (InitStyle != ICIS_NoInit) 12318 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc); 12319 12320 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo, 12321 BitWidth, Mutable, InitStyle); 12322 if (InvalidDecl) 12323 NewFD->setInvalidDecl(); 12324 12325 if (PrevDecl && !isa<TagDecl>(PrevDecl)) { 12326 Diag(Loc, diag::err_duplicate_member) << II; 12327 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12328 NewFD->setInvalidDecl(); 12329 } 12330 12331 if (!InvalidDecl && getLangOpts().CPlusPlus) { 12332 if (Record->isUnion()) { 12333 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12334 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12335 if (RDecl->getDefinition()) { 12336 // C++ [class.union]p1: An object of a class with a non-trivial 12337 // constructor, a non-trivial copy constructor, a non-trivial 12338 // destructor, or a non-trivial copy assignment operator 12339 // cannot be a member of a union, nor can an array of such 12340 // objects. 12341 if (CheckNontrivialField(NewFD)) 12342 NewFD->setInvalidDecl(); 12343 } 12344 } 12345 12346 // C++ [class.union]p1: If a union contains a member of reference type, 12347 // the program is ill-formed, except when compiling with MSVC extensions 12348 // enabled. 12349 if (EltTy->isReferenceType()) { 12350 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ? 12351 diag::ext_union_member_of_reference_type : 12352 diag::err_union_member_of_reference_type) 12353 << NewFD->getDeclName() << EltTy; 12354 if (!getLangOpts().MicrosoftExt) 12355 NewFD->setInvalidDecl(); 12356 } 12357 } 12358 } 12359 12360 // FIXME: We need to pass in the attributes given an AST 12361 // representation, not a parser representation. 12362 if (D) { 12363 // FIXME: The current scope is almost... but not entirely... correct here. 12364 ProcessDeclAttributes(getCurScope(), NewFD, *D); 12365 12366 if (NewFD->hasAttrs()) 12367 CheckAlignasUnderalignment(NewFD); 12368 } 12369 12370 // In auto-retain/release, infer strong retension for fields of 12371 // retainable type. 12372 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD)) 12373 NewFD->setInvalidDecl(); 12374 12375 if (T.isObjCGCWeak()) 12376 Diag(Loc, diag::warn_attribute_weak_on_field); 12377 12378 NewFD->setAccess(AS); 12379 return NewFD; 12380 } 12381 12382 bool Sema::CheckNontrivialField(FieldDecl *FD) { 12383 assert(FD); 12384 assert(getLangOpts().CPlusPlus && "valid check only for C++"); 12385 12386 if (FD->isInvalidDecl() || FD->getType()->isDependentType()) 12387 return false; 12388 12389 QualType EltTy = Context.getBaseElementType(FD->getType()); 12390 if (const RecordType *RT = EltTy->getAs<RecordType>()) { 12391 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl()); 12392 if (RDecl->getDefinition()) { 12393 // We check for copy constructors before constructors 12394 // because otherwise we'll never get complaints about 12395 // copy constructors. 12396 12397 CXXSpecialMember member = CXXInvalid; 12398 // We're required to check for any non-trivial constructors. Since the 12399 // implicit default constructor is suppressed if there are any 12400 // user-declared constructors, we just need to check that there is a 12401 // trivial default constructor and a trivial copy constructor. (We don't 12402 // worry about move constructors here, since this is a C++98 check.) 12403 if (RDecl->hasNonTrivialCopyConstructor()) 12404 member = CXXCopyConstructor; 12405 else if (!RDecl->hasTrivialDefaultConstructor()) 12406 member = CXXDefaultConstructor; 12407 else if (RDecl->hasNonTrivialCopyAssignment()) 12408 member = CXXCopyAssignment; 12409 else if (RDecl->hasNonTrivialDestructor()) 12410 member = CXXDestructor; 12411 12412 if (member != CXXInvalid) { 12413 if (!getLangOpts().CPlusPlus11 && 12414 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) { 12415 // Objective-C++ ARC: it is an error to have a non-trivial field of 12416 // a union. However, system headers in Objective-C programs 12417 // occasionally have Objective-C lifetime objects within unions, 12418 // and rather than cause the program to fail, we make those 12419 // members unavailable. 12420 SourceLocation Loc = FD->getLocation(); 12421 if (getSourceManager().isInSystemHeader(Loc)) { 12422 if (!FD->hasAttr<UnavailableAttr>()) 12423 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12424 "this system field has retaining ownership", 12425 Loc)); 12426 return false; 12427 } 12428 } 12429 12430 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ? 12431 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member : 12432 diag::err_illegal_union_or_anon_struct_member) 12433 << (int)FD->getParent()->isUnion() << FD->getDeclName() << member; 12434 DiagnoseNontrivial(RDecl, member); 12435 return !getLangOpts().CPlusPlus11; 12436 } 12437 } 12438 } 12439 12440 return false; 12441 } 12442 12443 /// TranslateIvarVisibility - Translate visibility from a token ID to an 12444 /// AST enum value. 12445 static ObjCIvarDecl::AccessControl 12446 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) { 12447 switch (ivarVisibility) { 12448 default: llvm_unreachable("Unknown visitibility kind"); 12449 case tok::objc_private: return ObjCIvarDecl::Private; 12450 case tok::objc_public: return ObjCIvarDecl::Public; 12451 case tok::objc_protected: return ObjCIvarDecl::Protected; 12452 case tok::objc_package: return ObjCIvarDecl::Package; 12453 } 12454 } 12455 12456 /// ActOnIvar - Each ivar field of an objective-c class is passed into this 12457 /// in order to create an IvarDecl object for it. 12458 Decl *Sema::ActOnIvar(Scope *S, 12459 SourceLocation DeclStart, 12460 Declarator &D, Expr *BitfieldWidth, 12461 tok::ObjCKeywordKind Visibility) { 12462 12463 IdentifierInfo *II = D.getIdentifier(); 12464 Expr *BitWidth = (Expr*)BitfieldWidth; 12465 SourceLocation Loc = DeclStart; 12466 if (II) Loc = D.getIdentifierLoc(); 12467 12468 // FIXME: Unnamed fields can be handled in various different ways, for 12469 // example, unnamed unions inject all members into the struct namespace! 12470 12471 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 12472 QualType T = TInfo->getType(); 12473 12474 if (BitWidth) { 12475 // 6.7.2.1p3, 6.7.2.1p4 12476 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get(); 12477 if (!BitWidth) 12478 D.setInvalidType(); 12479 } else { 12480 // Not a bitfield. 12481 12482 // validate II. 12483 12484 } 12485 if (T->isReferenceType()) { 12486 Diag(Loc, diag::err_ivar_reference_type); 12487 D.setInvalidType(); 12488 } 12489 // C99 6.7.2.1p8: A member of a structure or union may have any type other 12490 // than a variably modified type. 12491 else if (T->isVariablyModifiedType()) { 12492 Diag(Loc, diag::err_typecheck_ivar_variable_size); 12493 D.setInvalidType(); 12494 } 12495 12496 // Get the visibility (access control) for this ivar. 12497 ObjCIvarDecl::AccessControl ac = 12498 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility) 12499 : ObjCIvarDecl::None; 12500 // Must set ivar's DeclContext to its enclosing interface. 12501 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext); 12502 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl()) 12503 return nullptr; 12504 ObjCContainerDecl *EnclosingContext; 12505 if (ObjCImplementationDecl *IMPDecl = 12506 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12507 if (LangOpts.ObjCRuntime.isFragile()) { 12508 // Case of ivar declared in an implementation. Context is that of its class. 12509 EnclosingContext = IMPDecl->getClassInterface(); 12510 assert(EnclosingContext && "Implementation has no class interface!"); 12511 } 12512 else 12513 EnclosingContext = EnclosingDecl; 12514 } else { 12515 if (ObjCCategoryDecl *CDecl = 12516 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12517 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) { 12518 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension(); 12519 return nullptr; 12520 } 12521 } 12522 EnclosingContext = EnclosingDecl; 12523 } 12524 12525 // Construct the decl. 12526 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext, 12527 DeclStart, Loc, II, T, 12528 TInfo, ac, (Expr *)BitfieldWidth); 12529 12530 if (II) { 12531 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName, 12532 ForRedeclaration); 12533 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S) 12534 && !isa<TagDecl>(PrevDecl)) { 12535 Diag(Loc, diag::err_duplicate_member) << II; 12536 Diag(PrevDecl->getLocation(), diag::note_previous_declaration); 12537 NewID->setInvalidDecl(); 12538 } 12539 } 12540 12541 // Process attributes attached to the ivar. 12542 ProcessDeclAttributes(S, NewID, D); 12543 12544 if (D.isInvalidType()) 12545 NewID->setInvalidDecl(); 12546 12547 // In ARC, infer 'retaining' for ivars of retainable type. 12548 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID)) 12549 NewID->setInvalidDecl(); 12550 12551 if (D.getDeclSpec().isModulePrivateSpecified()) 12552 NewID->setModulePrivate(); 12553 12554 if (II) { 12555 // FIXME: When interfaces are DeclContexts, we'll need to add 12556 // these to the interface. 12557 S->AddDecl(NewID); 12558 IdResolver.AddDecl(NewID); 12559 } 12560 12561 if (LangOpts.ObjCRuntime.isNonFragile() && 12562 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl)) 12563 Diag(Loc, diag::warn_ivars_in_interface); 12564 12565 return NewID; 12566 } 12567 12568 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for 12569 /// class and class extensions. For every class \@interface and class 12570 /// extension \@interface, if the last ivar is a bitfield of any type, 12571 /// then add an implicit `char :0` ivar to the end of that interface. 12572 void Sema::ActOnLastBitfield(SourceLocation DeclLoc, 12573 SmallVectorImpl<Decl *> &AllIvarDecls) { 12574 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty()) 12575 return; 12576 12577 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1]; 12578 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl); 12579 12580 if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0) 12581 return; 12582 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext); 12583 if (!ID) { 12584 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) { 12585 if (!CD->IsClassExtension()) 12586 return; 12587 } 12588 // No need to add this to end of @implementation. 12589 else 12590 return; 12591 } 12592 // All conditions are met. Add a new bitfield to the tail end of ivars. 12593 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0); 12594 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc); 12595 12596 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext), 12597 DeclLoc, DeclLoc, nullptr, 12598 Context.CharTy, 12599 Context.getTrivialTypeSourceInfo(Context.CharTy, 12600 DeclLoc), 12601 ObjCIvarDecl::Private, BW, 12602 true); 12603 AllIvarDecls.push_back(Ivar); 12604 } 12605 12606 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl, 12607 ArrayRef<Decl *> Fields, SourceLocation LBrac, 12608 SourceLocation RBrac, AttributeList *Attr) { 12609 assert(EnclosingDecl && "missing record or interface decl"); 12610 12611 // If this is an Objective-C @implementation or category and we have 12612 // new fields here we should reset the layout of the interface since 12613 // it will now change. 12614 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) { 12615 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl); 12616 switch (DC->getKind()) { 12617 default: break; 12618 case Decl::ObjCCategory: 12619 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface()); 12620 break; 12621 case Decl::ObjCImplementation: 12622 Context. 12623 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface()); 12624 break; 12625 } 12626 } 12627 12628 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl); 12629 12630 // Start counting up the number of named members; make sure to include 12631 // members of anonymous structs and unions in the total. 12632 unsigned NumNamedMembers = 0; 12633 if (Record) { 12634 for (const auto *I : Record->decls()) { 12635 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I)) 12636 if (IFD->getDeclName()) 12637 ++NumNamedMembers; 12638 } 12639 } 12640 12641 // Verify that all the fields are okay. 12642 SmallVector<FieldDecl*, 32> RecFields; 12643 12644 bool ARCErrReported = false; 12645 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end(); 12646 i != end; ++i) { 12647 FieldDecl *FD = cast<FieldDecl>(*i); 12648 12649 // Get the type for the field. 12650 const Type *FDTy = FD->getType().getTypePtr(); 12651 12652 if (!FD->isAnonymousStructOrUnion()) { 12653 // Remember all fields written by the user. 12654 RecFields.push_back(FD); 12655 } 12656 12657 // If the field is already invalid for some reason, don't emit more 12658 // diagnostics about it. 12659 if (FD->isInvalidDecl()) { 12660 EnclosingDecl->setInvalidDecl(); 12661 continue; 12662 } 12663 12664 // C99 6.7.2.1p2: 12665 // A structure or union shall not contain a member with 12666 // incomplete or function type (hence, a structure shall not 12667 // contain an instance of itself, but may contain a pointer to 12668 // an instance of itself), except that the last member of a 12669 // structure with more than one named member may have incomplete 12670 // array type; such a structure (and any union containing, 12671 // possibly recursively, a member that is such a structure) 12672 // shall not be a member of a structure or an element of an 12673 // array. 12674 if (FDTy->isFunctionType()) { 12675 // Field declared as a function. 12676 Diag(FD->getLocation(), diag::err_field_declared_as_function) 12677 << FD->getDeclName(); 12678 FD->setInvalidDecl(); 12679 EnclosingDecl->setInvalidDecl(); 12680 continue; 12681 } else if (FDTy->isIncompleteArrayType() && Record && 12682 ((i + 1 == Fields.end() && !Record->isUnion()) || 12683 ((getLangOpts().MicrosoftExt || 12684 getLangOpts().CPlusPlus) && 12685 (i + 1 == Fields.end() || Record->isUnion())))) { 12686 // Flexible array member. 12687 // Microsoft and g++ is more permissive regarding flexible array. 12688 // It will accept flexible array in union and also 12689 // as the sole element of a struct/class. 12690 unsigned DiagID = 0; 12691 if (Record->isUnion()) 12692 DiagID = getLangOpts().MicrosoftExt 12693 ? diag::ext_flexible_array_union_ms 12694 : getLangOpts().CPlusPlus 12695 ? diag::ext_flexible_array_union_gnu 12696 : diag::err_flexible_array_union; 12697 else if (Fields.size() == 1) 12698 DiagID = getLangOpts().MicrosoftExt 12699 ? diag::ext_flexible_array_empty_aggregate_ms 12700 : getLangOpts().CPlusPlus 12701 ? diag::ext_flexible_array_empty_aggregate_gnu 12702 : NumNamedMembers < 1 12703 ? diag::err_flexible_array_empty_aggregate 12704 : 0; 12705 12706 if (DiagID) 12707 Diag(FD->getLocation(), DiagID) << FD->getDeclName() 12708 << Record->getTagKind(); 12709 // While the layout of types that contain virtual bases is not specified 12710 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place 12711 // virtual bases after the derived members. This would make a flexible 12712 // array member declared at the end of an object not adjacent to the end 12713 // of the type. 12714 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) 12715 if (RD->getNumVBases() != 0) 12716 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base) 12717 << FD->getDeclName() << Record->getTagKind(); 12718 if (!getLangOpts().C99) 12719 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member) 12720 << FD->getDeclName() << Record->getTagKind(); 12721 12722 // If the element type has a non-trivial destructor, we would not 12723 // implicitly destroy the elements, so disallow it for now. 12724 // 12725 // FIXME: GCC allows this. We should probably either implicitly delete 12726 // the destructor of the containing class, or just allow this. 12727 QualType BaseElem = Context.getBaseElementType(FD->getType()); 12728 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) { 12729 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor) 12730 << FD->getDeclName() << FD->getType(); 12731 FD->setInvalidDecl(); 12732 EnclosingDecl->setInvalidDecl(); 12733 continue; 12734 } 12735 // Okay, we have a legal flexible array member at the end of the struct. 12736 Record->setHasFlexibleArrayMember(true); 12737 } else if (!FDTy->isDependentType() && 12738 RequireCompleteType(FD->getLocation(), FD->getType(), 12739 diag::err_field_incomplete)) { 12740 // Incomplete type 12741 FD->setInvalidDecl(); 12742 EnclosingDecl->setInvalidDecl(); 12743 continue; 12744 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) { 12745 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) { 12746 // A type which contains a flexible array member is considered to be a 12747 // flexible array member. 12748 Record->setHasFlexibleArrayMember(true); 12749 if (!Record->isUnion()) { 12750 // If this is a struct/class and this is not the last element, reject 12751 // it. Note that GCC supports variable sized arrays in the middle of 12752 // structures. 12753 if (i + 1 != Fields.end()) 12754 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct) 12755 << FD->getDeclName() << FD->getType(); 12756 else { 12757 // We support flexible arrays at the end of structs in 12758 // other structs as an extension. 12759 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct) 12760 << FD->getDeclName(); 12761 } 12762 } 12763 } 12764 if (isa<ObjCContainerDecl>(EnclosingDecl) && 12765 RequireNonAbstractType(FD->getLocation(), FD->getType(), 12766 diag::err_abstract_type_in_decl, 12767 AbstractIvarType)) { 12768 // Ivars can not have abstract class types 12769 FD->setInvalidDecl(); 12770 } 12771 if (Record && FDTTy->getDecl()->hasObjectMember()) 12772 Record->setHasObjectMember(true); 12773 if (Record && FDTTy->getDecl()->hasVolatileMember()) 12774 Record->setHasVolatileMember(true); 12775 } else if (FDTy->isObjCObjectType()) { 12776 /// A field cannot be an Objective-c object 12777 Diag(FD->getLocation(), diag::err_statically_allocated_object) 12778 << FixItHint::CreateInsertion(FD->getLocation(), "*"); 12779 QualType T = Context.getObjCObjectPointerType(FD->getType()); 12780 FD->setType(T); 12781 } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported && 12782 (!getLangOpts().CPlusPlus || Record->isUnion())) { 12783 // It's an error in ARC if a field has lifetime. 12784 // We don't want to report this in a system header, though, 12785 // so we just make the field unavailable. 12786 // FIXME: that's really not sufficient; we need to make the type 12787 // itself invalid to, say, initialize or copy. 12788 QualType T = FD->getType(); 12789 Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime(); 12790 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) { 12791 SourceLocation loc = FD->getLocation(); 12792 if (getSourceManager().isInSystemHeader(loc)) { 12793 if (!FD->hasAttr<UnavailableAttr>()) { 12794 FD->addAttr(UnavailableAttr::CreateImplicit(Context, 12795 "this system field has retaining ownership", 12796 loc)); 12797 } 12798 } else { 12799 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag) 12800 << T->isBlockPointerType() << Record->getTagKind(); 12801 } 12802 ARCErrReported = true; 12803 } 12804 } else if (getLangOpts().ObjC1 && 12805 getLangOpts().getGC() != LangOptions::NonGC && 12806 Record && !Record->hasObjectMember()) { 12807 if (FD->getType()->isObjCObjectPointerType() || 12808 FD->getType().isObjCGCStrong()) 12809 Record->setHasObjectMember(true); 12810 else if (Context.getAsArrayType(FD->getType())) { 12811 QualType BaseType = Context.getBaseElementType(FD->getType()); 12812 if (BaseType->isRecordType() && 12813 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember()) 12814 Record->setHasObjectMember(true); 12815 else if (BaseType->isObjCObjectPointerType() || 12816 BaseType.isObjCGCStrong()) 12817 Record->setHasObjectMember(true); 12818 } 12819 } 12820 if (Record && FD->getType().isVolatileQualified()) 12821 Record->setHasVolatileMember(true); 12822 // Keep track of the number of named members. 12823 if (FD->getIdentifier()) 12824 ++NumNamedMembers; 12825 } 12826 12827 // Okay, we successfully defined 'Record'. 12828 if (Record) { 12829 bool Completed = false; 12830 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) { 12831 if (!CXXRecord->isInvalidDecl()) { 12832 // Set access bits correctly on the directly-declared conversions. 12833 for (CXXRecordDecl::conversion_iterator 12834 I = CXXRecord->conversion_begin(), 12835 E = CXXRecord->conversion_end(); I != E; ++I) 12836 I.setAccess((*I)->getAccess()); 12837 12838 if (!CXXRecord->isDependentType()) { 12839 if (CXXRecord->hasUserDeclaredDestructor()) { 12840 // Adjust user-defined destructor exception spec. 12841 if (getLangOpts().CPlusPlus11) 12842 AdjustDestructorExceptionSpec(CXXRecord, 12843 CXXRecord->getDestructor()); 12844 } 12845 12846 // Add any implicitly-declared members to this class. 12847 AddImplicitlyDeclaredMembersToClass(CXXRecord); 12848 12849 // If we have virtual base classes, we may end up finding multiple 12850 // final overriders for a given virtual function. Check for this 12851 // problem now. 12852 if (CXXRecord->getNumVBases()) { 12853 CXXFinalOverriderMap FinalOverriders; 12854 CXXRecord->getFinalOverriders(FinalOverriders); 12855 12856 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(), 12857 MEnd = FinalOverriders.end(); 12858 M != MEnd; ++M) { 12859 for (OverridingMethods::iterator SO = M->second.begin(), 12860 SOEnd = M->second.end(); 12861 SO != SOEnd; ++SO) { 12862 assert(SO->second.size() > 0 && 12863 "Virtual function without overridding functions?"); 12864 if (SO->second.size() == 1) 12865 continue; 12866 12867 // C++ [class.virtual]p2: 12868 // In a derived class, if a virtual member function of a base 12869 // class subobject has more than one final overrider the 12870 // program is ill-formed. 12871 Diag(Record->getLocation(), diag::err_multiple_final_overriders) 12872 << (const NamedDecl *)M->first << Record; 12873 Diag(M->first->getLocation(), 12874 diag::note_overridden_virtual_function); 12875 for (OverridingMethods::overriding_iterator 12876 OM = SO->second.begin(), 12877 OMEnd = SO->second.end(); 12878 OM != OMEnd; ++OM) 12879 Diag(OM->Method->getLocation(), diag::note_final_overrider) 12880 << (const NamedDecl *)M->first << OM->Method->getParent(); 12881 12882 Record->setInvalidDecl(); 12883 } 12884 } 12885 CXXRecord->completeDefinition(&FinalOverriders); 12886 Completed = true; 12887 } 12888 } 12889 } 12890 } 12891 12892 if (!Completed) 12893 Record->completeDefinition(); 12894 12895 if (Record->hasAttrs()) { 12896 CheckAlignasUnderalignment(Record); 12897 12898 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>()) 12899 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record), 12900 IA->getRange(), IA->getBestCase(), 12901 IA->getSemanticSpelling()); 12902 } 12903 12904 // Check if the structure/union declaration is a type that can have zero 12905 // size in C. For C this is a language extension, for C++ it may cause 12906 // compatibility problems. 12907 bool CheckForZeroSize; 12908 if (!getLangOpts().CPlusPlus) { 12909 CheckForZeroSize = true; 12910 } else { 12911 // For C++ filter out types that cannot be referenced in C code. 12912 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record); 12913 CheckForZeroSize = 12914 CXXRecord->getLexicalDeclContext()->isExternCContext() && 12915 !CXXRecord->isDependentType() && 12916 CXXRecord->isCLike(); 12917 } 12918 if (CheckForZeroSize) { 12919 bool ZeroSize = true; 12920 bool IsEmpty = true; 12921 unsigned NonBitFields = 0; 12922 for (RecordDecl::field_iterator I = Record->field_begin(), 12923 E = Record->field_end(); 12924 (NonBitFields == 0 || ZeroSize) && I != E; ++I) { 12925 IsEmpty = false; 12926 if (I->isUnnamedBitfield()) { 12927 if (I->getBitWidthValue(Context) > 0) 12928 ZeroSize = false; 12929 } else { 12930 ++NonBitFields; 12931 QualType FieldType = I->getType(); 12932 if (FieldType->isIncompleteType() || 12933 !Context.getTypeSizeInChars(FieldType).isZero()) 12934 ZeroSize = false; 12935 } 12936 } 12937 12938 // Empty structs are an extension in C (C99 6.7.2.1p7). They are 12939 // allowed in C++, but warn if its declaration is inside 12940 // extern "C" block. 12941 if (ZeroSize) { 12942 Diag(RecLoc, getLangOpts().CPlusPlus ? 12943 diag::warn_zero_size_struct_union_in_extern_c : 12944 diag::warn_zero_size_struct_union_compat) 12945 << IsEmpty << Record->isUnion() << (NonBitFields > 1); 12946 } 12947 12948 // Structs without named members are extension in C (C99 6.7.2.1p7), 12949 // but are accepted by GCC. 12950 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) { 12951 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union : 12952 diag::ext_no_named_members_in_struct_union) 12953 << Record->isUnion(); 12954 } 12955 } 12956 } else { 12957 ObjCIvarDecl **ClsFields = 12958 reinterpret_cast<ObjCIvarDecl**>(RecFields.data()); 12959 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) { 12960 ID->setEndOfDefinitionLoc(RBrac); 12961 // Add ivar's to class's DeclContext. 12962 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12963 ClsFields[i]->setLexicalDeclContext(ID); 12964 ID->addDecl(ClsFields[i]); 12965 } 12966 // Must enforce the rule that ivars in the base classes may not be 12967 // duplicates. 12968 if (ID->getSuperClass()) 12969 DiagnoseDuplicateIvars(ID, ID->getSuperClass()); 12970 } else if (ObjCImplementationDecl *IMPDecl = 12971 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) { 12972 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl"); 12973 for (unsigned I = 0, N = RecFields.size(); I != N; ++I) 12974 // Ivar declared in @implementation never belongs to the implementation. 12975 // Only it is in implementation's lexical context. 12976 ClsFields[I]->setLexicalDeclContext(IMPDecl); 12977 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac); 12978 IMPDecl->setIvarLBraceLoc(LBrac); 12979 IMPDecl->setIvarRBraceLoc(RBrac); 12980 } else if (ObjCCategoryDecl *CDecl = 12981 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) { 12982 // case of ivars in class extension; all other cases have been 12983 // reported as errors elsewhere. 12984 // FIXME. Class extension does not have a LocEnd field. 12985 // CDecl->setLocEnd(RBrac); 12986 // Add ivar's to class extension's DeclContext. 12987 // Diagnose redeclaration of private ivars. 12988 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface(); 12989 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 12990 if (IDecl) { 12991 if (const ObjCIvarDecl *ClsIvar = 12992 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) { 12993 Diag(ClsFields[i]->getLocation(), 12994 diag::err_duplicate_ivar_declaration); 12995 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 12996 continue; 12997 } 12998 for (const auto *Ext : IDecl->known_extensions()) { 12999 if (const ObjCIvarDecl *ClsExtIvar 13000 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) { 13001 Diag(ClsFields[i]->getLocation(), 13002 diag::err_duplicate_ivar_declaration); 13003 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 13004 continue; 13005 } 13006 } 13007 } 13008 ClsFields[i]->setLexicalDeclContext(CDecl); 13009 CDecl->addDecl(ClsFields[i]); 13010 } 13011 CDecl->setIvarLBraceLoc(LBrac); 13012 CDecl->setIvarRBraceLoc(RBrac); 13013 } 13014 } 13015 13016 if (Attr) 13017 ProcessDeclAttributeList(S, Record, Attr); 13018 } 13019 13020 /// \brief Determine whether the given integral value is representable within 13021 /// the given type T. 13022 static bool isRepresentableIntegerValue(ASTContext &Context, 13023 llvm::APSInt &Value, 13024 QualType T) { 13025 assert(T->isIntegralType(Context) && "Integral type required!"); 13026 unsigned BitWidth = Context.getIntWidth(T); 13027 13028 if (Value.isUnsigned() || Value.isNonNegative()) { 13029 if (T->isSignedIntegerOrEnumerationType()) 13030 --BitWidth; 13031 return Value.getActiveBits() <= BitWidth; 13032 } 13033 return Value.getMinSignedBits() <= BitWidth; 13034 } 13035 13036 // \brief Given an integral type, return the next larger integral type 13037 // (or a NULL type of no such type exists). 13038 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) { 13039 // FIXME: Int128/UInt128 support, which also needs to be introduced into 13040 // enum checking below. 13041 assert(T->isIntegralType(Context) && "Integral type required!"); 13042 const unsigned NumTypes = 4; 13043 QualType SignedIntegralTypes[NumTypes] = { 13044 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy 13045 }; 13046 QualType UnsignedIntegralTypes[NumTypes] = { 13047 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy, 13048 Context.UnsignedLongLongTy 13049 }; 13050 13051 unsigned BitWidth = Context.getTypeSize(T); 13052 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes 13053 : UnsignedIntegralTypes; 13054 for (unsigned I = 0; I != NumTypes; ++I) 13055 if (Context.getTypeSize(Types[I]) > BitWidth) 13056 return Types[I]; 13057 13058 return QualType(); 13059 } 13060 13061 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum, 13062 EnumConstantDecl *LastEnumConst, 13063 SourceLocation IdLoc, 13064 IdentifierInfo *Id, 13065 Expr *Val) { 13066 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13067 llvm::APSInt EnumVal(IntWidth); 13068 QualType EltTy; 13069 13070 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue)) 13071 Val = nullptr; 13072 13073 if (Val) 13074 Val = DefaultLvalueConversion(Val).get(); 13075 13076 if (Val) { 13077 if (Enum->isDependentType() || Val->isTypeDependent()) 13078 EltTy = Context.DependentTy; 13079 else { 13080 SourceLocation ExpLoc; 13081 if (getLangOpts().CPlusPlus11 && Enum->isFixed() && 13082 !getLangOpts().MSVCCompat) { 13083 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the 13084 // constant-expression in the enumerator-definition shall be a converted 13085 // constant expression of the underlying type. 13086 EltTy = Enum->getIntegerType(); 13087 ExprResult Converted = 13088 CheckConvertedConstantExpression(Val, EltTy, EnumVal, 13089 CCEK_Enumerator); 13090 if (Converted.isInvalid()) 13091 Val = nullptr; 13092 else 13093 Val = Converted.get(); 13094 } else if (!Val->isValueDependent() && 13095 !(Val = VerifyIntegerConstantExpression(Val, 13096 &EnumVal).get())) { 13097 // C99 6.7.2.2p2: Make sure we have an integer constant expression. 13098 } else { 13099 if (Enum->isFixed()) { 13100 EltTy = Enum->getIntegerType(); 13101 13102 // In Obj-C and Microsoft mode, require the enumeration value to be 13103 // representable in the underlying type of the enumeration. In C++11, 13104 // we perform a non-narrowing conversion as part of converted constant 13105 // expression checking. 13106 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13107 if (getLangOpts().MSVCCompat) { 13108 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy; 13109 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13110 } else 13111 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy; 13112 } else 13113 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get(); 13114 } else if (getLangOpts().CPlusPlus) { 13115 // C++11 [dcl.enum]p5: 13116 // If the underlying type is not fixed, the type of each enumerator 13117 // is the type of its initializing value: 13118 // - If an initializer is specified for an enumerator, the 13119 // initializing value has the same type as the expression. 13120 EltTy = Val->getType(); 13121 } else { 13122 // C99 6.7.2.2p2: 13123 // The expression that defines the value of an enumeration constant 13124 // shall be an integer constant expression that has a value 13125 // representable as an int. 13126 13127 // Complain if the value is not representable in an int. 13128 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy)) 13129 Diag(IdLoc, diag::ext_enum_value_not_int) 13130 << EnumVal.toString(10) << Val->getSourceRange() 13131 << (EnumVal.isUnsigned() || EnumVal.isNonNegative()); 13132 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) { 13133 // Force the type of the expression to 'int'. 13134 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get(); 13135 } 13136 EltTy = Val->getType(); 13137 } 13138 } 13139 } 13140 } 13141 13142 if (!Val) { 13143 if (Enum->isDependentType()) 13144 EltTy = Context.DependentTy; 13145 else if (!LastEnumConst) { 13146 // C++0x [dcl.enum]p5: 13147 // If the underlying type is not fixed, the type of each enumerator 13148 // is the type of its initializing value: 13149 // - If no initializer is specified for the first enumerator, the 13150 // initializing value has an unspecified integral type. 13151 // 13152 // GCC uses 'int' for its unspecified integral type, as does 13153 // C99 6.7.2.2p3. 13154 if (Enum->isFixed()) { 13155 EltTy = Enum->getIntegerType(); 13156 } 13157 else { 13158 EltTy = Context.IntTy; 13159 } 13160 } else { 13161 // Assign the last value + 1. 13162 EnumVal = LastEnumConst->getInitVal(); 13163 ++EnumVal; 13164 EltTy = LastEnumConst->getType(); 13165 13166 // Check for overflow on increment. 13167 if (EnumVal < LastEnumConst->getInitVal()) { 13168 // C++0x [dcl.enum]p5: 13169 // If the underlying type is not fixed, the type of each enumerator 13170 // is the type of its initializing value: 13171 // 13172 // - Otherwise the type of the initializing value is the same as 13173 // the type of the initializing value of the preceding enumerator 13174 // unless the incremented value is not representable in that type, 13175 // in which case the type is an unspecified integral type 13176 // sufficient to contain the incremented value. If no such type 13177 // exists, the program is ill-formed. 13178 QualType T = getNextLargerIntegralType(Context, EltTy); 13179 if (T.isNull() || Enum->isFixed()) { 13180 // There is no integral type larger enough to represent this 13181 // value. Complain, then allow the value to wrap around. 13182 EnumVal = LastEnumConst->getInitVal(); 13183 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2); 13184 ++EnumVal; 13185 if (Enum->isFixed()) 13186 // When the underlying type is fixed, this is ill-formed. 13187 Diag(IdLoc, diag::err_enumerator_wrapped) 13188 << EnumVal.toString(10) 13189 << EltTy; 13190 else 13191 Diag(IdLoc, diag::ext_enumerator_increment_too_large) 13192 << EnumVal.toString(10); 13193 } else { 13194 EltTy = T; 13195 } 13196 13197 // Retrieve the last enumerator's value, extent that type to the 13198 // type that is supposed to be large enough to represent the incremented 13199 // value, then increment. 13200 EnumVal = LastEnumConst->getInitVal(); 13201 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13202 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy)); 13203 ++EnumVal; 13204 13205 // If we're not in C++, diagnose the overflow of enumerator values, 13206 // which in C99 means that the enumerator value is not representable in 13207 // an int (C99 6.7.2.2p2). However, we support GCC's extension that 13208 // permits enumerator values that are representable in some larger 13209 // integral type. 13210 if (!getLangOpts().CPlusPlus && !T.isNull()) 13211 Diag(IdLoc, diag::warn_enum_value_overflow); 13212 } else if (!getLangOpts().CPlusPlus && 13213 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) { 13214 // Enforce C99 6.7.2.2p2 even when we compute the next value. 13215 Diag(IdLoc, diag::ext_enum_value_not_int) 13216 << EnumVal.toString(10) << 1; 13217 } 13218 } 13219 } 13220 13221 if (!EltTy->isDependentType()) { 13222 // Make the enumerator value match the signedness and size of the 13223 // enumerator's type. 13224 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy)); 13225 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType()); 13226 } 13227 13228 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy, 13229 Val, EnumVal); 13230 } 13231 13232 13233 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst, 13234 SourceLocation IdLoc, IdentifierInfo *Id, 13235 AttributeList *Attr, 13236 SourceLocation EqualLoc, Expr *Val) { 13237 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl); 13238 EnumConstantDecl *LastEnumConst = 13239 cast_or_null<EnumConstantDecl>(lastEnumConst); 13240 13241 // The scope passed in may not be a decl scope. Zip up the scope tree until 13242 // we find one that is. 13243 S = getNonFieldDeclScope(S); 13244 13245 // Verify that there isn't already something declared with this name in this 13246 // scope. 13247 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName, 13248 ForRedeclaration); 13249 if (PrevDecl && PrevDecl->isTemplateParameter()) { 13250 // Maybe we will complain about the shadowed template parameter. 13251 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl); 13252 // Just pretend that we didn't see the previous declaration. 13253 PrevDecl = nullptr; 13254 } 13255 13256 if (PrevDecl) { 13257 // When in C++, we may get a TagDecl with the same name; in this case the 13258 // enum constant will 'hide' the tag. 13259 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && 13260 "Received TagDecl when not in C++!"); 13261 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) { 13262 if (isa<EnumConstantDecl>(PrevDecl)) 13263 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id; 13264 else 13265 Diag(IdLoc, diag::err_redefinition) << Id; 13266 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 13267 return nullptr; 13268 } 13269 } 13270 13271 // C++ [class.mem]p15: 13272 // If T is the name of a class, then each of the following shall have a name 13273 // different from T: 13274 // - every enumerator of every member of class T that is an unscoped 13275 // enumerated type 13276 if (CXXRecordDecl *Record 13277 = dyn_cast<CXXRecordDecl>( 13278 TheEnumDecl->getDeclContext()->getRedeclContext())) 13279 if (!TheEnumDecl->isScoped() && 13280 Record->getIdentifier() && Record->getIdentifier() == Id) 13281 Diag(IdLoc, diag::err_member_name_of_class) << Id; 13282 13283 EnumConstantDecl *New = 13284 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val); 13285 13286 if (New) { 13287 // Process attributes. 13288 if (Attr) ProcessDeclAttributeList(S, New, Attr); 13289 13290 // Register this decl in the current scope stack. 13291 New->setAccess(TheEnumDecl->getAccess()); 13292 PushOnScopeChains(New, S); 13293 } 13294 13295 ActOnDocumentableDecl(New); 13296 13297 return New; 13298 } 13299 13300 // Returns true when the enum initial expression does not trigger the 13301 // duplicate enum warning. A few common cases are exempted as follows: 13302 // Element2 = Element1 13303 // Element2 = Element1 + 1 13304 // Element2 = Element1 - 1 13305 // Where Element2 and Element1 are from the same enum. 13306 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) { 13307 Expr *InitExpr = ECD->getInitExpr(); 13308 if (!InitExpr) 13309 return true; 13310 InitExpr = InitExpr->IgnoreImpCasts(); 13311 13312 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) { 13313 if (!BO->isAdditiveOp()) 13314 return true; 13315 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS()); 13316 if (!IL) 13317 return true; 13318 if (IL->getValue() != 1) 13319 return true; 13320 13321 InitExpr = BO->getLHS(); 13322 } 13323 13324 // This checks if the elements are from the same enum. 13325 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr); 13326 if (!DRE) 13327 return true; 13328 13329 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl()); 13330 if (!EnumConstant) 13331 return true; 13332 13333 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) != 13334 Enum) 13335 return true; 13336 13337 return false; 13338 } 13339 13340 struct DupKey { 13341 int64_t val; 13342 bool isTombstoneOrEmptyKey; 13343 DupKey(int64_t val, bool isTombstoneOrEmptyKey) 13344 : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {} 13345 }; 13346 13347 static DupKey GetDupKey(const llvm::APSInt& Val) { 13348 return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(), 13349 false); 13350 } 13351 13352 struct DenseMapInfoDupKey { 13353 static DupKey getEmptyKey() { return DupKey(0, true); } 13354 static DupKey getTombstoneKey() { return DupKey(1, true); } 13355 static unsigned getHashValue(const DupKey Key) { 13356 return (unsigned)(Key.val * 37); 13357 } 13358 static bool isEqual(const DupKey& LHS, const DupKey& RHS) { 13359 return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey && 13360 LHS.val == RHS.val; 13361 } 13362 }; 13363 13364 // Emits a warning when an element is implicitly set a value that 13365 // a previous element has already been set to. 13366 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements, 13367 EnumDecl *Enum, 13368 QualType EnumType) { 13369 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation())) 13370 return; 13371 // Avoid anonymous enums 13372 if (!Enum->getIdentifier()) 13373 return; 13374 13375 // Only check for small enums. 13376 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64) 13377 return; 13378 13379 typedef SmallVector<EnumConstantDecl *, 3> ECDVector; 13380 typedef SmallVector<ECDVector *, 3> DuplicatesVector; 13381 13382 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector; 13383 typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey> 13384 ValueToVectorMap; 13385 13386 DuplicatesVector DupVector; 13387 ValueToVectorMap EnumMap; 13388 13389 // Populate the EnumMap with all values represented by enum constants without 13390 // an initialier. 13391 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13392 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13393 13394 // Null EnumConstantDecl means a previous diagnostic has been emitted for 13395 // this constant. Skip this enum since it may be ill-formed. 13396 if (!ECD) { 13397 return; 13398 } 13399 13400 if (ECD->getInitExpr()) 13401 continue; 13402 13403 DupKey Key = GetDupKey(ECD->getInitVal()); 13404 DeclOrVector &Entry = EnumMap[Key]; 13405 13406 // First time encountering this value. 13407 if (Entry.isNull()) 13408 Entry = ECD; 13409 } 13410 13411 // Create vectors for any values that has duplicates. 13412 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13413 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]); 13414 if (!ValidDuplicateEnum(ECD, Enum)) 13415 continue; 13416 13417 DupKey Key = GetDupKey(ECD->getInitVal()); 13418 13419 DeclOrVector& Entry = EnumMap[Key]; 13420 if (Entry.isNull()) 13421 continue; 13422 13423 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) { 13424 // Ensure constants are different. 13425 if (D == ECD) 13426 continue; 13427 13428 // Create new vector and push values onto it. 13429 ECDVector *Vec = new ECDVector(); 13430 Vec->push_back(D); 13431 Vec->push_back(ECD); 13432 13433 // Update entry to point to the duplicates vector. 13434 Entry = Vec; 13435 13436 // Store the vector somewhere we can consult later for quick emission of 13437 // diagnostics. 13438 DupVector.push_back(Vec); 13439 continue; 13440 } 13441 13442 ECDVector *Vec = Entry.get<ECDVector*>(); 13443 // Make sure constants are not added more than once. 13444 if (*Vec->begin() == ECD) 13445 continue; 13446 13447 Vec->push_back(ECD); 13448 } 13449 13450 // Emit diagnostics. 13451 for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(), 13452 DupVectorEnd = DupVector.end(); 13453 DupVectorIter != DupVectorEnd; ++DupVectorIter) { 13454 ECDVector *Vec = *DupVectorIter; 13455 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements."); 13456 13457 // Emit warning for one enum constant. 13458 ECDVector::iterator I = Vec->begin(); 13459 S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values) 13460 << (*I)->getName() << (*I)->getInitVal().toString(10) 13461 << (*I)->getSourceRange(); 13462 ++I; 13463 13464 // Emit one note for each of the remaining enum constants with 13465 // the same value. 13466 for (ECDVector::iterator E = Vec->end(); I != E; ++I) 13467 S.Diag((*I)->getLocation(), diag::note_duplicate_element) 13468 << (*I)->getName() << (*I)->getInitVal().toString(10) 13469 << (*I)->getSourceRange(); 13470 delete Vec; 13471 } 13472 } 13473 13474 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 13475 SourceLocation RBraceLoc, Decl *EnumDeclX, 13476 ArrayRef<Decl *> Elements, 13477 Scope *S, AttributeList *Attr) { 13478 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX); 13479 QualType EnumType = Context.getTypeDeclType(Enum); 13480 13481 if (Attr) 13482 ProcessDeclAttributeList(S, Enum, Attr); 13483 13484 if (Enum->isDependentType()) { 13485 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13486 EnumConstantDecl *ECD = 13487 cast_or_null<EnumConstantDecl>(Elements[i]); 13488 if (!ECD) continue; 13489 13490 ECD->setType(EnumType); 13491 } 13492 13493 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0); 13494 return; 13495 } 13496 13497 // TODO: If the result value doesn't fit in an int, it must be a long or long 13498 // long value. ISO C does not support this, but GCC does as an extension, 13499 // emit a warning. 13500 unsigned IntWidth = Context.getTargetInfo().getIntWidth(); 13501 unsigned CharWidth = Context.getTargetInfo().getCharWidth(); 13502 unsigned ShortWidth = Context.getTargetInfo().getShortWidth(); 13503 13504 // Verify that all the values are okay, compute the size of the values, and 13505 // reverse the list. 13506 unsigned NumNegativeBits = 0; 13507 unsigned NumPositiveBits = 0; 13508 13509 // Keep track of whether all elements have type int. 13510 bool AllElementsInt = true; 13511 13512 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13513 EnumConstantDecl *ECD = 13514 cast_or_null<EnumConstantDecl>(Elements[i]); 13515 if (!ECD) continue; // Already issued a diagnostic. 13516 13517 const llvm::APSInt &InitVal = ECD->getInitVal(); 13518 13519 // Keep track of the size of positive and negative values. 13520 if (InitVal.isUnsigned() || InitVal.isNonNegative()) 13521 NumPositiveBits = std::max(NumPositiveBits, 13522 (unsigned)InitVal.getActiveBits()); 13523 else 13524 NumNegativeBits = std::max(NumNegativeBits, 13525 (unsigned)InitVal.getMinSignedBits()); 13526 13527 // Keep track of whether every enum element has type int (very commmon). 13528 if (AllElementsInt) 13529 AllElementsInt = ECD->getType() == Context.IntTy; 13530 } 13531 13532 // Figure out the type that should be used for this enum. 13533 QualType BestType; 13534 unsigned BestWidth; 13535 13536 // C++0x N3000 [conv.prom]p3: 13537 // An rvalue of an unscoped enumeration type whose underlying 13538 // type is not fixed can be converted to an rvalue of the first 13539 // of the following types that can represent all the values of 13540 // the enumeration: int, unsigned int, long int, unsigned long 13541 // int, long long int, or unsigned long long int. 13542 // C99 6.4.4.3p2: 13543 // An identifier declared as an enumeration constant has type int. 13544 // The C99 rule is modified by a gcc extension 13545 QualType BestPromotionType; 13546 13547 bool Packed = Enum->hasAttr<PackedAttr>(); 13548 // -fshort-enums is the equivalent to specifying the packed attribute on all 13549 // enum definitions. 13550 if (LangOpts.ShortEnums) 13551 Packed = true; 13552 13553 if (Enum->isFixed()) { 13554 BestType = Enum->getIntegerType(); 13555 if (BestType->isPromotableIntegerType()) 13556 BestPromotionType = Context.getPromotedIntegerType(BestType); 13557 else 13558 BestPromotionType = BestType; 13559 // We don't need to set BestWidth, because BestType is going to be the type 13560 // of the enumerators, but we do anyway because otherwise some compilers 13561 // warn that it might be used uninitialized. 13562 BestWidth = CharWidth; 13563 } 13564 else if (NumNegativeBits) { 13565 // If there is a negative value, figure out the smallest integer type (of 13566 // int/long/longlong) that fits. 13567 // If it's packed, check also if it fits a char or a short. 13568 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) { 13569 BestType = Context.SignedCharTy; 13570 BestWidth = CharWidth; 13571 } else if (Packed && NumNegativeBits <= ShortWidth && 13572 NumPositiveBits < ShortWidth) { 13573 BestType = Context.ShortTy; 13574 BestWidth = ShortWidth; 13575 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) { 13576 BestType = Context.IntTy; 13577 BestWidth = IntWidth; 13578 } else { 13579 BestWidth = Context.getTargetInfo().getLongWidth(); 13580 13581 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) { 13582 BestType = Context.LongTy; 13583 } else { 13584 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13585 13586 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth) 13587 Diag(Enum->getLocation(), diag::ext_enum_too_large); 13588 BestType = Context.LongLongTy; 13589 } 13590 } 13591 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType); 13592 } else { 13593 // If there is no negative value, figure out the smallest type that fits 13594 // all of the enumerator values. 13595 // If it's packed, check also if it fits a char or a short. 13596 if (Packed && NumPositiveBits <= CharWidth) { 13597 BestType = Context.UnsignedCharTy; 13598 BestPromotionType = Context.IntTy; 13599 BestWidth = CharWidth; 13600 } else if (Packed && NumPositiveBits <= ShortWidth) { 13601 BestType = Context.UnsignedShortTy; 13602 BestPromotionType = Context.IntTy; 13603 BestWidth = ShortWidth; 13604 } else if (NumPositiveBits <= IntWidth) { 13605 BestType = Context.UnsignedIntTy; 13606 BestWidth = IntWidth; 13607 BestPromotionType 13608 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13609 ? Context.UnsignedIntTy : Context.IntTy; 13610 } else if (NumPositiveBits <= 13611 (BestWidth = Context.getTargetInfo().getLongWidth())) { 13612 BestType = Context.UnsignedLongTy; 13613 BestPromotionType 13614 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13615 ? Context.UnsignedLongTy : Context.LongTy; 13616 } else { 13617 BestWidth = Context.getTargetInfo().getLongLongWidth(); 13618 assert(NumPositiveBits <= BestWidth && 13619 "How could an initializer get larger than ULL?"); 13620 BestType = Context.UnsignedLongLongTy; 13621 BestPromotionType 13622 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus) 13623 ? Context.UnsignedLongLongTy : Context.LongLongTy; 13624 } 13625 } 13626 13627 // Loop over all of the enumerator constants, changing their types to match 13628 // the type of the enum if needed. 13629 for (unsigned i = 0, e = Elements.size(); i != e; ++i) { 13630 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]); 13631 if (!ECD) continue; // Already issued a diagnostic. 13632 13633 // Standard C says the enumerators have int type, but we allow, as an 13634 // extension, the enumerators to be larger than int size. If each 13635 // enumerator value fits in an int, type it as an int, otherwise type it the 13636 // same as the enumerator decl itself. This means that in "enum { X = 1U }" 13637 // that X has type 'int', not 'unsigned'. 13638 13639 // Determine whether the value fits into an int. 13640 llvm::APSInt InitVal = ECD->getInitVal(); 13641 13642 // If it fits into an integer type, force it. Otherwise force it to match 13643 // the enum decl type. 13644 QualType NewTy; 13645 unsigned NewWidth; 13646 bool NewSign; 13647 if (!getLangOpts().CPlusPlus && 13648 !Enum->isFixed() && 13649 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) { 13650 NewTy = Context.IntTy; 13651 NewWidth = IntWidth; 13652 NewSign = true; 13653 } else if (ECD->getType() == BestType) { 13654 // Already the right type! 13655 if (getLangOpts().CPlusPlus) 13656 // C++ [dcl.enum]p4: Following the closing brace of an 13657 // enum-specifier, each enumerator has the type of its 13658 // enumeration. 13659 ECD->setType(EnumType); 13660 continue; 13661 } else { 13662 NewTy = BestType; 13663 NewWidth = BestWidth; 13664 NewSign = BestType->isSignedIntegerOrEnumerationType(); 13665 } 13666 13667 // Adjust the APSInt value. 13668 InitVal = InitVal.extOrTrunc(NewWidth); 13669 InitVal.setIsSigned(NewSign); 13670 ECD->setInitVal(InitVal); 13671 13672 // Adjust the Expr initializer and type. 13673 if (ECD->getInitExpr() && 13674 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType())) 13675 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy, 13676 CK_IntegralCast, 13677 ECD->getInitExpr(), 13678 /*base paths*/ nullptr, 13679 VK_RValue)); 13680 if (getLangOpts().CPlusPlus) 13681 // C++ [dcl.enum]p4: Following the closing brace of an 13682 // enum-specifier, each enumerator has the type of its 13683 // enumeration. 13684 ECD->setType(EnumType); 13685 else 13686 ECD->setType(NewTy); 13687 } 13688 13689 Enum->completeDefinition(BestType, BestPromotionType, 13690 NumPositiveBits, NumNegativeBits); 13691 13692 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType); 13693 13694 // Now that the enum type is defined, ensure it's not been underaligned. 13695 if (Enum->hasAttrs()) 13696 CheckAlignasUnderalignment(Enum); 13697 } 13698 13699 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr, 13700 SourceLocation StartLoc, 13701 SourceLocation EndLoc) { 13702 StringLiteral *AsmString = cast<StringLiteral>(expr); 13703 13704 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext, 13705 AsmString, StartLoc, 13706 EndLoc); 13707 CurContext->addDecl(New); 13708 return New; 13709 } 13710 13711 static void checkModuleImportContext(Sema &S, Module *M, 13712 SourceLocation ImportLoc, 13713 DeclContext *DC) { 13714 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 13715 switch (LSD->getLanguage()) { 13716 case LinkageSpecDecl::lang_c: 13717 if (!M->IsExternC) { 13718 S.Diag(ImportLoc, diag::err_module_import_in_extern_c) 13719 << M->getFullModuleName(); 13720 S.Diag(LSD->getLocStart(), diag::note_module_import_in_extern_c); 13721 return; 13722 } 13723 break; 13724 case LinkageSpecDecl::lang_cxx: 13725 break; 13726 } 13727 DC = LSD->getParent(); 13728 } 13729 13730 while (isa<LinkageSpecDecl>(DC)) 13731 DC = DC->getParent(); 13732 if (!isa<TranslationUnitDecl>(DC)) { 13733 S.Diag(ImportLoc, diag::err_module_import_not_at_top_level) 13734 << M->getFullModuleName() << DC; 13735 S.Diag(cast<Decl>(DC)->getLocStart(), 13736 diag::note_module_import_not_at_top_level) 13737 << DC; 13738 } 13739 } 13740 13741 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc, 13742 SourceLocation ImportLoc, 13743 ModuleIdPath Path) { 13744 Module *Mod = 13745 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 13746 /*IsIncludeDirective=*/false); 13747 if (!Mod) 13748 return true; 13749 13750 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 13751 13752 // FIXME: we should support importing a submodule within a different submodule 13753 // of the same top-level module. Until we do, make it an error rather than 13754 // silently ignoring the import. 13755 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule) 13756 Diag(ImportLoc, diag::err_module_self_import) 13757 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 13758 else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule) 13759 Diag(ImportLoc, diag::err_module_import_in_implementation) 13760 << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule; 13761 13762 SmallVector<SourceLocation, 2> IdentifierLocs; 13763 Module *ModCheck = Mod; 13764 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 13765 // If we've run out of module parents, just drop the remaining identifiers. 13766 // We need the length to be consistent. 13767 if (!ModCheck) 13768 break; 13769 ModCheck = ModCheck->Parent; 13770 13771 IdentifierLocs.push_back(Path[I].second); 13772 } 13773 13774 ImportDecl *Import = ImportDecl::Create(Context, 13775 Context.getTranslationUnitDecl(), 13776 AtLoc.isValid()? AtLoc : ImportLoc, 13777 Mod, IdentifierLocs); 13778 Context.getTranslationUnitDecl()->addDecl(Import); 13779 return Import; 13780 } 13781 13782 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 13783 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext); 13784 13785 // FIXME: Should we synthesize an ImportDecl here? 13786 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc, 13787 /*Complain=*/true); 13788 } 13789 13790 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 13791 Module *Mod) { 13792 // Bail if we're not allowed to implicitly import a module here. 13793 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery) 13794 return; 13795 13796 // Create the implicit import declaration. 13797 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 13798 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 13799 Loc, Mod, Loc); 13800 TU->addDecl(ImportD); 13801 Consumer.HandleImplicitImportDecl(ImportD); 13802 13803 // Make the module visible. 13804 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc, 13805 /*Complain=*/false); 13806 } 13807 13808 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name, 13809 IdentifierInfo* AliasName, 13810 SourceLocation PragmaLoc, 13811 SourceLocation NameLoc, 13812 SourceLocation AliasNameLoc) { 13813 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, 13814 LookupOrdinaryName); 13815 AsmLabelAttr *Attr = ::new (Context) AsmLabelAttr(AliasNameLoc, Context, 13816 AliasName->getName(), 0); 13817 13818 if (PrevDecl) 13819 PrevDecl->addAttr(Attr); 13820 else 13821 (void)ExtnameUndeclaredIdentifiers.insert( 13822 std::pair<IdentifierInfo*,AsmLabelAttr*>(Name, Attr)); 13823 } 13824 13825 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name, 13826 SourceLocation PragmaLoc, 13827 SourceLocation NameLoc) { 13828 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName); 13829 13830 if (PrevDecl) { 13831 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc)); 13832 } else { 13833 (void)WeakUndeclaredIdentifiers.insert( 13834 std::pair<IdentifierInfo*,WeakInfo> 13835 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc))); 13836 } 13837 } 13838 13839 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name, 13840 IdentifierInfo* AliasName, 13841 SourceLocation PragmaLoc, 13842 SourceLocation NameLoc, 13843 SourceLocation AliasNameLoc) { 13844 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc, 13845 LookupOrdinaryName); 13846 WeakInfo W = WeakInfo(Name, NameLoc); 13847 13848 if (PrevDecl) { 13849 if (!PrevDecl->hasAttr<AliasAttr>()) 13850 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl)) 13851 DeclApplyPragmaWeak(TUScope, ND, W); 13852 } else { 13853 (void)WeakUndeclaredIdentifiers.insert( 13854 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W)); 13855 } 13856 } 13857 13858 Decl *Sema::getObjCDeclContext() const { 13859 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext)); 13860 } 13861 13862 AvailabilityResult Sema::getCurContextAvailability() const { 13863 const Decl *D = cast<Decl>(getCurObjCLexicalContext()); 13864 // If we are within an Objective-C method, we should consult 13865 // both the availability of the method as well as the 13866 // enclosing class. If the class is (say) deprecated, 13867 // the entire method is considered deprecated from the 13868 // purpose of checking if the current context is deprecated. 13869 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 13870 AvailabilityResult R = MD->getAvailability(); 13871 if (R != AR_Available) 13872 return R; 13873 D = MD->getClassInterface(); 13874 } 13875 // If we are within an Objective-c @implementation, it 13876 // gets the same availability context as the @interface. 13877 else if (const ObjCImplementationDecl *ID = 13878 dyn_cast<ObjCImplementationDecl>(D)) { 13879 D = ID->getClassInterface(); 13880 } 13881 // Recover from user error. 13882 return D ? D->getAvailability() : AR_Available; 13883 } 13884